@quickback-dev/cli 0.16.5 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +12 -48
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/create.d.ts +20 -0
- package/dist/commands/create.d.ts.map +1 -1
- package/dist/commands/create.js +216 -151
- package/dist/commands/create.js.map +1 -1
- package/dist/commands/login.d.ts +4 -2
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +25 -17
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/start.d.ts +20 -0
- package/dist/commands/start.d.ts.map +1 -0
- package/dist/commands/start.js +163 -0
- package/dist/commands/start.js.map +1 -0
- package/dist/commands/whoami.d.ts.map +1 -1
- package/dist/commands/whoami.js +5 -4
- package/dist/commands/whoami.js.map +1 -1
- package/dist/docs/content.js +42 -42
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +27 -10
- package/dist/index.js.map +1 -1
- package/dist/lib/api-client.js +1 -1
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/api-client.test.js +15 -0
- package/dist/lib/api-client.test.js.map +1 -1
- package/dist/lib/auth.d.ts +39 -3
- package/dist/lib/auth.d.ts.map +1 -1
- package/dist/lib/auth.js +57 -3
- package/dist/lib/auth.js.map +1 -1
- package/dist/lib/drizzle-meta-routing.test.js +16 -3
- package/dist/lib/drizzle-meta-routing.test.js.map +1 -1
- package/dist/lib/file-loader.d.ts +6 -4
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +30 -27
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/file-loader.test.js +16 -7
- package/dist/lib/file-loader.test.js.map +1 -1
- package/dist/skill/docs/changelog.md +429 -1100
- package/dist/skill/docs/compiler/cloud-compiler/cli.md +54 -33
- package/dist/skill/docs/compiler/cloud-compiler/index.md +9 -9
- package/dist/skill/docs/compiler/config/providers.md +87 -0
- package/dist/skill/docs/compiler/config/single-tenant.md +5 -11
- package/dist/skill/docs/compiler/definitions/access.md +43 -57
- package/dist/skill/docs/compiler/definitions/feature.md +7 -11
- package/dist/skill/docs/compiler/definitions/firewall.md +2 -4
- package/dist/skill/docs/compiler/definitions/guards.md +16 -18
- package/dist/skill/docs/compiler/definitions/index.md +10 -14
- package/dist/skill/docs/compiler/definitions/masking.md +6 -6
- package/dist/skill/docs/compiler/definitions/read.md +6 -11
- package/dist/skill/docs/compiler/definitions/schema.md +18 -18
- package/dist/skill/docs/compiler/definitions/views.md +3 -5
- package/dist/skill/docs/compiler/getting-started/full-example.md +6 -8
- package/dist/skill/docs/compiler/getting-started/hand-crafted.md +3 -5
- package/dist/skill/docs/compiler/getting-started/index.md +23 -20
- package/dist/skill/docs/compiler/getting-started/patterns.md +19 -31
- package/dist/skill/docs/compiler/getting-started/template-blog.md +6 -10
- package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +49 -56
- package/dist/skill/docs/compiler/getting-started/template-empty.md +3 -5
- package/dist/skill/docs/compiler/getting-started/templates.md +58 -56
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +29 -23
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +12 -14
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +5 -2
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +5 -7
- package/dist/skill/docs/compiler/troubleshooting.md +10 -0
- package/dist/skill/docs/index.md +9 -0
- package/dist/skill/docs/stack/auth/security.md +69 -0
- package/dist/skill/docs/stack/cms/actions.md +28 -0
- package/dist/skill/docs/stack/cms/connecting.md +2 -2
- package/dist/skill/docs/stack/cms/index.md +2 -2
- package/dist/skill/docs/stack/cms/record-layouts.md +19 -19
- package/dist/skill/docs/stack/cms/schema-format.md +33 -3
- package/dist/skill/docs/stack/cms/schema-registry.md +22 -2
- package/dist/skill/docs/stack/cms/security.md +10 -12
- package/dist/skill/docs/stack/cms/table-views.md +1 -1
- package/dist/skill/docs/stack/index.md +8 -4
- package/dist/skill/docs/stack/realtime/durable-objects.md +46 -5
- package/dist/skill/docs/stack/realtime/index.md +20 -3
- package/dist/skill/docs/stack/realtime/using-realtime.md +8 -6
- package/dist/skill/docs/stack/vector/embeddings.md +7 -6
- package/package.json +1 -1
- package/src/skill/docs/changelog.md +486 -1097
- package/src/skill/docs/compiler/cloud-compiler/cli.md +54 -33
- package/src/skill/docs/compiler/cloud-compiler/index.md +9 -9
- package/src/skill/docs/compiler/config/domains.md +44 -10
- package/src/skill/docs/compiler/config/output.md +1 -1
- package/src/skill/docs/compiler/config/providers.md +87 -0
- package/src/skill/docs/compiler/config/single-tenant.md +5 -11
- package/src/skill/docs/compiler/definitions/access.md +43 -57
- package/src/skill/docs/compiler/definitions/feature.md +7 -11
- package/src/skill/docs/compiler/definitions/firewall.md +2 -4
- package/src/skill/docs/compiler/definitions/guards.md +16 -18
- package/src/skill/docs/compiler/definitions/index.md +10 -14
- package/src/skill/docs/compiler/definitions/masking.md +6 -6
- package/src/skill/docs/compiler/definitions/read.md +6 -11
- package/src/skill/docs/compiler/definitions/schema.md +18 -18
- package/src/skill/docs/compiler/definitions/views.md +3 -5
- package/src/skill/docs/compiler/getting-started/full-example.md +6 -8
- package/src/skill/docs/compiler/getting-started/hand-crafted.md +3 -5
- package/src/skill/docs/compiler/getting-started/index.md +23 -20
- package/src/skill/docs/compiler/getting-started/patterns.md +19 -31
- package/src/skill/docs/compiler/getting-started/template-blog.md +6 -10
- package/src/skill/docs/compiler/getting-started/template-cloudflare.md +49 -56
- package/src/skill/docs/compiler/getting-started/template-empty.md +3 -5
- package/src/skill/docs/compiler/getting-started/templates.md +58 -56
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +29 -23
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/crud.md +12 -14
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +5 -2
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +5 -7
- package/src/skill/docs/compiler/troubleshooting.md +10 -0
- package/src/skill/docs/index.md +9 -0
- package/src/skill/docs/stack/auth/plugins/index.md +74 -0
- package/src/skill/docs/stack/auth/security.md +69 -0
- package/src/skill/docs/stack/cms/actions.md +28 -0
- package/src/skill/docs/stack/cms/connecting.md +2 -2
- package/src/skill/docs/stack/cms/index.md +2 -2
- package/src/skill/docs/stack/cms/record-layouts.md +19 -19
- package/src/skill/docs/stack/cms/schema-format.md +33 -3
- package/src/skill/docs/stack/cms/schema-registry.md +22 -2
- package/src/skill/docs/stack/cms/security.md +10 -12
- package/src/skill/docs/stack/cms/table-views.md +1 -1
- package/src/skill/docs/stack/index.md +8 -4
- package/src/skill/docs/stack/realtime/durable-objects.md +46 -5
- package/src/skill/docs/stack/realtime/index.md +20 -3
- package/src/skill/docs/stack/realtime/using-realtime.md +8 -6
- package/src/skill/docs/stack/vector/embeddings.md +7 -6
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.16.4 — May 12, 2026\n\n### Compile didn't emit a migration — v0.16.3 corrupted drizzle snapshots, fixed + self-heal\n\nThe v0.16.3 release stamped a `$$__quickback_warning__$$` key onto every drizzle metadata JSON file under `quickback/drizzle/<dialect>/meta/` — both `_journal.json` and each `<n>_snapshot.json`. The original change description noted that drizzle-kit \"ignores unknown top-level fields when reading journals/snapshots\" — but that's only true for journals. Snapshots are parsed by a strict Zod schema that rejects extras, so on every compile after the upgrade, drizzle-kit logged each `<n>_snapshot.json` as `\"data is malformed\"`, lost its diff base, and silently emitted no migration on schema changes. Users hand-wrote migrations (e.g. `0033`) to compensate. Reproduced against `examples/recruitment` by adding a column to `candidates` — the recruit tree's 8 snapshots all came back malformed and zero migrations were generated.\n\nThe fix narrows `DRIZZLE_META_JSON_RE` to a journal-only matcher (`DRIZZLE_JOURNAL_JSON_RE`) so the warning is stamped only where it's safe. A new `stripJsonHeader()` helper runs over `existingFiles` when the staging step encounters a `<n>_snapshot.json`, so projects whose tree was already corrupted by v0.16.3 self-heal on the next compile: the bad header is stripped on the way into the staging dir, drizzle-kit's diff resolves correctly, and the emitted snapshot writes back without the offending key. No manual snapshot surgery required after upgrading — the next `quickback compile` quietly cleans up the prior corruption.\n\nPinned by `drizzle-meta-header.test.ts`: journals receive the warning key at position 0; snapshots are byte-identical input/output (no warning key); `stripJsonHeader` strips a present warning, no-ops on absent, and tolerates unparseable / array-shaped JSON.\n\n### `account.auth.*` now drives the server, not just the UI — closes a signup-disabled bypass\n\nA 2026-05-11 external pentest of a production Loop deployment confirmed that `account.auth.signup: false` only hid the SPA's signup screen while leaving `POST /auth/v1/sign-up/email` wide open. A new account could be created against the server, and because `account.auth.emailVerification: false` was the only emit point (it never set the server's `requireEmailVerification`), the freshly issued session was immediately usable. The same shape applied to `password`, `passkey`, and `emailOTP` — every \"friendly\" `account.auth.*` flag was a SPA build flag with no server counterpart. The Account UI promised \"signup is off\"; the server cheerfully accepted the registration.\n\n`apps/compiler/src/providers/auth/providers/better-auth/normalize-from-account.ts` introduces a one-way normalizer that runs in `parseCompilerInput` before any generator reads `providers.auth`. It maps `account.auth.*` into the Better Auth server config — `signup → emailAndPassword.disableSignUp` (inverted), `password → emailAndPassword.enabled`, `emailVerification → emailAndPassword.requireEmailVerification`, `passkey`/`emailOTP` → plugin additions — only when the user hasn't already set the BA field explicitly. Setting both sides incompatibly (e.g. `account.auth.signup: false` AND `emailAndPassword.disableSignUp: false`) throws at compile time with a precise multi-line error rather than picking a silent winner; the silent precedence is what created the bug in the first place.\n\nThe Account SPA's `VITE_ENABLE_*` flags are now derived from the same canonicalized BA config via a new `resolveAuthFeatureFlags()` helper in `generators/spa-builder.ts`, so the SPA bundle and the server cannot drift. The helper self-normalizes (idempotent) for direct callers and unit tests. Two new SPA flags ride along: `VITE_ENABLE_API_KEYS` (driven by the `apiKey` plugin) and `VITE_ENABLE_MAGIC_LINK` (driven by the `magicLink` plugin), so the existing api-keys route in `packages/account` can self-gate the same way passkey/emailOTP already do.\n\n**Breaking** for anyone who was implicitly relying on the open signup endpoint: projects that set `account.auth.signup: false` but actually wanted server signup to remain open must now explicitly set `providers.auth.config.emailAndPassword.disableSignUp: false` (and accept the risk). Same migration path for `emailVerification` (now actually enforced server-side when set) and the plugin flags. Loop's existing config requires no change — the next recompile + deploy starts returning `403` on `POST /auth/v1/sign-up/email`, which is exactly what the config has been claiming since the field was added.\n\nPinned by `account-auth-normalize.test.ts` (19 unit tests covering the normalizer + flag resolver + contradiction detection on both array- and object-form plugins) and `loop-pentest-regression.test.ts` (compiles a trimmed Loop config and asserts the generated `auth.ts` carries `disableSignUp: true`).\n\n---\n\n## v0.16.3 — May 9, 2026\n\n### Standalone action mount order — literal paths no longer get swallowed by sibling CRUD `/:id` routes\n\nWhen a feature exposed both CRUD routes and a standalone action at the same mount prefix, Hono could register the CRUD router first. A literal standalone path like `GET /api/v1/records/today-bundle` would then hit the CRUD router's `GET /:id`, treat `\"today-bundle\"` as a record id, and fail in the firewall layer as a fake record lookup instead of ever reaching the standalone handler.\n\nThe compiler now attaches an explicit registration priority to generated route mounts. Feature-level standalone action routers register before sibling CRUD routers when both mount at the exact same prefix, so literal paths win and `/:id` remains the fallback. The regression is pinned in `standalone-route-mount-order.test.ts`, which asserts both emitted routes and the final mount order in `src/index.ts`.\n\nThis is a routing-correctness fix, not a public API redesign. No user code changes are required, and existing standalone action paths do not need to be renamed. Recompile and shared-prefix standalone routes resolve correctly.\n\n---\n\n## v0.16.1 — May 9, 2026\n\n### Cloudflare ASSETS canonicalization — worker SPA emits no longer 307-loop\n\nCloudflare's static-assets binding canonicalizes any request for `/<dir>/index.html` into a 307 redirect to `/<dir>/` (the default `html_handling=auto-trailing-slash`). When a worker subrequest issues `c.env.ASSETS.fetch(new Request(new URL('/<dir>/index.html', …)))`, the binding returns the 307; the worker forwards it; the browser re-requests `/<dir>/`; the same SPA-fallback handler (or hostname middleware) catches the directory request and re-fetches `/<dir>/index.html`. Infinite loop. Caught by AttendVIP writing custom `/admin/` and `/m/` host-routing patches on the deployed worker — the fix in their patches was switching to `/admin/` (trailing slash, no `index.html`), which Cloudflare resolves to the directory's `index.html` content with a 200.\n\nThe compiler had the same bug baked into every emit point. `cloudflare.ts` now fetches `/<dir>/` everywhere it previously asked for `/<dir>/index.html`: CMS hostname middleware, `/cms/*` SPA catchall, apex `/` handler, account/admin hostname middleware, `/account/*` SPA catchall, and the multi-domain catchall. Eight regression tests in `cf-assets-canonicalization-spa-fallback.test.ts` pin every emit so a future copy/paste can't sneak the literal back in.\n\n### `account.customLogin` — drop a project-branded sign-in page in front of the SPA\n\nA new `account: { customLogin: true }` flag emits an explicit `app.get('/account/login', …)` route that serves a project-supplied static page instead of letting the bundled Account SPA's client router handle the path. Drop the page at `quickback/public/account/login/index.html` (a *directory*, not a bare `login.html` — see the canonicalization note above) and the existing `quickback/public/` passthrough copies it into the asset binding. The route is registered before the `/account/*` SPA catch-all so the static handler wins; everything else under `/account/...` (profile, organizations, devices, …) keeps going through the React SPA. Same surface AttendVIP was hand-patching post-compile — promoting the flag means the next compile no longer wipes their override. Default `false`.\n\n### Project-level realtime auto-broadcasts every resource by default\n\n`dbConfig.realtime: true` now treats every resource as realtime-enabled unless its `realtime` block explicitly opts out. The previous behavior set `effectiveResourceRealtime` to `undefined` when a resource didn't declare its own block — so a project that flipped the project-level flag still had to add per-table `realtime: { enabled: true }` everywhere to actually get auto-broadcasts. Caught against AttendVIP after the v0.15.x auto-broadcast wiring landed but didn't fire. New default: project-level on with no per-resource override = `{ enabled: true }`. Per-resource `realtime: { enabled: false }` still wins.\n\n### Drizzle metadata gets a DO NOT EDIT header + journal drift warning\n\nTwo changes that protect the drizzle plumbing from quiet corruption.\n\n`compile-runner.ts:addJsonHeader` now stamps drizzle's generated JSON (`_journal.json`, `<n>_snapshot.json`) with a `$__quickback_warning__$` key explaining the file is regenerated by the compiler and should not be edited by hand. The disclaimer matches the one already on `.ts` outputs — the journal had been the one drizzle file users felt entitled to \"tidy up\" because nothing in it said otherwise.\n\nA new check in the same module compares the journal entry count against the snapshot file count. drizzle-kit only produces one snapshot per `generate` run, so `journal.entries.length > snapshots + 1` means the journal claims migrations the snapshot side has lost (typical cause: a manual delete of an `<n>_snapshot.json` that left the journal entry behind). The compiler logs a warning and lists the orphan entries. Detected directly out of AttendVIP's `Travel 500` triage — drizzle-kit was diffing against a stale `0002_snapshot.json` and emitting bogus full `CREATE TABLE` migrations for tables that had been added in subsequent (now-orphaned) journal entries.\n\n### Two new compile-time validators (LOUD failures over silent traps)\n\n**`AUTHENTICATED` + tenant-scoped firewall now refuses to compile.** `pseudo-role-validator.ts` rejects any access tree that admits `AUTHENTICATED` on a resource whose firewall scopes by `organizationId`. The combination is the silent-empty trap: a sign-in-only caller with no active org passes the role gate, the firewall WHERE clause filters every row out, and the API returns `[]` with a 200. The error message names three valid resolutions — drop the org scope (`firewall: { exception: true }`), tighten the role to `USER` or a role with implied org membership, or split the route into a token-auth branch and an org-membership branch.\n\n**`createRealtime` imports without `dbConfig.realtime: true` now throw.** Project lib + action + feature-lib files are scanned at compile time for `import { createRealtime }` (and the equivalent named binding). When the project hasn't enabled realtime, the compile fails with the offending file paths and remediation: either enable `dbConfig.realtime: true` so the runtime helper exists, or remove the import. Caught against AttendVIP — three handler files (`broadcastAnnouncement.ts`, `declineActivityForGuest.ts`, `applyRsvp.ts`) imported `createRealtime` after the v0.15 auto-broadcast wiring landed, but their config never set `realtime: true`. The Worker compiled, deployed, and 500'd at first call. The user's framing was \"config should be the source of truth\" — this validator enforces that. Five regression tests in `realtime-import-without-config-rejected.test.ts`.\n\n### Fixes\n\n**1. `SYSADMIN` was missing from the per-feature standalone gate's `allowsWithoutOrg` set.** The standalone-action wrapper skips its `if (!ctx.activeOrgId)` gate for any access tree referencing a pseudo-role (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`) — but `SYSADMIN`, the v0.15.0 fifth marker, was missing from the matcher. Sysadmin actions on `cms.sysadmin: true` projects were 403'ing on cross-tenant calls (sysadmins have no member rows, so `ctx.activeOrgId` is unset by design). The matcher now includes `SYSADMIN`.\n\n**2. Apex `/` and `/account/login` get fallback redirects when neither CMS nor Account SPA is bundled.** Projects that opt out of both bundled SPAs still receive traffic at `/` (no apex handler, 404) and `/account/login` (no Account fallback, 404). Setting `auth.loginUrl` to an external sign-in host now activates two compiler-emitted redirects so those natural inbound URLs land somewhere useful: `/account/login → loginUrl?redirect=…` (preserves the bounce param) and `/ → loginUrl` (or `/account` when the Account SPA is bundled). Both opt in via `auth.loginUrl !== '/account/login'` so projects using the built-in `/account/login` keep the existing SPA-fallback behavior unchanged.\n\n**3. Record-based action URLs are now kebab-case to match OpenAPI.** `record-based.ts` was emitting URL paths from the camelCase action name (e.g. `/api/v1/widgets/:id/sendInvite`) while OpenAPI emit produced `/widgets/:id/send-invite`. Admin tooling and SDK consumers reading the OpenAPI spec hit 404s on every multi-word action. URL paths and OpenAPI emit now share a `urlPath = toKebabCase(urlSegment)` helper. Identifiers in audit `actionName`, error messages, and console logs stay camel — those are programmatic surfaces and breaking them would churn audit logs. Same fix shape as the v0.15.0 standalone-action URL casing.\n\n### Notes\n\nTest coverage: 1175 → 1183 (+8 across the canonicalization, customLogin, and createRealtime regression files). Verified end-to-end against AttendVIP — `quickback compile` produces a worker whose `/account/login`, hostname-routed account/admin SPAs, and apex / handler all return 200 with the right SPA shell on the deployed Cloudflare worker, no 307 loops.\n\nThe bundled docs (`packages/claude-skill/docs/changelog.md`, `packages/cli/src/skill/docs/changelog.md`) and the CLI's `packages/cli/src/docs/content.ts` are regenerated by `scripts/bundle-docs.ts` — run that before publishing the CLI bump.\n\n---\n\n## v0.16.0 — May 9, 2026\n\n### Agent Auth Protocol — first-class agent identity for AI callers\n\nQuickback now ships a server implementation of the [Agent Auth Protocol](https://agentauthprotocol.com) by way of `@better-auth/agent-auth`. Opt in with `auth.plugins.agentAuth: true` (or the array form `plugins: [\"agentAuth\"]`). When enabled, the compiler emits a complete agent-auth surface: discovery at `/.well-known/agent-configuration`, capability projection from the project's OpenAPI spec, a device-authorization approval page in the Account SPA at `/agents/approve`, and the four agent-auth tables (`agent`, `agentHost`, `agentCapabilityGrant`, `approvalRequest`) added to the auth schema automatically by `auth generate`.\n\n**OpenAPI capability projection runs by default.** The compiler emits `src/lib/openapi-spec.ts` (the project's full OpenAPI spec inlined as a const) and wires `createFromOpenAPI(openapiSpec, { ... })` into the `agentAuth(...)` call. Every operation with an `operationId` becomes an agent capability. Default `approvalStrength` map: `GET → \"session\"`, `POST/PUT/PATCH/DELETE → \"webauthn\"`. Default `defaultHostCapabilities`: `[\"GET\", \"HEAD\"]`.\n\nThe proxy `onExecute` makes a self-fetch to the worker's own URL with a Better Auth JWT minted for `agentSession.user.id`, so the inner request hits the existing JWT fast-path, populates `ctx`, and the full firewall + access + masking pipeline runs on the proxied call. No new middleware code, no parallel security path — agent capability calls go through the same gates as regular REST traffic. The cost is one Cloudflare subrequest per capability call (~50ms); fine for typical agent traffic. Opt out of OpenAPI projection with `agentAuth: { fromOpenAPI: false }` and wire `capabilities` + `onExecute` by hand.\n\nThe Account SPA gains `/agents/approve` (`packages/account/app/routes/agents.approve.tsx`) — modeled on the existing `/cli/authorize` device-code page. Pastes the user code, fetches the pending request, lists the requested capabilities with a \"Step-up\" badge on any capability whose `approvalStrength` is `\"webauthn\"`, then approves or denies. WebAuthn step-up itself is a placeholder for v0.16.0 — the upstream agent-auth API for the escalation call is still settling, so capabilities tagged `\"webauthn\"` will fail server-side until that lands. The badge tells the user what's coming.\n\n### Bearer-only on `/mcp` and the agent-auth surface\n\n`/mcp` now forwards **only** `Authorization: Bearer …` into the inner `app.request()` re-entry. Cookie + `x-api-key` forwarding has been removed. The MCP surface is server-to-server by nature — there are no browser callers, no CSRF surface to defend, and no benefit to fragmenting the auth model across three header conventions. Three Bearer flavors all land on the same header, resolved by the inner Hono middleware chain:\n\n- Better Auth session token via the official `bearer` plugin\n- OAuth access token via the OAuth Provider plugin\n- Agent JWT via `@better-auth/agent-auth`\n\nIf a project still wants API-key auth here, configure the `apiKey` plugin to accept its key via `Authorization: Bearer` so everything stays one channel. The existing `mcp-server.test.ts` regression seal flips from \"forwards Cookie + x-api-key\" to \"forwards only Authorization (bearer-only surface)\".\n\n### Auth DSL: `bearer`, `oauthProvider`, `agentAuth` are now first-class plugin entries\n\nBoth the array-form union and the `BetterAuthPlugins` interface in `apps/compiler/src/define/auth.ts` gain `\"bearer\"`, `\"oauthProvider\"`, and `\"agentAuth\"`. `bearer` was previously in the runtime registry but missing from the TS type, so callsites had to use `as any` or `// @ts-expect-error` to set it. Both are gone now. New typed options interfaces — `OAuthProviderOptions` (audience, login/consent paths, dynamic registration) and `AgentAuthOptions` (providerName, providerDescription, modes, fromOpenAPI, approvalStrength, defaultHostCapabilities) — let users override defaults through the object form.\n\nAuto-enable rule lives in the canonical `computeAutoAddedPlugins` (`generators/auth.ts`): turning on `agentAuth` force-adds `bearer` + `oauthProvider`. There is no useful agent-auth deployment without those two — surfacing it as auto-add rather than a confusing \"missing dependency\" runtime error matches the existing pattern (`oauthProvider` already auto-adds `jwt`).\n\n### `queue-consumer.ts` now emitted for `additionalQueues` too\n\nPrior to this release, the queue consumer emit gated on `embeddingFeatures.length > 0 || queueHandlers.length > 0`. Projects that declared queue infrastructure via `dbConfig.additionalQueues` but had no embeddings + no `services/queues/*` handlers shipped a `wrangler.toml` with `[[queues.consumers]]` entries pointing at a missing worker `queue` export. The CLI's archive-restore step kept a stale `queue-consumer.ts` around, so the file appeared \"stuck\" across compiles — same class of bug as the v0.15.0 services/queues/* regression caught against AttendVIP, just one source removed.\n\nThe gate is now a three-way OR: `hasEmbeddings || hasQueueHandlers || hasAdditionalQueues`. When only `additionalQueues` is set, the compiler emits a stub `queue-consumer.ts` whose `queue` export acks every message with a warning — Cloudflare needs an export for every consumer binding, and a noisy-but-correct stub beats a silent deploy break. `MainAppOptions` and `CloudflareMainAppOptions` gain `hasAdditionalQueues`; `generateQueueImport` and `generateCloudflareExport` mirror the new gate. Regression test: `src/__tests__/queue-additional-queues-gate.test.ts`.\n\n### Fixes\n\n**1. `bearer` was missing from the `BetterAuthPlugins` TypeScript interface.** The runtime plugin registry has had `bearer` since the pre-1.0 cuts, but `apps/compiler/src/define/auth.ts` never declared it on the typed shape — so any `quickback.config.ts` using `plugins: { bearer: true }` had to `as any`-cast or sit behind a `@ts-expect-error`. Both `bearer` and `oauthProvider` (same gap, same workaround) are now first-class typed entries; `agentAuth` joins them. The array-form union also gains all three. No behavior change at runtime; existing casts can come out.\n\n**2. MCP `buildInternalRequest` no longer forwards Cookie or `x-api-key`.** The MCP surface is server-to-server — there are no browser callers, no CSRF surface to defend, and no benefit to fragmenting the auth model across three header conventions. The inner `app.request()` re-entry now forwards only `Authorization: Bearer …`. Three Bearer flavors all land on the same header (BA session token via the `bearer` plugin, OAuth access token via OAuth Provider, agent JWT via `@better-auth/agent-auth`). Existing `mcp-server.test.ts` regression flipped from \"forwards Cookie + x-api-key\" to \"forwards only Authorization (bearer-only surface)\".\n\n**3. `agentAuth` now auto-enables `bearer` + `oauthProvider`.** There is no useful agent-auth deployment without those two — the agent surface is bearer-only and MCP clients need OAuth to register. Auto-enable lives in the canonical `computeAutoAddedPlugins` (`generators/auth.ts`), so it propagates to every consumer (better-auth generator, schema generation, package-deps emission). Same pattern as the existing `oauthProvider` → `jwt` rule. Surfaced in `agent-auth.test.ts` with a regression seal that asserts both plugins land in the merged plugin list whether the user wrote the array form or the object form.\n\n**4. `OpenAPISpec` literal type rejected by tsc on inlined spec.** Quickback's OpenAPI emit produces `$ref`-style parameter entries (`{ \"$ref\": \"#/components/parameters/X\" }`) that the agent-auth plugin's stricter `OpenAPIParameter` type doesn't model — `tsc` fails the generated project with \"Type … is not assignable to OpenAPIParameter\". The plugin handles refs correctly at runtime; only the structural narrowing on the TS literal needed help. The generated `agentAuth({ ...createFromOpenAPI(openapiSpec as any, { ... }) })` call now carries an `as any` cast on the spec with an inline comment explaining why. Drop when upstream models `$ref` parameters.\n\n### Notes\n\n`@better-auth/agent-auth` 0.4.5 ships ESM-only exports without a `require` condition, so the Better Auth CLI's `auth generate` step (jiti / CJS resolver) bails with `ERR_PACKAGE_PATH_NOT_EXPORTED`. The compiler image patches the package's `package.json` at install time to add a matching `require` condition pointing at the same dist file (Node 22+ supports `require(esm)`). Remove the patch in `apps/compiler/Dockerfile` when upstream ships proper exports.\n\nTest coverage: 1136 → 1152 (+11 `agent-auth.test.ts`, +5 `queue-additional-queues-gate.test.ts`). Verified end-to-end against `examples/recruitment` with `agentAuth` enabled — `quickback compile` produces a project whose `npm run build` typechecks clean and whose generated schema includes all four agent-auth tables (`agent`, `agentHost`, `agentCapabilityGrant`, `approvalRequest`).\n\n---\n\n## v0.15.0 — May 7, 2026\n\n### Sysadmin tier — cross-tenant DB-admin role for the CMS\n\nA new opt-in `cms: { sysadmin: true }` flag turns the CMS into a Supabase-style cross-tenant DB-admin tool gated by `user.role === 'sysadmin'`. Distinct from `'admin'` so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers stay decoupled. Off by default — projects without the feature get zero behavior change.\n\nWhen enabled, the compiler emits a `SYSADMIN` pseudo-role (fifth marker alongside `PUBLIC` / `AUTHENTICATED` / `USER` / `ADMIN`); a firewall escape hatch in every `buildFirewallConditions` that drops tenant scopes for `ctx.userRole === 'sysadmin'` while preserving soft-delete; a true cross-tenant `/admin/v1/sysadmin/organizations` endpoint that selects directly from the auth-schema `organization` table; and a relaxed cross-tenant guard that skips the `ORG_REQUIRED` 400 for sysadmins on list routes — that's how the SPA's \"All organizations\" sentinel reaches the firewall escape end-to-end.\n\nThe CMS SPA gains a two-mode design: org admins keep the existing membership-based switcher (Better Auth's `setActiveOrganization`); sysadmins get a `SysadminOrgSelector` that loads from the cross-tenant endpoint, defaults to \"All organizations\" (omits the org filter on reads), and pins selected tenants via `?organizationId=` on every API call (sysadmins have no member rows, so `setActive` would 403). A new `OrgGate` component handles no-active-org cases for org users — auto-pick when there's exactly one membership, full-frame picker for multiple, empty state for zero — so sessions that lost their active org don't dead-end.\n\nRefusing to compile `roles: [\"SYSADMIN\"]` without `cms.sysadmin: true` keeps the role from sitting as dead code. RLS providers (Neon, Supabase) emit `false` for `SYSADMIN` today; per-table RLS policy emit is a follow-up.\n\n### Durable Object `[[migrations]]` order is now preserved across recompiles\n\nCloudflare's migration system is append-only — every deploy must include previously-deployed migration tags in their original order, with new ones appended last. CF rejects deploys with `code: 10061` when the order shifts. The compiler used to iterate `bindings.durableObjects` in config order at emit time, so a user inserting a new DO into the middle of the array bumped every later auto-migration into the wrong slot, breaking deploys for projects with multiple DOs (caught by AttendVIP).\n\nThe CLI now sends the project's existing `wrangler.toml` (when present) in `existingFiles` alongside the drizzle meta. The compiler parses migration tags from it via `parseExistingMigrationTags`, then emits auto-generated DO `[[migrations]]` blocks in two phases: deployed entries first (preserving the existing wrangler.toml order), net-new entries appended last in `bindings.durableObjects` config order. Reordering DOs in the config array no longer reshuffles deployed migrations; inserting a new DO anywhere in the array always appends its migration block last. First compiles (no existing wrangler.toml) keep the current config-order behavior — no behavior change for new projects. User-declared `bindings.durableObjectMigrations` (historical entries) are unaffected; they continue to emit first.\n\n### Standalone-action wrapper no longer 403s `AUTHENTICATED`-only routes on org-scoped projects\n\nStandalone actions (`standalone: true`) on org-scoped projects emitted an unconditional `if (!ctx.activeOrgId) return 403 ACCESS_NO_ORG` gate before role checking. For an action declared `access: { roles: [\"AUTHENTICATED\"] }`, this contradicted the access rule itself: a signed-in user with no active org (e.g. just signed up but not yet joined an organization, or a token-auth caller) was the exact caller `AUTHENTICATED` was supposed to admit. Found by AttendVIP — every recompile re-introduced the bug because the fix lived in handler-side patches, not the generator. The standalone wrapper now skips the org gate when the access tree references any pseudo-role anywhere, including under `or:`/`and:` arms.\n\n### Queue handler emit no longer drops the `queue` export when there are no embeddings\n\n`compiler.ts` emits `src/queue-consumer.ts` whenever `embeddingFeatures.length > 0 || queueHandlers.length > 0`, but the worker entry only checked `hasEmbeddings`. Projects with custom queue handlers under `services/queues/*` and no embeddings got the consumer file generated and then no entry-point wiring — wrangler bound the queue to a missing handler at deploy time. Caught against AttendVIP's `sendCancelEmail` queue handler. `MainAppOptions` and `CloudflareMainAppOptions` gain a `hasQueueHandlers` flag; `generateQueueImport` and `generateCloudflareExport` now gate on `hasEmbeddings || hasQueueHandlers`.\n\n### `quickback/public/` — static-asset passthrough into `src/apps/`\n\nA new opt-in folder. Anything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile, where the wrangler `[assets]` binding (`directory = \"src/apps\"`) already serves it. So `quickback/public/robots.txt` becomes reachable at `https://your-domain/robots.txt`, `quickback/public/og/og-image.png` at `/og/og-image.png`, and so on. Favicons, `robots.txt`, OG images, marketing PDFs, sitemap fragments, `.well-known/` files — anything you'd previously have had to post-process into `src/apps/` after each compile.\n\nThe compiler does **not** parse, template, or otherwise touch these files. They ride past it as bytes — the CLI does the copy after `writeFilesWithMerge`, using `fs.copyFile` so binaries (PNGs, fonts, PDFs) stay byte-perfect rather than being corrupted by the utf-8 string channel the compiler manifest uses for source files. The compiler API contract is unchanged; nothing round-trips through `compile.quickback.dev`.\n\nRules:\n\n- **Optional.** If the folder doesn't exist, the step is a no-op.\n- **Stale-cleaned.** `src/` is wiped and rewritten each compile, so files removed from `quickback/public/` disappear from `src/apps/` automatically on the next run.\n- **Hidden entries skipped.** `.DS_Store`, `.git/`, dotfiles — none of these were intentional drops; including them would break worker asset bindings.\n- **Collisions fail loud.** A file in `quickback/public/` whose path would shadow a compiler-emitted manifest entry — e.g. `quickback/public/cms/index.html` against the SPA shell — fails the compile with the offending paths listed, rather than silently overwriting and producing a confused-looking SPA build. Move or rename the offending file.\n\nThe change is contained to the CLI: `packages/cli/src/lib/copy-public-assets.ts` (helper + `PublicAssetCollisionError`) and one block in `packages/cli/src/commands/compile.ts`. Test coverage in `copy-public-assets.test.ts` walks the missing-folder, single-file, nested-tree, binary-preservation, hidden-entry, single-collision, multi-collision, empty-folder, and split-output cases — nine tests, byte-level assertions on the binary path.\n\n---\n\n## v0.14.7 — May 7, 2026\n\n### Four more codegen bugs caught by AttendVIP — generated output now typechecks for projects with non-`id` PKs and DO-only features\n\nFiled after AttendVIP's `tsc` reported 230 errors against the generated `src/`. Triage split them into six patterns; four are surgical and ship here. The other two (TS2769 ×156 + TS2339 ×~50) trace to a deeper assumption — every queryable table has a string-typed `id` column — and are deferred to v0.14.8 along with the agreed `id` auto-inject design (see *Coming next* below).\n\n**1. Duplicate `guests` import in routes that use relationship-roles (`TS2300`).** The relationship-import injector (`generators/feature-generator.ts`) added `import { <table>, buildFirewallConditions as build<Table>FirewallConditions } from './<table>.resource'` whenever it detected a relationship-table reference in the routes file — without checking that the table binding was already imported from `./schema` upstream. So `guests.routes.ts` ended up with `guests` declared twice. Fix: scan the existing import block, only add identifiers that aren't already in scope (drop the binding from the new import line, or skip the line entirely if both binding and alias are imported).\n\n**2. `db` referenced before declaration in single-record + bulk action handlers (`TS2448` / `TS2304`).** `record-based.ts:195,541` baked `firewallClause = ...buildFirewallConditions(ctx, db)...` and used the same string in two places: (a) the outer pre-fetch `await unsafeDb.select().from(table).where(firewallClause)` — where `db` doesn't exist yet (`db = createScopedDb(unsafeDb, ctx)` is declared later for handler scope), and (b) inside `processBatch` where `db` is created from the tx/handle param. The outer use threw at typecheck (`'db' is used before its declaration`); at runtime it would have been a `ReferenceError`. Fix: pass `unsafeDb` (the in-scope handle) to `buildFirewallConditions` in both `firewallClause` definitions. The helper only uses its `db` arg for relationship-role subqueries (when `via:` is in play); either handle is a valid Drizzle client for that lookup.\n\n**3. PartyServer realtime gates passed 1 arg to a 2-arg `buildFirewall_X` (`TS2554`).** `optional-routes.ts` emitted `buildFirewall_<feature>(ctx as any)` in the WebSocket-upgrade gate for every Durable Object that declared `access: { resource }`. After v0.14.4 made `buildFirewallConditions(ctx, db)` 2-arg whenever the resource has any `via:` predicate, this gate stopped compiling for any DO whose target feature uses relationship-roles. AttendVIP's `event-pages` DO sits on `event_pages` (admin via `guestOf`), which is exactly that case. Fix: the gate already constructs `db = drizzle(c.env.<binding>)` for its own `db.select(...).limit(1)` — pass that same `db` into the firewall call. Mirrored in both the single-resource and multi-resource gate branches.\n\n**4. Durable-object-only features dropped their `lib/` files from output (`TS2307`).** `compiler.ts:546` only ran the feature-walker (and copied `featureLibFiles` to output) when the feature had at least one action file. AttendVIP's `user-profiles/` declares a single DO source under `lib/UserGateway.ts` and zero `actions/` — perfectly valid (per-user realtime gateway, the Slack/Linear pattern), but the walker skipped the feature entirely. The compile finished without error, then `index.ts` tried to import `./features/user-profiles/lib/UserGateway` and `tsc` 404'd the module. `event-pages/PageRoom.ts` worked only because that feature happens to also have `actions/`. Fix: run the discovery + lib-copy path whenever the feature has either actions OR lib files. Copying `lib/` files when the feature has at least one of either is the safe reading of the original intent.\n\n**Drops ~20 of the 230 attendvip errors** (TS2300 ×2, TS2448 ×11, TS2304 ×6, TS2554 ×2 from the realtime gate, TS2307 ×1 — depending on cache state). The remaining 210 are TS2769 (numeric-ID arrays where the column is `integer`, not `text`) and TS2339 (`.id` referenced on tables that have a non-`id` PK or a compound PK) — both downstream of the same root: `id` is currently *not* auto-injected, only audit columns are.\n\n### Account auth: emailOtp on AWS SES drops the magic-link companion (OTP-only)\n\nThe compiler used to auto-wire `createComboAuthSendVerificationOTP` from `@quickback-dev/better-auth-combo-auth` whenever a project used `emailOtp` with the `aws-ses` email provider — sign-in / sign-up / verify emails carried *both* a 6-digit OTP and a clickable magic link, with `useComboAuthEmail: true` in the SES config. This was on by default for every account-app project that picked AWS SES.\n\nTwo reasons to drop the magic-link half:\n\n1. **Mail-client URL prefetching can burn the OTP before the human sees the email.** Outlook Safe Links, Gmail mobile, corporate proxies, and security scanners all eagerly fetch URLs in incoming mail; the magic link's `?data=...` payload includes the OTP server-side, so the first GET completes the sign-in (consuming the one-time code) and the user clicking through 30 seconds later gets a \"code already used\" failure.\n2. **Two sign-in surfaces are harder to support.** The account SPA's `/welcome` and `/email-otp` routes only render the OTP form; the magic-link arm bypasses that UI entirely. One canonical entry point (enter the code) keeps the account flow legible.\n\nThe compiler now emits a plain `sendVerificationOTP` callback that calls `sendEmailWithSES` with `emailTemplates.emailOTP` directly — no combo wrapper, no magic-link URL. `useComboAuthEmail` is hardcoded to `false`. The `@quickback-dev/better-auth-combo-auth` package and the `magicLink` plugin are still available for users who explicitly opt in via a custom `sendVerificationOTP` in their config; the change here is just the auto-wired default.\n\nTest coverage: `auth-email-wiring.test.ts` was updated to assert the new shape — generated auth files for `emailOtp + aws-ses` now contain `emailTemplates.emailOTP` and `useComboAuthEmail: false`, and explicitly do not contain `createComboAuthSendVerificationOTP` or `better-auth-combo-auth`.\n\n### Coming next — `id` field auto-injection (v0.14.8)\n\nThe compiler treats `id` as load-bearing across CRUD/action route generators, FK probing, access checks, OpenAPI emission, and CMS — but doesn't add it for you the way it adds `createdAt`/`modifiedAt`/`createdBy`/`modifiedBy` (or `organizationId` in org-scoped features, or `deletedAt`/`deletedBy` for soft-delete tables). At the time of v0.14.7, tables that omitted `id` (or used a non-`id` single PK like `userId.primaryKey()`, or a compound `primaryKey({ columns: [...] })` constraint) were not yet supported by the generated route and OpenAPI pipeline.\n\n**Agreed direction:** mirror `injectAuditFields` with a new `injectIdField` that runs unconditionally — including on junction tables. Tables with no PK or a non-`id` PK get an `id` column auto-injected; existing column-level `.primaryKey()` on a non-`id` column gets demoted to `.notNull()`; `primaryKey({ columns: [...] })` constraints get rewritten to `uniqueIndex().on(...)`. The cost (one extra column per junction row) is minimal and closes the asymmetry — every table participating in routes gets a single string-typed `id`, just like every table gets `createdAt`. Migration tail (existing D1 databases need an ADD COLUMN + index rewrite per affected table) is generated alongside.\n\nNo user code changes required for the four fixes shipping in v0.14.7. Recompile and the affected features typecheck.\n\n---\n\n## v0.14.6 — May 7, 2026\n\n### Four more v0.14 compiler bugs caught by AttendVIP's MCP rollout\n\nFiled in `research/attendvip-v014-mcp-and-firewall-gaps.md` after AttendVIP patched these locally and asked us to upstream them. All four ride a single MCP `tools/call` against a team-scoped resource over a Bearer api-key — fix any one and the next bug surfaces. We're shipping them as one patch release with end-to-end coverage of the chain.\n\n**1. MCP `tools/call` URL is double-prefixed for action tools.** The OpenAPI spec emits action paths as `/api/v1/<action>` already-absolute, but the MCP request builder did `'/api/v1' + tool._path` unconditionally — so action tool calls hit `/api/v1/api/v1/<action>` and 404'd. CRUD tools (bare `_path: '/customers'`) were unaffected. Fix: prefix only when `_path` doesn't already start with `/api/v1/`.\n\n**2. Auth middleware ignored `Authorization: Bearer <api-key>`.** MCP clients (claude.ai, etc.) only set `Authorization: Bearer ...`. The api-key block read from `x-api-key` header / `?api_key=` / `?key=` query but not from `Authorization`; the JWT fast-path narrowly gated on `bearerToken.startsWith('eyJ')`. Non-JWT bearers fell through to BA session auth, which doesn't recognise api-keys, so the request authenticated as anonymous and `tools/list` returned only PUBLIC tools. Fix: api-key extraction now also accepts a non-JWT `Authorization: Bearer <token>` as the key candidate. Three transports for one credential — header / query / Bearer.\n\n**3. `auth.roleHierarchy` was silently inert for runtime role checks.** A user configured `auth.roleHierarchy: ['owner', 'admin', 'member']` and expected an `owner` to satisfy any check requiring `admin` or `member`. But the api-key + JWT fast-paths populated `ctx.roles` with the single org-member role, and the access checker did strict intersection — `owner ∩ {admin, member} = ∅` → 403. Fix: at the api-key, JWT fast-path, AND BA session paths, expand the user's role via `auth.roleHierarchy` so a higher role inherits all lower-role privileges. The hierarchy is auto-normalized — users who write the array reversed (`['owner', 'admin', 'member']` instead of the documented `['member', 'admin', 'owner']`) now get the same correct expansion.\n\n**4. Team-firewall predicate hardcoded `eq(table.teamId, ctx.activeTeamId!)` even when no team was active.** The `!` non-null assertion lied at runtime — api-keys, JWTs, and sessions without an active team carry `undefined`. The resulting SQL was `team_id = NULL` which matches nothing, so api-key callers saw zero rows on team-scoped resources. Fix: emit the team predicate as `(ctx.activeTeamId ? eq(...) : undefined)` — drizzle's `and(...)` drops `undefined`, so the WHERE collapses to the org scope only. Org and owner predicates are deliberately NOT softened the same way (those are security boundaries, not optional scopes).\n\nAfter upstreaming, the AttendVIP one-shot verification passes:\n\n```bash\ncurl -fs -X POST https://attend.vip/mcp \\\n -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"listEvents\",\"arguments\":{}}}' \\\n | jq '.result.content[0].text | fromjson | .data | length' # > 0\n```\n\nNo user code changes required for any of the four. Recompile and the MCP path works end-to-end against team-scoped, role-gated resources via Bearer api-key.\n\n---\n\n## v0.14.5 — May 7, 2026\n\n### MCP `tools/call` no longer crashes with `undefined (reading 'AUTH_DB')`\n\nThe generated MCP server's `tools/call` dispatch re-enters the same Hono app via `app.request(internalReq)` so every tool invocation runs through the full middleware chain (auth, firewall, access, guards, masking). But the call passed only the request — not `env` or `executionCtx` — so the sub-request handler ran with `c.env === undefined`. Any tool whose route touched a Cloudflare binding (e.g. the `AUTH_DB` D1, KV, R2, Queues) crashed with `Cannot read properties of undefined (reading 'AUTH_DB')`. Found by AttendVIP — every action that hit auth-side data (acceptInvite, etc.) failed.\n\n**Fix:** `mountMcp` now threads `c.env` and `c.executionCtx` through to `handle → handleRpc → callTool → app.request(internalReq, undefined, env, executionCtx)`. Hono's `request()` 3rd/4th args set the bindings + execution context for the sub-request, so the action handler sees the same env the outer worker received. Tools/list was unaffected — it reads ctx in-process and never re-enters the app.\n\nNo user code changes required. Recompile against v0.14.5 and the MCP endpoint dispatches actions correctly against all bindings.\n\n---\n\n## v0.14.4 — May 7, 2026\n\n### `via:` firewall predicates no longer crash with `ReferenceError: db is not defined`\n\nThe relationship-role generator (v0.14.0) emits a `buildFirewallConditions` body that references `db`, `inArray`, and `sql` at function scope when any predicate has `via:` — but the resource-file imports it generated only pulled in `eq, and, isNull, type SQL`. So every endpoint guarded by `firewall: [{ field, via }]` threw `ReferenceError: db is not defined` at the very first request, and the catch-all returned 500 before the firewall query ever ran. Found by AttendVIP on `/api/v1/event-pages` against v0.14.3 — none of the v0.14.0 → v0.14.3 unit tests exercised emitted-import resolution, so the bug rode through three patch releases.\n\nTwo fixes:\n\n1. **Imports in the generated resource file now include `inArray, sql`** when the firewall has any `via:` predicate. Hidden behind a flag so a no-via resource still gets the minimal import surface.\n2. **`buildFirewallConditions` now takes `(ctx, db)`** and the wrapper template (`WITH_FIREWALL_HELPER`) pulls `const db = c.get('db' as never) as any;` from the Hono context before invoking it. Every CRUD/action call site (single-record + batch + record-based-action) was updated to pass `db` through.\n\nRegression test added (`firewall-via-imports.test.ts`) that parses the generated resource file's top-level imports and asserts every free identifier referenced in `buildFirewallConditions` resolves to either an import or a function parameter — so a future generator change that introduces a new free identifier (`exists`, `not`, etc.) without importing it fails the unit suite instead of leaking to a real project.\n\nNo user code changes required — recompile and `via:` predicates work end-to-end.\n\n---\n\n## v0.14.3 — May 7, 2026\n\n### Relationship-role consumers now resolve the relationship-table binding at runtime\n\nPre-fix, the v0.14.0 relationship-role generator emitted imports like `import { eventGuests, buildFirewallConditions as buildEventGuestsFirewallConditions } from '../event-guests/event-guests.resource'` on every consuming resource — but the relationship-table's own `.resource.ts` file imported `event_guests` from `./schema` for its own use without re-exporting it. So the consuming file got `undefined` at runtime, every relationship subquery failed with `Cannot read properties of undefined`, and the whole authz layer was unreachable on real projects.\n\nFound by AttendVIP within minutes of recompiling against v0.14.2: the moment they hit any endpoint guarded by `firewall: [{ field, via }]` or `crud.<op>.access roles: ['guest']`, the request errored before the firewall query ran.\n\nThe fix is one line in `generateTableResourceHelpers` — re-export the Drizzle table binding from the `.resource` file alongside the existing import. The `.resource` file is the public surface of the table; the schema is an implementation detail. This decision was implicit in the relationship-import resolver's path choice but not enforced on the producer side.\n\n```ts\n// generated <table>.resource.ts (after fix)\n\nexport { event_guests }; // ← was missing\n```\n\nRegression test added (`authz-end-to-end.test.ts`) that asserts every `.resource` file re-exports its Drizzle binding, so this can't drift again. No user code changes required — recompile and the cross-feature relationship subqueries resolve correctly.\n\n---\n\n## v0.14.2 — May 7, 2026\n\n### Wrangler `[[migrations]]` no longer drops historical Durable Object lifecycle entries\n\nCloudflare requires the `[[migrations]]` list in `wrangler.toml` to be **append-only**: once a tag has been deployed, removing it on a subsequent compile causes the next deploy to fail with `Cannot apply <new|deleted|renamed|transferred>-class migration to class <X>` — CF replays the full migrations log on every push and notices the tag is gone.\n\nPre-fix, the compiler regenerated the `[[migrations]]` blocks from scratch on every compile, emitting only entries for the *current* `durableObjects` bindings. Any historical lifecycle events the user had hand-maintained — `deleted_classes`, `renamed_classes`, `transferred_classes` — were silently dropped and the deploy then broke. AttendVIP hit this first: a `qb-do-deleted-legacy-notes-2026-05-05` deletion entry got dropped, and the next deploy tried to re-apply `qb-do-Notepad`'s `new_sqlite_classes` against the existing class.\n\nThe fix adds a new config slot — `bindings.durableObjectMigrations` — for historical entries that survive recompiles. Declared entries are emitted FIRST in the generated `wrangler.toml`'s migrations list (preserving chronological order), then the auto-generated current-class creation entries follow, deduplicated by tag so an explicit user entry wins over the auto-emit.\n\n```ts\n// quickback.config.ts\nbindings: {\n durableObjects: [\n { name: 'NOTEPAD', className: 'Notepad', from: 'lib/Notepad' },\n ],\n durableObjectMigrations: [\n // Carry forward across recompiles — Cloudflare's migration list is append-only.\n {\n tag: 'qb-do-deleted-legacy-notes-2026-05-05',\n deletedClasses: ['LegacyNotes'],\n },\n ],\n}\n```\n\nAll four lifecycle shapes are supported: `newClasses` / `newSqliteClasses` (creations), `deletedClasses` (removals), `renamedClasses` (`{ from, to }` inline-table-array), `transferredClasses` (`{ from, from_script, to }` for moves between workers). The user-declared entry can also override the auto-emit by reusing the same tag — useful when a DO started life as KV-backed before SQLite-DOs existed.\n\nThis is a config-side fix, not a wrangler.toml-merging one — Quickback doesn't read your existing `wrangler.toml`. The discipline is the same as for any append-only log: declare lifecycle events as you make them. Auto-detection of removed classes from the schema diff is on the roadmap; for now the compiler trusts your declaration.\n\n7 new tests covering deletion, rename, transfer, multi-entry ordering, override-via-same-tag, no-history bit-identical output, and the historical-only-no-current-DOs edge case.\n\n---\n\n## v0.14.1 — May 7, 2026\n\n### Bulk action variants now appear in `openapi.json`\n\nRecord-based actions with `bulkVariant: true` (introduced in v0.14.0) generate a working `POST /<base>/batch/<actionName>` route at runtime, but the OpenAPI generator wasn't aware of them — so the bulk endpoints were invisible to typed-client codegen (`api-types.gen.ts`) and to MCP-driven agents discovering operations from the spec. AttendVIP's v0.14.0 rollout (seven actions with `bulkVariant: true`: `approve`, `checkIn`, `checkOut`, `setVisibility`, `cancelInvite`, `sendInvite`, `sessionApprove`) found this within hours of shipping.\n\nThe OpenAPI generator now emits each bulk variant as a sibling operation to its per-record action, with the documented request shape (`{ ids: string[], input, failFast? }`), correct 200 / 207 / 400 responses, an `x-bulk-variant: true` marker, and a separate `<resource><Action>Bulk` `operationId` so client codegen can distinguish single from bulk. The fix also threads `bulkVariant` through `getAllActions` so any other downstream consumer of the action registry sees the flag — previously the parser captured it but the spec-emit path silently dropped it.\n\nNo changes required in user code. Re-running `quickback compile` regenerates `openapi.json` with both routes per `bulkVariant: true` action; downstream `api-types.gen.ts` builds pick up the new operations on the next codegen run.\n\n### Cross-tenant \"my events\" pattern documented with a worked example\n\nThe v0.14.0 docs noted that relationship-roles do **not** solve cross-tenant aggregation (\"a guest's view of events across all tenants they were invited to\") and pointed at function-form access as the workaround, but didn't show what that looked like in practice. The access docs now carry a full standalone-action example for `GET /my-events` — the canonical attendee-dashboard pattern — including the two security guardrails (always filter by `ctx.userId`; the action takes responsibility for soft-delete and other invariants the firewall would otherwise apply). Standalone actions are already mandatorily audit-logged in the runtime, so the cross-tenant traversal is recorded automatically.\n\nSee [Access → Cross-tenant \"my events\" dashboards](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this).\n\n---\n\n## v0.14.0 — May 7, 2026\n\n### Relationship-based authorization roles\n\nQuickback's role system now supports a third kind of role beyond Better Auth org membership and the four pseudo-roles (`PUBLIC`/`AUTHENTICATED`/`USER`/`ADMIN`): **relationship-roles** that bind to a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate. The original ask was a B2B event-management app where logged-in users who aren't team members but ARE confirmed guests of an event need to see that event's sessions, pages, and tracks — same data, different access lane. The old workarounds (function-form access, hand-written actions, `firewall: { exception: true }`) all gave up some combination of OpenAPI/MCP visibility, CRUD code generation, or tenant safety.\n\nDeclare the relationship once in `quickback.config.ts`, then reference it from `firewall:` or `access.roles:`:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // relationship table\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n eventStaff: {\n or: [{ via: 'guestOf' }, { roles: ['admin', 'owner'] }],\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row scoping\n],\nread: { access: { roles: ['admin', 'member', 'guest'] } }, // ← OR-composed\ncrud: {\n create: { access: { roles: ['admin', 'guest'] } }, // inline async lookup\n update: { access: { roles: ['admin'] } },\n}\n```\n\nThe compiler emits an inline Drizzle subquery against the relationship table and AND-composes it as the outermost firewall clause. The relationship table's own `buildFirewallConditions(ctx)` is called inside the subquery so soft-delete and tenant scope on the relationship row are always honored — soft-deleting an `event_guests` row revokes access immediately. Anonymous callers fail closed (the subquery short-circuits to `WHERE 1 = 0` when `ctx.userId` is null). Cross-tenant grants are impossible because the resource's tenant filter sits as the outermost AND, never folded into a role OR. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via) and [Access → Relationship-based authorization](/compiler/definitions/access#relationship-based-authorization).\n\nWhat works in v0.14.0:\n\n| Surface | Status |\n|---|---|\n| `firewall: [{ field, via }]` row-level scoping | Full |\n| `crud.<op>.access` `roles: ['guest']` (inline emission) | Full |\n| `read.access` and `read.views.*.access` | Full |\n| `masking.<f>.show` `roles: ['guest']` | Compile-refused (workaround pointer) |\n| `actions.<n>.access` `roles: ['guest']` | Compile-refused (workaround pointer) |\n\nThe runtime evaluator fails closed on relationship arms regardless of which surface you hit, so silent grants are impossible everywhere. The two refused surfaces have clear compile-time errors pointing to the working pattern (gate the row at the firewall layer with `via:`, gate the role at the access layer with BA roles).\n\nCompile-time refusals also catch: unknown `via:` reference, cycles in role composition (`a → b → a`), reserved role-name shadowing (auth-provider-derived only — `guest`/`speaker`/`attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on), unknown relationship `from` table, resource missing the `resource.column`, relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through), `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped), and `+` hierarchy on relationship-roles (terminal, like pseudo-roles).\n\nCross-tenant \"my events\" dashboards (a logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*) are **not** solved by relationship-roles — the tenant firewall stays the outermost AND. For that pattern, use a user-scoped firewall (`firewall: { owner: { column: 'userId' } }`) or function-form access on a dedicated route. Documented prominently in [access.mdx](/compiler/definitions/access#cross-tenant-my-events-dashboards-are-not-this) so users don't reach for relationship-roles first and get confused.\n\nRoadmap: `lowering: 'session'` ergonomics, inline relationship emission for `actions.access` (needs `relationshipBindings` design), async/batched mask functions for `masking.show`. The schema slots are reserved so v2 lands non-breaking.\n\n### Bulk variants of record-based actions\n\nRecord-based actions can now opt into an auto-generated bulk route alongside the per-record route. Set `bulkVariant: true` on a `defineAction({...})` and the compiler emits `POST /:resource/batch/{action}` that loops the same access + transition + execute pipeline over a `{ ids: [...], input, failFast? }` body. The original ask was an event-management UX where every domain bulk operation (approve N guests, rescind N invites, advance N applications) became a hand-written standalone action that re-implemented a per-record action's transition + execute logic in a `for` loop — `PATCH /:resource/batch` couldn't do it because state lives on a protected field, which is the right call for safety.\n\n```ts\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true, // ← opt-in\n transition: { field: \"status\", via: \"nextStatus\", fromTo: { /* ... */ } },\n async execute({ db, record, input, whereTransition }) {\n // exact same body as before — runs once per id\n },\n});\n```\n\nPer-record outcomes return as 207 Multi-Status with the same `{ success, errors, meta }` shape as `PATCH /batch`. Each id flows through the firewall fetch, the per-record `evaluateAccessReason` split (403 role / 409 record-precondition), the transition pre-check, and the same `whereTransition` factory the single-record route uses — so a stale-state record fails for that id alone, not the whole batch. `failFast: true` aborts on the first failure and (on Postgres / Supabase / Neon / libsql / sqlite drivers) wraps the loop in `db.transaction()` so prior writes roll back; D1 is documented as fail-fast-without-rollback because it has no `db.transaction`.\n\nCompile-time refusals: `bulkVariant: true` is rejected on standalone actions (no record context to loop over) and on actions that declare `unsafe` (cross-tenant per-record audit not yet wired). Method is forced to POST regardless of the action's `method` setting — the one-row-to-many-rows asymmetry makes inheriting GET/DELETE confusing. Max batch size is 100 ids per request, mirroring the CRUD batch endpoints. See [Actions → Bulk variant](/compiler/definitions/actions#bulk-variant).\n\n### Aggregations on read views\n\nRead views can now declare pre-computed metrics that surface on the response next to the row payload, without a custom standalone action. Every dashboard tile that previously turned into a standalone action just for \"count of X grouped by Y\" now lives in the same view config that drives the rows.\n\n```ts\nread: {\n views: {\n pipeline: {\n fields: [\"id\", \"jobId\", \"candidateId\", \"status\", \"appliedAt\"],\n aggregations: {\n totalApplications: { fn: \"count\" },\n byStatus: { fn: \"groupBy\", field: \"status\" },\n },\n },\n },\n}\n```\n\nResponse carries `aggregations: { ... }` alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": { \"applied\": 102, \"screening\": 41, \"interview\": 18, \"offer\": 7, \"rejected\": 5 }\n }\n}\n```\n\nAggregations always run over the **same firewalled, filtered set** as the row query — pagination is intentionally ignored, so `?status=applied&limit=10` returns the 10 paged rows AND the count over every applied row. Supported `fn`s: `sum`, `avg`, `min`, `max`, `count` (with or without `field` — `COUNT(*)` vs `COUNT(field)`), `count_distinct`, and `groupBy` (returns `{ value: count }`, NULLs bucket as `\"(none)\"`).\n\nCompile-time validation: `field` must reference a real column; `sum`/`avg` require numeric column types; the same masking opt-out gate that governs `query.{filterable, sortable, searchable}` applies to aggregations (a `sum(salary)` leaks structure even when the row payload is redacted); aggregation names cannot collide with the reserved response fields `data`, `pagination`, `view`. No raw SQL `expr:` form in v1 — column references only. See [Views → Aggregations](/compiler/definitions/views#aggregations).\n\n---\n\n## v0.13.5 — May 6, 2026\n\n### Object-form `auth.plugins` no longer crashes the compiler\n\nThe documented object form for per-plugin config — `plugins: { oauthProvider: {...} }`, `plugins: { organization: { teams: { enabled: true } } }`, etc. (see [Better Auth Plugins → Custom configuration](/stack/auth/plugins#oauth-provider-mcp-ready)) — was rejected by the compiler with `plugins.includes is not a function`. `hasCliAuthRoutes` called `.includes()` directly on `auth.config.plugins` to detect `deviceAuthorization`, and `generateAuthFiles` flattened plugins to a string array before handing them to the better-auth generator, silently dropping every per-plugin user option on the way through.\n\nBoth paths now run through a shared resolver that preserves the user's input format (object in → object out, array in → array out) and only adds the compiler's auto-included plugins (`organization`, `admin`, `apiKey`, plus `bearer` when `deviceAuthorization` is present) as `true` entries that don't clobber user config. Per-plugin options like `oauthProvider: { scopes: [...] }`, `organization: { teams: { enabled: true } }`, and `deviceAuthorization: { verificationUri: '...' }` now reach the generated `auth.ts` as written.\n\nBetter Auth's `ac` / `roles` access-control objects (the result of `createAccessControl(...)`) still require a custom `auth.ts` override — they're live runtime values that can't survive the JSON config trip from CLI → compiler. A declarative escape hatch for that is on the roadmap.\n\n### `roles: [\"PUBLIC\"]` is allowed on writes and actions again\n\nv0.10.17 added a compile-time block that rejected `roles: [\"PUBLIC\"]` on `crud.create` / `crud.update` / `crud.delete` and on every action. The intent — \"anonymous mutations are usually a misconfiguration\" — collided with the legitimate use cases the rest of Quickback was built around: Gmail one-click RSVP confirms, public RSVP forms, magic-link redemption, List-Unsubscribe-Post handlers, webhook ingest, captcha-gated contact forms. None of those carry a session, so `AUTHENTICATED` 401s the caller before the handler can validate its own token, and the suggested escape hatch (\"custom action that does its own auth + `firewall: { exception: true }`\") was itself blocked by the same validator.\n\nThe block is removed. `PUBLIC` is the explicit, uppercase opt-in for unauthenticated access on every access node — reads, CRUD writes, views, and actions. The compiler trusts the marker; row-level safety comes from firewall, masking, and the action's own token validation. `PUBLIC` actions continue to receive **mandatory audit logging** (IP, input, result, timing) in the runtime regardless. `crud.create`/`update`/`delete` typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n\n`USER` and `ADMIN` keep their compile-time prerequisites (firewall must scope by `userId` / admin plugin must be enabled).\n\n---\n\n## v0.12.0 — May 5, 2026\n\n### Per-room authorization for PartyServer rooms\n\n`bindings.durableObjects[].access` lets the compiler emit a path-scoped gate that runs the declared resource's existing firewall + `read.access` pipeline before the WebSocket upgrade — same pillars `GET /api/v1/<resource>/:id` enforces, zero hand-written auth code.\n\n```ts\ndurableObjects: [\n // Single-resource: roomId IS the chat row id.\n { name: 'Chat', className: 'Chat', from: 'lib/Chat',\n access: { resource: 'chats' } },\n\n // Multi-resource: regex dispatches kind → resource.\n { name: 'Notepad', className: 'Notepad', from: 'lib/Notepad',\n access: {\n roomId: { pattern: '^(day-note|interaction|record):([A-Za-z0-9_-]+)$', kindGroup: 1, idGroup: 2 },\n resources: {\n 'day-note': { resource: 'day-notes' },\n 'interaction': { resource: 'interactions' },\n 'record': { resource: 'records' },\n },\n } },\n\n // Anonymous game lobbies / public pads: explicit opt-out.\n { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',\n access: 'public' },\n],\n```\n\nThe gate 401s unauthenticated callers, 403s when the firewall hides the row, 404s when the row is missing, and lets the upgrade proceed otherwise. DOs without an `access` declaration keep the v0.11.1 catchall (just `ctx.authenticated`). Resource references are validated against feature names at compile time so typos break the build, not the first WebSocket upgrade. See [PartyServer Rooms → Per-room authorization via access](/stack/realtime/partyserver-rooms#per-room-authorization-via-access-v012).\n\n---\n\n## v0.11.1 — May 5, 2026\n\n### PartyServer auto-mount is now secure by default\n\nThe `/realtime/*` auto-mount shipped in v0.11.0 didn't gate WebSocket upgrades — anyone who knew a room ID (CUID2, hard to guess but not a security boundary) could open a connection. `authMiddleware` populated the request context but `partyserverMiddleware` doesn't 401 anonymous upgrades on its own.\n\nThe auto-mount now wraps `partyserverMiddleware` in an auth check: `401 Unauthorized` if the caller has no resolved auth context, otherwise the upgrade proceeds. The four auth mechanisms the rest of the worker honors (session cookie, JWT bearer, `x-api-key` header, `?api_key=` / `?key=` query) all unlock connections automatically.\n\nPer-room access (e.g., \"is this user a member of the org that owns this room?\") is still your `Server` class's responsibility in `onConnect` — the auto-mount only enforces \"are you authenticated at all.\" Hand-written mounts with custom `onBeforeConnect` continue to work unchanged; declare them at `/realtime/*` before the auto-mount runs to opt out of the default gate.\n\nNo code changes required — `quickback compile` regenerates the gated mount automatically. Single-tenant alphas weren't exploitable in practice (room IDs aren't logged or surfaced); multi-tenant projects should redeploy to pick this up.\n\n---\n\n## v0.11.0 — May 5, 2026\n\n### OAuth Provider plugin (MCP-ready)\n\nQuickback can now act as a standards-compliant OAuth 2.1 + OIDC authorization server via [`@better-auth/oauth-provider`](https://better-auth.com/docs/plugins/oauth-provider). Enable it with `plugins: [\"oauthProvider\"]` in your auth config — the compiler auto-includes Better Auth's `jwt` plugin (the OAuth provider delegates access-token signing to it) and the Account SPA gains a `/consent` page for the standard authorization-code flow.\n\nThis replaces Better Auth's deprecated `mcp` plugin and gives every future MCP client (Cursor, Claude Desktop, claude.ai connectors, custom tooling) RFC 7591 dynamic client registration + the well-known discovery documents they need to bootstrap themselves. See [Auth Plugins → OAuth Provider](/stack/auth/plugins#oauth-provider-mcp-ready).\n\n### API key auth via query parameter\n\nThe auth middleware now accepts API keys as `?api_key=...` or `?key=...` query parameters in addition to the `x-api-key` header. The header takes precedence when both are sent. This unblocks clients that can't inject custom headers — most notably claude.ai's MCP connector, which previously returned zero tools because every list/call attempt was unauthenticated.\n\nThe query-param form lands in access logs and `Referer` headers; prefer the header whenever the client supports it. See [Auth Plugins → API Keys](/stack/auth/plugins#api-keys).\n\n### PartyServer rooms + realtime URL split (breaking)\n\nThe realtime URL space is reorganized so the names match what each primitive does:\n\n- **`/realtime/v1/*` → `/broadcast/v1/*`** — the existing org-wide Broadcaster (Postgres-changes fan-out, ws-ticket auth) moves to its semantically accurate prefix. Same code, same behavior, just a different mount point.\n- **`/realtime/<binding>/<room-id>` is the new mount for [PartyServer](/stack/realtime/partyserver-rooms) rooms** — bidirectional, per-room (per-document) Durable Objects with presence and lifecycle hooks. Auto-mounted via `hono-party` whenever a project declares any in-worker DO via `bindings.durableObjects[].from`. Use these for collaborative editing, live cursors, and per-room state.\n\n**Breaking changes** — recompile + redeploy required:\n\n- The `REALTIME_URL` runtime env var is renamed to `BROADCAST_URL` (used by the org member-update broadcast hook in separate-mode realtime). If you set this via `wrangler secret put REALTIME_URL`, re-set it as `BROADCAST_URL`.\n- The auth-ui SPA helpers `getRealtimeWsUrl()` / `getRealtimeTicketUrl()` are renamed to `getBroadcastWsUrl()` / `getBroadcastTicketUrl()`. The `appConfig.routes.api.realtime` field is renamed to `appConfig.routes.api.broadcast`.\n- WebSocket subscribers that hardcoded `/realtime/v1/websocket` or `/realtime/v1/ws-ticket` need to be updated to `/broadcast/v1/...`. The bundled CMS and Account SPAs handle this automatically; custom clients need a one-line change.\n\n**Pre-installed deps in the compiler image:** `partyserver`, `partysocket`, and `hono-party` are now cached in `/deps/node_modules` so opt-in collab projects compile without an extra `npm install` step. `Y-PartyServer` (Yjs CRDT support) stays opt-in.\n\n**Recipe:** see the new [PartyServer Rooms](/stack/realtime/partyserver-rooms) doc page and the `examples/recruitment` interview-room demo for an end-to-end example with presence and live notes.\n\n---\n\n## v0.10.20 — May 4, 2026\n\n### In-worker Durable Objects via `bindings.durableObjects[].from`\n\n`bindings.durableObjects` previously only emitted the binding declaration — useful for cross-worker DOs (`scriptName: \"other-worker\"`), but not enough for app-owned classes that live in this worker's source. Authors had to hand-edit `src/index.ts` (to add `export { ItemStream } from './...'`) and `wrangler.toml` (to add the `[[migrations]]` block) on every compile.\n\nAdding `from` flips the entry into in-worker mode and the compiler does both:\n\n```ts\ndurableObjects: [\n {\n name: \"ITEM_STREAM\",\n className: \"ItemStream\",\n from: \"features/loops/lib/ItemStream\", // module path under src/\n },\n]\n```\n\nGenerates:\n- `src/index.ts`: `export { ItemStream } from './features/loops/lib/ItemStream';` — wrangler resolves the binding by class export.\n- `wrangler.toml`: a `[[migrations]]` block with `tag = \"qb-do-ItemStream\"` and `new_sqlite_classes = [\"ItemStream\"]`.\n- `CloudflareBindings`: `ITEM_STREAM: DurableObjectNamespace` so `c.env.ITEM_STREAM.idFromName(...)` typechecks.\n\nWhere the class file lives: in-worker DO classes go under `quickback/lib/` or `quickback/features/<feature>/lib/` — both copy verbatim into the generated `src/` tree on every compile (the rest of `src/` is wiped). The `from` value is the resulting `src/`-relative path with no `./` prefix and no `.ts` suffix.\n\n`from` and `scriptName` are mutually exclusive — the compiler rejects entries that set both. Cross-worker entries (`scriptName` set) skip the re-export and the migration block; the exporting worker owns its own migration table.\n\n`migrationTag` (default `qb-do-${className}`) is stable across regenerations and **must never be removed or renamed once deployed** — wrangler tracks applied tags and will reject deploys that try to walk them back. `useSqlite` defaults to `true`; set to `false` for legacy KV-backed DOs.\n\nSee [Bindings → Durable Objects](/compiler/config/bindings#durableobjects) for the full reference.\n\n---\n\n## v0.10.19 — May 4, 2026\n\n### Fix: bundled-SPA auth survives `wrangler dev` on custom_domain projects\n\n`wrangler dev` rewrites the configured `custom_domain` host in **every** response header value (Location, Content-Security-Policy, X-…) to the local hostname, with a case-sensitive substring matcher. That mangles the CSP `connect-src` for projects with `domain: \"api.example.com\"` + bundled CMS / Account SPAs:\n\n```\n# Compiled (correct)\nconnect-src 'self' https://api.example.com …\n\n# Served by wrangler dev (mangled)\nconnect-src 'self' https://localhost:8787 …\n```\n\nResult: the bundled SPA's hardcoded `VITE_QUICKBACK_API_URL` fetches get blocked in dev because the CSP only allows localhost. Reported by Loop on the 0.10.18 thread; verified end-to-end with a minimal `wrangler@4.85.0 dev --local` repro.\n\nThe compiler now emits the SPA-baked-origin literal in `connect-src` with the host's first letter capitalised (`https://Api.example.com`). CSP host-source matching is ASCII case-insensitive per CSP3, so browsers accept it for connections to `https://api.example.com`; wrangler's case-sensitive matcher misses it. The case-shift is applied at compile time and only to URLs whose host matches the configured `custom_domain` — other origins (localhost, third-party hosts) are unchanged.\n\n`TRUSTED_ORIGINS` keeps its lowercase prod entries: it's consumed by the CORS `isTrustedOrigin` check via `Array.includes()` against the browser-supplied Origin header (always lowercase). The CSP fix only needs to land on the SPA-baked literal — that's the entry the SPA's hardcoded fetch needs covered.\n\nIf wrangler ships a fix for the response-header rewrite, the case-shifted source remains a valid CSP entry that browsers match identically — no follow-up needed in user code.\n\n**Action required:** none. Recompile (`quickback compile`) to pick up the fix.\n\n---\n\n## v0.10.18 — May 2, 2026\n\n### `experimentalRemote` — share deployed D1 with `wrangler dev`\n\nPer-binding `experimental_remote = true` flag emitted into the generated `wrangler.toml`. Useful for \"share prod auth in dev, keep feature writes sandboxed\":\n\n```ts\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n experimentalRemote: {\n auth: true, // wrangler dev reads/writes deployed AUTH_DB\n features: false, // (default) features stays local\n audit: false,\n webhooks: false,\n files: false,\n },\n }),\n}\n```\n\nKeys are logical binding names — `auth` flips the flag on the `AUTH_DB` binding, `features` flips it on `DB` (or the legacy single-DB binding), `audit` / `webhooks` / `files` follow the same pattern. Off by default; only enable for databases you intend to share.\n\n### Google OAuth + signup ToS\n\nThe Account SPA now wires Google OAuth end-to-end when `auth.providers.auth.config.socialProviders.google.enabled: true`. The compiler bakes the right `VITE_ENABLE_GOOGLE_OAUTH` flag into the SPA's `.env` so the social-login button renders only when the provider is enabled — no more dead buttons.\n\nSignup flow gains a Terms-of-Service checkbox gate (configurable via the Account SPA's branding config).\n\n### CLI compile auth gate + device-auth redirect fix\n\n- `quickback compile` now requires authentication for cloud-compiler runs (closes the unauth public-compile path).\n- The device-flow `/cli/authorize` page was sending `?returnTo=` to login, but `signup.tsx` and the `_authenticated` middleware only read `?redirect=` — so a user who clicked \"Create one\" from `/login` lost the return URL. Standardized on `?redirect=` everywhere.\n\n### Skill restructure (Claude Code skill)\n\nThe bundled Claude Code skill was reorganized for clarity:\n\n- `SKILL.md` is now a thin orientation pointer, not a 600-line dump\n- Reference docs split into `Compiler` and `Stack` sections\n- Docs bundled as **files** the model navigates with `Read` / `Glob` rather than via `quickback docs <topic>` shell calls — same content, fewer tool calls per lookup\n- Tightened against audit gaps surfaced by red-team review\n\nRun `quickback claude install` to pick up the new skill layout.\n\n---\n\n## v0.10.17 — May 2, 2026\n\n### Security fix: CSP auto-config no longer widens `default-src`\n\nWhen 0.10.15's auto-config was asked to add a value to a directive the user hadn't declared (e.g. `https://fonts.googleapis.com` → `style-src` when only `default-src` was set), it incorrectly pushed the value into `default-src` itself. Because CSP3 fall-back semantics make `default-src` the fallback for `script-src`, `img-src`, `media-src`, and others, this widened the attack surface to every directive that fell back to it — a `style-src`-only host became reachable from `script-src`.\n\n0.10.17 fixes the logic: missing target directives are now **scaffolded** with the user's `default-src` values as baseline, then extended with the auto-config addition. `default-src` stays clean. The new directive (e.g. `style-src`) covers exactly the styles the SPA needs and nothing else.\n\nBefore (0.10.16):\n```\ndefault-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com @trustedOrigins https://api.example.com\n```\n\nAfter (0.10.17):\n```\ndefault-src 'self'\nstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com\nfont-src 'self' https://fonts.gstatic.com\nconnect-src 'self' @trustedOrigins https://api.example.com\n```\n\n**Action required:** recompile (`quickback compile`) to regenerate the security middleware with the corrected scaffolding. Configs that already declared each `*-src` directive explicitly were unaffected by the bug — the regression only surfaced when users wrote `defaultSrc: ['@self']` and let auto-config fill in the rest.\n\nThe user-side workaround from 0.10.16 (declaring each directive with `['@self']` to force scaffold) is no longer needed in 0.10.17 — the compiler does the right thing automatically.\n\n---\n\n## v0.10.16 — May 2, 2026\n\n### CSP auto-config now covers SPA-baked-in API origins\n\nWhen the bundled CMS or Account SPA is enabled, the compiler already inlines the API URL into the SPA bundle as a string literal at build time (`VITE_QUICKBACK_API_URL=https://${unifiedDomain}`). That hardcoded URL is what the SPA actually fetches — regardless of which origin is currently serving the page. CSP `connect-src` must allow it explicitly.\n\n0.10.16's auto-config picks up every domain the compiler already knows about — `config.domain`, the inferred `quickback.{baseDomain}`, `cms.domain`, `account.domain`, the admin domain — and adds `https://${each}` to `connectSrc` whenever a bundled SPA is enabled.\n\nThe motivating case: running the SPA on `localhost:5173` while it's still baked against `https://quickback.your-app.com`. Pre-0.10.16 the localhost CSP's `'self'` blocked the prod URL; users were patching it manually. Now it just works.\n\n```\n[security] auto-added https://quickback.loop.kardoe.com to csp.connectSrc — account: true → bundled Account SPA → SPA bundle hardcodes https://quickback.loop.kardoe.com as VITE_QUICKBACK_API_URL / etc.\n```\n\n`@trustedOrigins` (the CORS allowlist) is unchanged — it still gets added independently. The two cover different things: `@trustedOrigins` permits CORS-allowed sibling subdomains; the new SPA-baked addition permits the exact URL the SPA's compiled bundle hardcodes.\n\nCombined with 0.10.15's bundled-SPA defaults, most projects can now write the minimal:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n}\n```\n\n…and the compiler fills in styleSrc font hosts, fontSrc gstatic, connectSrc trusted origins, and connectSrc SPA-baked URLs.\n\n---\n\n## v0.10.15 — May 2, 2026\n\n### CSP auto-config — bundled-SPA origins added automatically\n\nWhen `security.csp` is set, the compiler now widens directives **additively** based on the project's enabled features. The four rules:\n\n| Trigger | Auto-added | Directive |\n|---|---|---|\n| `cms: true` OR `account: true` | `'unsafe-inline'`, `https://fonts.googleapis.com` | `styleSrc` |\n| `cms: true` OR `account: true` | `https://fonts.gstatic.com` | `fontSrc` |\n| `csp` set (always) | `@trustedOrigins` | `connectSrc` |\n\nAnything you already wrote stays — auto-config never removes or overrides. Every applied addition prints to stderr at compile so the magic is visible:\n\n```\n[security] auto-added 'unsafe-inline' to csp.styleSrc — account: true → bundled Account SPA → inline style attributes from Tailwind / TanStack Router\n[security] auto-added @trustedOrigins to csp.connectSrc — CORS-trusted origins must be reachable from XHR/fetch (matches cors() allowlist)\n```\n\nThe recipe in [the security docs](/compiler/config/security#example-paste-in-csp-for-a-quickback-spa-project) becomes ~5 lines shorter — most projects no longer need to list `fonts.googleapis.com` / `fonts.gstatic.com` / `@trustedOrigins` themselves. **Loop's CSP shrinks dramatically** after recompiling against this version.\n\n**Opt-out:** `security: { cspAutoConfig: false, csp: { ... } }` for projects fronted by a CDN that injects its own CSP, or teams that want strict from-scratch control.\n\n**Smart fallback:** if you set `defaultSrc` but omit the target directive (e.g. `defaultSrc: ['@self']` and nothing for `connectSrc`), the addition lands in `defaultSrc` rather than creating a sibling directive — CSP fall-back semantics mean a sibling would *narrow* your intent, so we preserve the broader fallback.\n\n### Troubleshooting table for CSP violations\n\nThe security docs page now includes a [Troubleshooting CSP violations](/compiler/config/security#troubleshooting-csp-violations) table mapping browser console errors back to the directive that needs widening. Useful when auto-config is disabled or the project has a non-bundled SPA hitting third-party origins.\n\n### Out of scope (deferred)\n\n- **Per-request CSP nonces** (`@nonce` sentinel implementation) — Phase 2 / 0.10.16. Sentinel still errors at compile in 0.10.15.\n- **`revocationCheck: 'kv'` for `auth.jwt`** — schema accepts it, runtime still errors at compile. Slipped from 0.10.15 to 0.10.16.\n- **Public R2 host auto-add to `imgSrc`** — most R2 access today goes through the worker so the SPA fetches from `'@self'`. Will revisit once we have a clean way to discover public-bucket hosts at compile.\n\n---\n\n## v0.10.14 — May 1, 2026\n\n### `auth.jwt` — JWT bearer-token fast-path config\n\nQuickback's bearer-token JWT (the one minted by the auth middleware and consumed by the fast-path on every subsequent request) is now configurable. The most-tuned knob is `expiresIn` — drop it to bound the post-revocation replay window without affecting browser SPAs, which auto-refresh via `set-auth-token` on every authed call:\n\n```ts\nauth: {\n jwt: {\n expiresIn: 30, // 30s post-revocation replay window\n issuer: 'my-api', // iss claim (verified on the way back in)\n audience: 'partner-svc', // aud claim\n secretEnv: 'CUSTOM_JWT_SECRET', // override BETTER_AUTH_SECRET if you need the JWT secret rotated independently\n },\n}\n```\n\n`revocationCheck: 'kv'` (KV-denylist consult on every fast-path verify, ~5-15ms edge-cached, no D1 hit) is reserved in the schema today but **deferred to 0.10.15** — setting it errors at compile so the migration path is explicit. `'none'` (today's behaviour, 0 cost, replay bound by TTL) stays the default.\n\nSee [the docs page](/compiler/config/auth) for the full knob list and tuning recommendations.\n\n### MCP admin endpoints hidden from non-admin `tools/list`\n\nBetter Auth admin endpoints (`/admin/list-users`, `/admin/ban-user`, `/admin/impersonate-user`, etc. — 9 in total) now carry `x-access: { userRole: ['admin'] }` in the generated OpenAPI spec, which means the MCP server's existing access-filter automatically drops them from `tools/list` for callers without an admin token. Anonymous and member-role callers no longer see admin tooling enumerated through MCP; admin endpoints still exist on the HTTP surface (Better Auth gates them server-side regardless).\n\n### Declarative `security` config block\n\nEvery security response-header (`Content-Security-Policy`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`, `Cross-Origin-Resource-Policy`, `X-Frame-Options`, `Strict-Transport-Security`, `Referrer-Policy`, `Permissions-Policy`) is now configurable from `quickback.config.ts`. Loop's `postcompile-patch.mjs` (which re-injected a fuller CSP and COOP after every `quickback compile`) can now be deleted in favour of:\n\n```ts\nsecurity: {\n csp: {\n defaultSrc: ['@self'],\n scriptSrc: ['@self'],\n styleSrc: ['@self', '@unsafe-inline'],\n frameAncestors: ['@none'],\n objectSrc: ['@none'],\n upgradeInsecureRequests: true,\n },\n coop: 'same-origin',\n}\n```\n\n`@`-prefixed sentinels (`@self`, `@none`, `@unsafe-inline`, `@unsafe-eval`, `@trustedOrigins`, `@nonce`) save users from awkward `\"'self'\"` quoting and let `@trustedOrigins` resolve to the same allowlist `cors()` uses. Unknown sentinels throw at compile rather than silently stringify into the wire CSP.\n\nThe compiler runs lint rules over the resolved config — errors for `@nonce` (deferred to 0.10.15), `@unsafe-inline + @nonce` (silently broken), and sentinel-only directives that would resolve to nothing at runtime; warnings for `@unsafe-inline` in `script-src`, wildcard sources, missing `default-src`, HSTS preload-list misconfiguration, etc.\n\nDefaults preserve 0.10.13 behaviour byte-for-byte — adding the block without setting any field is a no-op.\n\nSee [the docs page](/compiler/config/security) for the full reference.\n\n### HSTS no longer pins `localhost` to HTTPS\n\nThe generated middleware now skips `Strict-Transport-Security` when the request hostname is `localhost`, `127.0.0.1`, or `*.localhost`. Without this gate, `wrangler dev` would pin the developer's browser to HTTPS for `max-age` seconds — observable across every project on that machine since HSTS keys on hostname, not port. Affects every project running locally.\n\n### Out of scope (deferred)\n\n- **Per-request CSP nonces** — Phase 2 / 0.10.15. Sentinel exists at config-validation level so users can author their final CSP today knowing it'll start working when nonces ship.\n- **Asset-hash CSP** for inline `<style>` and `<script>` blocks emitted by the bundled SPAs — Phase 3.\n- **Per-route CSP overrides** (e.g. one looser policy for `/admin`) — single global CSP for now.\n\n---\n\n## v0.10.13 — May 1, 2026\n\n### Clickjacking protection on every generated Worker\n\nEvery Worker now emits two clickjacking-defence headers on every\nresponse:\n\n- `Content-Security-Policy: frame-ancestors 'self' <TRUSTED_ORIGINS…>`\n- `X-Frame-Options: SAMEORIGIN`\n\nThe CSP allowlist is sourced from the same `TRUSTED_ORIGINS` constant\nthat gates CORS, so users configure their domains in one place\n(`auth.trustedOrigins` / `auth.trustedOriginDefaults` in\n`quickback.config.ts`) and both CORS and frame-ancestors stay in\nlockstep. `'self'` is always allowed so an app's own SPAs can frame\ntheir own routes (e.g. an account login popover hosted on the same\norigin).\n\nModern browsers obey `frame-ancestors` and ignore `X-Frame-Options`\nwhen both are set; the legacy header is included for clients that\ndon't speak CSP3. The CSP intentionally only sets `frame-ancestors` —\nadding `script-src` / `default-src` would need a much wider audit\nacross SPA assets, inline scripts, and third-party embeds, so that's\nleft as a follow-up.\n\nRecompile (`quickback compile`) and redeploy to pick this up — no\nconfig change needed unless you want to allow extra cross-origin\niframe embeds, in which case add them to `auth.trustedOrigins`.\n\n---\n\n## v0.10.12 — May 1, 2026\n\n### Bundled-docs sync for the MCP recon fix\n\nPatch release that re-bundles the CLI's offline docs (consulted by the\nClaude Code skill, Cursor rules, and other AI assistants) so they\nreflect the corrected `tools/list` access-filter behavior and CORS\nposture shipped in v0.10.11. The `compiler/config/agents.mdx` page\nitself was already corrected on the docs site immediately after the\n0.10.11 release; this bump propagates that text into the bundle inside\n`@quickback-dev/cli`.\n\nNo runtime or compiler behavior change — re-running `quickback compile`\nagainst this version produces the same output as v0.10.11.\n\n---\n\n## v0.10.11 — May 1, 2026\n\n### MCP `tools/list` is now access-filtered + recon-tightened\n\nThe generated MCP-over-HTTP server (`src/routes/mcp.ts`) had three holes\nthat turned a standard pentest into trivial recon:\n\n1. `tools/list` returned the entire tool catalogue to anyone — including\n admin-only endpoints — without checking auth or roles. Tool\n descriptions also leaked sentences like `[UNSAFE] bypasses tenant\n scoping and requires elevated access` verbatim.\n2. The endpoint set `Access-Control-Allow-Origin: *` so any origin could\n pull the catalogue from a browser.\n3. Unauthenticated `GET /mcp` enumerated every tool name in its\n discovery payload.\n\nFix:\n\n- Each tool now carries sanitised access metadata (`_access` covering\n `roles` / `userRole` / `or` / `and`, plus `_public` for `PUBLIC`\n pseudo-role or empty `security`). `tools/list` filters against the\n caller's `ctx` — unauth callers see only `_public` tools, authed\n callers see only role-gated tools they pass. Record predicates and\n function-form access (opaque at list time) are dropped.\n- Wildcard CORS removed entirely. The parent app's `cors()` middleware\n (origin allowlist via `TRUSTED_ORIGINS` + `BETTER_AUTH_URL`) now\n applies uniformly to `/mcp`, same as every other route.\n- `[UNSAFE] ... bypasses tenant scoping ...` flavour text is gone.\n `annotations.destructiveHint` and `_unsafe` remain — those are the\n spec-correct signals for clients to warn users.\n- Unauthenticated `GET /mcp` no longer lists tool names. Inventory is\n only available via the access-filtered `tools/list`.\n\nThis filter is recon-mitigation, not a security boundary: `tools/call`\nstill re-enters the Hono app and runs every middleware (auth, firewall,\naccess, guards, masking), so hiding a tool from list never weakens the\nunderlying gate.\n\nKnown follow-up: Better Auth admin endpoints (`ban-user`, `create-user`,\n`impersonate-user`, etc.) don't yet emit `x-access` in the OpenAPI spec,\nso any logged-in user still sees them in `tools/list` (the actual call\nis still gated by the admin plugin). Tracked separately.\n\n---\n\n## v0.10.10 — April 29, 2026\n\n### Reject reserved keys inside `access.record` at compile time\n\n`access.record` is a flat field map evaluated as implicit AND between\nentries — keys must be column names. Putting `and: [...]` (or `or` /\n`roles` / `userRole`) inside `record` was a real-world footgun: the\nruntime treated the literal string `\"and\"` as a column lookup, the\npredicate failed on every row, and the caller got a silent `403` /\nempty list with nothing pointing at the misuse. The TypeScript type\ncouldn't catch this — `RecordConditions` is an open-ended index\nsignature, so any key parses.\n\nThe compiler now walks every access node attached to a resource (CRUD\nops, `read.access`, view access, masking `show` / `query`, action\naccess) and throws a clear migration error when `record` contains a\nreserved key:\n\n- `and` / `or` inside `record` → use the top-level `and` / `or`\n sibling: `{ and: [{ record: { ... } }, { record: { ... } }] }`\n- `roles` / `userRole` inside `record` → put them at the access node\n alongside `record`: `{ roles: [...], record: { ... } }`\n\nThe error names the exact origin (`crud.update.access`,\n`actions.focus.access.or[1]`, etc.) so the fix lands in the right place.\n\n---\n\n## v0.10.9 — April 29, 2026\n\n### Role hierarchy now expands in record-based action access\n\n`auth.roleHierarchy: ['member', 'admin', 'owner']` plus\n`access: { roles: ['member+'] }` on a record-based action used to\nsilently 403 valid callers. The standalone-action route generator\ninlined the expanded role list as a JSON literal, but the\nrecord-based generator read the access config back through the\nruntime `actions['name'].access` import — the user's source, where\nthe unexpanded `'member+'` shorthand still lived. The runtime did\nliteral string matching against `ctx.roles`, so an `owner` calling\nthe action got `['member+'] !== 'owner'` and was rejected.\n\nFixed: record-based action routes now inline the expanded list the\nsame way standalone routes do. `input` and `execute` still flow\nthrough the runtime import (closures aren't serializable); only the\naccess config is lifted to a JSON literal so the compile-time\nexpansion actually reaches the matcher.\n\nA regression test (`role-hierarchy-action-routes.test.ts`) locks the\nbehavior in — it asserts that `member+` never reaches the route\noutput and that the access config is no longer read from\n`actions[name].access` at runtime.\n\n---\n\n## v0.10.8 — April 29, 2026\n\n### Audit support on postgres targets, plus a generated-API quality pass\n\n**Audit on PG.** Until this release, `audit_events` only existed on cloudflare-d1 — projects on Neon (or any postgres target) silently skipped audit logging on `unsafe:` and `PUBLIC`-role actions, and hard delete was hard-blocked. Postgres has no equivalent of D1's separate-database binding model, but it has native schemas — so the audit table now lives in a dedicated `audit` schema in the same database as features (`drizzle.pgSchema('audit')`). The `hasSecurityAudit` gate accepts D1 OR any PG dialect; the `auditDatabaseId` requirement only fires for D1 (which still uses the separate-binding model). The recruitment example wires `auditDatabaseId` so the recompile path stays green.\n\n**`auditDatabaseId` is now a compile-time requirement** (D1 only). Previously, projects with unsafe/PUBLIC actions but no audit id silently produced a `database_id = \"local-audit\"` placeholder in production `wrangler.toml`; Cloudflare's worker upload step then rejected it with code 10021 *after* assets and migrations had already run. The compile-time error names the exact `wrangler d1 create <project>-audit` command and the `auditDatabaseId` config key where the returned id goes.\n\n### Five fixes from a Loop integration ticket pass\n\n**Action input → OpenAPI / MCP.** `defineAction({ input: z.object({...}) })` schemas now flow into `requestBody` on the OpenAPI operation and `inputSchema.properties` / `_bodyFields` on the MCP tool list. Simple `z.object` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation — full-fidelity output with no static translator to maintain. Pre-fix, every action came out as a no-arg endpoint, which gutted typed SDK generation and made MCP useless for actions that take parameters.\n\n**OpenAPI fidelity.** Three surgical fixes that strict validators (zod, openapi-typescript, openapi-fetch) had been complaining about:\n- Response schemas now emit `required[]` for every non-nullable column, so generated SDKs treat them as guaranteed-present rather than optional.\n- `text(_, { enum: [...] })` columns emit as closed `{ type: \"string\", enum: [...] }`, narrowing to literal unions.\n- `id` only claims `format: \"uuid\"` when the project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }` — strict validators stop rejecting responses against their own spec.\n\n**Mask auto-detector now checks the column exists.** The auto-mask predicate used to be unconditionally `show: { or: 'owner', roles: ['admin'] }` — including for tables with no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`). The generated mask function would reference a non-existent column and fail under TypeScript checks. The auto-detector now verifies the resolved owner column exists in the parsed schema before emitting the `or` clause; when it doesn't, the rule falls back to roles-only and the compiler emits a warning so the behavior is transparent.\n\n**Error code consistency.** The generated CRUD layer was emitting raw codes (`'UNAUTHORIZED'`, `'NOT_NULL_VIOLATION'`, `'UNIQUE_VIOLATION'`, `'INSERT_FAILED'`, `'UPDATE_FAILED'`) that were never in the `QuickbackErrorCode` enum, so consumers couldn't switch exhaustively on `code`. New `database` layer + `DB_NOT_NULL_VIOLATION` / `DB_UNIQUE_VIOLATION` / `DB_INSERT_FAILED` / `DB_UPDATE_FAILED` / `NOT_FOUND` codes are now in the enum, the routes use `AuthErrors.missing()` / `DatabaseErrors.*()` helpers throughout, and the OpenAPI `Error` component emits `code` as a closed enum sourced from the canonical `QUICKBACK_ERROR_CODES` list. Generated SDKs can now `switch` on `code` without a default branch swallowing unknown values. See [API errors](/compiler/targets/hono-api/using-the-api/errors#database).\n\n**Dropped dead `auditFields` preamble from action route generators.** The audit wrapper's `Proxy` already hard-stamps `createdAt` / `createdBy` / `modifiedAt` / `modifiedBy` on every INSERT and `modifiedAt` / `modifiedBy` on every UPDATE — the `auditFields` const the route preamble built was never read. Dropped from `standalone.ts` / `record-based.ts` and from the `ActionExecutorParams` JSDoc. Migrated 7 example handlers (drop `modifiedAt: auditFields!.modifiedAt` from `.set` payloads — the wrapper handles it). Note: `.onConflictDoUpdate({ set })` is *not* intercepted by the wrapper, so `upsertBatch`-style handlers keep an explicit `modifiedAt: now`.\n\n---\n\n## One file per action: greenfield action authoring\n\nAction authoring collapses to a single shape. Each action is its own file under `<feature>/actions/<name>.ts` using `defineAction({...})`. The filename is the action name AND the URL segment.\n\n```typescript\n// features/applications/actions/advance.ts\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, auditFields, whereTransition }) { /* … */ },\n});\n```\n\n`defineAction` is imported from a generated per-feature helper at `<feature>/.quickback/define-action.ts` — types `record`, `input`, and audit fields without manual annotations. The directory says what `:id` mounts to; the imports say what the body reads or writes.\n\n**Discovery rules:**\n- `actions/<name>.ts` binds to the feature's primary table (the `<feature>.ts` file at the feature root).\n- `actions/<table>/<name>.ts` binds to the sibling table file `<table>.ts` — for multi-table features.\n- Setting `path:` makes the action standalone (custom URL, no record fetch, no firewall preload).\n- Tableless features (no top-level `*.ts` files) require every action to be standalone.\n- Action names are unique per `(bindTable, name)` pair — sibling-bound actions on different tables may share a verb (e.g. `actions/episodes/publish.ts` + `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and don't collide). Standalone actions are unique per `(method, path)`.\n- Files under `<feature>/lib/` are copied verbatim for feature-local helpers; `quickback/lib/` is exposed via the `~/lib/*` alias for cross-feature shared code (with a one-way import rule enforced at compile time).\n\n**Retired** (rejected at load time with migration guidance):\n\n- `actions.ts` (bundled multi-action file)\n- `_feature.ts` (shared preamble + tableless actions)\n- `handlers/` directory + `handler:` string ref\n- `defineActions(table, {…})` and `defineActions(null, {…})`\n- `export default { actions: {…} }`\n- Colocated `defineActions` inside table files\n- `standalone: true` flag (presence of `path:` is the new signal)\n- `*-actions.ts` / `*.actions.ts` filename patterns\n\nThe phantom-`unsafe` regex bug that flattened nested `unsafe: { … }` blocks into a fake top-level action is gone — the parser now reads action files as real TS modules with real imports, so type inference, jump-to-definition, and rename refactoring all work end-to-end.\n\nThe CLI loader rejects retired primitives at load time with batched migration errors. Existing projects need to be migrated by hand to the new shape before recompiling.\n\nSee the [Actions docs](/compiler/definitions/actions) for the full reference.\n\n---\n\n## Multi-table actions per feature\n\nFeatures used to support exactly one `defineActions(table, …)` call via `actions.ts`, which forced unnatural feature splits whenever multiple tables in the same feature needed actions (a podcast feature with `episodes`, `shows`, `seasons`, `collections`, etc.). One feature directory can now own actions on multiple tables across three discovery modes:\n\n- **Colocated** (canonical) — `<table>.ts` containing both `defineTable` and `defineActions(<table>, …)`. One file per entity. Default for new features.\n- **`actions.ts`** (existing) — single primary-table actions file at feature root. Unchanged behaviour.\n- **`actions/<table>.ts`** — per-table action files for teams that want strict schema/behavior separation or need to break an import cycle.\n\nPlus the universal `_feature.ts` slot (at feature root) for **non-table-bound feature-level actions** (`export default { actions: { … } }` shape) and **shared Zod schemas** that get prepended once to the merged actions module so every sibling action sees them. Allowed in any of the three modes — orthogonal to table binding.\n\nThe decision flowchart: *one table with actions → colocate. Multiple tables with actions → colocate each. Hit a cycle or want strict separation → `actions/<table>.ts`. Want schema/actions split for a single-table feature → `actions.ts`. Non-table actions → always `_feature.ts`.*\n\nConflicts are batched and printed once before the compiler aborts — no \"fix one, recompile, fix the next\" loop. The CLI hard-errors when a feature mixes `actions.ts` with table-bound mode, when the same table has its `defineActions` declared in two places, when an `actions/<x>.ts` first-arg doesn't match the basename, or when `_feature.ts` contains `defineActions(table, …)`. Legacy `*-actions.ts` / `*.actions.ts` filenames in a feature dir trigger a soft warning naming the offending paths.\n\nWithin the legacy bundled `actions.ts` DSL, action names had to be unique within a feature — the runtime module merged every source into one keyspace, so colliding `publish` actions on `episodes` and `shows` would have silently overwritten each other. The retired `actions.ts` shape is no longer accepted, so this constraint is gone: the current one-file-per-action layout keys uniqueness per `(bindTable, name)` pair, and the codegen aggregator mangles the JS map key per bind-table while keeping the URL segment bare. Sibling-bound `actions/episodes/publish.ts` and `actions/shows/publish.ts` mount at `/episodes/:id/publish` and `/shows/:id/publish` and compile cleanly.\n\nInline `execute:` bodies must be arrow functions (`execute: async (ctx) => { … }`). `async function` and plain `function` shapes were silently misparsed by the route emitter — they now hard-error at parse time pointing at the canonical arrow form, with a suggestion to use `handler:` for callers who genuinely need a named function declaration.\n\n`handlers/` walks recursively now — `handlers/<table>/<action>.ts` is the canonical layout. A new `lib/` directory under each feature gets copied verbatim into the output for feature-local helpers.\n\nMigration: existing `actions.ts` projects compile bit-identically — the legacy single-table path is unchanged. Legacy `*-actions.ts` filenames produce a soft warning and silently aren't picked up; rename to `<table>.ts` (colocated), `actions/<table>.ts`, or single `actions.ts`.\n\n---\n\n## Firewall: named-scope shape restored, auto-detection synonyms widened\n\nThe named-scope firewall shape (`firewall: { organization: { column: 'tenant_id' } }`) is back as a co-equal user-facing input alongside the predicate array. DSL v2 step 8 had walled it off, but the internal architecture still kept named-scope around for the route + scoped-db generators — so re-accepting it at the input boundary is a thin coercion layer, not an architectural change.\n\n```typescript\n// All three are now valid; all compile to the same predicate array internally.\nfirewall: { organization: { column: 'tenant_id' } } // named-scope (compact)\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true }\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n] // predicate array (explicit)\n```\n\nPick the form that reads better — named-scope for the common one-line case, predicate array when you need custom `in`-lists or non-scope predicates.\n\n**Auto-detection synonyms expanded.** When `firewall:` is omitted entirely, the compiler scans the schema for an isolation column. The org-scope list now accepts `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` (American + British). User-scope still accepts `userId` only.\n\n**`ownerId` is now a targeted error signal.** When a table carries `ownerId` but no isolation column AND no explicit `firewall:`, the compiler raises a specific error: `\\`ownerId\\` is business-logic ownership, not access control — Quickback won't auto-derive a firewall from it. Either rename to \\`userId\\` if this column controls access, add a separate \\`userId\\` / \\`organizationId\\` column, or specify \\`firewall:\\` explicitly.` This replaces the generic \"missing isolation column\" error in the `ownerId`-only case and preserves the documented distinction between RLS-style access control (`userId`) and business-logic ownership (`ownerId`).\n\nMigration: nothing breaks. Projects on the predicate-array shape compile bit-identically. Projects on the named-scope shape — including any test fixtures or example projects that were left on the legacy form — now compile cleanly again.\n\n---\n\n## v0.10.0 — April 26, 2026\n\n### `q.scope()` column DSL + unified `masking.query` gate\n\nTwo related DSL consolidations land. The `q.scope()` half is purely additive; the `masking.query` half rejects three legacy per-capability flags at compile time (migration is mechanical — see below).\n\n**`q.scope(kind)` — single-declaration tenant scoping.** Replaces the three-place pattern (column declaration + firewall predicate + implicit ownership-guard) with one column. `q.scope('organization')` compiles to `text(...).notNull()` and tells the compiler:\n\n1. Auto-derive the firewall predicate (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`) so the explicit `firewall:` block can be omitted entirely.\n2. Add the column to `GUARDS_CONFIG.systemManaged` so client input is rejected at the guard layer.\n3. Auto-populate from `ctx` on create / upsert.\n\nThe systemManaged extension generalises beyond `q.scope()`: any firewall predicate whose `equals` references `ctx.*` adds its `field` to the systemManaged set. So a hand-rolled `firewall: [{ field: 'tenantId', equals: 'ctx.activeOrgId' }]` gets the same treatment.\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → ctx.activeOrgId\n ownerId: q.scope('owner'), // → ctx.userId\n teamId: q.scope('team'), // → ctx.activeTeamId\n}\n```\n\nThe auto-derived firewall also includes the soft-delete predicate (`{ field: 'deletedAt', isNull: true }`) when audit-field injection is on (the default). See [`q.scope()` in the schema docs](/compiler/definitions/schema#qscope--tenant-scope-columns).\n\n**`masking[col].query.roles` — unified role gate for filter / sort / search.** The three legacy per-capability flags (`filterable`, `searchable`, `sortable`) are replaced by a single allowlist that says \"these roles can query the column.\"\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n query: { roles: ['admin'] }, // optional — defaults to show.roles\n },\n}\n```\n\nWhen omitted, `query` inherits from `show.roles` (\"if you can see it, you can query it\") which is the right shape for almost all PII. A view's own `query.{filterable,searchable,sortable}` allowlist is the opt-in for higher-privileged roles; the existing intersection validator gates it at compile time. See [Masking query gate](/compiler/definitions/masking#query-gate-filter--sort--search).\n\n**Breaking:** Setting `masking[col].filterable / .searchable / .sortable` is rejected at compile time with a migration hint. Replace with `query.roles` (or just delete the flags — `query` defaults to `show.roles`).\n\n---\n\n## v0.9.0 — April 25, 2026\n\n### DSL v2: unified `read:` pipeline, transactional batches, ID-probe defense\n\nStep 8 of the DSL v2 refactor lands. The headline shift is that the read\nside of every resource now has its own block — `read:` — that owns the\ncollection-level `GET /` endpoint, single-record `GET /:id`, and named view\nprojections. The legacy `crud.list` and `crud.get` shapes are rejected at\ncompile time. See the new [Read pipeline](/compiler/definitions/read) page\nfor the full reference and migration table.\n\n**Breaking changes** (compile-time errors with migration hints):\n\n- `crud.list` → [`read.access`](/compiler/definitions/read) (plus `read.pageSize` / `read.maxPageSize`)\n- `crud.get` → `read.access` (single-record GET inherits automatically; use record-level conditions on `read.access` for differentiated single-record gates)\n- Top-level `views: {...}` → [`read.views: {...}`](/compiler/definitions/read#views-under-read-views)\n- `crud.list.fields` / `crud.get.fields` → declare a named view under `read.views` and call `/views/{name}`\n\n**Pre-record access ordering on `/:id`**: handlers now run a role-only\naccess check **before** the firewall query, so a caller without a matching\nrole gets 403 before the database is touched. This closes the 404-vs-403\nID-probe channel — an unauthorized caller can no longer distinguish \"row\nexists in another tenant\" from \"row doesn't exist.\" See\n[Access evaluation order](/compiler/definitions/access#evaluation-order).\n\n**Transactional batch operations**: batch endpoints now expose a\n`failFast` option (replacing the old `atomic` naming) and a\n`meta.transactional` response field. On tx-supporting providers\n(postgres, supabase, neon, libsql, better-sqlite3, bun-sqlite), `failFast: true`\nwraps the per-record loop in `db.transaction(...)` so any failure rolls\nback the entire batch. On Cloudflare D1 (no `db.transaction`), `failFast: true`\nstill stops on the first error but prior writes stay committed; inspect\n`meta.transactional` to know which guarantee you got. Embedding queue\nmessages and realtime broadcasts are emitted **after** the transaction\ncommits, so a rolled-back batch produces no orphan jobs. See\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n**`firewallErrorMode` lifted off the firewall block**: the field that\ncontrols 403-vs-404 on firewall misses now lives at the resource top level\n(sibling to `firewall:`), since the firewall config is now a predicate\narray and this is a presentation-layer choice. Existing `firewall.errorMode`\nvalues should be lifted to `firewallErrorMode` at the resource level.\n\n**Read-only resources**: an empty `crud: {}` block (or omitting `crud:`\nentirely) is valid for read-only resources. `read:` alone is enough to\nexpose `GET /` and `GET /:id`.\n\n**Strict-mode top-level keys**: the strict allow-list now includes `dev` so\n`defineConfig({ dev: { ... } })` is accepted at the top level.\n\n---\n\n## v0.8.7 — April 17, 2026\n\n### Security: Hono CVE cluster fix\n\nHono is bumped to `^4.12.14` across the monorepo, the compiler Docker image's pre-installed deps, and every generator path that emits Hono into compiled projects. Older ranges (`^4.0.0` / `^4.5.0` / `^4.6.0` / `^4.7.11`) covered the vulnerable window. Recompile to pick up the fix in your generated project's `package.json`.\n\n### Cloudflare Email Sending is now in public beta\n\nQuickback already defaults to the Workers `send_email` binding for Cloudflare deploys, and Cloudflare Email Sending has now graduated to public beta — production-ready with zero-config, no API keys, no third-party accounts. No action needed; recompiling any existing project continues to wire the default Cloudflare transport. AWS SES remains a fully supported opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups. See [Email Configuration](/compiler/config#email-configuration).\n\n### Minor/patch dep sweep\n\nAligned the whole dep surface — monorepo, compiler Docker image, and generator emissions into compiled projects — so new compiles and existing recompiles converge on the same versions:\n\n- `wrangler@^4.83.0`\n- `drizzle-orm@^0.45.2`, `drizzle-kit@^0.31.10`\n- `zod@^4.3.6`\n- `@cloudflare/workers-types@^4.20260417.1` (also deduped — was accidentally declared in both `dependencies` and `devDependencies` in some paths)\n- `@tanstack/react-query@^5.99.0` (Account app)\n\n---\n\n## v0.8.5 — April 15, 2026\n\n### Fix: Better Auth 1.5 and `@cloudflare/workers-types` Compatibility\n\nGenerated API code failed to typecheck after Better Auth bumped to 1.5 and `@cloudflare/workers-types` tightened `BufferSource` to `ArrayBufferView<ArrayBuffer>`. Four unrelated surfaces broke:\n\n- **`databaseHooks.member.update.after` was removed** in Better Auth 1.5. The compiler now emits the member role-change broadcast hook as `organizationHooks.afterUpdateMemberRole` inside the `organization()` plugin call, which is the current supported shape.\n- **`REALTIME_URL` and `ACCESS_TOKEN`** are always emitted as optional `CloudflareBindings` fields when the organization plugin is active, so the broadcast hook typechecks even when `realtimeMode` is `\"inline\"` (or realtime isn't configured at all).\n- **`auth.api.listOrganizations` / `getFullOrganization` / `session.session.activeOrganizationId`** — third-party Better Auth plugins narrow the inferred `auth.api` type and hide organization-plugin endpoints. The generated middleware and `/admin/v1/organizations` route now cast through `any` for these calls.\n- **`crypto.subtle.sign` / `verify`** no longer accept `Uint8Array<ArrayBufferLike>` directly. Generated `jwt.ts` casts encoded payloads to `BufferSource`.\n\nNo config changes required — recompile to pick up the fixes.\n\n### CMS Admin Gate Now Enforced Server-Side\n\n`cms: { access: \"admin\" }` previously only hid the CMS link in Account UI and rendered an \"Access Denied\" screen inside the SPA — the static assets, `/api/v1/schema`, and `/api/v1/custom_view` CRUD were reachable by any authenticated user. A non-admin with an API token or cookie could bypass the UI and read schema metadata or saved CMS views directly.\n\nThis release adds server-side enforcement at every CMS-facing surface:\n\n- **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests redirect to login; authenticated non-admins get `403 Admin access required`. Static bundles (JS/CSS) remain reachable so browser caches aren't invalidated.\n- **`/api/v1/schema`** — returns `403` to non-admins.\n- **`custom_view` CRUD** — now gated on the new `userRole: [\"admin\"]` primitive rather than org membership.\n- **In-SPA gate** — unchanged; defense in depth behind the server-side gates.\n\nYour resource CRUD endpoints are unaffected — they keep their per-resource `crud.access.roles`.\n\n### New `userRole` Access Primitive\n\nAdded `userRole?: string[]` to the declarative `Access` config, evaluated against `ctx.userRole` (the Better Auth admin-plugin `user.role` column). This is distinct from `roles`, which matches `ctx.roles` (org membership).\n\n```typescript\n// Old: in multi-tenant this meant org-admin, not platform-admin\naccess: { roles: ['admin'] }\n\n// New: explicitly require user.role === 'admin' regardless of org membership\naccess: { userRole: ['admin'] }\n\n// \"Org owner OR platform admin\"\naccess: { or: [{ roles: ['owner'] }, { userRole: ['admin'] }] }\n\n// Platform admins see SSNs across every org\nmasking: { ssn: { type: 'ssn', show: { userRole: ['admin'] } } }\n```\n\n`userRole` works everywhere `Access` is accepted — CRUD, actions, views, masking, and inside `or`/`and` combinators. See [Access - userRole vs roles](/compiler/definitions/access#userrole-vs-roles).\n\n### Fix: `ReferenceError: customAlphabet is not defined` in generated POST handlers\n\nProjects with `providers.database.config.generateId: \"short\"` (or `\"nanoid\"` / `\"cuid\"`) compiled routes that called the ID helper but never imported it. Every generated `src/features/**/*.routes.ts` had `customAlphabet('0123...', 6)()` in its POST body but no matching `import { customAlphabet } from 'nanoid';` at the top of the file. Every `POST /api/v1/<resource>` and batch-create returned `500` with `ReferenceError: customAlphabet is not defined` on the first write.\n\nThe compiler now emits the correct import alongside the ID expression for all three modes: `nanoid`, `customAlphabet`, and `createId` from `@paralleldrive/cuid2`.\n\nNo config changes required — recompile to pick up the fix.\n\n### Fix: Dangling `export const` in generated `actions.ts` breaks `tsc`\n\nWhen a feature authored actions as `export const xActions = defineActions(...)` (instead of `export default defineActions(...)`), the compiler's preamble extractor leaked the assignment's left-hand side into the generated `src/features/<feature>/actions.ts`. The output contained a dangling `export const xActions =` with no right-hand side, and `tsc --noEmit` failed with `TS1109: Expression expected`. Runtime happened to work because the unused placeholder was never evaluated, but typecheck was red.\n\nThe preamble extractor now anchors its boundary to the start of the top-level statement containing `defineActions(...)`, covering `export default`, `export const X =`, `const X =`, and bare call forms. Local Zod helper declarations above the call continue to be preserved.\n\n### Fix: Files worker `database_id` reverted to `\"local-files\"` on every compile\n\nProjects using the two-worker R2 architecture had their files worker's `wrangler.toml` (`apps/backend/cloudflare-workers/files/wrangler.toml`) rewritten with `database_id = \"local-files\"` on every `quickback compile`, even when `providers.database.config.filesDatabaseId` was set to a real D1 UUID. The main worker's binding was correct — only the files worker fell through. Remote deploys of the files worker bound to a non-existent D1, so file serving and access-control reads failed with a binding error.\n\nThe files-worker wrangler generator now reads `filesDatabaseId` (and `filesDatabaseName`) from `providers.database.config` as a fallback when they aren't set on `providers.fileStorage.config`, matching the precedence chain already used by the main worker. Local dev is unaffected — `wrangler dev --local` uses `.wrangler/state/` regardless of the configured ID.\n\nNo config changes required — recompile and redeploy the files worker.\n\n---\n\n## v0.8.6 — April 16, 2026\n\n### Fix: Audit columns silently dropped from tables with a same-line index callback\n\nTables authored with the composite-index shape Drizzle / prettier produces —\n\n```ts\nexport const episodeTags = sqliteTable(\"episode_tags\", {\n id: text(\"id\").primaryKey(),\n episodeId: text(\"episode_id\").notNull(),\n tagId: text(\"tag_id\").notNull(),\n}, (t) => [ // <-- \"}, (t) =>\" on one line\n uniqueIndex(\"episode_tag_unique\").on(t.episodeId, t.tagId),\n]);\n```\n\nnever received audit field injection. A regex in `injectAuditFields` required a literal `\\n` between the columns-object `},` and the `(t) =>` index callback, so same-line closers were silently skipped and the function returned the source unchanged. drizzle-kit then diffed the audit-less schema against the previous snapshot and emitted `ALTER TABLE ... DROP COLUMN created_at/modified_at/deleted_at/created_by/modified_by/deleted_by` for every affected table. Any project that applied those migrations had production CRUD return `500` because the generated firewall helper still referenced `deletedAt`.\n\nThe regex is now whitespace-flexible and the identifier class accepts any valid JS identifier (`t`, `table`, `_t`, `tbl2`). A defensive guard throws at compile time if all three terminator patterns fail on a recognizable Drizzle table — no more silent drops.\n\n**Recovery path:**\n\n- Most projects: recompile. drizzle-kit will detect the audit columns are missing from the DB snapshot and emit an `ADD COLUMN` migration to restore them. Apply it.\n- Projects that already hand-patched their schema and ran a manual `ADD COLUMN` migration (like the `podcast-app` workaround in commit `98d8758`): the next compile will regenerate a matching `ADD COLUMN` migration that will fail with \"duplicate column name\" against a DB that already has the columns. Mark the new migration as applied without running it (e.g. `INSERT INTO __drizzle_migrations` in the features DB) or hand-edit the generated SQL to a no-op, then continue normally.\n\n### Fix: `firewall.exception` generated `isNull(<table>.deletedAt)` against a missing column\n\nResources with `firewall: { exception: true }` always emitted `return isNull(<table>.deletedAt);` inside `buildFirewallConditions()`, regardless of whether the table actually had a `deletedAt` column. Projects that disabled audit injection globally (`compiler.features.auditFields: false`) or authored a schema without `deletedAt` ended up with Drizzle resolving `<table>.deletedAt` to `undefined` at query time — every `GET /api/v1/<resource>` returned `500`.\n\nThe three concerns are now fully independent:\n\n- **`firewall.exception: true`** — only disables tenant scoping (org/user/team `WHERE` clauses). It does not gate audit fields or soft-delete.\n- **Audit fields** — always injected unless globally opted out. Unchanged.\n- **Soft-delete filter** — emitted only when the schema actually has `deletedAt` *or* the user explicitly set `firewall.softDelete`.\n\nIn the default configuration (audit injection on), behavior is unchanged: exception resources still filter `deletedAt IS NULL`. Only the broken case changes — exception resources on a schema without `deletedAt` now return `undefined` (no firewall), matching the column reality.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.4 — April 14, 2026\n\n### New `generateId: \"short\"` Strategy\n\nAdded a compact ID option for tables where short, shareable codes matter more than collision resistance at scale:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n generateId: \"short\",\n }),\n}\n```\n\nGenerates 6-character alphanumeric IDs (e.g. `a3F9xK`) using nanoid's `customAlphabet` with the full 62-char alphabet (`0-9A-Za-z`). Requires the `nanoid` package in your project (same as the existing `\"nanoid\"` strategy).\n\n**When to use:** room codes, invite links, share URLs, ephemeral records — anywhere the ID appears in a URL or needs to be human-typeable.\n\n**When not to use:** high-volume tables. 62^6 ≈ 56.8B combinations means ~238K rows before a 50% collision probability (birthday bound). For large tables stick with `\"uuid\"`, `\"cuid\"`, or `\"prefixed\"`.\n\nSee [Providers - ID Generation Options](/compiler/config/providers#id-generation-options) for the full list of strategies.\n\n---\n\n## v0.8.3 — April 14, 2026\n\n### Fix: `wrangler.toml` Route Placement and Binding IDs\n\nTwo bugs in the generated `wrangler.toml` that blocked production deployment without manual edits:\n\n**Routes were nested under `[dev]`.** The `routes = [...]` array was emitted after the `[dev]` section header, so TOML parsed it as `dev.routes` and wrangler ignored the custom domain (warning: `Unexpected fields found in dev field: \"routes\"`). Routes now emit as a top-level key.\n\n**D1 and KV bindings used placeholder IDs.** Despite `databaseId`, `filesDatabaseId`, and `kvId` being set in the quickback config, the generated `wrangler.toml` wrote `\"local-features\"`, `\"local-files\"`, and `\"local\"` instead of the real UUIDs. The compiler now resolves IDs from multiple config sources:\n\n| Binding | Config sources checked (in order) |\n|---------|-----------------------------------|\n| `AUTH_DB` | `database.config.authDatabaseId` |\n| `DB` | `database.config.featuresDatabaseId`, `database.config.databaseId` |\n| `FILES_DB` | `fileStorage.config.filesDatabaseId`, `database.config.filesDatabaseId` |\n| `KV` | `database.config.kvNamespaceId`, `storage.config.namespaceId`, `auth.config.kvId` |\n\nSee [Providers - Database Options](/compiler/config/providers#database-options) for the full list of supported ID properties.\n\n### Fix: Account SPA Post-Login Redirect on Unified Domain\n\nWhen the Account SPA was served at `/account/` on the unified quickback domain (e.g. `secure.example.com/account/`), post-login redirects dropped the basepath and sent users to `/dashboard` instead of `/account/dashboard`. Sign-out redirects had the same issue.\n\nThe SPA now shares a basepath module across the router and all raw `window.location.href` assignments, so login, signup, email OTP, welcome, and sign-out flows all stay under the correct path prefix regardless of whether the SPA is on the unified domain or its own dedicated auth subdomain.\n\nNo config changes required — recompile to pick up the fix.\n\n---\n\n## v0.8.2 — April 11, 2026\n\n### Catch-All `VITE_QUICKBACK_URL` Environment Variable\n\nInstead of setting four separate URL env vars, you can now point at a single Quickback origin:\n\n```bash\n# One variable — done.\nVITE_QUICKBACK_URL=https://secure.example.com\n```\n\nWhen set, it's used as a fallback for the individual URLs:\n\n| Individual var (explicit) | Fallback when unset |\n|---|---|\n| `VITE_QUICKBACK_API_URL` | `${VITE_QUICKBACK_URL}` |\n| `VITE_QUICKBACK_ACCOUNT_URL` | `${VITE_QUICKBACK_URL}/account` |\n| `VITE_QUICKBACK_CMS_URL` | `${VITE_QUICKBACK_URL}/cms` |\n\n`VITE_QUICKBACK_APP_URL` stays independent — it points at the tenant's own frontend, not the Quickback server.\n\n**Non-breaking.** Individual vars still take precedence when set, so existing configurations work unchanged. The compiler now also emits `VITE_QUICKBACK_URL` into the generated SPA `.env` files, and library users can set `__QUICKBACK_URL__` on `globalThis` for the same effect.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n---\n\n## v0.8.1 — April 9, 2026\n\n### Role Hierarchy with `+` Suffix\n\nYou can now define a role hierarchy in your config and use the `+` suffix in access rules to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nauth: {\n roleHierarchy: ['member', 'admin', 'owner'],\n}\n\n// In resource definitions\ncrud: {\n list: { access: { roles: [\"member+\"] } }, // member, admin, owner\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only\n}\n```\n\nRoles are expanded at compile time. No `+` = exact match. See [Access - Role Hierarchy](/compiler/definitions/access#role-hierarchy) for details.\n\n---\n\n## v0.8.0 — April 9, 2026\n\n### Breaking: VITE URL Environment Variables Renamed\n\nAll Quickback-generated URL environment variables are now namespaced under `VITE_QUICKBACK_*` to avoid collisions with other Vite projects.\n\n| Old | New |\n|-----|-----|\n| `VITE_API_URL` | `VITE_QUICKBACK_API_URL` |\n| `VITE_ACCOUNT_URL` | `VITE_QUICKBACK_ACCOUNT_URL` |\n| `VITE_APP_URL` | `VITE_QUICKBACK_APP_URL` |\n| `VITE_CMS_URL` | `VITE_QUICKBACK_CMS_URL` |\n\n**Non-URL variables are unchanged:** `VITE_ENABLE_*` feature flags, branding vars (`VITE_APP_NAME`, etc.), and `VITE_STRIPE_PUBLISHABLE_KEY` stay as-is.\n\n**Action required:**\n- **Compiled projects** — re-run `quickback compile`. The compiler generates the new names automatically.\n- **Standalone deploys** — update `.env`, `.env.production`, and `wrangler.toml` files manually.\n- **Library users** — the `__QUICKBACK_API_URL__` / `__QUICKBACK_APP_URL__` globalThis names are unchanged, but if you pipe Vite env vars into them, update the var names.\n\nSee [Environment Variables](/stack/account-ui/environment-variables) for the full reference.\n\n### CMS Access Control\n\nThe `cms.access` config option now enforces access at the CMS level, not just link visibility in Account UI.\n\n```typescript\ncms: { access: \"admin\" }\n```\n\nWhen set to `\"admin\"`, non-admin users (`user.role !== \"admin\"`) see an \"Access Denied\" screen with a sign-out button instead of the CMS. When set to `\"user\"` (the default), any authenticated user can access the CMS.\n\nSee [CMS Connecting](/stack/cms/connecting) and [Compiler Config](/compiler/config) for details.\n\n### SPA Sub-Route Fix\n\nFixed a bug where hard-refreshing or directly navigating to SPA sub-routes (e.g., `/account/profile`, `/cms/tables/users`) returned a blank white screen. The Worker now correctly serves `index.html` for all SPA paths, allowing the client-side router to handle routing.\n\n---\n\n## v0.5.11 — February 24, 2026\n\n### Email OTP & Auth Fixes\n\n- Fixed email-OTP magic links not working correctly\n- Removed deprecated `/internal/validate` endpoint — use standard Better Auth session validation instead\n- Auth is now required for all API routes when running locally (previously some routes were unprotected in dev)\n\n### Multiple Table Exports Fix\n\n- Fixed a compiler error when a single file exports multiple Drizzle tables alongside a `defineTable()` default export\n- The CLI now properly detects and reports this with a clear error message pointing to the fix\n\n### Headless Drizzle Rename Hints\n\n- Added `compiler.migrations.renames` configuration for CI/CD environments where Drizzle's interactive rename prompts would block compilation\n- Compile errors now include explicit rename key paths and fail fast on malformed rename config keys\n- See [Configuration](/compiler/config) for details\n\n### Security Contract Report Artifacts\n\n- Added generated security contract artifacts to compiler output:\n - `reports/security-contracts.report.json`\n - `reports/security-contracts.report.sig.json`\n- Added config-driven signing controls:\n - `compiler.securityContracts.report.signature.enabled`\n - `compiler.securityContracts.report.signature.required`\n - `compiler.securityContracts.report.signature.key` / `keyEnv` / `keyId`\n- Missing required signing keys now fail loudly with explicit remediation guidance\n- Added strict config validation for report/signature paths and signing options\n\n### Mandatory Unsafe Action Audit Trail\n\n- Added structured unsafe action config (`unsafe: { reason, adminOnly, crossTenant, targetScope }`)\n- Cross-tenant unsafe actions now require Better Auth authentication plus platform admin role (`ctx.userRole === \"admin\"`)\n- Added mandatory audit logging for unsafe cross-tenant actions (success, denial, and error paths)\n- Cloudflare output now includes optional `AUDIT_DB` wiring, `drizzle.audit.config.ts`, and `db:migrate:audit:*` scripts when unsafe actions are present\n- Added compile-time raw SQL guard for actions and handlers (`allowRawSql: true` required per action)\n\n---\n\n## v0.5.10 — February 19, 2026\n\n### Compiler Page Parsing & CLI Output\n\n- Improved compiler page parsing for `definePage()` definitions\n- Better CLI output formatting during compilation\n- Added `apiPath` to schema registry for CMS integration\n\n### Bug Fixes\n\n- Fixed hyphenated action names not being properly quoted in generated code (e.g., `mark-complete` now generates valid JavaScript)\n- API key authentication (`x-api-key` header) is now handled separately from session tokens (`Bearer` header)\n\n---\n\n## v0.5.9 — February 16, 2026\n\n### CMS Pages & CLI Page Support\n\n- Added `definePage()` support for CMS-managed pages\n- Auth middleware improvements for page routes\n- CLI now supports page definitions alongside table and action definitions\n\n---\n\n## v0.5.8 — February 14, 2026\n\n### CMS App\n\n- Introduced the Quickback CMS — a schema-driven admin panel that connects to your generated API\n- CMS namespace added to actions for admin-specific operations\n- Fixed `guard` → `access` naming inconsistency in CMS action definitions\n\n### Schema Registry & Firewall Improvements\n\n- Added schema registry generator — the compiler now outputs a JSON schema registry used by the CMS\n- Firewall error modes: choose between `reveal` (403 with details) and `hide` (opaque 404) for security-sensitive deployments\n\n### Bug Fixes\n\n- Fixed anonymous user email format generation\n- Organization selector improvements in Account UI\n- Config validation now catches more errors at compile time\n- Better CRUD error handling with structured error responses\n- Fixed masking to use representative star counts instead of fixed formatting\n\n---\n\n## v0.5.7 — February 12, 2026\n\n### Scoped Database for Actions\n\nActions now receive a **security-scoped database** instead of a raw Drizzle instance. The compiler generates a proxy wrapper that automatically enforces org isolation, owner filtering, and soft-delete visibility — the same protections that CRUD routes have always had.\n\nThe scoped DB uses duck-typed column detection at runtime:\n\n| Column Detected | SELECT / UPDATE / DELETE | INSERT |\n|---|---|---|\n| `organizationId` | Adds `WHERE organizationId = ?` | Auto-injects `organizationId` from context |\n| `ownerId` | Adds `WHERE ownerId = ?` | Auto-injects `ownerId` from context |\n| `deletedAt` | Adds `WHERE deletedAt IS NULL` | — |\n\nThis means **every action is secure by default** — no manual `WHERE` clauses needed.\n\n```typescript\ndefineActions(todos, {\n complete: {\n type: \"record\",\n execute: async ({ db, ctx, record, input }) => {\n // db is scoped — only sees records in user's org, excludes soft-deleted\n const siblings = await db.select().from(todos);\n // ↑ automatically filtered to ctx.activeOrgId + deletedAt IS NULL\n },\n },\n});\n```\n\n#### Unsafe Mode\n\nActions that intentionally need to bypass security (admin reports, cross-org queries, migrations) can declare `unsafe: true` to receive a raw, unscoped database handle:\n\n```typescript\ndefineActions(analytics, {\n globalReport: {\n unsafe: true,\n execute: async ({ db, rawDb, ctx, input }) => {\n // db → still scoped (safety net)\n // rawDb → bypasses all security filters\n const allOrgs = await rawDb.select().from(organizations);\n },\n },\n});\n```\n\nWithout `unsafe: true`, `rawDb` is `undefined`.\n\n**Related docs:** [Actions](/compiler/definitions/actions), [Actions API](/compiler/targets/hono-api/using-the-api/actions-api)\n\n---\n\n### Cascading Soft Delete\n\nSoft-deleting a parent record now **automatically cascades** to child and junction tables within the same feature. The compiler detects foreign key references at build time and generates cascade UPDATE statements.\n\n```\nDELETE /api/v1/projects/:id\n```\n\nGenerated behavior:\n```typescript\n// 1. Soft delete the parent\nawait db.update(projects)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projects.id, id));\n\n// 2. Auto-cascade to children (compiler-generated)\nawait db.update(projectMembers)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectMembers.projectId, id));\n\nawait db.update(projectTasks)\n .set({ deletedAt: now, deletedBy: userId })\n .where(eq(projectTasks.projectId, id));\n```\n\nRules:\n- Only applies to **soft delete** (the default). Hard delete relies on database-level `ON DELETE CASCADE`.\n- Only cascades within the **same feature** — cross-feature references are not affected.\n- Child tables must have `deletedAt` / `deletedBy` columns (auto-added by the compiler's audit fields).\n\n**Related docs:** [Actions API — Cascading Soft Delete](/compiler/targets/hono-api/using-the-api/actions-api#cascading-soft-delete)\n\n---\n\n### Advanced Query Parameters\n\nNew query parameter capabilities for all list endpoints:\n\n- **Field selection** — `?fields=id,name,status` returns only the columns you need\n- **Multi-sort** — `?sort=status:asc,createdAt:desc` sorts by multiple fields\n- **Total count** — `?count=true` returns total matching records in response headers (`X-Total-Count`)\n- **Full-text search** — `?search=keyword` searches across all text columns\n\n```bash\n# Get only names and statuses, sorted by status then date, with total count\nGET /api/v1/todos?fields=id,name,status&sort=status:asc,createdAt:desc&count=true\n\n# Search across all text fields\nGET /api/v1/todos?search=urgent\n```\n\n**Related docs:** [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params)\n\n---\n\n### Audit Field Improvements\n\n- `deletedAt` and `deletedBy` fields are now **always injected** by the compiler for tables with soft delete enabled — no need to define them in your schema\n- All audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are auto-managed\n\n---\n\n## v0.5.6 — February 8, 2026\n\n### Database Naming Conventions\n\n- Default table and column naming changed to **snake_case** with `usePlurals: false`\n- Table names derived from generated Better Auth schema for consistency\n- Removed legacy single-database mode — split databases (auth + features) is now the standard\n\n### Auth Variable Shadowing Fix\n\n- Fixed `member` variable in auth middleware that shadowed the Drizzle `member` table import\n- Renamed to `sessionMember` to avoid conflicts in generated routes\n\n---\n\n## v0.5.5 — February 5, 2026\n\n### Better Auth Plugins\n\n- Published `@quickback-dev/better-auth-upgrade-anonymous` v1.1.0 — post-passkey email collection flow\n- Published `@quickback-dev/better-auth-combo-auth` — combined email + password + OTP authentication\n- Published `@quickback-dev/better-auth-aws-ses` — AWS SES email provider for Better Auth\n\n### OpenAPI Spec Generation\n\n- Generated APIs now include a full OpenAPI specification at `/openapi.json`\n- Better Auth endpoints included in the spec\n- Runtime route: `GET /openapi.json`\n\n### Security Hardening\n\n- Global error handler prevents leaking internal error details\n- Security headers middleware (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)\n- `BETTER_AUTH_SECRET` properly passed to generated config\n\n---\n\n## v0.5.4 — January 30, 2026\n\n### Account UI\n\n- Pre-built authentication UI deployed as Cloudflare Workers\n- Features: sessions, organizations, passkeys, passwordless, admin panel, API keys\n- Dual-mode: standalone (degit template) or embedded with Quickback projects\n\n### Webhook System\n\n- Inbound webhook endpoints with signature verification\n- Outbound webhooks via Cloudflare Queues with automatic retries\n- Configurable per-feature webhook events\n\n### Realtime & Vector Search\n\n- Durable Objects + WebSocket realtime subscriptions\n- Vector embeddings via Cloudflare Vectorize\n- KV and R2 storage integrations\n\n---\n\n## v0.5.0 — January 2026\n\n### Initial Release\n\n- **Quickback Compiler** — TypeScript-first backend compiler\n- **Four Security Pillars** — Firewall, Access, Guards, Masking\n- **`defineTable()`** — Schema + security configuration in a single file\n- **Templates** — Cloudflare Workers, Bun standalone, B2B SaaS\n- **Cloud Compiler** — Remote compilation via `compiler.quickback.dev`\n- **CLI** — `quickback create`, `quickback compile`, `quickback init`\n- **Better Auth Integration** — Organizations, roles, sessions\n- **Drizzle ORM** — Schema-first with automatic migrations\n- **Cloudflare D1** — Split database support (auth + features)"
|
|
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)."
|
|
7
7
|
},
|
|
8
8
|
"compiler/claude-code-skill": {
|
|
9
9
|
"title": "AI Developer Tools",
|
|
@@ -15,7 +15,7 @@ export const DOCS = {
|
|
|
15
15
|
},
|
|
16
16
|
"compiler/cloud-compiler/cli": {
|
|
17
17
|
"title": "CLI Reference",
|
|
18
|
-
"content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Create a Project\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare`
|
|
18
|
+
"content": "The Quickback CLI is the fastest way to create, compile, and manage your backend projects.\n\n## Installation\n\n```bash\n# One-shot via npx — recommended for first run\nnpx @quickback-dev/cli start\n\n# Or install globally for repeat use\nnpm install -g @quickback-dev/cli\n```\n\n## Commands\n\n### Start a Project (interactive)\n\n```bash\nquickback start\n```\n\nInteractive onboarding designed for new users. No flags required.\n\n- Prompts for a template (curated free-tier picker: `cloudflare`, `todos`, `blog`, `empty`)\n- Prompts for a project name (defaults to the current directory's name if empty)\n- Auto-detects whether to scaffold in-place or create a `./<name>/` subdirectory\n- Defers login until just before the compile step — cancel at the auth prompt and the scaffold stays on disk, ready for `quickback compile` later\n\n**Example:**\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n### Create a Project (scriptable)\n\n```bash\nquickback create <template> <name>\n```\n\n**Templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold (free)\n- `todos` — Working todos example with masking + actions + a named view (free)\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes (free)\n- `empty` — Cloudflare scaffold, no example features (free)\n- `saas` — Full B2B SaaS: orgs, R2 file storage, webhooks, split databases, realtime (pro)\n\n**Example:**\n```bash\nquickback create todos my-app\n```\n\nThis scaffolds a complete project with:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Example feature with full security configuration (for `todos` / `blog` / `saas`)\n\nSee the [Templates](/compiler/getting-started/templates) page for a deeper guide on choosing between them.\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nReads your definitions and generates:\n- Database migrations (Drizzle)\n- API route handlers (Hono)\n- TypeScript client SDK\n- OpenAPI specification\n\nRun this after making changes to your definitions.\n\n#### Generated `src/` is hermetic\n\nEvery file under `src/` carries a `Generated by quickback.dev` header and is owned by the compiler. Before each compile writes its output, the CLI:\n\n1. Snapshots the existing `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` (a plain recursive copy — `cp -R` semantics, no compression).\n2. Wipes `src/` entirely.\n3. Writes the fresh manifest from the compiler.\n\nThis prevents stale output: removed features stop leaving orphan folders, deleted SPA assets with old content hashes get cleared, and `.DS_Store` files don't keep retired directories alive.\n\nThe most recent **3** archives are retained (older ones are pruned automatically). If a compile produces unexpected output, your last-known-good tree is sitting in `quickback/.archives/` ready to grep or copy back:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n```\n\nAs a safety net, the wipe is **skipped** when the manifest contains zero files for the target directory — that's almost always an upstream compile bug, and we'd rather keep your last working tree than overwrite it with nothing.\n\n### View Documentation\n\n```bash\nquickback docs # List available topics\nquickback docs <topic> # Show documentation for a topic\n```\n\n**Available topics:**\n- `firewall` - Data isolation layer\n- `access` - Role-based permissions\n- `guards` - Field protection\n- `masking` - PII redaction\n- `actions` - Custom business logic\n- `api` - CRUD endpoints reference\n- `config` - Configuration reference\n- `features` - Schema definitions\n\nDocumentation is bundled with the CLI and works offline.\n\n### Manage Claude Code Skill\n\n```bash\nquickback claude install # Interactive install\nquickback claude install --global # Install to ~/.claude/skills/\nquickback claude install --local # Install to ./quickback/.claude/\nquickback claude update # Update to latest version\nquickback claude remove # Remove installed skill\nquickback claude status # Check installation status\n```\n\nThe Quickback skill for Claude Code provides AI assistance for:\n- Creating resource definitions with proper security layers\n- Configuring Firewall, Access, Guards, and Masking\n- Debugging configuration issues\n- Understanding security patterns\n\n## Authentication\n\n### Login\n\n```bash\nquickback login\n```\n\nUses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) (RFC 8628) to authenticate securely without exposing tokens in URLs.\n\n**How it works:**\n\n1. The CLI requests a one-time device code from the Quickback API.\n2. A code is displayed in your terminal (e.g., `AUL8-H93S`).\n3. Your browser opens to the Quickback account page where you approve the code.\n4. The CLI detects approval and exchanges it for a session token.\n5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.\n6. Credentials are stored locally.\n\n```\n$ quickback login\n\n🔐 Quickback Login\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n Your code: AUL8-H93S\n\n Visit: https://account.quickback.dev/cli/authorize\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n✓ Login successful!\nWelcome, Paul Stenhouse!\n\nUsing organization: Acme\n✓ Active organization: Acme\n```\n\nThis flow works in headless environments (SSH, containers, WSL) since it doesn't require a localhost callback.\n\n### Logout\n\n```bash\nquickback logout\n```\n\nClears stored credentials from `~/.quickback/credentials.json`.\n\n### Check Auth Status\n\n```bash\nquickback whoami\n```\n\nShows the currently authenticated user, organization, and token expiration.\n\n### Credential Storage\n\nCredentials are stored at `~/.quickback/credentials.json`:\n\n```json\n{\n \"token\": \"...\",\n \"user\": {\n \"id\": \"...\",\n \"email\": \"paul@example.com\",\n \"name\": \"Paul Stenhouse\",\n \"tier\": \"free\"\n },\n \"expiresAt\": \"2026-02-16T01:42:21.519Z\",\n \"organization\": {\n \"id\": \"...\",\n \"name\": \"Acme\",\n \"slug\": \"acme\"\n }\n}\n```\n\nSessions expire after 7 days. Run `quickback login` again to re-authenticate.\n\n### Organizations\n\nAfter login, the CLI auto-selects your organization:\n- **One organization** - automatically set as active.\n- **Multiple organizations** - you're prompted to choose one.\n\nThe active organization is stored in your credentials and sent with compile requests, so the compiler knows which org context to use.\n\n## Quick Start\n\n```bash\n# 1. Start a new project (interactive — picks template, scaffolds,\n# prompts for login only when needed)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n\n# 2. Run locally\nnpm run dev\n```\n\nOr the scriptable form:\n\n```bash\n# 1. Create the project (scaffolds + compiles + installs)\nquickback create todos my-app # prompts for login on first compile\ncd my-app\n\n# 2. Run\nnpm run dev\n\n# 3. Recompile after editing definitions\nquickback compile\n```\n\n## Options\n\n| Flag | Description |\n|------|-------------|\n| `-v, --version` | Show version number |\n| `-h, --help` | Show help message |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `QUICKBACK_API_KEY` | API key for authentication (alternative to `quickback login`) |\n| `QUICKBACK_API_URL` | Override compiler API URL |\n\n### API Key Authentication\n\nUse an API key instead of interactive login. Useful for CI/CD pipelines and automated workflows:\n\n```bash\n# Pass API key for a single command\nQUICKBACK_API_KEY=your_api_key quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_KEY=your_api_key\nquickback compile\n```\n\nThe API key takes precedence over stored credentials from `quickback login`.\n\nYou can create API keys from your [Quickback account](https://account.quickback.dev/profile). Each key is scoped to your organization.\n\n### Custom Compiler URL\n\nPoint the CLI to a different compiler (local or custom):\n\n```bash\n# Use a local compiler\nQUICKBACK_API_URL=http://localhost:3020 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3020\nquickback compile\n```\n\nSee [Local Compiler](/compiler/cloud-compiler/local-compiler) for running the compiler locally with Docker.\n\n## Troubleshooting\n\n### \"Command not found: quickback\"\n\nMake sure the CLI is installed globally:\n```bash\nnpm install -g @quickback-dev/cli\n```\n\nOr use npx (no global install needed):\n```bash\nnpx @quickback-dev/cli start\n```\n\n### Compile errors\n\n1. Check your `quickback.config.ts` exists and is valid\n2. Ensure all tables in `quickback/features/` have valid exports\n3. Run `quickback compile` with `--verbose` for detailed output\n4. For rename-related Drizzle failures in CI/headless runs, configure `compiler.migrations.renames` in `quickback.config.ts`\n\n### Authentication issues\n\nClear credentials and re-authenticate:\n```bash\nquickback logout\nquickback login\n```\n\n### \"Could not load organizations\"\n\nThis can happen if your session token expired or if the API is temporarily unavailable. Re-login:\n```bash\nquickback logout\nquickback login\n```"
|
|
19
19
|
},
|
|
20
20
|
"compiler/cloud-compiler/endpoints": {
|
|
21
21
|
"title": "Endpoints",
|
|
@@ -23,7 +23,7 @@ export const DOCS = {
|
|
|
23
23
|
},
|
|
24
24
|
"compiler/cloud-compiler": {
|
|
25
25
|
"title": "Cloud Compiler",
|
|
26
|
-
"content": "Quickback offers a hosted compiler at `https://compiler.quickback.dev`. The CLI uses it to turn your definitions into a complete backend.\n\n## How It Works\n\n```\n┌──────────────┐ ┌──────────────────────┐\n│ quickback │ POST │ compiler.quickback │\n│ CLI │────────▶│ .dev/compile │\n│ │ │ │\n│ Sends: │ │ Returns: │\n│ - config │ │ - Hono routes │\n│ - features │◀────────│ - Drizzle migrations │\n│ - meta │ │ - TypeScript SDK │\n└──────────────┘ └──────────────────────┘\n```\n\n1. The CLI reads your `quickback.config.ts` and feature definitions.\n2. It sends them to the cloud compiler as a JSON payload.\n3. The compiler generates all backend files (routes, migrations, SDK, OpenAPI spec).\n4. The CLI writes the generated files to your project.\n\n## Quick Start\n\n```bash\n# 1.
|
|
26
|
+
"content": "Quickback offers a hosted compiler at `https://compiler.quickback.dev`. The CLI uses it to turn your definitions into a complete backend.\n\n## How It Works\n\n```\n┌──────────────┐ ┌──────────────────────┐\n│ quickback │ POST │ compiler.quickback │\n│ CLI │────────▶│ .dev/compile │\n│ │ │ │\n│ Sends: │ │ Returns: │\n│ - config │ │ - Hono routes │\n│ - features │◀────────│ - Drizzle migrations │\n│ - meta │ │ - TypeScript SDK │\n└──────────────┘ └──────────────────────┘\n```\n\n1. The CLI reads your `quickback.config.ts` and feature definitions.\n2. It sends them to the cloud compiler as a JSON payload.\n3. The compiler generates all backend files (routes, migrations, SDK, OpenAPI spec).\n4. The CLI writes the generated files to your project.\n\n## Quick Start\n\n```bash\n# 1. Scaffold + compile interactively\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks through template selection, scaffolding, login (only when needed), and the first compile in one flow. Or do it scriptably:\n\n```bash\nnpm install -g @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\nquickback compile # prompts for login on the first run\n```\n\n## Existing Databases\n\nWhen recompiling an existing project, the CLI automatically sends your Drizzle meta files so the compiler generates **incremental** migrations instead of fresh `CREATE TABLE` statements.\n\nMeta files are loaded from `<project>/quickback/drizzle/` only — Quickback owns this state and never reads from a project-root `drizzle/` folder:\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\nMigration and report artifacts are written to the `quickback/` state directory:\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\nNo extra configuration needed — the CLI handles this automatically.\n\n## Next Steps\n\n- [CLI Reference](/compiler/cloud-compiler/cli) — All CLI commands\n- [Authentication](/compiler/cloud-compiler/authentication) — Login flow and API keys\n- [Endpoints](/compiler/cloud-compiler/endpoints) — Compiler API reference\n- [Troubleshooting](/compiler/cloud-compiler/troubleshooting) — Common issues\n- [Local Compiler](/compiler/cloud-compiler/local-compiler) — Run the compiler locally"
|
|
27
27
|
},
|
|
28
28
|
"compiler/cloud-compiler/local-compiler": {
|
|
29
29
|
"title": "Local Compiler",
|
|
@@ -59,7 +59,7 @@ export const DOCS = {
|
|
|
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## 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| `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### 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\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 |"
|
|
63
63
|
},
|
|
64
64
|
"compiler/config/security": {
|
|
65
65
|
"title": "Security Headers",
|
|
@@ -67,7 +67,7 @@ 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 | `/admin/v1/organizations` generated | Skipped |\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
|
|
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 | `/admin/v1/organizations` generated | Skipped |\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",
|
|
@@ -75,7 +75,7 @@ export const DOCS = {
|
|
|
75
75
|
},
|
|
76
76
|
"compiler/definitions/access": {
|
|
77
77
|
"title": "Access - Role & Condition-Based Access Control",
|
|
78
|
-
"content": "Define who can perform CRUD operations and under what conditions.\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable('applications', {\n id: text('id').primaryKey(),\n candidateId: text('candidate_id').notNull(),\n jobId: text('job_id').notNull(),\n stage: text('stage').notNull(),\n notes: text('notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest → highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncrud: {\n create: { access: { roles: [\"admin+\"] } }, // admin, owner\n delete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n}\n```\n\nThe `+` suffix expands at compile time — `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic — user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column — independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused — get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership (multi-tenant) or single-tenant mirror of `user.role` | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth admin plugin) | `\"user\"`, `\"admin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" — not a platform-wide admin.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want to let Better Auth system admins through regardless of org membership (e.g., for support/ops), use `userRole: [\"admin\"]`.\n\nIn single-tenant mode (`features.organizations: false`), `ctx.roles` mirrors `user.role`, so `roles: [\"admin\"]` and `userRole: [\"admin\"]` behave the same. Using `userRole` in single-tenant code is still preferred — it documents intent and keeps the gate correct if you later enable orgs.\n\n### When to use `userRole`\n\n```typescript\n// Platform admin can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['admin'] } },\n}\n\n// Support staff (user.role === 'admin') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['admin'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform admins\nread: { access: { userRole: ['admin'] } },\ncrud: {\n create: { access: { userRole: ['admin'] } },\n update: { access: { userRole: ['admin'] } },\n delete: { access: { userRole: ['admin'] } },\n}\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `\"user\"` and `\"admin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships five UPPERCASE role markers that are **not backed by a Better Auth role column** — they're system-level shortcuts handled directly by the compiler. The casing carries the boundary: UPPERCASE = pseudo-role (no plugin context required), lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === \"user\"`) |\n| `ADMIN` | required | Better Auth admin plugin **must** be enabled | `ctx.authenticated && ctx.userRole === \"admin\"` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list — they're OR'd together.\n\n#### `PUBLIC` — unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks — anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node — reads, CRUD writes (`crud.create`/`update`/`delete`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous CRUD endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** — data is scoped by the firewall (organization, owner, team)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** — using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.\n\n```typescript\n// Public listing page — anyone can browse, but scoped to an org\nexport default defineTable(listings, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"PUBLIC\"] } }, // Public browsing + detail\n crud: {\n create: { access: { roles: [\"admin\", \"member\"] } }, // Auth required to create\n },\n});\n```\n\n#### `AUTHENTICATED` — any signed-in user\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in user can hit, regardless of role or org membership. No plugin context required.\n\n```typescript\n// Public events feed — any signed-in user can list/read; anonymous gets 401\nread: { access: { roles: [\"AUTHENTICATED\"] } }\n```\n\n#### `USER` — per-user records\n\nUse `roles: [\"USER\"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.\n\n```typescript\n// \"My todos\" — each caller sees only their own rows\nexport default defineTable(todos, {\n firewall: [{ field: 'userId', equals: 'ctx.userId' }],\n read: { access: { roles: [\"USER\"] } },\n crud: {\n create: { access: { roles: [\"USER\"] } },\n update: { access: { roles: [\"USER\"] } },\n delete: { access: { roles: [\"USER\"] } },\n },\n});\n```\n\nIf you forget the `userId` firewall predicate, the compiler throws:\n\n> `roles: [\"USER\"]` requires the resource to be scoped per-user. Add a `userId` column (auto-scoped) or an explicit owner predicate. If you want any signed-in user to read all records, use `roles: [\"AUTHENTICATED\"]` instead.\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically — admins are excluded and should use `[\"USER\", \"ADMIN\"]` if the same route should serve both.\n\n#### `ADMIN` — Better Auth admin-plugin admins\n\nUse `roles: [\"ADMIN\"]` for system-administrator endpoints. **Requires the Better Auth admin plugin** so `user.role` exists. Compiles to `ctx.userRole === \"admin\"`.\n\n```typescript\n// Platform-admin-only audit log\nread: { access: { roles: [\"ADMIN\"] } }\n```\n\nWithout the admin plugin you get a compile error pointing you to either enable the plugin or use lowercase `roles: [\"admin\"]` (the org-membership admin role).\n\n#### `SYSADMIN` — cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins — the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a system admin can read\nread: { access: { roles: [\"USER\", \"ADMIN\"] } }\n\n// Org owner OR system admin\ndelete: { access: { roles: [\"owner\", \"ADMIN\"] } }\n```\n\n> Note: today, an `ADMIN` match still goes through the `userId` firewall scope on USER-scoped resources — admins see only records they own on those routes. Use `firewall: { exception: true }` on a separate admin-only route if you need cross-user visibility.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// System admin (requires admin plugin)\naccess: { roles: [\"ADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\naccess: { roles: [\"member+\"] } // expands to [\"member\", \"admin\", \"owner\"]\naccess: { roles: [\"admin+\"] } // expands to [\"admin\", \"owner\"]\naccess: { roles: [\"admin\"] } // exact match (no expansion)\n```\n\n```typescript\n// Field conditions - value can be string | number | boolean\ntype FieldCondition =\n | { equals: value | '$ctx.userId' | '$ctx.activeOrgId' }\n | { notEquals: value }\n | { in: value[] }\n | { notIn: value[] }\n | { lessThan: number }\n | { greaterThan: number }\n | { lessThanOrEqual: number }\n | { greaterThanOrEqual: number };\n```\n\n## Relationship-based authorization\n\nBeyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership (\"user is a confirmed guest of this event\") rather than an org/admin gate.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name string\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional filter\n },\n },\n roles: {\n guest: { via: 'guestOf' },\n // Composite: any guest OR an org owner/admin\n eventStaff: {\n or: [\n { via: 'guestOf' },\n { roles: ['admin', 'owner'] },\n ],\n },\n },\n },\n});\n```\n\n### Using relationship-roles in resources\n\nResource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.\n\n**Today (v1) this works on:**\n\n| Surface | Status | Notes |\n|---|---|---|\n| `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |\n| `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |\n| `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |\n| `masking.<field>.show` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — async/batched mask functions deferred |\n| `actions.<name>.access` `roles: ['guest']` | ⚠ Refused at compile | v1 limitation — explicit `relationshipBindings` deferred |\n\nFor the surfaces that are not yet supported, the compiler refuses at build time with a clear error pointing to a workaround. The runtime evaluator fails closed on relationship arms regardless, so silent grants are impossible.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // ← row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // ← who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern — \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" — is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` — a flat per-user table.\n- **A standalone action that walks the relationship table itself** — see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\n\nexport default defineAction({\n description: \"List events the caller is a confirmed guest of, across all tenants.\",\n path: '/my-events',\n method: 'GET',\n input: z.object({}),\n // Any signed-in user. Row visibility comes from the query, not the role.\n access: { roles: ['AUTHENTICATED'] },\n async execute({ db, ctx }) {\n // 1. Find every event the caller has a confirmed guest row for.\n const guestRows = await db\n .select({ eventId: guests.eventId })\n .from(guests)\n .where(\n and(\n eq(guests.userId, ctx.userId!),\n eq(guests.status, 'confirmed'),\n // guests.organizationId is NOT filtered here — that's the whole\n // point of the cross-tenant lane. The relationship row's org is\n // ambient information that this action explicitly traverses.\n )\n );\n\n if (guestRows.length === 0) return { events: [] };\n\n // 2. Pull the matching events. NOTE: this query also bypasses\n // `events.organizationId` scope — by design — so explicitly filter\n // out soft-deleted rows yourself if your `events` table uses them.\n const eventIds = guestRows.map((r) => r.eventId);\n const rows = await db\n .select()\n .from(events)\n .where(inArray(events.id, eventIds));\n\n return { events: rows };\n },\n});\n```\n\nWhy this is a standalone action and not a CRUD route:\n\n- **Tenant firewall would block it.** The default `firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }]` on `events` is correct for every other read — only the cross-tenant dashboard wants to step outside it, and that's a deliberate, explicit step taken in handler code.\n- **The join is the access control.** A relationship-role at the firewall layer can't express \"filter by this user's relationships, ignoring the org context.\" The handler does that join directly.\n- **Audit-logged automatically.** Standalone actions are mandatorily audit-logged in the runtime — the cross-tenant traversal is recorded with `ctx.userId`, IP, and timing.\n\nTwo important guardrails when you write one of these:\n\n1. **Always filter by `ctx.userId` in the relationship lookup.** If you accept a `userId` from the request body and trust it, you've built an IDOR. The example above uses `ctx.userId!` directly so the only events returned are the caller's.\n2. **You take responsibility for soft-delete and other invariants the firewall would otherwise apply.** Add the `deletedAt` filter, status checks, and any other row-level predicates by hand. The action is OUTSIDE the firewall pipeline by design — the cost is that you can't lean on the auto-applied predicates.\n\nIf you find yourself writing more than one of these per project, that's usually a signal to revisit the schema (could a user-owned `userEvents` materialized view replace the join?) rather than a sign Quickback should ship a higher-level abstraction. Cross-tenant lanes are intentionally explicit.\n\n### Compile-time refusals (consolidated)\n\nThe validator and resolver reject:\n\n- Unknown key in `authz` block (typo guard — `realtionships` would otherwise silently produce a permanently-denied role).\n- Reserved role-name (auth-provider-derived). Names like `guest`, `speaker`, `attendee` are free; `admin`/`owner`/`member` are reserved when the BA org plugin is on.\n- Cycle in role composition (`a → b → a`).\n- Relationship `from` references unknown table.\n- Relationship-role used on a resource missing the `resource.column`.\n- Relationship table with `firewall: { exception: true }` (would let cross-tenant grants slip through).\n- `lowering: 'session'` (reserved for v2 — staleness/invalidation ergonomics not yet shipped).\n- `+` hierarchy suffix on a relationship-role name (terminal, like pseudo-roles).\n- Relationship-roles in `masking.show` / `actions.access` (deferred surfaces — see the table above).\n\n## Read & CRUD Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under `crud:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.\n\n```typescript\nread: {\n // LIST + GET - GET /resource and GET /resource/:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25, // Default page size\n maxPageSize: 100, // Client can't exceed this\n views: { // Per-view field projections\n summary: {\n fields: ['id', 'candidateId', 'jobId', 'stage'],\n access: { roles: [\"interviewer\"] },\n },\n },\n}\n\ncrud: {\n // CREATE - POST /resource\n create: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] },\n defaults: { // Default values for new records\n stage: 'applied',\n },\n },\n\n // UPDATE - PATCH /resource/:id\n update: {\n access: {\n or: [\n { roles: [\"hiring-manager\", \"recruiter\"] },\n { roles: [\"interviewer\"], record: { stage: { equals: \"interview\" } } }\n ]\n },\n },\n\n // DELETE - DELETE /resource/:id\n delete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // 'soft' (default) or 'hard'\n },\n\n // PUT - PUT /resource/:id (only when generateId: false + guards: false)\n put: {\n access: { roles: [\"hiring-manager\", \"sync-service\"] },\n },\n}\n```\n\n## Evaluation Order\n\nGenerated `/:id` and batch handlers evaluate access in this fixed order:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nStep 2 closes the 404-vs-403 ID-probe channel: an unauthorized caller without\na matching role gets 403 before the database is touched, so they can't tell\napart \"row exists out-of-scope\" from \"row doesn't exist.\" A caller with the\nright role but the wrong tenant gets 403 by default (firewall reveals via\nthe access layer); set\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) to return an\nopaque 404 instead.\n\nFunction-form access (`access: async (ctx, record) => ...`) is opaque to\nthe pre-record phase and always passes there; it's fully evaluated post-record.\n\n## List Filtering (Query Parameters)\n\nThe LIST endpoint automatically supports filtering via query params:\n\n```\nGET /jobs?status=open # Exact match\nGET /jobs?salaryMin.gt=50000 # Greater than\nGET /jobs?salaryMin.gte=50000 # Greater than or equal\nGET /jobs?salaryMax.lt=200000 # Less than\nGET /jobs?salaryMax.lte=200000 # Less than or equal\nGET /jobs?status.ne=closed # Not equal\nGET /jobs?title.like=Engineer # Pattern match (LIKE %value%)\nGET /jobs?status.in=open,draft # IN clause\n```\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n## Sorting & Pagination\n\n```\nGET /jobs?sort=createdAt&order=desc # Sort by field\nGET /jobs?limit=25&offset=50 # Pagination\n```\n\n- **Default limit**: 50\n- **Max limit**: 100 (or `maxPageSize` if configured)\n- **Default order**: `asc`\n\n## Delete Modes\n\n```typescript\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"soft\", // Sets deletedAt/deletedBy, record stays in DB\n}\n\ndelete: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n mode: \"hard\", // Permanent deletion from database\n}\n```\n\n## Context Variables\n\nUse `$ctx.` prefix to reference context values in conditions:\n\n```typescript\n// User can only view their own records\naccess: {\n record: { userId: { equals: \"$ctx.userId\" } }\n}\n\n// Nested path support for complex context objects\naccess: {\n record: { ownerId: { equals: \"$ctx.user.id\" } }\n}\n```\n\n### AppContext Reference\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `$ctx.userId` | `string` | Current authenticated user's ID |\n| `$ctx.activeOrgId` | `string` | User's active organization ID |\n| `$ctx.activeTeamId` | `string \\| null` | User's active team ID (if applicable) |\n| `$ctx.roles` | `string[]` | User's roles in current context |\n| `$ctx.isAnonymous` | `boolean` | Whether user is anonymous |\n| `$ctx.user` | `object` | Full user object from auth provider |\n| `$ctx.user.id` | `string` | User ID (nested path example) |\n| `$ctx.user.email` | `string` | User's email address |\n| `$ctx.{property}` | `any` | Any custom context property |\n\n## Function-Based Access\n\nFor complex access logic that can't be expressed declaratively, use a function:\n\n```typescript\ncrud: {\n update: {\n access: async (ctx, record) => {\n // Custom logic - return true to allow, false to deny\n if (ctx.roles.includes('admin')) return true;\n if (record.ownerId === ctx.userId) return true;\n\n // Check custom business logic\n const membership = await checkTeamMembership(ctx.userId, record.teamId);\n return membership.canEdit;\n }\n }\n}\n```\n\nFunction access receives:\n- `ctx`: The full AppContext object\n- `record`: The record being accessed (for get/update/delete operations)"
|
|
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)"
|
|
79
79
|
},
|
|
80
80
|
"compiler/definitions/actions": {
|
|
81
81
|
"title": "Actions",
|
|
@@ -87,31 +87,31 @@ export const DOCS = {
|
|
|
87
87
|
},
|
|
88
88
|
"compiler/definitions/feature": {
|
|
89
89
|
"title": "feature() — single-export sugar",
|
|
90
|
-
"content": "The `q.table()` + `defineTable()` pair has been co-equal with Drizzle since day one. It works, but it means two exports and two concepts for something most feature files treat as one unit: a table with a security contract.\n\n`feature()` collapses both into a single default export.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n
|
|
90
|
+
"content": "The `q.table()` + `defineTable()` pair has been co-equal with Drizzle since day one. It works, but it means two exports and two concepts for something most feature files treat as one unit: a table with a security contract.\n\n`feature()` collapses both into a single default export.\n\n## Before\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport const contacts = q.table(\"contacts\", {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n});\n\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n\nexport type Contact = typeof contacts.$infer;\n```\n\n## After\n\n```ts title=\"quickback/features/contacts.ts\"\n\nexport default feature(\"contacts\", {\n columns: {\n id: q.id(),\n organizationId: q.text().required().index(),\n address: q.text().required().index(),\n name: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n guards: { createable: [\"address\", \"name\"] },\n});\n```\n\nType inference still works — `typeof import(\"./contacts\").default.$infer` gives you the `Contact` row type.\n\n## How it works\n\n`feature(name, config)` is a **compile-time sugar**, not a runtime abstraction. When the compiler sees `export default feature(...)`, it rewrites the source to the canonical two-export form before any parsing runs. Every downstream layer — dialect pass, audit injection, security contracts, generated routes, OpenAPI, MCP tools, RLS emission — runs on the same Drizzle source it always did. Zero runtime cost; zero semantic difference from `q.table()` + `defineTable()`.\n\nThat means:\n\n- **Both forms remain supported indefinitely.** Mix them freely — some files `feature(...)`, some files `q.table() + defineTable()`, some files Drizzle `sqliteTable() + defineTable()`. The compiler dispatches per file.\n- **Action files reference the table by default import.** `import contacts from \"./contacts\"` gives you the same typed handle `q.table(\"contacts\", ...)` would have returned, so `defineActions(contacts, { … })` still works.\n- **Diagnostics are identical.** Missing firewall → same warning. Protected-field wiring → same check. Nothing about `feature()` weakens the secure-by-default posture.\n\n## Aliases\n\n`q` is canonical (matches Zod's `z.`, Superstruct's `s.`). `qb` is exported as an alias if you'd rather self-document the namespace:\n\n```ts\n\nexport default feature(\"contacts\", {\n columns: { id: qb.id(), name: qb.text().required() },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // …\n});\n```\n\nSame object, two names — pick one.\n\n## When to use which\n\n| Pattern | When |\n|---|---|\n| `feature(name, {...})` | Default. One table, one security contract, one file. |\n| `q.table()` + `defineTable()` | Multiple tables per file (rare), or you want to reference the table identifier before the default export. |\n| `sqliteTable()` / `pgTable()` + `defineTable()` | Interop with existing Drizzle code / migrations. |\n| `q.table(...)` alone (no `defineTable`) | Internal join/lookup/pivot tables with no public API. Compiler warns so you confirm the opt-out is intentional. |\n\n## Feature directory layout\n\nA feature directory holds tables, optional shared schemas, and the handler files that back any actions:\n\n```\nfeatures/podcast/\n├── episodes.ts ← defineTable + (optional) defineActions(episodes, {…})\n├── shows.ts ← defineTable + (optional) defineActions(shows, {…})\n├── episode-tags.ts ← defineTable only (junction)\n├── _feature.ts ← non-table-bound actions + shared zod schemas\n├── handlers/\n│ ├── episodes/{publish,revertToDraft}.ts\n│ └── shows/…\n└── lib/\n └── shared.ts ← feature-local helpers, copied verbatim\n```\n\nThree things to know:\n\n- **`handlers/` walks recursively**, keyed by relative path (`handlers/episodes/publish.ts`). The canonical layout is per-table subdirectories so action handlers stay grouped with the table they act on.\n- **`lib/` rides along** — feature-local helper modules get copied verbatim into the generated output. Use this for shared utilities that both handlers and inline `execute:` bodies reference.\n- **`_feature.ts` is the universal slot** for non-table-bound actions and shared schemas. Top-level decls in `_feature.ts` get prepended once to the merged actions module, so a `const sharedSchema = z.object({…})` in `_feature.ts` is referenceable from any sibling action's `input:` without re-declaring it.\n\nFor everything action-related — three modes, conflict rules, the `_feature.ts` shape — see [Actions](/compiler/definitions/actions).\n\n## Handlers — one `q` namespace for everything\n\nCustom action handlers need to run queries against the database. Quickback's compiled projects expose the Drizzle query-builder helpers on the same `q` namespace you use for schema authoring, so handler code stays inside one DSL:\n\n```ts title=\"quickback/features/mail/handlers/inbound.ts\"\n\nexport const execute = async ({ unsafeDb, input }) => {\n // Find the mailbox this email was addressed to\n const mailbox = await unsafeDb.query.mailboxes.findFirst({\n where: q.eq(mailboxes.address, input.mailboxAddress),\n });\n if (!mailbox) return { error: \"unknown mailbox\" };\n\n // Look up the thread by in-reply-to + organization scope\n const thread = input.parsed.inReplyTo\n ? await unsafeDb.query.threads.findFirst({\n where: q.and(\n q.eq(threads.organizationId, mailbox.organizationId),\n q.eq(threads.lastMessageId, input.parsed.inReplyTo),\n ),\n })\n : null;\n\n // Insert the new message\n await unsafeDb.insert(messages).values({\n id: crypto.randomUUID(),\n threadId: thread?.id,\n organizationId: mailbox.organizationId,\n subject: input.parsed.subject,\n createdAt: new Date().toISOString(),\n });\n\n return { ok: true };\n};\n```\n\nThe `q` in handlers is a runtime re-export of Drizzle's query builder — `q.eq`, `q.and`, `q.or`, `q.not`, `q.ne`, `q.gt`, `q.gte`, `q.lt`, `q.lte`, `q.like`, `q.ilike`, `q.inArray`, `q.notInArray`, `q.isNull`, `q.isNotNull`, `q.between`, `q.desc`, `q.asc`, `q.sql`. Pure re-export, zero wrapper cost.\n\n**The compiler generates `src/lib/q.ts`** in every project so the runtime `q` is always available. You never need to `import { eq } from \"drizzle-orm\"` in a handler — though you can if you want (Quickback doesn't hide drizzle, it just offers a consistent surface that matches the schema DSL).\n\n## Why one namespace\n\nQuickback is an opinionated wrapper with opinionated security. One DSL for schema (`q.table`, `q.text`, `q.id`), one DSL for queries (`q.eq`, `q.and`, `q.gte`), one opt-in for routes (`feature()` / `defineTable`). You never need to learn the names of the underlying tools to write a feature — the same way Next.js users don't need to know they're using webpack, or Astro users don't need to know they're using Vite."
|
|
91
91
|
},
|
|
92
92
|
"compiler/definitions/firewall": {
|
|
93
93
|
"title": "Firewall - Data Isolation",
|
|
94
|
-
"content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string }// column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nPredicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n crud: {\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n },\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
|
|
94
|
+
"content": "The firewall generates WHERE clauses automatically to isolate data by user, organization, or team.\n\n## Basic Usage\n\nThe cleanest pattern is `q.scope()` — declare the tenant column once and the firewall is auto-derived:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n organizationId: q.scope('organization'), // Auto-derives the firewall\n },\n // No firewall: block needed — auto-derived as\n // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },\n // { field: 'deletedAt', isNull: true }]\n // ... guards, crud, read\n});\n```\n\nIf you need to declare the firewall explicitly, two forms are accepted — pick whichever reads better:\n\n**Named-scope** (compact, default for simple overrides):\n\n```typescript\nfirewall: { organization: { column: 'tenant_id' } }\nfirewall: { owner: { column: 'account_user_id' } }\nfirewall: { exception: true } // opt out of tenant scoping entirely\n```\n\n**Predicate array** (explicit, required for `in`-lists or custom non-scope predicates):\n\n```typescript\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n```\n\nBoth shapes compile to the same canonical predicate array internally — the named-scope object is coerced at parse time. Pick by readability.\n\n## Auto-detected column synonyms\n\nWhen you omit the `firewall:` block entirely, the compiler scans the schema for one of these isolation columns and auto-derives the predicates:\n\n| Scope | Accepted column names |\n|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` |\n| User | `userId` |\n| Team | `teamId` |\n\n`ownerId` is **not** auto-detected — it's reserved for business-logic ownership (who owns this record), not access control. A table that has only `ownerId` and no isolation column raises a targeted error explaining the distinction; either rename to `userId` if the column controls access, add an isolation column, or specify `firewall:` explicitly.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string }// column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nPredicates are AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization — \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" — declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate:\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n guestOf: {\n from: 'event_guests', // table name\n subject: { column: 'userId', equals: 'ctx.userId' }, // caller side\n resource: { column: 'eventId' }, // resource side\n where: { status: 'confirmed' }, // optional row filter\n },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' },\n]\n```\n\nCompiles to:\n\n```sql\nWHERE sessions.organizationId = ?\n AND sessions.eventId IN (\n SELECT eventId FROM event_guests\n WHERE userId = ?\n AND status = 'confirmed'\n AND <event_guests' own firewall — tenant scope + soft-delete>\n )\n```\n\nKey properties:\n\n- **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.\n- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.\n- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.\n- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).\n\nSee [Access — relationships](/compiler/definitions/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Context Sources\n\nWhen `equals` references the request context, use these standard sources:\n\n| Source | Description |\n|--------|-------------|\n| `ctx.userId` | Current authenticated user's ID |\n| `ctx.activeOrgId` | User's active organization ID |\n| `ctx.activeTeamId` | User's active team ID |\n\nThese values are populated by the auth middleware from the user's session. Any predicate where `equals` starts with `ctx.` is treated as server-derived: the column lands in `GUARDS_CONFIG.systemManaged` (clients cannot submit it) and is auto-populated on create / upsert from the context.\n\n## Auto-Derivation\n\nWhen the `firewall:` block is omitted, the compiler scans the schema for known scope columns and synthesises the predicate array:\n\n| Column found | Predicate emitted |\n|--------------|-------------------|\n| `organizationId` / `organisationId` / `orgId` / `organization` / `organisation` / `org` | `{ field: '...', equals: 'ctx.activeOrgId' }` |\n| `userId` | `{ field: 'userId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` — appended automatically whenever the schema carries the column, regardless of which firewall shape you wrote |\n\n`q.scope(kind)` is the canonical way to declare the column — auto-derivation works the same way for plain `q.text().required()` or Drizzle `text(...).notNull()` columns named to match the convention.\n\n**Rules:**\n- Exactly one isolation column → auto-derived.\n- Zero columns AND no PUBLIC route → compile-time error (\"missing isolation column\").\n- Two or more (e.g. `organizationId` + `ownerId`) → compile-time error; declare `firewall:` explicitly.\n\n## What `{ exception: true }` Actually Does\n\n`{ exception: true }` disables **tenant scoping only** — the generated `buildFirewallConditions()` emits no tenant `WHERE` clauses. It does **not** affect:\n\n- **Audit field injection.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`, `deletedAt`, `deletedBy` are always added to every table unless you disable them globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column (which it does by default, thanks to audit injection), the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out of soft-delete filtering on an exception resource, either set `compiler.features.auditFields: false` globally or hand-author a schema without `deletedAt`.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` — no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from admin.** `userRole === 'admin'` callers still go through the firewall normally — only `userRole === 'sysadmin'` triggers the bypass. Admins keep their existing universal-bypass at the *access* layer (cross-org reads on per-record routes via `?organizationId=`), but the firewall's row predicate remains in force. Sysadmin is opt-in, configured per-project, and intended for the cross-tenant CMS DB-admin tier — see [CMS Configuration](/compiler/config#cms-configuration).\n\nIf your project doesn't set `cms.sysadmin: true`, the escape branch is never emitted and the role value is functionally inert.\n\n## Common Patterns\n\n```typescript\n// Public/system table - no tenant filtering (soft-delete still applied)\nfirewall: [{ exception: true }]\n\n// Organization-scoped (auto-derived when organizationId is present — block can be omitted)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// User-owned personal data\nfirewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Multi-tenant + per-team scoping\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'teamId', equals: 'ctx.activeTeamId' },\n { field: 'deletedAt', isNull: true },\n]\n\n// Custom ctx field\nfirewall: [\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' },\n]\n\n// Status-gated (literal value, not ctx-derived — does NOT add to systemManaged)\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'status', in: ['active', 'pending'] },\n]\n```\n\n## Error Responses\n\nWhen a record isn't found behind the firewall (wrong org, soft-deleted, or genuinely doesn't exist), the error response depends on `firewallErrorMode`:\n\n### Reveal Mode (Default)\n\nReturns **403** with a structured error:\n\n```json\n{\n \"error\": \"Record not found or not accessible\",\n \"layer\": \"firewall\",\n \"code\": \"FIREWALL_NOT_FOUND\",\n \"hint\": \"Check the record ID and your organization membership\"\n}\n```\n\nThis is developer-friendly and helps debug access issues during development.\n\n### Hide Mode\n\nReturns **404** with a generic error:\n\n```json\n{\n \"error\": \"Not found\",\n \"code\": \"NOT_FOUND\"\n}\n```\n\nUse `firewallErrorMode: 'hide'` for security-hardened deployments where you don't want attackers to distinguish between \"record exists but you can't access it\" and \"record doesn't exist\":\n\n```typescript\nexport default defineTable(records, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n firewallErrorMode: 'hide', // Opaque 404s prevent record enumeration\n});\n```\n\n### Foreign-Key Referential Checks\n\nGenerated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:\n\n```json\n{\n \"error\": \"Referenced jobs row not found\",\n \"code\": \"FK_NOT_FOUND\",\n \"layer\": \"validation\",\n \"field\": \"jobId\"\n}\n```\n\nThis closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).\n\nThe check runs after guards but before the insert, so it appears as `layer: \"validation\"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.\n\n### Pre-Record ID-Probe Defense\n\nIndependent of `firewallErrorMode`, generated `/:id` handlers run a\n**role-only access check before** the firewall query (see\n[Access ordering](/compiler/definitions/access#evaluation-order)). A caller\nwithout the right role gets 403 before the database is touched, so they\ncan't distinguish \"row exists out-of-scope\" from \"row doesn't exist\" via\nresponse timing or status differences.\n\n`firewallErrorMode` controls what happens **after** the role check passes\nbut the firewall hides the row — i.e., when an authorized caller asks for\na record in another tenant. Use `'hide'` to make that case indistinguishable\nfrom a non-existent ID.\n\n## Rules\n\n- Every resource MUST have at least one tenant predicate OR `{ exception: true }` OR a PUBLIC route\n- `{ exception: true }` cannot be combined with tenant predicates in the same array\n\n## Why Can't You Mix `{ exception: true }` with Tenant Predicates?\n\nThey represent opposite intentions:\n- `{ exception: true }` = \"Don't generate tenant `WHERE` clauses, data is public/global\"\n- Tenant predicates = \"Generate tenant `WHERE` clauses to isolate data\"\n\nCombining them would be contradictory — you can't both isolate and not isolate. (Note: soft-delete filtering is independent of this decision, see above.)\n\n## Handling \"Some Public, Some Private\" Data\n\nIf you need records that are sometimes public and sometimes scoped, you have two options:\n\n### Option 1: Two Separate Tables\n\nSplit into two tables - one public, one scoped:\n\n```typescript\n// features/job-templates/template-library.ts - Public job templates\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nexport default defineTable(customTemplates, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n // ...\n});\n```\n\n### Option 2: Use Access Control Instead\n\nKeep tenant scope but make access permissive, then control visibility via `access`:\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n // Anyone in the org can list — visibility differences are handled\n // via record-level access conditions on /:id\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n // Use record conditions to allow public jobs OR owned jobs on GET /:id\n // (single-record GET inherits read.access, with optional record-level overrides)\n // ...\n});\n```\n\n### Which to Choose?\n\n| Scenario | Recommendation |\n|----------|----------------|\n| Truly global data (app config, public job templates) | `exception: true` in separate resource |\n| \"Public within org\" but still org-isolated | Ownership scope + permissive access rules |\n| Recruiter can toggle job postings public/private | Ownership scope + `visibility` field + access conditions |"
|
|
95
95
|
},
|
|
96
96
|
"compiler/definitions/guards": {
|
|
97
97
|
"title": "Guards - Field Modification Rules",
|
|
98
|
-
"content": "Control which fields can be modified in CREATE vs UPDATE operations.\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().default('applied'),\n appliedAt: text('applied_at').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: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"],\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n },\n
|
|
98
|
+
"content": "Control which fields can be modified in CREATE vs UPDATE operations.\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().default('applied'),\n appliedAt: text('applied_at').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: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"],\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Configuration Options\n\n```typescript\nguards: {\n // Fields allowed on CREATE\n createable?: string[];\n\n // Fields allowed on UPDATE/PATCH\n updatable?: string[];\n\n // Fields only modifiable via specific actions\n protected?: Record<string, string[]>;\n\n // Fields set on CREATE, never modified after\n immutable?: string[];\n}\n```\n\n## How It Works\n\n| List | What it controls |\n|------|------------------|\n| `createable` | Fields allowed in create (POST) request body |\n| `updatable` | Fields allowed in update (PATCH) request body |\n| `protected` | Fields blocked from direct writes, only modifiable via named actions |\n| `immutable` | Fields allowed on create, blocked on all updates |\n\n**Combining lists:**\n\n- `createable` + `updatable` - Most fields go in both (can set on create AND modify later)\n- `createable` only - Field is set once, cannot be changed via update\n- `protected` - Don't also list in `createable` or `updatable` (they're mutually exclusive)\n- `immutable` - Don't also list in `updatable` (contradiction)\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\", \"source\"],\n updatable: [\"notes\"],\n // \"candidateId\", \"jobId\" are only in createable = set once, can't change via update\n protected: {\n stage: [\"advance-stage\", \"reject\"], // NOT in createable/updatable\n },\n immutable: [\"appliedAt\"], // NOT in updatable\n}\n```\n\n**If a field is not listed anywhere, it cannot be set by the client.**\n\n## System-Managed Fields (Always Protected)\n\n`GUARDS_CONFIG.systemManaged` rejects any field in this set from client input — even with `guards: false`. The set always includes the audit fields:\n\n- `createdAt`, `createdBy`\n- `modifiedAt`, `modifiedBy`\n- `deletedAt`, `deletedBy`\n\nIt also extends with **scope columns** — any firewall predicate whose `equals` references `ctx.*` adds its `field` to systemManaged. Most commonly this comes from `q.scope()`:\n\n```typescript\ncolumns: {\n organizationId: q.scope('organization'), // → adds 'organizationId' to systemManaged\n}\n```\n\nThe same applies to a hand-rolled firewall:\n\n```typescript\nfirewall: [\n { field: 'tenantId', equals: 'ctx.activeOrgId' }, // → systemManaged\n { field: 'workspaceId', equals: 'ctx.activeWorkspaceId' }, // → systemManaged\n { field: 'status', equals: 'active' }, // literal, NOT added\n]\n```\n\nThe semantic rule is \"if the firewall says this column's value comes from the request context, the client cannot submit it.\" The value is auto-populated on create / upsert from `ctx`.\n\n## Example\n\n```typescript\nguards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"],\n protected: {\n stage: [\"advance-stage\", \"reject\"], // Only these actions can modify stage\n },\n immutable: [\"appliedAt\", \"candidateId\", \"jobId\"],\n}\n```\n\n## Disabling Guards\n\n```typescript\nguards: false // Only system fields protected\n```\n\nWhen `guards: false` is set, all user-defined fields become writable via direct create/update/upsert operations. This is useful for:\n- External sync scenarios where you need full field control\n- Batch upsert operations where field restrictions would be limiting\n- Simple tables where field-level protection isn't needed\n\n## Upsert with External IDs\n\nWhen you disable guards AND use client-provided IDs, you unlock upsert operations. This is designed for **syncing data from external systems**.\n\n### Requirements for Upsert\n\n1. `generateId: false` in database config (client provides IDs)\n2. `guards: false` in resource definition\n\n### How Upsert Works\n\n```\nPUT /resource/:id\n├── Record exists? → UPDATE (replace all fields)\n└── Record missing? → CREATE with provided ID\n```\n\n### Database Config\n\n```typescript\n// quickback.config.ts\nexport default {\n database: {\n generateId: false, // Client provides IDs (enables upsert)\n // Other options: 'uuid' | 'cuid' | 'nanoid' | 'short' | 'prefixed' | 'serial'\n }\n};\n```\n\n### Table Definition\n\n```typescript\n// features/integrations/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: false, // Disables field restrictions\n upsert: {\n access: { roles: ['hiring-manager', 'sync-service'] }\n },\n});\n```\n\n## What's Still Protected with guards: false\n\nEven with `guards: false`, system-managed fields are ALWAYS protected. This includes:\n\n- `createdAt`, `createdBy` — set on INSERT only\n- `modifiedAt`, `modifiedBy` — auto-updated\n- `deletedAt`, `deletedBy` — set on soft delete\n- Any column declared via `q.scope()` (or any firewall predicate using `equals: 'ctx.*'`) — auto-populated from request context\n\nSo `guards: false` only opens up user-defined business fields. Tenant scope and audit fields stay locked down regardless.\n\n## Ownership Auto-Population\n\nWhen upsert creates a new record, ownership fields are auto-set from context:\n\n```typescript\n// Client sends: PUT /ats-imports/ext-123 { candidateName: \"Jane Doe\" }\n// Server creates:\n{\n id: \"ext-123\", // Client-provided\n candidateName: \"Jane Doe\", // Client-provided\n organizationId: ctx.activeOrgId, // Auto-set from firewall\n createdAt: now, // Auto-set\n createdBy: ctx.userId, // Auto-set\n modifiedAt: now, // Auto-set\n modifiedBy: ctx.userId, // Auto-set\n}\n```\n\n## Use Cases for Upsert/External IDs\n\n| Use Case | Why upsert? |\n|----------|----------|\n| External API sync | External system controls the ID |\n| Webhook handlers | Events come with their own IDs |\n| Data migration | Preserve IDs from source system |\n| Idempotent updates | Safe to retry (no duplicate creates) |\n| Bulk upsert | Create or update in one operation |\n\n## ID Generation Options\n\n| `generateId` | Upsert Available? | Notes |\n|--------------|----------------|-------|\n| `'uuid'` | No | Server generates UUID |\n| `'cuid'` | No | Server generates CUID |\n| `'nanoid'` | No | Server generates nanoid |\n| `'short'` | No | Server generates 6-char alphanumeric ID (e.g. `a3F9xK`) |\n| `'prefixed'` | No | Server generates prefixed ID (e.g. `room_abc123`) |\n| `'serial'` | No | Database auto-increments |\n| `false` | Yes (if guards: false) | Client provides ID |\n\n## Compile-Time Validation\n\nThe Quickback compiler validates your guards configuration and will error if:\n\n1. **Field in both `createable` and `protected`** - A field cannot be both client-writable on create and action-only\n2. **Field in both `updatable` and `protected`** - A field cannot be both client-writable on update and action-only\n3. **Field in both `updatable` and `immutable`** - Contradictory: immutable fields cannot be updated\n4. **Field in `protected` doesn't exist in schema** - Referenced field must exist in the table\n5. **Field in `createable`/`updatable`/`immutable` doesn't exist in schema** - All referenced fields must exist"
|
|
99
99
|
},
|
|
100
100
|
"compiler/definitions": {
|
|
101
101
|
"title": "Definitions Overview",
|
|
102
|
-
"content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n
|
|
102
|
+
"content": "Before diving into specific features, let's understand how Quickback's pieces connect. This page gives you the mental model for everything that follows.\n\n## The Big Picture\n\nQuickback is a **backend compiler**. You write definition files, and Quickback compiles them into a production-ready API.\n\n1. **You write definitions** - Table files with schema and security config using `defineTable`\n2. **Quickback compiles them** - Analyzes your definitions at build time\n3. **You get a production API** - `GET /jobs`, `POST /jobs`, `PATCH /jobs/:id`, `DELETE /jobs/:id`, batch operations, plus custom actions\n\n## File Structure\n\nYour definitions live in a `quickback/features/` folder organized by feature:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/\n│ └── {feature-name}/\n│ ├── candidates.ts # Table + config (defineTable)\n│ ├── applications.ts # Secondary table + config\n│ ├── interview-scores.ts # Internal table (no routes)\n│ ├── actions.ts # Custom actions (optional)\n│ └── handlers/ # Action handlers (optional)\n│ └── advance-stage.ts\n├── src/ # Generated code (output)\n└── package.json\n```\n\n**Table files** use `defineTable` to combine schema and security config:\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: {\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\nexport type Candidate = typeof candidates.$inferSelect;\n```\n\n**Key points:**\n- Tables with `export default defineTable(...)` → resource routes generated\n- Tables without default export → internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` → `/api/v1/applications`\n\n## The Four Security Layers\n\nEvery API request passes through four security layers, in order:\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/team\n```\n\n### 1. Firewall (Data Isolation)\n\nThe firewall controls **which records** a user can see. It automatically adds WHERE clauses to every query based on your schema columns:\n\n| Column in Schema | What happens |\n|------------------|--------------|\n| `organization_id` | Data isolated by organization |\n| `user_id` | Data isolated by user (personal data) |\n\nNo manual configuration needed - Quickback applies smart rules based on your schema.\n\nFor relationship-based row visibility (e.g. \"user can see this event because they have a confirmed `event_guests` row pointing at it\"), declare the relationship under `authz.relationships` and reference it from the firewall with a `via:` predicate. See [Firewall → Relationship-based scoping](/compiler/definitions/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall →](/compiler/definitions/firewall)\n\n### 2. Access (CRUD Permissions)\n\nAccess controls **which operations** a user can perform. It checks roles and record conditions. Reads (`GET /` and `GET /:id`) live under `read:`; writes live under top-level `create:`, `update:`, `delete:`, and `upsert:`.\n\n```typescript\nread: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n},\ncreate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\nupdate: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\ndelete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n```\n\n[Learn more about Access →](/compiler/definitions/access)\n\n### 3. Guards (Field Modification Rules)\n\nGuards control **which fields** can be modified in each operation.\n\n| Guard Type | What it means |\n|------------|---------------|\n| `createable` | Fields that can be set when creating |\n| `updatable` | Fields that can be changed when updating |\n| `protected` | Fields that can only be changed via specific actions |\n| `immutable` | Fields that can never be changed after creation |\n\n[Learn more about Guards →](/compiler/definitions/guards)\n\n### 4. Masking (Data Redaction)\n\nMasking hides sensitive fields from users who shouldn't see them.\n\n```typescript\nmasking: {\n email: { type: 'email' }, // Shows: j***@e******.com\n phone: { type: 'phone' }, // Shows: ******4567\n salary: { type: 'redact' }, // Shows: [REDACTED]\n}\n```\n\n[Learn more about Masking →](/compiler/definitions/masking)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Firewall** checks: Is candidate `cnd_123` in the user's organization?\n - Yes → Continue\n - No → 404 Not Found (as if it doesn't exist)\n\n2. **Access** checks: Can interviewers perform GET?\n - Yes → Continue\n - No → 403 Forbidden\n\n3. **Guards** don't apply to GET (they're for writes)\n\n4. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`\n - Email: `jane@company.com` → `j***@c******.com`\n - Phone: `555-123-4567` → `******4567`\n\n5. **Response** sent with masked data\n\n## Locked Down by Default\n\nQuickback is **secure by default**. Nothing is accessible until you explicitly allow it.\n\n| Layer | Default | What you must do |\n|-------|---------|------------------|\n| Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Actions | BLOCKED | Explicitly define `access` for each action |\n\n**You must deliberately open each door.** This prevents accidental data exposure.\n\n## Other Resource Options\n\nBeyond the four security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.\n\n| Option | What it does | Full reference |\n|---|---|---|\n| `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/compiler/definitions/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/stack/cms/schema-registry) |\n| `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/stack/cms/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/stack/cms/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `layouts` | Named record-page layouts — group fields into sections (collapsed, multi-column). Falls back to auto-grouping if unset. | [CMS Record Layouts](/stack/cms/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack → Embeddings](/stack/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack → Realtime](/stack/realtime/using-realtime) |\n| `path` | Override the route base path (defaults to feature name). | — |\n\nAll options are optional — omit them and Quickback uses sensible defaults (auto-detected display column, auto-grouped layout, no embeddings, no realtime).\n\n## Next Steps\n\n1. [Database Schema](/compiler/definitions/schema) — Define your tables\n2. [Firewall](/compiler/definitions/firewall) — Set up data isolation\n3. [Access](/compiler/definitions/access) — Configure read and write permissions\n4. [Guards](/compiler/definitions/guards) — Control field modifications\n5. [Masking](/compiler/definitions/masking) — Hide sensitive data\n6. [Views](/compiler/definitions/views) — Column-level security\n7. [Validation](/compiler/definitions/validation) — Field validation rules\n8. [Actions](/compiler/definitions/actions) — Add custom business logic"
|
|
103
103
|
},
|
|
104
104
|
"compiler/definitions/masking": {
|
|
105
105
|
"title": "Masking - Field Redaction",
|
|
106
|
-
"content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `redact` | [REDACTED] |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n| `accesstoken`, `refreshtoken`, `clientsecret`, `signingsecret`, `bearer` | `redact` | [REDACTED] |\n| `stripe`, `webhook` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n#### Tables without an owner column\n\nThe default auto-mask predicate is `show: { or: 'owner', roles: ['admin'] }` — admins always see the value, the row's owner sees their own. If the table has no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and emits a second warning so the rule is still safe but transparent:\n\n```bash\n[Warning] Auto-masking on \"people.email\" requested owner OR-show, but \"people\"\n has no \"ownerId\" column. Falling back to roles-only (roles: [\"admin\"]).\n Declare `masking: { email: { show: { roles: [...] } } }` explicitly to\n silence this and pick a real predicate.\n```\n\nThis is a real behavioral signal, not boilerplate — the auto-detector can't tell whether the table is \"ownerless on purpose\" (e.g. a shared lookup table) or \"should have an owner column but was authored without one.\" Declare the predicate explicitly to silence the warning and lock in the intent.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n
|
|
106
|
+
"content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Automatic Masking (Secure by Default)\n\nQuickback automatically applies masking to columns that match sensitive naming patterns. This ensures a high security posture even if you don't explicitly configure masking.\n\n### Sensitive Keywords & Default Masks\n\n| Pattern | Default Mask | Description |\n| :--- | :--- | :--- |\n| `email` | `email` | p***@e******.com |\n| `phone`, `mobile`, `fax` | `phone` | ******4567 |\n| `ssn`, `socialsecurity`, `nationalid` | `ssn` | *****6789 |\n| `creditcard`, `cc`, `cardnumber`, `cvv` | `creditCard` | ************1234 |\n| `iban` | `redact` | [REDACTED] |\n| `password`, `secret`, `token`, `apikey`, `privatekey` | `redact` | [REDACTED] |\n| `accesstoken`, `refreshtoken`, `clientsecret`, `signingsecret`, `bearer` | `redact` | [REDACTED] |\n| `stripe`, `webhook` | `redact` | [REDACTED] |\n\n### Build-Time Alerts\n\nIf the compiler auto-detects a sensitive column that you haven't explicitly configured, it will emit a warning:\n\n```bash\n[Warning] Auto-masking enabled for sensitive column \"users.email\". Explicitly configure masking to silence this warning.\n```\n\nTo silence this warning or change the behavior, simply define the field explicitly in your `masking` configuration. Explicit configurations always take precedence over auto-detected defaults.\n\n#### Tables without an owner column\n\nThe default auto-mask predicate is `show: { or: 'owner', roles: ['admin'] }` — admins always see the value, the row's owner sees their own. If the table has no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and emits a second warning so the rule is still safe but transparent:\n\n```bash\n[Warning] Auto-masking on \"people.email\" requested owner OR-show, but \"people\"\n has no \"ownerId\" column. Falling back to roles-only (roles: [\"admin\"]).\n Declare `masking: { email: { show: { roles: [...] } } }` explicitly to\n silence this and pick a real predicate.\n```\n\nThis is a real behavioral signal, not boilerplate — the auto-detector can't tell whether the table is \"ownerless on purpose\" (e.g. a shared lookup table) or \"should have an owner column but was authored without one.\" Declare the predicate explicitly to silence the warning and lock in the intent.\n\n### Overriding Defaults\n\nIf you want to show a sensitive field to everyone (disable masking) or use a different rule, define it explicitly in the `resource.masking` block:\n\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Show email to everyone (overrides auto-masking)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Silence warning but keep secure (recruiter and above only)\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } }\n }\n});\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: { createable: [\"name\", \"email\", \"phone\", \"resumeUrl\"], updatable: [\"name\", \"phone\"] },\n masking: {\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n read: { access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] } },\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n});\n```\n\n## Built-in Mask Types\n\n| Type | Example Input | Masked Output |\n|------|---------------|---------------|\n| `'email'` | `john@yourdomain.com` | `j***@y*********.com` |\n| `'phone'` | `555-123-4567` | `******4567` |\n| `'ssn'` | `123-45-6789` | `*****6789` |\n| `'creditCard'` | `4111111111111111` | `************1111` |\n| `'name'` | `John Smith` | `J*** S****` |\n| `'redact'` | `anything` | `[REDACTED]` |\n| `'custom'` | (your logic) | (your output) |\n\n## Configuration\n\n```typescript\nmasking: {\n // Basic masking - everyone sees masked value\n phone: { type: 'phone' },\n\n // Show unmasked to specific roles\n email: {\n type: 'email',\n show: { roles: ['hiring-manager', 'recruiter'] }\n },\n\n // Show unmasked to owner (createdBy === ctx.userId)\n resumeUrl: {\n type: 'redact',\n show: { or: 'owner' }\n },\n\n // Custom mask function\n externalProfileUrl: {\n type: 'custom',\n mask: (value) => value.slice(0, 4) + '...' + value.slice(-4),\n show: { roles: ['recruiter'] }\n },\n}\n```\n\n## Show Conditions\n\n```typescript\nshow: {\n roles?: string[]; // Unmasked if user has any of these roles\n or?: 'owner'; // Unmasked if user is the record owner\n}\n```\n\nThe `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.\n\n### Relationship-roles in masking (v1 limitation)\n\nRelationship-roles declared under `authz.roles` (e.g. `guest: { via: 'guestOf' }`) are **not yet supported in `show:` clauses**. The compiler refuses to build with a clear error message because async, db-aware mask functions plus a batched relationship matcher (to avoid N+1 on list responses) are required to ship safely — that pipeline has not yet landed. The runtime evaluator fails closed on unrecognized arms, so silent grants are impossible.\n\n**Workarounds**, depending on intent:\n\n- **Gate on BA roles only**: keep masking simple and put the relationship check at the access layer instead — `read.views.<v>.access: { roles: ['guest'] }` returns a curated field projection that excludes the sensitive column entirely for non-staff callers, without involving masking.\n- **Move the field into a view that's gated by the relationship-role at access**: same pattern — column-level security via field projection rather than per-row masking.\n\nA future async-mask pipeline with batched lookups will lift this limitation; the schema slot is reserved so the v2 add will be non-breaking.\n\n## Query Gate (filter / sort / search)\n\nMasking has a second concern beyond hiding values in the response: a non-admin caller could enumerate masked PII via the query string — e.g. `?filter=email:like:%@target.com` — and infer presence even when the response payload is redacted. The `query` allowlist closes this:\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] },\n // Optional — defaults to show.roles when omitted\n query: { roles: ['admin'] },\n },\n}\n```\n\n`query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — \"if you can see it, you can query it\" — which is the right shape for almost all PII.\n\nA view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin'] } },\n // query: defaults to show.roles → ['admin']\n},\nread: {\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member', 'admin'] },\n query: {\n searchable: ['name'], // email NOT listed → not searchable on this view\n },\n },\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['admin'] },\n query: {\n filterable: ['email'], // ✓ admin satisfies email's query gate\n searchable: ['name', 'email'],\n },\n },\n },\n},\n```\n\n`query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required().filterable('like').searchable(),\n email: q.text().required().filterable('eq').searchable(),\n phone: q.text().optional().filterable('eq'),\n resumeUrl: q.text().optional(),\n organizationId: q.scope('organization'),\n },\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl'],\n updatable: ['name', 'phone'],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin+'] } },\n phone: { type: 'phone', show: { roles: ['admin+'] } },\n resumeUrl: {\n type: 'custom',\n mask: () => '[RESUME LINK HIDDEN]',\n show: { roles: ['admin+'] },\n },\n },\n read: {\n access: { roles: ['member+'] },\n views: {\n pipeline: {\n fields: ['id', 'name'],\n access: { roles: ['member+'] },\n query: { searchable: ['name'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl'],\n access: { roles: ['admin+'] },\n query: {\n filterable: ['email', 'phone'],\n searchable: ['name', 'email'],\n },\n },\n },\n },\n create: { access: { roles: ['admin+'] } },\n update: { access: { roles: ['admin+'] } },\n delete: { access: { roles: ['owner'] }, mode: 'soft' },\n});\n```"
|
|
107
107
|
},
|
|
108
108
|
"compiler/definitions/read": {
|
|
109
109
|
"title": "Read - Unified Read Pipeline",
|
|
110
|
-
"content": "The `read` block owns the read side of every resource: the collection-level\n`GET /` endpoint, single-record `GET /:id`, and named view projections. It\nreplaces the legacy `crud.list` and `crud.get` shapes — those are rejected\nat compile time in DSL v2.\n\n## Basic Usage\n\n```typescript\n// features/customers/customers.ts\n\nexport const customers = sqliteTable('customers', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n ssn: text('ssn'),\n status: text('status').notNull(),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n },\n read: {\n access: { roles: ['member', 'admin'] },\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'ssn', 'status'],\n access: { roles: ['admin'] },\n },\n },\n },\n
|
|
110
|
+
"content": "The `read` block owns the read side of every resource: the collection-level\n`GET /` endpoint, single-record `GET /:id`, and named view projections. It\nreplaces the legacy `crud.list` and `crud.get` shapes — those are rejected\nat compile time in DSL v2.\n\n## Basic Usage\n\n```typescript\n// features/customers/customers.ts\n\nexport const customers = sqliteTable('customers', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n ssn: text('ssn'),\n status: text('status').notNull(),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n },\n read: {\n access: { roles: ['member', 'admin'] },\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'ssn', 'status'],\n access: { roles: ['admin'] },\n },\n },\n },\n create: { access: { roles: ['admin'] } },\n update: { access: { roles: ['admin'] } },\n delete: { access: { roles: ['admin'] }, mode: 'soft' },\n});\n```\n\n## What `read` Owns\n\n| Endpoint | Gate |\n|----------|------|\n| `GET /api/v1/{resource}` | `read.access` |\n| `GET /api/v1/{resource}/:id` | `read.access` |\n| `GET /api/v1/{resource}/views/{name}` | `read.views[name].access` (falls back to `read.access`) |\n\nSingle-record `GET /:id` inherits `read.access` automatically — there's no\nseparate `read.get` block. If you need different access for single records,\nuse record-level conditions on `read.access`:\n\n```typescript\nread: {\n access: {\n or: [\n { roles: ['admin'] },\n { roles: ['member'], record: { ownerId: { equals: '$ctx.userId' } } },\n ],\n },\n}\n```\n\n## Configuration Options\n\n```typescript\ninterface ReadConfig {\n // Role/condition gate for collection reads, single-record reads, and the\n // default view fallback.\n access?: Access;\n\n // Optional read-side firewall override. If omitted, the resource-level\n // `firewall` block is used (the common case).\n firewall?: FirewallConfig;\n\n // Pagination defaults for collection reads.\n pageSize?: number; // Default page size (default: 50)\n maxPageSize?: number; // Hard cap (default: 100)\n\n // Named field projections. Each view has its own access and field list.\n views?: {\n [viewName: string]: ViewConfig;\n };\n}\n\ninterface ViewConfig {\n fields: string[]; // Columns returned by this view\n access?: Access; // Per-view access (falls back to read.access)\n pageSize?: number;\n maxPageSize?: number;\n}\n```\n\n## Access Ordering on `/:id`\n\nSingle-record `GET /:id` evaluates checks in this order to close the\n404-vs-403 ID-probe channel:\n\n1. **Auth gate** — 401 if unauthenticated\n2. **Pre-record access** — role-only check (skips `access.record` predicates)\n3. **Firewall query** — `WHERE` clause filters by ownership\n4. **Post-record access** — full check including record-level predicates\n5. **Masking** — applied to the response\n\nAn unauthorized caller without a matching role gets 403 from step 2 before\nthe database is touched, so they can't distinguish \"row exists in another\ntenant\" from \"row doesn't exist.\" A caller with the right role but the wrong\ntenant gets the firewall's configured response (403 by default; see\n[`firewallErrorMode: 'hide'`](/compiler/definitions/firewall) for an opaque\n404 instead).\n\nFunction-form access is opaque to the pre-check (it always passes there) and\nis fully evaluated post-record, so `access: async (ctx, record) => ...`\nstill works as before.\n\n## Views Under `read.views`\n\nViews are named field projections — Column Level Security. They live under\n`read.views` (not at the resource top level). See\n[Views](/compiler/definitions/views) for the full feature reference.\n\n```typescript\nread: {\n access: { roles: ['member', 'admin'] },\n views: {\n public: {\n fields: ['id', 'title', 'status'],\n access: { roles: ['PUBLIC'] },\n },\n internal: {\n fields: ['id', 'title', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\nNamed views are emitted at dedicated path routes:\n\n- `GET /api/v1/jobs/views/internal`\n- If `read.defaultView` is set, bare `GET /api/v1/jobs` resolves to that view.\n\n## Migrating from `crud.list` / `crud.get`\n\nDSL v2 rejects both at compile time. The migration is mechanical:\n\n| Before (DSL v1) | After (DSL v2) |\n|---|---|\n| `crud.list.access` | `read.access` |\n| `crud.list.pageSize` | `read.pageSize` |\n| `crud.list.maxPageSize` | `read.maxPageSize` |\n| `crud.list.fields: [...]` | Move to a named view under `read.views` |\n| `crud.get.access` | `read.access` (or record-level conditions) |\n| `crud.get.fields: [...]` | Move to a named view; clients call `/views/{name}` |\n| Top-level `views: {...}` | `read.views: {...}` |\n\nExample before/after:\n\n```typescript\n// Before — DSL v1\ncrud: {\n list: {\n access: { roles: ['member'] },\n pageSize: 25,\n },\n get: {\n access: { roles: ['member'] },\n fields: ['id', 'name', 'status'], // per-field projection\n },\n create: { access: { roles: ['admin'] } },\n}\n\n// After — DSL v2\nread: {\n access: { roles: ['member'] },\n pageSize: 25,\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member'] },\n },\n },\n}\ncreate: { access: { roles: ['admin'] } }\n```\n\nClients that previously hit `GET /:id` to retrieve only summary fields now\nmove that projection to a named collection view such as\n`GET /api/v1/jobs/views/summary`. Single-record `GET /:id` always returns the\nfull masked record.\n\n## Read-Only Resources\n\nA resource that exposes only reads is valid with no write-operation blocks at all:\n\n```typescript\nexport default defineTable(balanceSnapshots, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: { access: { roles: ['member', 'admin'] } },\n // no create/update/delete/upsert — no writes\n});\n```\n\n## See Also\n\n- [Views](/compiler/definitions/views) — Full reference for named projections\n- [Access](/compiler/definitions/access) — Roles, record conditions, and combinators\n- [Firewall](/compiler/definitions/firewall) — Tenant scoping and `firewallErrorMode`\n- [Views API](/compiler/targets/hono-api/using-the-api/views-api) — Calling views from clients"
|
|
111
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 crud: {\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\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 crud: { /* ... */ },\n read: { /* ... */ },\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 crud: { /* ... */ },\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 CRUD 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 CRUD 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 CRUD 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 CRUD 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 CRUD 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 `crud.delete.mode` nor `crud.batchDelete.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\ncrud: { delete: {} }\n\n// hard delete — no deletedAt/deletedBy columns, no soft-delete predicate\ncrud: { delete: { mode: 'hard' }, batchDelete: { 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 CRUD 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, 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"
|
|
115
115
|
},
|
|
116
116
|
"compiler/definitions/validation": {
|
|
117
117
|
"title": "Validation",
|
|
@@ -119,7 +119,7 @@ export const DOCS = {
|
|
|
119
119
|
},
|
|
120
120
|
"compiler/definitions/views": {
|
|
121
121
|
"title": "Views - Column Level Security",
|
|
122
|
-
"content": "Views implement **Column Level Security (CLS)** - controlling which columns users can access. This complements **Row Level Security (RLS)** provided by the [Firewall](/compiler/definitions/firewall), which controls which rows users can access.\n\n> **Migration note**: views were previously declared at the resource top\n> level (`views: {...}`). In DSL v2 they live under\n> [`read.views`](/compiler/definitions/read#views-under-read-views) so the\n> read pipeline owns its own configuration. The top-level form is rejected\n> at compile time.\n\n| Security Layer | Controls | Quickback Feature |\n|----------------|----------|-------------------|\n| Row Level Security | Which records | Firewall |\n| Column Level Security | Which fields | Views |\n\nViews provide named field projections with role-based access control. Use views to return different sets of columns to different users without duplicating CRUD endpoints.\n\n## When to Use Views\n\n| Concept | Purpose | Example |\n|---------|---------|---------|\n| CRUD list | Full records | Returns all columns |\n| Masking | Hide values | Email `j***@c******.com` |\n| Views | Exclude columns | Only `id`, `name`, `source` |\n\n- **CRUD list** returns all fields to authorized users\n- **Masking** transforms sensitive values but still includes the column\n- **Views** completely exclude columns from the response\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable('candidates', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n phone: text('phone'),\n source: text('source'),\n resumeUrl: text('resume_url'),\n internalNotes: text('internal_notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(candidates, {\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n\n // Named field projections\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'source', 'resumeUrl', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n report: {\n fields: ['id', 'name', 'source', 'createdAt'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n});\n```\n\n## Generated Endpoints\n\nEach named view generates a dedicated GET endpoint:\n\n```\nGET /api/v1/candidates # Full read - read.access fields\nGET /api/v1/candidates/views/pipeline # interviewer/recruiter/etc.\nGET /api/v1/candidates/views/full # hiring-manager/recruiter only\nGET /api/v1/candidates/views/report # report fields\n```\n\nIf `read.defaultView` is set, bare `GET /api/v1/candidates` can also resolve\nto that named view. Without `defaultView`, bare `GET /api/v1/candidates`\nreturns `VIEW_REQUIRED` once views are declared.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n### Pagination\n\n| Parameter | Description | Default | Max |\n|-----------|-------------|---------|-----|\n| `limit` | Number of records to return | 50 | 100 |\n| `offset` | Number of records to skip | 0 | - |\n\n```bash\n# Get first 10 records\nGET /api/v1/candidates/views/pipeline?limit=10\n\n# Get records 11-20\nGET /api/v1/candidates/views/pipeline?limit=10&offset=10\n```\n\n### Filtering\n\n```bash\n# Filter by exact value\nGET /api/v1/candidates/views/pipeline?source=linkedin\n\n# Filter with operators\nGET /api/v1/candidates/views/pipeline?createdAt.gt=2024-01-01\n\n# Multiple filters (AND logic)\nGET /api/v1/candidates/views/pipeline?source=linkedin&name.like=Smith\n```\n\n### Sorting\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n\n```bash\nGET /api/v1/candidates/views/pipeline?sort=name&order=asc\n```\n\n## Security\n\nAll four security pillars apply to views:\n\n| Pillar | Behavior |\n|--------|----------|\n| **Firewall** | WHERE clause applied (same as list) |\n| **Access** | Per-view access control |\n| **Guards** | N/A (read-only) |\n| **Masking** | Applied to returned fields |\n\n### Firewall\n\nViews automatically apply the same firewall conditions as the list endpoint. Users only see records within their organization scope.\n\n### Access Control\n\nEach view has its own access configuration:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Pipeline view - available to all roles\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Full view - recruiter and above\n full: {\n fields: ['id', 'name', 'source', 'email', 'phone', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\n### Masking\n\nMasking rules are applied to the returned fields. If a view includes a masked field like `email`, the masking rules still apply:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Even if an interviewer accesses the 'full' view, email will be masked\n // because masking rules take precedence\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n### How Views and Masking Work Together\n\nViews and masking are orthogonal concerns:\n- **Views** control field selection (which columns appear)\n- **Masking** controls field transformation (how values appear based on role)\n\nExample configuration:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name'], // email NOT included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email'], // email included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n| Endpoint | Role | `email` in response? | `email` value |\n|----------|------|---------------------|---------------|\n| `/views/pipeline` | interviewer | No | N/A |\n| `/views/pipeline` | recruiter | No | N/A |\n| `/views/full` | interviewer | Yes | `j***@c******.com` |\n| `/views/full` | recruiter | Yes | `jane@company.com` |\n\n## Aggregations\n\nViews can declare pre-computed aggregations that run alongside the row\nquery and surface as `aggregations: { ... }` on the response. This avoids a\ncustom standalone action for every \"count of X grouped by Y\" dashboard\ntile — the firewall and view filters already in place drive the metric.\n\n```typescript\nread: {\n access: { roles: ['owner', 'admin', 'member'] },\n views: {\n pipeline: {\n fields: ['id', 'jobId', 'candidateId', 'status', 'appliedAt'],\n aggregations: {\n totalApplications: { fn: 'count' },\n byStatus: { fn: 'groupBy', field: 'status' },\n },\n },\n },\n}\n```\n\nResponse now carries the aggregations alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": {\n \"applied\": 102,\n \"screening\": 41,\n \"interview\": 18,\n \"offer\": 7,\n \"rejected\": 5\n }\n }\n}\n```\n\n### Supported aggregation functions\n\n| `fn` | `field` | Returns | Example |\n|---|---|---|---|\n| `sum` | required, numeric | scalar number | `{ fn: 'sum', field: 'guestCount' }` |\n| `avg` | required, numeric | scalar number | `{ fn: 'avg', field: 'salary' }` |\n| `min` | required | scalar number | `{ fn: 'min', field: 'price' }` |\n| `max` | required | scalar number | `{ fn: 'max', field: 'price' }` |\n| `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |\n| `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |\n| `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |\n\n`groupBy` always returns a count map keyed by the distinct values of `field`.\n`NULL` values bucket under the literal string `\"(none)\"`. Other rollup\nfunctions (`groupBy` + `sum` of another column) are deferred to a future\nrelease.\n\n### Filter and firewall inheritance\n\nAggregations always run over the **same** filtered, firewalled set as the\nrow query. Pagination is intentionally ignored — you get the value over\nevery matching record, not just the current page.\n\nIn practice: a request like\n`GET /applications/views/pipeline?status=applied&jobId=job_123&limit=10`\nreturns the first 10 applied rows for that job, AND `byStatus` reflects\nonly that filtered set (which will be `{ applied: <total> }` since the\nfilter pinned the status). This is the only consistent default — divorcing\nthe metric from the user's filters would surprise.\n\n### Constraints (compile-time)\n\n- `field` must reference a real column on the table.\n- `sum`/`avg` require numeric column types (`int`, `real`, `decimal`,\n `numeric`, `bigint`). Non-numeric columns are rejected at compile time.\n- The same masking opt-out gate that governs `query.{filterable, sortable,\n searchable}` applies to aggregations: the view's roles must satisfy the\n masking rule, otherwise the aggregation is rejected. (A `sum(salary)`\n leaks structure across the masked set even when the row payload is\n redacted.)\n- Aggregation names cannot collide with the reserved response fields\n `data`, `pagination`, `view`.\n- No raw SQL `expr:` form. Column references only — declare a generated\n column or write a custom action if you need arithmetic.\n\n## Response Format\n\nView responses include metadata about the view:\n\n```json\n{\n \"data\": [\n { \"id\": \"cnd_123\", \"name\": \"Jane Doe\", \"source\": \"linkedin\" },\n { \"id\": \"cnd_456\", \"name\": \"John Smith\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"pagination\": {\n \"count\": 2,\n \"page\": 1,\n \"pageSize\": 50,\n \"hasMore\": false\n }\n}\n```\n\nWhen the view declares `aggregations`, the response also includes an\n`aggregations: { ... }` field. See [Aggregations](#aggregations).\n\n## Complete Example\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n guards: {\n createable: ['title', 'department', 'status', 'salaryMin', 'salaryMax'],\n updatable: ['title', 'department', 'status'],\n },\n\n masking: {\n salaryMin: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n salaryMax: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Public job board view\n board: {\n fields: ['id', 'title', 'department', 'status'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Internal view with salary info\n internal: {\n fields: ['id', 'title', 'department', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n // Compensation report\n compensation: {\n fields: ['id', 'title', 'department', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n\n crud: {\n create: { access: { roles: ['owner', 'hiring-manager'] } },\n update: { access: { roles: ['owner', 'hiring-manager'] } },\n delete: { access: { roles: ['owner', 'hiring-manager'] } },\n },\n});\n```"
|
|
122
|
+
"content": "Views implement **Column Level Security (CLS)** - controlling which columns users can access. This complements **Row Level Security (RLS)** provided by the [Firewall](/compiler/definitions/firewall), which controls which rows users can access.\n\n> **Migration note**: views were previously declared at the resource top\n> level (`views: {...}`). In DSL v2 they live under\n> [`read.views`](/compiler/definitions/read#views-under-read-views) so the\n> read pipeline owns its own configuration. The top-level form is rejected\n> at compile time.\n\n| Security Layer | Controls | Quickback Feature |\n|----------------|----------|-------------------|\n| Row Level Security | Which records | Firewall |\n| Column Level Security | Which fields | Views |\n\nViews provide named field projections with role-based access control. Use views to return different sets of columns to different users without duplicating CRUD endpoints.\n\n## When to Use Views\n\n| Concept | Purpose | Example |\n|---------|---------|---------|\n| CRUD list | Full records | Returns all columns |\n| Masking | Hide values | Email `j***@c******.com` |\n| Views | Exclude columns | Only `id`, `name`, `source` |\n\n- **CRUD list** returns all fields to authorized users\n- **Masking** transforms sensitive values but still includes the column\n- **Views** completely exclude columns from the response\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\n\nexport const candidates = sqliteTable('candidates', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull(),\n phone: text('phone'),\n source: text('source'),\n resumeUrl: text('resume_url'),\n internalNotes: text('internal_notes'),\n organizationId: text('organization_id').notNull(),\n});\n\nexport default defineTable(candidates, {\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n\n // Named field projections\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'source', 'resumeUrl', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n report: {\n fields: ['id', 'name', 'source', 'createdAt'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n});\n```\n\n## Generated Endpoints\n\nEach named view generates a dedicated GET endpoint:\n\n```\nGET /api/v1/candidates # Full read - read.access fields\nGET /api/v1/candidates/views/pipeline # interviewer/recruiter/etc.\nGET /api/v1/candidates/views/full # hiring-manager/recruiter only\nGET /api/v1/candidates/views/report # report fields\n```\n\nIf `read.defaultView` is set, bare `GET /api/v1/candidates` can also resolve\nto that named view. Without `defaultView`, bare `GET /api/v1/candidates`\nreturns `VIEW_REQUIRED` once views are declared.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n### Pagination\n\n| Parameter | Description | Default | Max |\n|-----------|-------------|---------|-----|\n| `limit` | Number of records to return | 50 | 100 |\n| `offset` | Number of records to skip | 0 | - |\n\n```bash\n# Get first 10 records\nGET /api/v1/candidates/views/pipeline?limit=10\n\n# Get records 11-20\nGET /api/v1/candidates/views/pipeline?limit=10&offset=10\n```\n\n### Filtering\n\n```bash\n# Filter by exact value\nGET /api/v1/candidates/views/pipeline?source=linkedin\n\n# Filter with operators\nGET /api/v1/candidates/views/pipeline?createdAt.gt=2024-01-01\n\n# Multiple filters (AND logic)\nGET /api/v1/candidates/views/pipeline?source=linkedin&name.like=Smith\n```\n\n### Sorting\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n\n```bash\nGET /api/v1/candidates/views/pipeline?sort=name&order=asc\n```\n\n## Security\n\nAll four security pillars apply to views:\n\n| Pillar | Behavior |\n|--------|----------|\n| **Firewall** | WHERE clause applied (same as list) |\n| **Access** | Per-view access control |\n| **Guards** | N/A (read-only) |\n| **Masking** | Applied to returned fields |\n\n### Firewall\n\nViews automatically apply the same firewall conditions as the list endpoint. Users only see records within their organization scope.\n\n### Access Control\n\nEach view has its own access configuration:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Pipeline view - available to all roles\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Full view - recruiter and above\n full: {\n fields: ['id', 'name', 'source', 'email', 'phone', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\n### Masking\n\nMasking rules are applied to the returned fields. If a view includes a masked field like `email`, the masking rules still apply:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Even if an interviewer accesses the 'full' view, email will be masked\n // because masking rules take precedence\n full: {\n fields: ['id', 'name', 'email'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n### How Views and Masking Work Together\n\nViews and masking are orthogonal concerns:\n- **Views** control field selection (which columns appear)\n- **Masking** controls field transformation (how values appear based on role)\n\nExample configuration:\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n},\n\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name'], // email NOT included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email'], // email included\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n },\n}\n```\n\n| Endpoint | Role | `email` in response? | `email` value |\n|----------|------|---------------------|---------------|\n| `/views/pipeline` | interviewer | No | N/A |\n| `/views/pipeline` | recruiter | No | N/A |\n| `/views/full` | interviewer | Yes | `j***@c******.com` |\n| `/views/full` | recruiter | Yes | `jane@company.com` |\n\n## Aggregations\n\nViews can declare pre-computed aggregations that run alongside the row\nquery and surface as `aggregations: { ... }` on the response. This avoids a\ncustom standalone action for every \"count of X grouped by Y\" dashboard\ntile — the firewall and view filters already in place drive the metric.\n\n```typescript\nread: {\n access: { roles: ['owner', 'admin', 'member'] },\n views: {\n pipeline: {\n fields: ['id', 'jobId', 'candidateId', 'status', 'appliedAt'],\n aggregations: {\n totalApplications: { fn: 'count' },\n byStatus: { fn: 'groupBy', field: 'status' },\n },\n },\n },\n}\n```\n\nResponse now carries the aggregations alongside `data`:\n\n```json\n{\n \"data\": [/* paginated rows */],\n \"view\": \"pipeline\",\n \"pagination\": { \"count\": 50, \"page\": 1, \"pageSize\": 50, \"hasMore\": true },\n \"aggregations\": {\n \"totalApplications\": 173,\n \"byStatus\": {\n \"applied\": 102,\n \"screening\": 41,\n \"interview\": 18,\n \"offer\": 7,\n \"rejected\": 5\n }\n }\n}\n```\n\n### Supported aggregation functions\n\n| `fn` | `field` | Returns | Example |\n|---|---|---|---|\n| `sum` | required, numeric | scalar number | `{ fn: 'sum', field: 'guestCount' }` |\n| `avg` | required, numeric | scalar number | `{ fn: 'avg', field: 'salary' }` |\n| `min` | required | scalar number | `{ fn: 'min', field: 'price' }` |\n| `max` | required | scalar number | `{ fn: 'max', field: 'price' }` |\n| `count` | optional | `COUNT(*)` if omitted, `COUNT(field)` (non-null) if given | `{ fn: 'count' }` |\n| `count_distinct` | required | scalar number | `{ fn: 'count_distinct', field: 'sourceId' }` |\n| `groupBy` | required | `{ value: count }` map | `{ fn: 'groupBy', field: 'status' }` |\n\n`groupBy` always returns a count map keyed by the distinct values of `field`.\n`NULL` values bucket under the literal string `\"(none)\"`. Other rollup\nfunctions (`groupBy` + `sum` of another column) are deferred to a future\nrelease.\n\n### Filter and firewall inheritance\n\nAggregations always run over the **same** filtered, firewalled set as the\nrow query. Pagination is intentionally ignored — you get the value over\nevery matching record, not just the current page.\n\nIn practice: a request like\n`GET /applications/views/pipeline?status=applied&jobId=job_123&limit=10`\nreturns the first 10 applied rows for that job, AND `byStatus` reflects\nonly that filtered set (which will be `{ applied: <total> }` since the\nfilter pinned the status). This is the only consistent default — divorcing\nthe metric from the user's filters would surprise.\n\n### Constraints (compile-time)\n\n- `field` must reference a real column on the table.\n- `sum`/`avg` require numeric column types (`int`, `real`, `decimal`,\n `numeric`, `bigint`). Non-numeric columns are rejected at compile time.\n- The same masking opt-out gate that governs `query.{filterable, sortable,\n searchable}` applies to aggregations: the view's roles must satisfy the\n masking rule, otherwise the aggregation is rejected. (A `sum(salary)`\n leaks structure across the masked set even when the row payload is\n redacted.)\n- Aggregation names cannot collide with the reserved response fields\n `data`, `pagination`, `view`.\n- No raw SQL `expr:` form. Column references only — declare a generated\n column or write a custom action if you need arithmetic.\n\n## Response Format\n\nView responses include metadata about the view:\n\n```json\n{\n \"data\": [\n { \"id\": \"cnd_123\", \"name\": \"Jane Doe\", \"source\": \"linkedin\" },\n { \"id\": \"cnd_456\", \"name\": \"John Smith\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"pagination\": {\n \"count\": 2,\n \"page\": 1,\n \"pageSize\": 50,\n \"hasMore\": false\n }\n}\n```\n\nWhen the view declares `aggregations`, the response also includes an\n`aggregations: { ... }` field. See [Aggregations](#aggregations).\n\n## Complete Example\n\n```typescript\n// features/jobs/jobs.ts\nexport default defineTable(jobs, {\n guards: {\n createable: ['title', 'department', 'status', 'salaryMin', 'salaryMax'],\n updatable: ['title', 'department', 'status'],\n },\n\n masking: {\n salaryMin: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n salaryMax: { type: 'redact', show: { roles: ['owner', 'hiring-manager'] } },\n },\n\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Public job board view\n board: {\n fields: ['id', 'title', 'department', 'status'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Internal view with salary info\n internal: {\n fields: ['id', 'title', 'department', 'status', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n // Compensation report\n compensation: {\n fields: ['id', 'title', 'department', 'salaryMin', 'salaryMax'],\n access: { roles: ['owner', 'hiring-manager'] },\n },\n },\n },\n\n create: { access: { roles: ['owner', 'hiring-manager'] } },\n update: { access: { roles: ['owner', 'hiring-manager'] } },\n delete: { access: { roles: ['owner', 'hiring-manager'] } },\n});\n```"
|
|
123
123
|
},
|
|
124
124
|
"compiler/getting-started/claude-code": {
|
|
125
125
|
"title": "AI Tools",
|
|
@@ -127,35 +127,35 @@ export const DOCS = {
|
|
|
127
127
|
},
|
|
128
128
|
"compiler/getting-started/full-example": {
|
|
129
129
|
"title": "Complete Example",
|
|
130
|
-
"content": "This example shows a complete resource definition using all five security layers, and the production code Quickback generates from it.\n\n## What You Define\n\nA `candidates` resource for a multi-tenant recruitment application with:\n- Organization-level data isolation\n- Role-based CRUD permissions\n- Field-level write protection\n- PII masking for sensitive fields\n- Column-level views for different access levels\n\n```typescript title=\"quickback/features/candidates/candidates.ts\"\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n source: q.text().optional(), // e.g. \"linkedin\", \"referral\", \"careers-page\"\n internalNotes: q.text().optional(),\n organizationId: q.scope(\"organization\"),\n // Note: createdAt, createdBy, modifiedAt, modifiedBy are auto-injected\n },\n\n // firewall — auto-derived from q.scope(\"organization\") + soft-delete deletedAt;\n // explicit declaration is optional once a scope column is declared.\n\n // GUARDS — Field-level protection\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl', 'source'],\n updatable: ['name', 'phone'],\n },\n\n // MASKING — PII redaction (query.roles defaults to show.roles)\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n // READ — Collection + per-id GET, plus named views\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n },\n\n // CRUD — Write operations\n crud: {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n },\n});\n```\n\n> Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.\n\n---\n\n## What Quickback Generates\n\nRun `quickback compile` and Quickback generates production-ready code.\n\n### Security Helpers\n\n```typescript title=\"src/features/candidates/candidates.resource.ts\"\n\n/**\n * Firewall conditions for candidates\n * Auto-derived from q.scope(\"organization\") + audit-injected deletedAt.\n * 2 predicates: tenant scope AND soft-delete filter.\n */\nexport function buildFirewallConditions(ctx: AppContext) {\n return and(\n eq(candidates.organizationId, ctx.activeOrgId!),\n isNull(candidates.deletedAt),\n );\n}\n\n/**\n * Guards configuration for field modification rules.\n * organizationId is added to systemManaged because q.scope(\"organization\")\n * is bound to ctx.activeOrgId — clients cannot submit it.\n */\nexport const GUARDS_CONFIG = {\n createable: new Set(['name', 'email', 'phone', 'resumeUrl', 'source']),\n updatable: new Set(['name', 'phone']),\n immutable: new Set([]),\n protected: {},\n systemManaged: new Set([\n 'createdAt', 'createdBy',\n 'modifiedAt', 'modifiedBy',\n 'deletedAt', 'deletedBy',\n 'organizationId', // ← added by q.scope(\"organization\")\n ]),\n};\n\n/**\n * Validates field input for CREATE operations.\n */\nexport function validateCreate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notCreateable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.createable.has(field) && !GUARDS_CONFIG.immutable.has(field)) {\n notCreateable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n protectedFields.length === 0 &&\n notCreateable.length === 0;\n\n return { valid, systemManaged, protected: protectedFields, notCreateable };\n}\n\n/**\n * Validates field input for UPDATE operations.\n */\nexport function validateUpdate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const immutable: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notUpdatable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (GUARDS_CONFIG.immutable.has(field)) {\n immutable.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.updatable.has(field)) {\n notUpdatable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n immutable.length === 0 &&\n protectedFields.length === 0 &&\n notUpdatable.length === 0;\n\n return { valid, systemManaged, immutable, protected: protectedFields, notUpdatable };\n}\n\n/**\n * Masks sensitive fields based on user role\n */\nexport function maskCandidate<T extends Record<string, any>>(\n record: T,\n ctx: AppContext\n): T {\n const masked: any = { ...record };\n\n // email: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['email'] != null) {\n masked['email'] = masks.email(masked['email']);\n }\n }\n\n // phone: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['phone'] != null) {\n masked['phone'] = masks.phone(masked['phone']);\n }\n }\n\n return masked as T;\n}\n\nexport function maskCandidates<T extends Record<string, any>>(\n records: T[],\n ctx: AppContext\n): T[] {\n return records.map(r => maskCandidate(r, ctx));\n}\n\n// CRUD Access configuration (write operations only)\nexport const CRUD_ACCESS = {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n};\n\n// Views configuration (read pipeline)\nexport const VIEWS_CONFIG = {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n} as const;\n```\n\n### API Routes\n\nThe generated routes wire everything together:\n\n```typescript title=\"src/features/candidates/candidates.routes.ts\"\n\n buildFirewallConditions,\n validateCreate,\n validateUpdate,\n maskCandidate,\n maskCandidates,\n VIEWS_CONFIG,\n CRUD_ACCESS,\n} from './candidates.resource';\n\nconst app = new Hono();\n\n// GET /candidates/views/:viewName — named view projection\nconst READ_ACCESS = { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] };\n\napp.get('/views/:viewName', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n const viewName = c.req.param('viewName');\n const params = Object.fromEntries(new URL(c.req.url).searchParams);\n const view = VIEWS_CONFIG[viewName as keyof typeof VIEWS_CONFIG];\n if (!view) return c.json({ error: 'Unknown view', code: 'VIEW_NOT_FOUND' }, 400);\n\n // Per-view access gate (falls back to read-level access)\n if (!await evaluateAccess(view.access ?? READ_ACCESS, ctx)) {\n return c.json(AccessErrors.roleRequired(view.access?.roles ?? READ_ACCESS.roles, ctx.roles), 403);\n }\n\n // Query with firewall conditions, project view fields, mask, return.\n const results = await db.select(/* projected fields */).from(candidates)\n .where(buildFirewallConditions(ctx));\n\n return c.json({ data: maskCandidates(results, ctx), view: viewName });\n});\n\n// POST /candidates - Create with guards\napp.post('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.create.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.create.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateCreate(body);\n if (!validation.valid) {\n if (validation.systemManaged.length > 0) {\n return c.json(GuardErrors.systemManaged(validation.systemManaged), 400);\n }\n if (validation.notCreateable.length > 0) {\n return c.json(GuardErrors.fieldNotCreateable(validation.notCreateable), 400);\n }\n }\n\n // Apply ownership and audit fields\n const data = {\n id: 'cnd_' + crypto.randomUUID().replace(/-/g, ''),\n ...body,\n organizationId: ctx.activeOrgId,\n createdAt: new Date().toISOString(),\n createdBy: ctx.userId,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.insert(candidates).values(data).returning();\n return c.json(maskCandidate(result[0], ctx), 201);\n});\n\n// PATCH /candidates/:id - Update with guards\napp.patch('/:id', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n const id = c.req.param('id');\n\n // Fetch with firewall\n const [record] = await db.select().from(candidates)\n .where(and(buildFirewallConditions(ctx), eq(candidates.id, id)));\n\n if (!record) {\n return c.json({ error: 'Not found', code: 'NOT_FOUND' }, 404);\n }\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.update.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.update.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateUpdate(body);\n if (!validation.valid) {\n if (validation.notUpdatable.length > 0) {\n return c.json(GuardErrors.fieldNotUpdatable(validation.notUpdatable), 400);\n }\n }\n\n // Apply audit fields\n const data = {\n ...body,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.update(candidates).set(data)\n .where(eq(candidates.id, id)).returning();\n\n return c.json(maskCandidate(result[0], ctx));\n});\n\nexport default app;\n```\n\n---\n\n## Runtime Behavior\n\n### Masking by Role\n\n| Role | `email` | `phone` |\n|------|---------|---------|\n| **hiring-manager** | `jane@example.com` | `555-123-4567` |\n| **recruiter** | `jane@example.com` | `555-123-4567` |\n| **interviewer** | `j***@e******.com` | `******4567` |\n\n### Views + Masking Interaction\n\nViews control **which fields are returned**. Masking controls **what values are shown**.\n\n| Endpoint | Role | `phone` in response? | `phone` value |\n|----------|------|--------------------|-------------|\n| `/candidates/views/pipeline` | interviewer | No | N/A |\n| `/candidates/views/pipeline` | recruiter | No | N/A |\n| `/candidates/views/full` | interviewer | No | N/A (no access) |\n| `/candidates/views/full` | recruiter | Yes | `555-123-4567` |\n\n### Guards Enforcement\n\n```bash\n# Allowed: Create with createable fields\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"email\": \"jane@example.com\", \"source\": \"linkedin\" }\n\n# Rejected: Update non-updatable field\nPATCH /candidates/cnd_123\n{ \"email\": \"new@example.com\" }\n# -> 400: \"Field 'email' is not updatable\"\n\n# Rejected: Set system-managed field\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"createdBy\": \"hacker\" }\n# -> 400: \"System-managed fields cannot be set: createdBy\"\n```\n\n---\n\n## Generated API Endpoints\n\n| Method | Endpoint | Access |\n|--------|----------|--------|\n| `GET` | `/candidates` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/:id` | owner, hiring-manager, recruiter, interviewer |\n| `POST` | `/candidates` | hiring-manager, recruiter |\n| `PATCH` | `/candidates/:id` | hiring-manager, recruiter |\n| `DELETE` | `/candidates/:id` | hiring-manager |\n| `GET` | `/candidates/views/pipeline` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/views/full` | hiring-manager, recruiter |\n\n---\n\n## Key Takeaways\n\n1. **~50 lines of configuration** generates **~500+ lines of production code**\n2. **Security is declarative** - you describe *what* you want, not *how*\n3. **All layers work together** - Firewall -> Access -> Guards -> Masking\n4. **Code is readable and auditable** - no magic, just TypeScript\n5. **Type-safe from definition to API** - Drizzle schema drives everything"
|
|
130
|
+
"content": "This example shows a complete resource definition using all five security layers, and the production code Quickback generates from it.\n\n## What You Define\n\nA `candidates` resource for a multi-tenant recruitment application with:\n- Organization-level data isolation\n- Role-based write permissions\n- Field-level write protection\n- PII masking for sensitive fields\n- Column-level views for different access levels\n\n```typescript title=\"quickback/features/candidates/candidates.ts\"\n\nexport default feature('candidates', {\n columns: {\n id: q.id(),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n resumeUrl: q.text().optional(),\n source: q.text().optional(), // e.g. \"linkedin\", \"referral\", \"careers-page\"\n internalNotes: q.text().optional(),\n organizationId: q.scope(\"organization\"),\n // Note: createdAt, createdBy, modifiedAt, modifiedBy are auto-injected\n },\n\n // firewall — auto-derived from q.scope(\"organization\") + soft-delete deletedAt;\n // explicit declaration is optional once a scope column is declared.\n\n // GUARDS — Field-level protection\n guards: {\n createable: ['name', 'email', 'phone', 'resumeUrl', 'source'],\n updatable: ['name', 'phone'],\n },\n\n // MASKING — PII redaction (query.roles defaults to show.roles)\n masking: {\n email: { type: 'email', show: { roles: ['hiring-manager', 'recruiter'] } },\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n },\n\n // READ — Collection + per-id GET, plus named views\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n },\n },\n\n // WRITE OPERATIONS\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n});\n```\n\n> Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.\n\n---\n\n## What Quickback Generates\n\nRun `quickback compile` and Quickback generates production-ready code.\n\n### Security Helpers\n\n```typescript title=\"src/features/candidates/candidates.resource.ts\"\n\n/**\n * Firewall conditions for candidates\n * Auto-derived from q.scope(\"organization\") + audit-injected deletedAt.\n * 2 predicates: tenant scope AND soft-delete filter.\n */\nexport function buildFirewallConditions(ctx: AppContext) {\n return and(\n eq(candidates.organizationId, ctx.activeOrgId!),\n isNull(candidates.deletedAt),\n );\n}\n\n/**\n * Guards configuration for field modification rules.\n * organizationId is added to systemManaged because q.scope(\"organization\")\n * is bound to ctx.activeOrgId — clients cannot submit it.\n */\nexport const GUARDS_CONFIG = {\n createable: new Set(['name', 'email', 'phone', 'resumeUrl', 'source']),\n updatable: new Set(['name', 'phone']),\n immutable: new Set([]),\n protected: {},\n systemManaged: new Set([\n 'createdAt', 'createdBy',\n 'modifiedAt', 'modifiedBy',\n 'deletedAt', 'deletedBy',\n 'organizationId', // ← added by q.scope(\"organization\")\n ]),\n};\n\n/**\n * Validates field input for CREATE operations.\n */\nexport function validateCreate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notCreateable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.createable.has(field) && !GUARDS_CONFIG.immutable.has(field)) {\n notCreateable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n protectedFields.length === 0 &&\n notCreateable.length === 0;\n\n return { valid, systemManaged, protected: protectedFields, notCreateable };\n}\n\n/**\n * Validates field input for UPDATE operations.\n */\nexport function validateUpdate(input: Record<string, any>) {\n const systemManaged: string[] = [];\n const immutable: string[] = [];\n const protectedFields: Array<{ field: string; actions: string[] }> = [];\n const notUpdatable: string[] = [];\n\n for (const field of Object.keys(input)) {\n if (GUARDS_CONFIG.systemManaged.has(field)) {\n systemManaged.push(field);\n continue;\n }\n if (GUARDS_CONFIG.immutable.has(field)) {\n immutable.push(field);\n continue;\n }\n if (field in GUARDS_CONFIG.protected) {\n const actions = [...GUARDS_CONFIG.protected[field]];\n protectedFields.push({ field, actions });\n continue;\n }\n if (!GUARDS_CONFIG.updatable.has(field)) {\n notUpdatable.push(field);\n }\n }\n\n const valid = systemManaged.length === 0 &&\n immutable.length === 0 &&\n protectedFields.length === 0 &&\n notUpdatable.length === 0;\n\n return { valid, systemManaged, immutable, protected: protectedFields, notUpdatable };\n}\n\n/**\n * Masks sensitive fields based on user role\n */\nexport function maskCandidate<T extends Record<string, any>>(\n record: T,\n ctx: AppContext\n): T {\n const masked: any = { ...record };\n\n // email: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['email'] != null) {\n masked['email'] = masks.email(masked['email']);\n }\n }\n\n // phone: show to hiring-manager, recruiter\n if (!ctx.roles?.some(r => ['hiring-manager', 'recruiter'].includes(r))) {\n if (masked['phone'] != null) {\n masked['phone'] = masks.phone(masked['phone']);\n }\n }\n\n return masked as T;\n}\n\nexport function maskCandidates<T extends Record<string, any>>(\n records: T[],\n ctx: AppContext\n): T[] {\n return records.map(r => maskCandidate(r, ctx));\n}\n\n// Write access configuration (internal normalized shape)\nexport const CRUD_ACCESS = {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },\n};\n\n// Views configuration (read pipeline)\nexport const VIEWS_CONFIG = {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source', 'internalNotes'],\n access: { roles: ['hiring-manager', 'recruiter'] },\n },\n} as const;\n```\n\n### API Routes\n\nThe generated routes wire everything together:\n\n```typescript title=\"src/features/candidates/candidates.routes.ts\"\n\n buildFirewallConditions,\n validateCreate,\n validateUpdate,\n maskCandidate,\n maskCandidates,\n VIEWS_CONFIG,\n CRUD_ACCESS,\n} from './candidates.resource';\n\nconst app = new Hono();\n\n// GET /candidates/views/:viewName — named view projection\nconst READ_ACCESS = { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] };\n\napp.get('/views/:viewName', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n const viewName = c.req.param('viewName');\n const params = Object.fromEntries(new URL(c.req.url).searchParams);\n const view = VIEWS_CONFIG[viewName as keyof typeof VIEWS_CONFIG];\n if (!view) return c.json({ error: 'Unknown view', code: 'VIEW_NOT_FOUND' }, 400);\n\n // Per-view access gate (falls back to read-level access)\n if (!await evaluateAccess(view.access ?? READ_ACCESS, ctx)) {\n return c.json(AccessErrors.roleRequired(view.access?.roles ?? READ_ACCESS.roles, ctx.roles), 403);\n }\n\n // Query with firewall conditions, project view fields, mask, return.\n const results = await db.select(/* projected fields */).from(candidates)\n .where(buildFirewallConditions(ctx));\n\n return c.json({ data: maskCandidates(results, ctx), view: viewName });\n});\n\n// POST /candidates - Create with guards\napp.post('/', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.create.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.create.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateCreate(body);\n if (!validation.valid) {\n if (validation.systemManaged.length > 0) {\n return c.json(GuardErrors.systemManaged(validation.systemManaged), 400);\n }\n if (validation.notCreateable.length > 0) {\n return c.json(GuardErrors.fieldNotCreateable(validation.notCreateable), 400);\n }\n }\n\n // Apply ownership and audit fields\n const data = {\n id: 'cnd_' + crypto.randomUUID().replace(/-/g, ''),\n ...body,\n organizationId: ctx.activeOrgId,\n createdAt: new Date().toISOString(),\n createdBy: ctx.userId,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.insert(candidates).values(data).returning();\n return c.json(maskCandidate(result[0], ctx), 201);\n});\n\n// PATCH /candidates/:id - Update with guards\napp.patch('/:id', async (c) => {\n const ctx = c.get('ctx');\n const db = c.get('db');\n const id = c.req.param('id');\n\n // Fetch with firewall\n const [record] = await db.select().from(candidates)\n .where(and(buildFirewallConditions(ctx), eq(candidates.id, id)));\n\n if (!record) {\n return c.json({ error: 'Not found', code: 'NOT_FOUND' }, 404);\n }\n\n // Access check\n if (!await evaluateAccess(CRUD_ACCESS.update.access, ctx)) {\n return c.json(AccessErrors.roleRequired(\n CRUD_ACCESS.update.access.roles,\n ctx.roles\n ), 403);\n }\n\n const body = await c.req.json();\n\n // Guards validation\n const validation = validateUpdate(body);\n if (!validation.valid) {\n if (validation.notUpdatable.length > 0) {\n return c.json(GuardErrors.fieldNotUpdatable(validation.notUpdatable), 400);\n }\n }\n\n // Apply audit fields\n const data = {\n ...body,\n modifiedAt: new Date().toISOString(),\n modifiedBy: ctx.userId,\n };\n\n const result = await db.update(candidates).set(data)\n .where(eq(candidates.id, id)).returning();\n\n return c.json(maskCandidate(result[0], ctx));\n});\n\nexport default app;\n```\n\n---\n\n## Runtime Behavior\n\n### Masking by Role\n\n| Role | `email` | `phone` |\n|------|---------|---------|\n| **hiring-manager** | `jane@example.com` | `555-123-4567` |\n| **recruiter** | `jane@example.com` | `555-123-4567` |\n| **interviewer** | `j***@e******.com` | `******4567` |\n\n### Views + Masking Interaction\n\nViews control **which fields are returned**. Masking controls **what values are shown**.\n\n| Endpoint | Role | `phone` in response? | `phone` value |\n|----------|------|--------------------|-------------|\n| `/candidates/views/pipeline` | interviewer | No | N/A |\n| `/candidates/views/pipeline` | recruiter | No | N/A |\n| `/candidates/views/full` | interviewer | No | N/A (no access) |\n| `/candidates/views/full` | recruiter | Yes | `555-123-4567` |\n\n### Guards Enforcement\n\n```bash\n# Allowed: Create with createable fields\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"email\": \"jane@example.com\", \"source\": \"linkedin\" }\n\n# Rejected: Update non-updatable field\nPATCH /candidates/cnd_123\n{ \"email\": \"new@example.com\" }\n# -> 400: \"Field 'email' is not updatable\"\n\n# Rejected: Set system-managed field\nPOST /candidates\n{ \"name\": \"Jane Smith\", \"createdBy\": \"hacker\" }\n# -> 400: \"System-managed fields cannot be set: createdBy\"\n```\n\n---\n\n## Generated API Endpoints\n\n| Method | Endpoint | Access |\n|--------|----------|--------|\n| `GET` | `/candidates` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/:id` | owner, hiring-manager, recruiter, interviewer |\n| `POST` | `/candidates` | hiring-manager, recruiter |\n| `PATCH` | `/candidates/:id` | hiring-manager, recruiter |\n| `DELETE` | `/candidates/:id` | hiring-manager |\n| `GET` | `/candidates/views/pipeline` | owner, hiring-manager, recruiter, interviewer |\n| `GET` | `/candidates/views/full` | hiring-manager, recruiter |\n\n---\n\n## Key Takeaways\n\n1. **~50 lines of configuration** generates **~500+ lines of production code**\n2. **Security is declarative** - you describe *what* you want, not *how*\n3. **All layers work together** - Firewall -> Access -> Guards -> Masking\n4. **Code is readable and auditable** - no magic, just TypeScript\n5. **Type-safe from definition to API** - Drizzle schema drives everything"
|
|
131
131
|
},
|
|
132
132
|
"compiler/getting-started/hand-crafted": {
|
|
133
133
|
"title": "Hand-Crafted Setup",
|
|
134
|
-
"content": "If you have an existing project and want to add Quickback-generated API endpoints, you can set up the definitions directory manually instead of using a template.\n\n## Prerequisites\n\n- An existing Hono-based project (Cloudflare Workers or Bun)\n- Node.js 18+ or Bun installed\n- The Quickback CLI: `npm install -g @quickback-dev/cli`\n\n## Setup\n\n### 1. Create the Quickback Directory\n\nCreate a `quickback/` directory in your project root with the following structure:\n\n```\nyour-project/\n├── quickback/\n│ ├── quickback.config.ts\n│ └── features/\n│ └── (your features go here)\n├── src/ # Your existing code\n├── package.json\n└── ...\n```\n\n```bash\nmkdir -p quickback/features\n```\n\n### 2. Write Your Config\n\nCreate `quickback/quickback.config.ts`:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\nAdjust the providers to match your existing stack. See [Providers](/compiler/config/providers) for all options.\n\n### 3. Create Your First Feature\n\nCreate a feature directory with a schema + security definition:\n\n```bash\nmkdir quickback/features/candidates\n```\n\nCreate `quickback/features/candidates/candidates.ts`:\n\n```typescript\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n
|
|
134
|
+
"content": "If you have an existing project and want to add Quickback-generated API endpoints, you can set up the definitions directory manually instead of using a template.\n\n## Prerequisites\n\n- An existing Hono-based project (Cloudflare Workers or Bun)\n- Node.js 18+ or Bun installed\n- The Quickback CLI: `npm install -g @quickback-dev/cli`\n\n## Setup\n\n### 1. Create the Quickback Directory\n\nCreate a `quickback/` directory in your project root with the following structure:\n\n```\nyour-project/\n├── quickback/\n│ ├── quickback.config.ts\n│ └── features/\n│ └── (your features go here)\n├── src/ # Your existing code\n├── package.json\n└── ...\n```\n\n```bash\nmkdir -p quickback/features\n```\n\n### 2. Write Your Config\n\nCreate `quickback/quickback.config.ts`:\n\n```typescript\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n features: [\"organizations\"],\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n});\n```\n\nAdjust the providers to match your existing stack. See [Providers](/compiler/config/providers) for all options.\n\n### 3. Create Your First Feature\n\nCreate a feature directory with a schema + security definition:\n\n```bash\nmkdir quickback/features/candidates\n```\n\nCreate `quickback/features/candidates/candidates.ts`:\n\n```typescript\n\nexport const candidates = sqliteTable(\"candidates\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n email: text(\"email\").notNull(),\n phone: text(\"phone\"),\n source: text(\"source\"),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\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\"] }, mode: \"soft\" },\n});\n```\n\n### 4. Log In and Compile\n\n```bash\nquickback login\nquickback compile\n```\n\nThe compiler generates a complete `src/` directory with route handlers, middleware, database schemas, and migrations.\n\n### 5. Integrate with Your Existing Code\n\nThe compiled output creates a self-contained Hono app in `src/index.ts`. If you need to integrate the generated routes into an existing Hono app, you can import the feature routes directly:\n\n```typescript\n\nconst app = new Hono();\n\n// Your existing routes\napp.get(\"/\", (c) => c.json({ status: \"ok\" }));\n\n// Mount generated feature routes\napp.route(\"/api/v1/candidates\", candidatesRoutes);\n\nexport default app;\n```\n\n## Directory Structure\n\nThe compiler expects this structure inside `quickback/`:\n\n```\nquickback/\n├── quickback.config.ts # Required: compiler configuration\n└── features/ # Required: feature definitions\n ├── candidates/\n │ ├── candidates.ts # Schema + security (defineTable)\n │ └── actions.ts # Optional: custom actions\n ├── jobs/\n │ ├── jobs.ts\n │ └── actions.ts\n └── ...\n```\n\nEach feature directory should contain:\n- **`{name}.ts`** — The main definition file using `defineTable()` (required)\n- **`actions.ts`** — Custom actions using `defineActions()` (optional)\n\n## Adding Features\n\nTo add a new feature, create a new directory under `quickback/features/` and recompile:\n\n```bash\nmkdir quickback/features/jobs\n# Create jobs/jobs.ts with defineTable(...)\nquickback compile\n```\n\nThe compiler detects all features automatically — no registration needed.\n\n## Recompiling\n\nAfter any change to your definitions, recompile to regenerate the output:\n\n```bash\nquickback compile\n```\n\nThe compiler regenerates the entire `src/` directory. Your definitions in `quickback/` are the source of truth — never edit the generated files directly.\n\n**Warning:** Don't edit files in `src/` manually. They will be overwritten on the next compile. All changes should be made in your `quickback/` definitions.\n\n## Next Steps\n\n- [Configuration reference](/compiler/config) — All config options\n- [Schema definitions](/compiler/definitions/schema) — Define tables with `defineTable()`\n- [Security pillars](/compiler/definitions) — Firewall, Access, Guards, Masking\n- [Templates](/compiler/getting-started/templates) — Use a template for new projects instead"
|
|
135
135
|
},
|
|
136
136
|
"compiler/getting-started": {
|
|
137
137
|
"title": "Getting Started",
|
|
138
|
-
"content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n##
|
|
138
|
+
"content": "Get started with Quickback in minutes. This guide shows you how to define a complete table with security configuration.\n\n## Start a Project\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`quickback start` is interactive — it asks for a template and project name, 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; finish later with `quickback login && quickback compile`.\n\nPrefer a scriptable form?\n\n```bash\nnpm install -g @quickback-dev/cli\nquickback create cloudflare my-app\ncd my-app\n```\n\nBoth paths scaffold the same project:\n- `quickback.config.ts` — Project configuration\n- `quickback/features/` — Your table definitions\n- Working example feature with full security configuration (when you pick `todos`/`blog`/`saas`)\n\n**Available templates:**\n- `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold (free)\n- `todos` — Working CRUD example with masking + actions (free)\n- `blog` — Single-tenant blog, PUBLIC reads, admin writes (free)\n- `empty` — Cloudflare scaffold, no example features (free)\n- `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks (pro)\n\n## File Structure\n\nEach table gets its own file with schema and security config together:\n\n```\nquickback/\n├── quickback.config.ts\n└── features/\n └── jobs/\n ├── jobs.ts # Table + security config\n ├── applications.ts # Related table + config\n ├── actions.ts # Custom actions (optional)\n └── handlers/ # Action handlers (optional)\n └── close-job.ts\n```\n\n## Complete Example\n\nHere's a complete `jobs` table with all security layers in a single `feature()` call:\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 // Ownership — required for firewall data isolation\n organizationId: q.scope(\"organization\"),\n },\n\n // 1. FIREWALL — Data isolation\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n // 2. GUARDS — Field modification rules\n guards: {\n createable: [\"title\", \"department\", \"status\", \"salaryMin\", \"salaryMax\"],\n updatable: [\"title\", \"department\", \"status\"],\n },\n\n // 3. READ — Collection + per-id GET (gates GET / and GET /:id)\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n pageSize: 25,\n },\n\n // 4. WRITE OPERATIONS\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] }, mode: \"soft\" },\n});\n```\n\nOne import, one export, every security layer declared in one place. Secure by default — no write routes ship until you opt in with top-level `create`, `update`, `delete`, or `upsert`.\n\n### Alternatives — same result, different shape\n\nIf you'd rather split the table declaration from the security config (e.g. to reference the table in an action file), use the two-export form. Identical output:\n\n```typescript\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n // … same columns\n});\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n // … same config\n});\n\nexport type Job = typeof jobs.$infer;\n```\n\nOr if you're interop'ing with existing Drizzle schemas, you can author with `sqliteTable` / `pgTable` directly — the compiler dispatches per file, and all forms can coexist in the same project.\n\nSee [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle) for the full picture.\n\n## What Each Layer Does\n\n1. **Firewall**: Automatically adds `WHERE organizationId = ?` to every query. Users in Org A can never see Org B's data.\n2. **Guards**: Controls which fields can be modified — `createable` for POST, `updatable` for PATCH, `protected` for action-only fields.\n3. **Write Access**: Role-based access control for each operation. All roles can read, only hiring managers can write.\n\n## Compile and Run\n\n```bash\n# Compile your definitions — prompts you to sign in or sign up\n# if you haven't already (no separate `quickback login` step needed)\nquickback compile\n\n# Run locally\nnpm run dev\n```\n\nThe first compile prompts for an account; subsequent compiles re-use the stored session.\n\n## Generated Endpoints\n\nQuickback generates these endpoints from the example above:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/api/v1/jobs` | List jobs (all roles) |\n| `GET` | `/api/v1/jobs/:id` | Get single job |\n| `POST` | `/api/v1/jobs` | Create job (hiring managers only) |\n| `PATCH` | `/api/v1/jobs/:id` | Update job (hiring managers only) |\n| `DELETE` | `/api/v1/jobs/:id` | Soft delete job (hiring managers only) |\n\n## Test Your API\n\nAfter `quickback compile` and `npm run dev`, your API is running locally. Open a second terminal and try these requests:\n\n```bash\n# 1. Create a user account\ncurl -X POST http://localhost:8787/api/auth/sign-up/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\", \"name\": \"Admin\"}'\n\n# 2. Sign in and get a session token\ncurl -X POST http://localhost:8787/api/auth/sign-in/email \\\n -H \"Content-Type: application/json\" \\\n -d '{\"email\": \"admin@example.com\", \"password\": \"securepassword123\"}'\n# → Response includes a session token in Set-Cookie header\n\n# 3. Create a record (use the session cookie from step 2)\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=<token>\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# 4. List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Cookie: better-auth.session_token=<token>\"\n```\n\n## Next Steps\n\n- [Template Walkthroughs](/compiler/getting-started/templates) — Detailed setup guides\n- [Full Example](/compiler/getting-started/full-example) — Complete resource walkthrough\n- [Database Schema](/compiler/definitions/schema) — Column types, relations, audit fields\n- [Firewall](/compiler/definitions/firewall) — Data isolation patterns\n- [Access](/compiler/definitions/access) — Role & condition-based control\n- [Guards](/compiler/definitions/guards) — Field modification rules\n- [Masking](/compiler/definitions/masking) — Field redaction for sensitive data\n- [Actions](/compiler/definitions/actions) — Custom business logic endpoints\n\n## See Also\n\n- [Quickback Stack](/stack) — The runtime environment where your compiled API runs (D1, KV, R2, auth)\n- [Account UI](/stack/account-ui) — Pre-built authentication and account management UI\n- [Using the API](/compiler/targets/hono-api/using-the-api) — CRUD endpoints, filtering, and batch operations"
|
|
139
139
|
},
|
|
140
140
|
"compiler/getting-started/patterns": {
|
|
141
141
|
"title": "Common Patterns",
|
|
142
|
-
"content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Public Read, Authenticated Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\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 read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n
|
|
142
|
+
"content": "Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.\n\n## Public Read, Authenticated Write\n\nA job board where all team members can browse open positions but only hiring managers can create or edit jobs:\n\n```typescript\n// quickback/features/jobs/jobs.ts\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 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\n## User-Scoped Personal Data\n\nInterview notes that belong to a specific interviewer. Each interviewer only sees their own notes:\n\n```typescript\n// Schema includes both organizationId AND ownerId (q DSL)\n\nexport const interviewNotes = q.table(\"interview_notes\", {\n id: q.id(),\n candidateId: q.text().required(),\n content: q.text().required(),\n rating: q.int().optional(),\n organizationId: q.scope(\"organization\"),\n ownerId: q.text().required(),\n});\n\nexport default defineTable(interviewNotes, {\n firewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'ownerId', equals: 'ctx.userId' }, // Only the interviewer can see their own notes\n ],\n guards: {\n createable: [\"candidateId\", \"content\", \"rating\"],\n updatable: [\"content\", \"rating\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] } },\n});\n```\n\nThe owner predicate (`{ field: 'ownerId', equals: 'ctx.userId' }`) means even hiring managers can only see notes they authored. To let hiring managers see all notes regardless of author, drop the owner predicate from the firewall and gate per-id access via record conditions instead.\n\n## Multi-Table Feature with Internal Tables\n\nA feature with a main table exposed via API and a junction table used only in actions:\n\n```typescript\n// quickback/features/applications/applications.ts — exposed via API\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"stage\", \"notes\"],\n updatable: [\"notes\"],\n },\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```typescript\n// quickback/features/applications/interview-scores.ts — internal, no API routes\n// No default export = no routes generated\nexport const interviewScores = sqliteTable(\"interview_scores\", {\n applicationId: text(\"application_id\").notNull(),\n interviewerId: text(\"interviewer_id\").notNull(),\n score: integer(\"score\").notNull(),\n feedback: text(\"feedback\"),\n organizationId: text(\"organization_id\").notNull(), // Always scope junction tables\n});\n```\n\n```typescript\n// quickback/features/applications/actions.ts — uses the internal table\n\nexport default defineActions(applications, {\n submitScore: {\n type: \"record\",\n input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),\n access: { roles: [\"owner\", \"hiring-manager\", \"interviewer\"] },\n execute: async ({ db, record, input, ctx }) => {\n await db.insert(interviewScores).values({\n applicationId: record.id,\n interviewerId: ctx.userId,\n score: input.score,\n feedback: input.feedback,\n });\n return record;\n },\n },\n});\n```\n\n## Admin-Only Status Field\n\nA field that only hiring managers can modify, but everyone can see:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"candidateId\", \"jobId\", \"notes\"],\n updatable: [\"notes\"], // Recruiters can only update notes\n protected: [\"stage\"], // Stage can only be changed via actions\n },\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: [\"hiring-manager\"] } },\n});\n```\n\nThen create an action that hiring managers use to change stage:\n\n```typescript\n// quickback/features/applications/actions.ts\nexport default defineActions(applications, {\n advanceStage: {\n type: \"record\",\n input: z.object({ stage: z.enum([\"applied\", \"screening\", \"interview\", \"offer\", \"hired\", \"rejected\"]) }),\n access: { roles: [\"hiring-manager\"] },\n execute: async ({ db, record, input }) => {\n await db.update(applications).set({ stage: input.stage }).where(eq(applications.id, record.id));\n return { ...record, stage: input.stage };\n },\n },\n});\n```\n\n## Sensitive Data with Role-Based Masking\n\nA candidate record where PII is masked differently per role:\n\n```typescript\nexport default defineTable(candidates, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"name\", \"email\", \"phone\", \"resumeUrl\", \"source\"],\n updatable: [\"name\", \"phone\"],\n },\n masking: {\n email: { type: \"email\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n phone: { type: \"phone\", show: { roles: [\"hiring-manager\", \"recruiter\"] } },\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"hiring-manager\"] } },\n});\n```\n\n| Role | email | phone |\n|------|-------|-------|\n| hiring-manager | `jane@example.com` | `555-123-4567` |\n| recruiter | `jane@example.com` | `555-123-4567` |\n| interviewer | `j***@e******.com` | `***-***-4567` |\n\n## External System Sync\n\nAn import table for syncing candidates from an external ATS via upsert:\n\n```typescript\n// quickback/features/ats-imports/ats-imports.ts\nexport default defineTable(atsImports, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: {\n createable: [\"externalId\", \"source\", \"candidateName\", \"candidateEmail\", \"rawPayload\"],\n updatable: [\"candidateName\", \"candidateEmail\", \"rawPayload\", \"syncedAt\"],\n },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n delete: { access: { roles: [\"owner\"] } },\n});\n```\n\n## See Also\n\n- [Full Example](/compiler/getting-started/full-example) — Complete walkthrough with generated code\n- [Firewall](/compiler/definitions/firewall) — All data isolation options\n- [Actions](/compiler/definitions/actions) — Custom business logic"
|
|
143
143
|
},
|
|
144
144
|
"compiler/getting-started/template-blog": {
|
|
145
145
|
"title": "Blog Template",
|
|
146
|
-
"content": "The blog template creates a single-tenant backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts via Better Auth's admin plugin.\n\nThis template uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, no `organizationId` columns. Roles come from `user.role` instead of org membership.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Single-tenant config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions.ts # Publish/unpublish actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nKey difference from the multi-tenant templates: `organizations: false` disables the Better Auth organization plugin. See [Single-Tenant Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"ownerId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n
|
|
146
|
+
"content": "The blog template creates a single-tenant backend for a blog or CMS, deployed to Cloudflare Workers with D1. Public visitors can read content without authentication, while admins manage posts via Better Auth's admin plugin.\n\nThis template uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, no `organizationId` columns. Roles come from `user.role` instead of org membership.\n\n## Create the Project\n\n```bash\nquickback create blog my-site\ncd my-site\n```\n\nThis scaffolds a project with:\n\n```\nmy-site/\n├── quickback/\n│ ├── quickback.config.ts # Single-tenant config\n│ └── features/\n│ └── posts/\n│ ├── posts.ts # Schema + security (defineTable)\n│ └── actions.ts # Publish/unpublish actions\n├── src/ # Compiled output (generated)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-site\",\n template: \"hono\",\n features: {\n organizations: false,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nKey difference from the multi-tenant templates: `organizations: false` disables the Better Auth organization plugin. See [Single-Tenant Mode](/compiler/config/single-tenant) for details.\n\n### Posts Feature (posts.ts)\n\nThe template includes a `posts` feature with public read access and admin-only write access:\n\n```typescript\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n excerpt: text(\"excerpt\"),\n status: text(\"status\").notNull().default(\"draft\"),\n publishedAt: text(\"published_at\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: [\n { field: 'ownerId', equals: 'ctx.userId' },\n { field: 'deletedAt', isNull: true },\n ],\n guards: {\n createable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n updatable: [\"title\", \"slug\", \"content\", \"excerpt\", \"status\", \"publishedAt\"],\n immutable: [\"id\", \"ownerId\"],\n },\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] }, mode: \"soft\" },\n});\n```\n\n- **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`\n- **`admin`** role on `create`, `update`, and `delete` requires an authenticated user with `role: \"admin\"` (set via Better Auth's admin plugin)\n- **`owner`** firewall scope tracks who created each post via `ownerId`\n- **`softDelete`** marks posts as deleted rather than removing them from the database\n\n### Post Actions (actions.ts)\n\nThe template includes publish/unpublish actions with guard conditions:\n\n```typescript\n\nexport default defineActions(posts, {\n publish: {\n description: \"Publish a draft post\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"draft\" } },\n },\n sideEffects: \"sync\",\n },\n unpublish: {\n description: \"Revert a published post to draft\",\n input: z.object({}),\n guard: {\n roles: [\"admin\"],\n record: { status: { equals: \"published\" } },\n },\n sideEffects: \"sync\",\n },\n});\n```\n\nThese actions are admin-only and include record-level guards — you can only publish drafts and unpublish published posts.\n\n## Setup Steps\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Log In to the Compiler\n\n```bash\nquickback login\n```\n\n### 3. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\n### 4. Create D1 Database\n\nThe blog template uses a single D1 database (no split databases):\n\n```bash\nnpx wrangler d1 create my-site\n```\n\nCopy the database ID from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-site\"\ndatabase_id = \"paste-id-here\"\n```\n\n### 5. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\n### 6. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Using the API\n\n### Public Endpoints (No Auth Required)\n\n```bash\n# List all posts\ncurl http://localhost:8787/api/v1/posts\n\n# Get a single post\ncurl http://localhost:8787/api/v1/posts/post-id-here\n```\n\n### Admin Endpoints (Auth Required)\n\n```bash\n# Create a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts \\\n -H \"Authorization: Bearer $TOKEN\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Hello World\", \"slug\": \"hello-world\", \"content\": \"...\"}'\n\n# Publish a post (admin only)\ncurl -X POST http://localhost:8787/api/v1/posts/post-id/actions/publish \\\n -H \"Authorization: Bearer $TOKEN\"\n```\n\n### Pairing with a Frontend\n\nSince this is a JSON API, pair it with any frontend framework:\n\n```typescript\n// Astro, Next.js, SvelteKit, etc.\nconst posts = await fetch('https://api.mysite.com/api/v1/posts').then(r => r.json());\n\n// Admin operations require authentication\nconst res = await fetch('https://api.mysite.com/api/v1/posts', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ title: 'New Post', slug: 'new-post', content: '...' }),\n});\n```\n\n## Adding More Features\n\nAdd new content types by creating feature directories. For example, a `pages` feature for static pages:\n\n```typescript\n// quickback/features/pages/pages.ts\n\nexport const pages = sqliteTable(\"pages\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n slug: text(\"slug\").notNull().unique(),\n content: text(\"content\"),\n ownerId: text(\"owner_id\").notNull(),\n});\n\nexport default defineTable(pages, {\n firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],\n read: {\n access: { roles: [\"PUBLIC\"] },\n },\n create: { access: { roles: [\"admin\"] } },\n update: { access: { roles: [\"admin\"] } },\n delete: { access: { roles: [\"admin\"] } },\n});\n```\n\nThen recompile:\n\n```bash\nquickback compile\n```\n\n## Deploying to Production\n\n```bash\n# Apply remote migrations\nnpm run db:migrate:remote\n\n# Deploy to Cloudflare\nnpm run deploy\n```\n\n## Next Steps\n\n- [Single-Tenant Mode](/compiler/config/single-tenant) — How single-tenant mode works\n- [Access Control](/compiler/definitions/access) — PUBLIC role and role-based permissions\n- [Custom Actions](/compiler/definitions/actions) — Add business logic beyond CRUD\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare) — Multi-tenant alternative"
|
|
147
147
|
},
|
|
148
148
|
"compiler/getting-started/template-cloudflare": {
|
|
149
149
|
"title": "Cloudflare Template",
|
|
150
|
-
"content": "The Cloudflare template creates a production-ready backend running on Cloudflare Workers with D1 (SQLite at the edge), KV storage, and Better Auth.\n\n## Create the Project\n\n```bash\
|
|
150
|
+
"content": "The Cloudflare template creates a production-ready backend running on Cloudflare Workers with D1 (SQLite at the edge), KV storage, and Better Auth.\n\n`cloudflare` is a **bare scaffold** — multi-tenant orgs + auth + DB are wired in, but there are no example features. Add your own feature files under `quickback/features/`. If you want a working example to read first, use the [todos template](/compiler/getting-started/templates#multi-tenant-scaffolds-free) — same providers, but with a complete `todos` feature ready to extend.\n\n## Create the Project\n\nThe fastest path is `start` — interactive, scaffold + login + compile in one flow:\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n# pick \"Cloudflare (bare scaffold)\" at the prompt\n```\n\nScriptable equivalent:\n\n```bash\nquickback create cloudflare my-app # aliases: cf\ncd my-app\n```\n\nThis scaffolds a project with:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # (empty — add your own)\n├── src/ # Compiled output (generated by `quickback compile`)\n├── package.json\n├── tsconfig.json\n├── wrangler.toml\n└── drizzle.config.ts\n```\n\n## Generated Configuration\n\n### quickback.config.ts\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n auth: {\n // Use \"role+\" in access rules to mean \"this role and above\".\n // e.g. roles: [\"member+\"] expands to [\"member\", \"admin\", \"owner\"].\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\", realtime: true },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\n### Adding your first feature\n\nCreate a file at `quickback/features/<name>/<name>.ts` and export a `defineTable(...)` default. The shape used by the `todos` template makes a good starting point — see [todos.ts in the template registry](/compiler/getting-started/templates#multi-tenant-scaffolds-free) for a full multi-tenant example with masking, actions, and a named view.\n\n```typescript\n// quickback/features/posts/posts.ts\n\nexport const posts = sqliteTable(\"posts\", {\n id: text(\"id\").primaryKey(),\n title: text(\"title\").notNull(),\n body: text(\"body\"),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(posts, {\n firewall: { organization: {}, owner: {}, softDelete: {} },\n guards: {\n createable: [\"title\", \"body\"],\n updatable: [\"title\", \"body\"],\n immutable: [\"id\", \"organizationId\", \"userId\"],\n },\n read: { access: { roles: [\"member+\"] } },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\n## Setup Steps\n\nIf you used `quickback start`, dependencies, the first compile, and login are already done — skip to step 4. If you used `quickback create`, run these:\n\n### 1. Install Dependencies\n\n```bash\nnpm install\n```\n\n### 2. Compile Your Definitions\n\n```bash\nquickback compile\n```\n\nThis prompts for an account on the first run (sign in or create one in the browser), then generates the full `src/` directory, migrations, and configuration files. Subsequent compiles re-use the stored session.\n\n### 3. Create D1 Databases\n\nThe Cloudflare template uses **dual database mode** by default — separate databases for auth and application data.\n\n```bash\n# Create the auth database\nnpx wrangler d1 create my-app-auth\n\n# Create the features database\nnpx wrangler d1 create my-app-features\n```\n\nCopy the database IDs from the output and update your `wrangler.toml`:\n\n```toml\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"paste-auth-id-here\"\n\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"paste-features-id-here\"\n```\n\n### 4. Run Migrations (Local)\n\n```bash\nnpm run db:migrate:local\n```\n\nThis applies migrations to both databases locally.\n\n### 5. Start Development Server\n\n```bash\nnpm run dev\n```\n\nYour API is running at `http://localhost:8787`.\n\n## Wrangler Configuration\n\nThe compiler generates a `wrangler.toml` with all required bindings:\n\n```toml\nname = \"my-app\"\nmain = \"src/index.ts\"\ncompatibility_date = \"2025-03-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n\n[observability]\nenabled = true\n\n[placement]\nmode = \"smart\"\n\n# Auth database\n[[d1_databases]]\nbinding = \"AUTH_DB\"\ndatabase_name = \"my-app-auth\"\ndatabase_id = \"your-auth-db-id\"\n\n# Features database\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"my-app-features\"\ndatabase_id = \"your-features-db-id\"\n\n# Key-value storage\n[[kv_namespaces]]\nbinding = \"KV\"\nid = \"your-kv-id\"\n```\n\n### Optional Bindings\n\nDepending on your configuration, the compiler may also generate bindings for:\n\n| Binding | Type | When Generated |\n|---------|------|----------------|\n| `R2_BUCKET` | R2 Bucket | `fileStorage` configured |\n| `AI` | Workers AI | `embeddings` configured on any feature |\n| `VECTORIZE` | Vectorize Index | `embeddings` configured |\n| `EMBEDDINGS_QUEUE` | Queue | `embeddings` configured |\n| `WEBHOOKS_DB` | D1 | Webhooks enabled |\n| `WEBHOOKS_QUEUE` | Queue | Webhooks enabled |\n| `BROADCASTER` | Service | `realtime` configured |\n\n## Dual Database Mode\n\nBy default, the Cloudflare template separates auth tables from application tables:\n\n- **`AUTH_DB`** — Better Auth tables (`users`, `sessions`, `accounts`, `organizations`, `members`)\n- **`DB`** — Your feature tables (`todos`, etc.)\n\nThis keeps auth data isolated and allows independent scaling. Each database gets its own migration directory:\n\n```\nquickback/drizzle/\n├── auth/ # Auth migrations\n│ ├── meta/\n│ └── 0000_*.sql\n└── features/ # Feature migrations\n ├── meta/\n └── 0000_*.sql\n```\n\n## Deploying to Production\n\n### 1. Apply Remote Migrations\n\n```bash\nnpm run db:migrate:remote\n```\n\n### 2. Deploy to Cloudflare\n\n```bash\nnpm run deploy\n```\n\nThis runs `wrangler deploy` to push your worker to Cloudflare's edge network.\n\n## Available Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `dev` | `wrangler dev` | Start local dev server |\n| `deploy` | `npm run db:migrate:remote && wrangler deploy` | Deploy to production |\n| `db:migrate:local` | Runs auth + features migrations locally | Apply migrations to local D1 |\n| `db:migrate:remote` | Runs auth + features migrations remotely | Apply migrations to production D1 |\n\n## Next Steps\n\n- [Add a new feature](/compiler/definitions/schema) — Define your own tables with security\n- [Configure access control](/compiler/definitions/access) — Set role-based permissions\n- [Add custom actions](/compiler/definitions/actions) — Business logic beyond CRUD\n- [Environment variables](/compiler/config/variables) — Configure secrets and bindings"
|
|
151
151
|
},
|
|
152
152
|
"compiler/getting-started/template-empty": {
|
|
153
153
|
"title": "Empty Scaffolding Templates",
|
|
154
|
-
"content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nMulti-tenant mode (`organizations: true`) is the default. Change to `organizations: false` for [single-tenant mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: {},\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n
|
|
154
|
+
"content": "The `empty` template creates a project with only the configuration file — no example features. Use this when you know exactly what you want to build and don't need starter code.\n\n## Available Empty Templates\n\n| Template | Runtime | Database | Command |\n|----------|---------|----------|---------|\n| `empty` | Cloudflare Workers | D1 | `quickback create empty my-app` |\n\nAlias: `quickback create scaffold my-app` (same as `empty`)\n\n## Create the Project\n\n```bash\nquickback create empty my-app\n```\n\nThis scaffolds a minimal project:\n\n```\nmy-app/\n├── quickback/\n│ ├── quickback.config.ts # Compiler configuration\n│ └── features/ # Empty — add your own\n├── package.json\n└── tsconfig.json\n```\n\n## Generated Configuration\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n features: {\n organizations: true,\n },\n providers: {\n runtime: { name: \"cloudflare\", config: {} },\n database: {\n name: \"cloudflare-d1\",\n config: { binding: \"DB\" },\n },\n auth: { name: \"better-auth\", config: {} },\n },\n};\n```\n\nMulti-tenant mode (`organizations: true`) is the default. Change to `organizations: false` for [single-tenant mode](/compiler/config/single-tenant).\n\n## Adding Your First Feature\n\nCreate a feature directory with a schema file:\n\n```bash\nmkdir -p quickback/features/products\n```\n\n```typescript\n// quickback/features/products/products.ts\n\nexport const products = sqliteTable(\"products\", {\n id: text(\"id\").primaryKey(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n price: integer(\"price\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n userId: text(\"user_id\").notNull(),\n});\n\nexport default defineTable(products, {\n firewall: {\n organization: {},\n owner: {},\n softDelete: {},\n },\n guards: {\n createable: [\"name\", \"description\", \"price\"],\n updatable: [\"name\", \"description\", \"price\"],\n },\n read: {\n access: { roles: [\"member+\"] },\n },\n create: { access: { roles: [\"member+\"] } },\n update: { access: { roles: [\"member+\"] } },\n delete: { access: { roles: [\"admin+\"] }, mode: \"soft\" },\n});\n```\n\nThen compile:\n\n```bash\nquickback login # First time only\nquickback compile\n```\n\n## Setup Steps\n\nFollow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). The only difference is you'll need to add at least one feature before compiling.\n\n## Next Steps\n\n- [Schema Definitions](/compiler/definitions/schema) — Define tables with Drizzle ORM\n- [Firewall](/compiler/definitions/firewall) — Data isolation and tenant scoping\n- [Access Control](/compiler/definitions/access) — Role-based permissions\n- [Guards](/compiler/definitions/guards) — Field-level write protection\n- [Full Example](/compiler/getting-started/full-example) — Complete feature walkthrough"
|
|
155
155
|
},
|
|
156
156
|
"compiler/getting-started/templates": {
|
|
157
157
|
"title": "Templates",
|
|
158
|
-
"content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\n## Available Templates\n\n###
|
|
158
|
+
"content": "Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.\n\nThe fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. Every template below can be reached either via `start`'s picker (free tier) or scriptably via `quickback create <template> <name>`.\n\n```bash\n# Interactive (recommended for first-time use)\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n## Available Templates\n\n### Multi-tenant scaffolds (free)\n\nCloudflare Workers + D1 + Better Auth with the organization plugin and a `member` / `admin` / `owner` role hierarchy wired in.\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `cloudflare` | Bare scaffold — auth + DB + Hono, no example feature | `quickback create cloudflare my-app` |\n| `todos` | Working todos feature: schema, masking, two actions (`complete` / `uncomplete`), and a `dashboard` named view | `quickback create todos my-app` |\n\nThe **todos** template is the recommended first read — it exercises every security pillar (firewall, access, guards, masking) plus actions and views in ~80 lines you can scan in five minutes.\n\n### Single-tenant starter (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `blog` | Single-tenant blog with PUBLIC reads, admin writes, `publish` / `unpublish` actions | `quickback create blog my-site` |\n\nThe **blog** template uses Better Auth's admin plugin (not the org plugin) and [single-tenant mode](/compiler/config/single-tenant) (`organizations: false`).\n\n### Empty scaffold (free)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `empty` | `quickback.config.ts` only — no example features | `quickback create empty my-app` |\n\nThe empty template creates the project structure with `quickback.config.ts` only. Add your first feature by creating a file under `quickback/features/<name>/<name>.ts` exporting `defineTable(...)` — there is no separate `init` step.\n\n### B2B SaaS (Pro)\n\n| Template | Includes | Command |\n|----------|----------|---------|\n| `saas` | Multi-tenant + **R2 file storage** + **outbound webhooks** + split databases + realtime + named views | `quickback create saas my-app` |\n\n## What Each Template Includes\n\nThe `cloudflare`, `todos`, `blog`, and `saas` templates all scaffold:\n\n- **`quickback.config.ts`** — Pre-configured with the right providers\n- **`quickback/features/`** — Feature definitions (empty for `cloudflare`; populated for `todos` / `blog` / `saas`)\n- **Deployment scripts** — `npm run deploy` for Cloudflare via wrangler\n\nThe `empty` template includes only:\n\n- **`quickback.config.ts`**\n- **`package.json`** — dependencies ready to install\n\n## Choosing a Template\n\n### Cloudflare bare scaffold\n\nBest when you already know the conventions and want empty walls. Multi-tenant orgs are wired in; you add your own feature files.\n\n### Todos (recommended for newcomers)\n\nBest for learning by reading. Full multi-tenant security pillars, two actions, a named view (`/api/v1/todos/views/dashboard`), and field masking on the `description` column — all in a single ~80-line file you can copy-edit into your own table.\n\n### Blog (single-tenant CMS)\n\nBest for personal sites, blogs, or any app with a single tenant. Uses [single-tenant mode](/compiler/config/single-tenant) — no organizations, roles come from `user.role` via Better Auth's admin plugin.\n\n- Public JSON API for content\n- Admin-only editing\n- Pair with any frontend (Astro, Next.js, SvelteKit, etc.)\n\n### Empty\n\nBest when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.\n\n### SaaS (Pro)\n\nBest for production B2B work. Adds R2 file uploads, outbound webhooks (with retry/dedupe), split auth/features/webhooks databases, realtime broadcast, and named views.\n\n## Template Aliases\n\nFor convenience, templates have short aliases:\n\n| Alias | Full id |\n|-------|---------|\n| `cloudflare` / `cf` | `betterauth-d1-cloudflare` |\n| `todos` | `todos-cloudflare` |\n| `blog` | `blog-cloudflare` |\n| `saas` | `b2bsaas-cloudflare` |\n| `empty` / `scaffold` | `empty-cloudflare` |\n\n## After Scaffolding\n\n`quickback start` runs scaffold + login + compile + install + drizzle in one flow. If you used the scriptable `quickback create` instead (or cancelled at the login prompt), finish setup with:\n\n```bash\ncd my-app\nquickback compile # prompts for login on first run; reuses session after\nnpm run dev\n```\n\nSee the individual template guides for detailed setup:\n- [Cloudflare Template](/compiler/getting-started/template-cloudflare)\n- [Blog Template](/compiler/getting-started/template-blog)\n- [Empty Scaffolding](/compiler/getting-started/template-empty)\n- [Single-Tenant Mode](/compiler/config/single-tenant)"
|
|
159
159
|
},
|
|
160
160
|
"compiler": {
|
|
161
161
|
"title": "Quickback Compiler",
|
|
@@ -191,7 +191,7 @@ export const DOCS = {
|
|
|
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, or delete multiple records in a single request. They are **auto-enabled** when the corresponding CRUD operation exists in your definition.\n\n## Available Endpoints\n\n| Endpoint | Method | Auto-enabled When |\n|----------|--------|-------------------|\n| `/{resource}/batch` | `POST` | `crud.create` exists |\n| `/{resource}/batch` | `PATCH` | `crud.update` exists |\n| `/{resource}/batch` | `DELETE` | `crud.delete` exists |\n| `/{resource}/batch` | `PUT` | `crud.put` exists |\n\nTo disable a batch operation, set it to `false` in your definition:\n\n```typescript\ncrud: {\n create: { access: { roles: ['hiring-manager'] } },\n batchCreate: 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 CRUD operation. You can override per-batch settings:\n\n```typescript\nexport default defineTable(applications, {\n crud: {\n create: { access: { roles: ['hiring-manager', 'recruiter'] } },\n update: { access: { roles: ['hiring-manager', 'recruiter'] } },\n delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },\n\n // Override batch-specific settings\n batchCreate: {\n access: { roles: ['hiring-manager'] }, // More restrictive than single create\n maxBatchSize: 50, // Default: 100\n allowFailFast: true, // Default: true\n },\n batchUpdate: {\n maxBatchSize: 100,\n allowFailFast: true,\n },\n batchDelete: {\n access: { roles: ['hiring-manager'] },\n maxBatchSize: 100,\n allowFailFast: true,\n },\n\n // Disable a batch operation entirely\n batchUpsert: 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) | 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"
|
|
195
195
|
},
|
|
196
196
|
"compiler/targets/hono-api/using-the-api/caching": {
|
|
197
197
|
"title": "Caching & ETags",
|
|
@@ -199,7 +199,7 @@ export const DOCS = {
|
|
|
199
199
|
},
|
|
200
200
|
"compiler/targets/hono-api/using-the-api/crud": {
|
|
201
201
|
"title": "CRUD Endpoints",
|
|
202
|
-
"content": "Quickback automatically generates RESTful CRUD endpoints for each resource you define. This page covers the write side (create, update, delete, upsert) and lists collection-read endpoints. Read-side configuration lives under [`read:`](/compiler/definitions/read).\n\n> **Migration note**: `crud.list` and `crud.get` are rejected at compile time in DSL v2. List-level access moves to [`read.access`](/compiler/definitions/read), and per-field projections move to named views under [`read.views`](/compiler/definitions/read#views-under-read-views). See the [migration table](/compiler/definitions/read#migrating-from-crud-list-crud-get).\n\n## Quick Reference\n\nAll endpoints require authentication. Include your session cookie or Bearer token:\n\n```bash\n# List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\"\n\n# Get a single record\ncurl http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# Create a record\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# Update a record\ncurl -X PATCH http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Staff Engineer\"}'\n\n# Delete a record\ncurl -X DELETE http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# List with filters, sorting, and pagination\ncurl \"http://localhost:8787/api/v1/jobs?status=open&sort=createdAt:desc&limit=25&count=true\" \\\n -H \"Authorization: Bearer <token>\"\n```\n\n## Endpoint Overview\n\nFor a resource named `jobs`, Quickback generates:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/jobs` | List all records |\n| `GET` | `/jobs/:id` | Get a single record |\n| `POST` | `/jobs` | Create a new record |\n| `POST` | `/jobs/batch` | Batch create multiple records |\n| `PATCH` | `/jobs/:id` | Update a record |\n| `PATCH` | `/jobs/batch` | Batch update multiple records |\n| `DELETE` | `/jobs/:id` | Delete a record |\n| `DELETE` | `/jobs/batch` | Batch delete multiple records |\n| `PUT` | `/jobs/:id` | Upsert a record (requires config) |\n| `PUT` | `/jobs/batch` | Batch upsert multiple records (requires config) |\n\n## List & Get Records\n\n`GET /{resource}` and `GET /{resource}/:id` are part of the [read pipeline](/compiler/definitions/read). Configuration (access, pagination, view projections) lives under `read:`. Filtering, sorting, and pagination query parameters work the same on both endpoints — see [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n pageSize: 25,\n maxPageSize: 100,\n views: {\n summary: { fields: ['id', 'title', 'status'], access: { roles: ['interviewer'] } },\n },\n}\n```\n\nCalls a client makes:\n\n```bash\nGET /jobs # Collection — gated by read.access\nGET /jobs/:id # Single — gated by read.access (with ID-probe defense)\nGET /jobs/views/summary # Named view projection\n```\n\n### ID-probe defense on `/:id`\n\nSingle-record reads run a role-only access check **before** the firewall query, so an unauthorized caller can't tell apart \"row exists in another tenant\" from \"row doesn't exist.\" See [Access ordering](/compiler/definitions/read#access-ordering-on-id) for details.\n\n| Status | Description |\n|--------|-------------|\n| `401` | Not authenticated |\n| `403` | Authenticated but role doesn't satisfy `read.access` |\n| `404` | Authenticated and role passes, but firewall excluded the record (or it doesn't exist). Set [`firewallErrorMode: 'reveal'`](/compiler/definitions/firewall) to return 403 instead. |\n\n### FK Label Resolution\n\nForeign key columns are automatically enriched with `_label` fields containing the referenced table's display value. For example, `departmentId` gets a corresponding `department_label` field. See [Display Column](/compiler/definitions/schema#display-column) for details.\n\n## Create Record\n\n```\nPOST /jobs\nContent-Type: application/json\n\n{\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000\n}\n```\n\nCreates a new record. Only fields listed in `guards.createable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_456\",\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000,\n \"createdAt\": \"2024-01-15T11:00:00Z\",\n \"createdBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or missing required field |\n| `403` | User lacks permission to create records |\n\n## Update Record\n\n```\nPATCH /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Staff Engineer\"\n}\n```\n\nUpdates an existing record. Only fields listed in `guards.updatable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"title\": \"Staff Engineer\",\n \"modifiedAt\": \"2024-01-15T12:00:00Z\",\n \"modifiedBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or field not updatable |\n| `403` | User lacks permission to update this record |\n| `404` | Record not found |\n\n## Delete Record\n\n```\nDELETE /jobs/:id\n```\n\nDeletes a record. Behavior depends on the `delete.mode` configuration.\n\n### Soft Delete (default)\n\nSets `deletedAt` and `deletedBy` fields. Record remains in database but is filtered from queries.\n\n#### Cascade\n\nWhen a parent is soft-deleted, every child table that holds an FK to it — both **same-feature** children and **cross-feature** children (e.g. `applications` referencing `jobs` from a different feature directory) — receives the same `deletedAt` / `deletedBy` stamp in the same request. The cascade UPDATE always AND-merges the child's own firewall (`build<Child>FirewallConditions(ctx)`), so a delete in one tenant can never reach a child row in another tenant.\n\nIf a child column declared `.references(() => parent.id, { onDelete: '...' })`, the cascade respects that intent — only `cascade` and `set null` participate. FKs without `onDelete` are cascaded for backwards-compat with the legacy shape.\n\n### Hard Delete\n\nPermanently removes the record from the database.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"deleted\": true\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `403` | User lacks permission to delete this record |\n| `404` | Record not found |\n\n## Upsert Record (PUT)\n\n```\nPUT /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Contract Recruiter\",\n \"department\": \"Talent Acquisition\",\n \"status\": \"open\",\n \"externalId\": \"ext-123\"\n}\n```\n\nCreates or updates a record by ID. Requires special configuration:\n\n1. `generateId: false` in database config\n2. `guards: false` in resource definition\n\n### Behavior\n\n- If record exists: Updates all provided fields\n- If record doesn't exist: Creates with the provided ID\n\n### Use Cases\n\n- Syncing data from external systems\n- Webhook handlers with external IDs\n- Idempotent operations (safe to retry)\n\nSee [Guards documentation](/compiler/definitions/guards#putupsert-with-external-ids) for setup details.\n\n## Batch Operations\n\nQuickback provides batch endpoints for efficient bulk operations. Batch operations automatically inherit from their corresponding CRUD operations and maintain full security layer consistency.\n\n### Batch Create Records\n\n```\nPOST /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" },\n { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nCreates multiple records in a single request. Each record follows the same validation rules as single create operations.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects to create |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response (Partial Success - Default)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"id\": \"job_2\", \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] }\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#### HTTP Status Codes\n\n- `201` - All records created successfully\n- `207` - Partial success (some records failed)\n- `400` - `failFast: true` was set and one or more records failed\n\n#### Batch Size Limit\n\nDefault: 100 records per request (configurable via `maxBatchSize`)\n\n### Batch Update Records\n\n```\nPATCH /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\" },\n { \"id\": \"job_3\", \"status\": \"closed\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nUpdates multiple records in a single request. All records must include an `id` field.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and fields to update |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"job_3\", \"status\": \"closed\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\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#### Features\n\n- **Batch fetching**: Single database query for all IDs (with firewall)\n- **Per-record access**: Access checks run with record context\n- **Field validation**: Guards apply to each record individually\n\n### Batch Delete Records\n\n```\nDELETE /jobs/batch\nContent-Type: application/json\n\n{\n \"ids\": [\"job_1\", \"job_2\", \"job_3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nDeletes multiple records in a single request. Supports both soft and hard delete modes.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `ids` | Array | Array of record IDs to delete |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response (Soft Delete)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" },\n { \"id\": \"job_2\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"id\": \"job_3\",\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\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#### Delete Modes\n\n- **Soft delete** (default): Sets `deletedAt`, `deletedBy`, `modifiedAt`, `modifiedBy` fields\n- **Hard delete**: Permanently removes records from database\n\n### Batch Upsert Records\n\n```\nPUT /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nCreates or updates multiple records in a single request. Creates if ID doesn't exist, updates if it does.\n\n**Strict Requirements** (same as single PUT):\n1. `generateId: false` in database config (user provides IDs)\n2. `guards: false` in resource definition (no field restrictions)\n3. All records must include an `id` field\n\n**Note**: System-managed fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are always protected and will be rejected if included in the request, regardless of guards configuration.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and all fields |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\", \"modifiedAt\": \"2024-01-15T16:00:00Z\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\", \"createdAt\": \"2024-01-15T16:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"atomic\": false\n }\n}\n```\n\n#### How It Works\n\n1. Batch existence check with firewall\n2. Split records into CREATE and UPDATE batches\n3. Validate new records with `validateCreate()`\n4. Validate existing records with `validateUpdate()`\n5. Check CREATE access for new records\n6. Check UPDATE access for existing records (per-record)\n7. Execute bulk insert and individual updates\n8. Return combined results\n\n### Batch Operation Features\n\n#### Partial Success Mode (Default)\n\nBy default, batch operations use **partial success** mode:\n- All records are processed independently\n- Failed records go into `errors` array with detailed error information\n- Successful records go into `success` array\n- HTTP status `207 Multi-Status` if any errors, `201`/`200` if all success\n\n```json\n{\n \"success\": [ /* succeeded records */ ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { /* original input */ },\n \"error\": {\n \"error\": \"Human-readable message\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": {\n \"total\": 10,\n \"succeeded\": 8,\n \"failed\": 2,\n \"atomic\": false\n }\n}\n```\n\n#### Fail-Fast Mode (Opt-in)\n\nSet `options.failFast: true` to stop on the first error. On providers that\nsupport transactions, the loop is wrapped in `db.transaction(...)` so prior\nwrites roll back. The response's `meta.transactional` field tells you\nwhether you got real rollback or just early-stop semantics — see\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n```json\n{\n \"records\": [ /* ... */ ],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\nOn the first failure under `failFast: true`:\n- Processing stops; no further records are attempted\n- HTTP status `400 Bad Request`\n- A single error is returned\n\n```json\n{\n \"error\": \"Batch failed at index 2\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { /* the actual error */ }\n }\n}\n```\n\n#### Human-Readable Errors\n\nAll batch operation errors include:\n- **Layer identification**: Which security layer rejected the request\n- **Error code**: Machine-readable code for programmatic handling\n- **Clear message**: Human-readable explanation\n- **Details**: Contextual information (fields, IDs, reasons)\n- **Helpful hints**: Actionable guidance for resolution\n\n#### Performance Optimizations\n\n- **Batch size limits**: Default 100 records (prevents memory exhaustion)\n- **Single firewall query**: `WHERE id IN (...)` instead of N queries\n- **Bulk operations**: Single INSERT for multiple records (CREATE, UPSERT)\n- **O(1) lookups**: Map-based record lookup instead of Array.find()\n\n#### Configuration\n\nBatch operations are **auto-enabled** when corresponding CRUD operations exist:\n\n```typescript\n// Auto-enabled - no configuration needed\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } }\n // batchCreate and batchUpdate automatically available\n}\n\n// Customize batch operations\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n batchCreate: {\n access: { roles: ['hiring-manager'] }, // Different access rules\n maxBatchSize: 50, // Lower limit\n allowFailFast: false // Disable failFast mode\n }\n}\n\n// Disable batch operations\ncrud: {\n create: { access: { roles: ['recruiter'] } },\n batchCreate: false // Explicitly disable\n}\n```\n\n#### Security Layer Application\n\nBatch operations maintain **full security layer consistency**:\n\n1. **Firewall**: Auto-apply ownership fields, batch fetch with isolation\n2. **Access**: Operation-level for CREATE, per-record for UPDATE/DELETE\n3. **Guards**: Per-record field validation (same rules as single operations)\n4. **Masking**: Applied to success array (respects user permissions)\n5. **Audit**: Single timestamp for entire batch for consistency\n\n## Authentication\n\nAll endpoints require authentication. Include your auth token in the request header:\n\n```\nAuthorization: Bearer <your-token>\n```\n\nThe user's context (userId, roles, organizationId) is extracted from the token and used to:\n\n1. Apply firewall filters (data isolation)\n2. Check access permissions\n3. Set audit fields (createdBy, modifiedBy)\n\n## Error Responses\n\nAll errors use a flat structure with contextual fields:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\nSee [Errors](/compiler/targets/hono-api/using-the-api/errors) for the complete reference of error codes by security layer."
|
|
202
|
+
"content": "Quickback automatically generates RESTful CRUD endpoints for each resource you define. This page covers the write side (create, update, delete, upsert) and lists collection-read endpoints. Read-side configuration lives under [`read:`](/compiler/definitions/read).\n\n> **Migration note**: `crud.list` and `crud.get` are rejected at compile time in DSL v2. List-level access moves to [`read.access`](/compiler/definitions/read), and per-field projections move to named views under [`read.views`](/compiler/definitions/read#views-under-read-views). See the [migration table](/compiler/definitions/read#migrating-from-crud-list-crud-get).\n\n## Quick Reference\n\nAll endpoints require authentication. Include your session cookie or Bearer token:\n\n```bash\n# List records\ncurl http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\"\n\n# Get a single record\ncurl http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# Create a record\ncurl -X POST http://localhost:8787/api/v1/jobs \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Senior Engineer\", \"department\": \"Engineering\", \"status\": \"open\"}'\n\n# Update a record\ncurl -X PATCH http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"title\": \"Staff Engineer\"}'\n\n# Delete a record\ncurl -X DELETE http://localhost:8787/api/v1/jobs/job_123 \\\n -H \"Authorization: Bearer <token>\"\n\n# List with filters, sorting, and pagination\ncurl \"http://localhost:8787/api/v1/jobs?status=open&sort=createdAt:desc&limit=25&count=true\" \\\n -H \"Authorization: Bearer <token>\"\n```\n\n## Endpoint Overview\n\nFor a resource named `jobs`, Quickback generates:\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/jobs` | List all records |\n| `GET` | `/jobs/:id` | Get a single record |\n| `POST` | `/jobs` | Create a new record |\n| `POST` | `/jobs/batch` | Batch create multiple records |\n| `PATCH` | `/jobs/:id` | Update a record |\n| `PATCH` | `/jobs/batch` | Batch update multiple records |\n| `DELETE` | `/jobs/:id` | Delete a record |\n| `DELETE` | `/jobs/batch` | Batch delete multiple records |\n| `PUT` | `/jobs/:id` | Upsert a record (requires config) |\n| `PUT` | `/jobs/batch` | Batch upsert multiple records (requires config) |\n\n## List & Get Records\n\n`GET /{resource}` and `GET /{resource}/:id` are part of the [read pipeline](/compiler/definitions/read). Configuration (access, pagination, view projections) lives under `read:`. Filtering, sorting, and pagination query parameters work the same on both endpoints — see [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params).\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n pageSize: 25,\n maxPageSize: 100,\n views: {\n summary: { fields: ['id', 'title', 'status'], access: { roles: ['interviewer'] } },\n },\n}\n```\n\nCalls a client makes:\n\n```bash\nGET /jobs # Collection — gated by read.access\nGET /jobs/:id # Single — gated by read.access (with ID-probe defense)\nGET /jobs/views/summary # Named view projection\n```\n\n### ID-probe defense on `/:id`\n\nSingle-record reads run a role-only access check **before** the firewall query, so an unauthorized caller can't tell apart \"row exists in another tenant\" from \"row doesn't exist.\" See [Access ordering](/compiler/definitions/read#access-ordering-on-id) for details.\n\n| Status | Description |\n|--------|-------------|\n| `401` | Not authenticated |\n| `403` | Authenticated but role doesn't satisfy `read.access` |\n| `404` | Authenticated and role passes, but firewall excluded the record (or it doesn't exist). Set [`firewallErrorMode: 'reveal'`](/compiler/definitions/firewall) to return 403 instead. |\n\n### FK Label Resolution\n\nForeign key columns are automatically enriched with `_label` fields containing the referenced table's display value. For example, `departmentId` gets a corresponding `department_label` field. See [Display Column](/compiler/definitions/schema#display-column) for details.\n\n## Create Record\n\n```\nPOST /jobs\nContent-Type: application/json\n\n{\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000\n}\n```\n\nCreates a new record. Only fields listed in `guards.createable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_456\",\n \"title\": \"Senior Engineer\",\n \"department\": \"Engineering\",\n \"status\": \"open\",\n \"salaryMin\": 120000,\n \"salaryMax\": 180000,\n \"createdAt\": \"2024-01-15T11:00:00Z\",\n \"createdBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or missing required field |\n| `403` | User lacks permission to create records |\n\n## Update Record\n\n```\nPATCH /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Staff Engineer\"\n}\n```\n\nUpdates an existing record. Only fields listed in `guards.updatable` are accepted.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"title\": \"Staff Engineer\",\n \"modifiedAt\": \"2024-01-15T12:00:00Z\",\n \"modifiedBy\": \"user_789\"\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid field or field not updatable |\n| `403` | User lacks permission to update this record |\n| `404` | Record not found |\n\n## Delete Record\n\n```\nDELETE /jobs/:id\n```\n\nDeletes a record. Behavior depends on the `delete.mode` configuration.\n\n### Soft Delete (default)\n\nSets `deletedAt` and `deletedBy` fields. Record remains in database but is filtered from queries.\n\n#### Cascade\n\nWhen a parent is soft-deleted, every child table that holds an FK to it — both **same-feature** children and **cross-feature** children (e.g. `applications` referencing `jobs` from a different feature directory) — receives the same `deletedAt` / `deletedBy` stamp in the same request. The cascade UPDATE always AND-merges the child's own firewall (`build<Child>FirewallConditions(ctx)`), so a delete in one tenant can never reach a child row in another tenant.\n\nIf a child column declared `.references(() => parent.id, { onDelete: '...' })`, the cascade respects that intent — only `cascade` and `set null` participate. FKs without `onDelete` are cascaded for backwards-compat with the legacy shape.\n\n### Hard Delete\n\nPermanently removes the record from the database.\n\n### Response\n\n```json\n{\n \"data\": {\n \"id\": \"job_123\",\n \"deleted\": true\n }\n}\n```\n\n### Errors\n\n| Status | Description |\n|--------|-------------|\n| `403` | User lacks permission to delete this record |\n| `404` | Record not found |\n\n## Upsert Record (PUT)\n\n```\nPUT /jobs/:id\nContent-Type: application/json\n\n{\n \"title\": \"Contract Recruiter\",\n \"department\": \"Talent Acquisition\",\n \"status\": \"open\",\n \"externalId\": \"ext-123\"\n}\n```\n\nCreates or updates a record by ID. Requires special configuration:\n\n1. `generateId: false` in database config\n2. `guards: false` in resource definition\n\n### Behavior\n\n- If record exists: Updates all provided fields\n- If record doesn't exist: Creates with the provided ID\n\n### Use Cases\n\n- Syncing data from external systems\n- Webhook handlers with external IDs\n- Idempotent operations (safe to retry)\n\nSee [Guards documentation](/compiler/definitions/guards#putupsert-with-external-ids) for setup details.\n\n## Batch Operations\n\nQuickback provides batch endpoints for efficient bulk operations. Batch operations automatically inherit from their corresponding CRUD operations and maintain full security layer consistency.\n\n### Batch Create Records\n\n```\nPOST /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" },\n { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nCreates multiple records in a single request. Each record follows the same validation rules as single create operations.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects to create |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response (Partial Success - Default)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Frontend Engineer\", \"department\": \"Engineering\", \"status\": \"open\" },\n { \"id\": \"job_2\", \"title\": \"Product Designer\", \"department\": \"Design\", \"status\": \"draft\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"title\": \"Data Analyst\", \"department\": \"Analytics\", \"status\": \"open\" },\n \"error\": {\n \"error\": \"Field cannot be set during creation\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] }\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#### HTTP Status Codes\n\n- `201` - All records created successfully\n- `207` - Partial success (some records failed)\n- `400` - `failFast: true` was set and one or more records failed\n\n#### Batch Size Limit\n\nDefault: 100 records per request (configurable via `maxBatchSize`)\n\n### Batch Update Records\n\n```\nPATCH /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\" },\n { \"id\": \"job_3\", \"status\": \"closed\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nUpdates multiple records in a single request. All records must include an `id` field.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and fields to update |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Senior Frontend Engineer\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" },\n { \"id\": \"job_2\", \"department\": \"Product Design\", \"modifiedAt\": \"2024-01-15T14:00:00Z\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { \"id\": \"job_3\", \"status\": \"closed\" },\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\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#### Features\n\n- **Batch fetching**: Single database query for all IDs (with firewall)\n- **Per-record access**: Access checks run with record context\n- **Field validation**: Guards apply to each record individually\n\n### Batch Delete Records\n\n```\nDELETE /jobs/batch\nContent-Type: application/json\n\n{\n \"ids\": [\"job_1\", \"job_2\", \"job_3\"],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nDeletes multiple records in a single request. Supports both soft and hard delete modes.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `ids` | Array | Array of record IDs to delete |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response (Soft Delete)\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" },\n { \"id\": \"job_2\", \"deletedAt\": \"2024-01-15T15:00:00Z\", \"deletedBy\": \"user_789\" }\n ],\n \"errors\": [\n {\n \"index\": 2,\n \"id\": \"job_3\",\n \"error\": {\n \"error\": \"Not found\",\n \"layer\": \"firewall\",\n \"code\": \"NOT_FOUND\",\n \"details\": { \"id\": \"job_3\" }\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#### Delete Modes\n\n- **Soft delete** (default): Sets `deletedAt`, `deletedBy`, `modifiedAt`, `modifiedBy` fields\n- **Hard delete**: Permanently removes records from database\n\n### Batch Upsert Records\n\n```\nPUT /jobs/batch\nContent-Type: application/json\n\n{\n \"records\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\" }\n ],\n \"options\": {\n \"failFast\": false\n }\n}\n```\n\nCreates or updates multiple records in a single request. Creates if ID doesn't exist, updates if it does.\n\n**Strict Requirements** (same as single PUT):\n1. `generateId: false` in database config (user provides IDs)\n2. `guards: false` in resource definition (no field restrictions)\n3. All records must include an `id` field\n\n**Note**: System-managed fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`, `deletedAt`, `deletedBy`) are always protected and will be rejected if included in the request, regardless of guards configuration.\n\n#### Request Body\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `records` | Array | Array of record objects with `id` and all fields |\n| `options.failFast` | Boolean | If `true`, stop on first error and roll back on tx-supporting providers (default: `false`) |\n\n#### Response\n\n```json\n{\n \"success\": [\n { \"id\": \"job_1\", \"title\": \"Updated Frontend Engineer\", \"department\": \"Engineering\", \"modifiedAt\": \"2024-01-15T16:00:00Z\" },\n { \"id\": \"new_job\", \"title\": \"New Backend Engineer\", \"department\": \"Engineering\", \"status\": \"draft\", \"createdAt\": \"2024-01-15T16:00:00Z\" }\n ],\n \"errors\": [],\n \"meta\": {\n \"total\": 2,\n \"succeeded\": 2,\n \"failed\": 0,\n \"atomic\": false\n }\n}\n```\n\n#### How It Works\n\n1. Batch existence check with firewall\n2. Split records into CREATE and UPDATE batches\n3. Validate new records with `validateCreate()`\n4. Validate existing records with `validateUpdate()`\n5. Check CREATE access for new records\n6. Check UPDATE access for existing records (per-record)\n7. Execute bulk insert and individual updates\n8. Return combined results\n\n### Batch Operation Features\n\n#### Partial Success Mode (Default)\n\nBy default, batch operations use **partial success** mode:\n- All records are processed independently\n- Failed records go into `errors` array with detailed error information\n- Successful records go into `success` array\n- HTTP status `207 Multi-Status` if any errors, `201`/`200` if all success\n\n```json\n{\n \"success\": [ /* succeeded records */ ],\n \"errors\": [\n {\n \"index\": 2,\n \"record\": { /* original input */ },\n \"error\": {\n \"error\": \"Human-readable message\",\n \"layer\": \"guards\",\n \"code\": \"GUARD_FIELD_NOT_CREATEABLE\",\n \"details\": { \"fields\": [\"status\"] },\n \"hint\": \"These fields are set automatically or must be omitted\"\n }\n }\n ],\n \"meta\": {\n \"total\": 10,\n \"succeeded\": 8,\n \"failed\": 2,\n \"atomic\": false\n }\n}\n```\n\n#### Fail-Fast Mode (Opt-in)\n\nSet `options.failFast: true` to stop on the first error. On providers that\nsupport transactions, the loop is wrapped in `db.transaction(...)` so prior\nwrites roll back. The response's `meta.transactional` field tells you\nwhether you got real rollback or just early-stop semantics — see\n[Batch Operations: Transactional semantics](/compiler/targets/hono-api/using-the-api/batch-operations#transactional-semantics).\n\n```json\n{\n \"records\": [ /* ... */ ],\n \"options\": {\n \"failFast\": true\n }\n}\n```\n\nOn the first failure under `failFast: true`:\n- Processing stops; no further records are attempted\n- HTTP status `400 Bad Request`\n- A single error is returned\n\n```json\n{\n \"error\": \"Batch failed at index 2\",\n \"layer\": \"validation\",\n \"code\": \"BATCH_FAILFAST_STOPPED\",\n \"details\": {\n \"failedAt\": 2,\n \"reason\": { /* the actual error */ }\n }\n}\n```\n\n#### Human-Readable Errors\n\nAll batch operation errors include:\n- **Layer identification**: Which security layer rejected the request\n- **Error code**: Machine-readable code for programmatic handling\n- **Clear message**: Human-readable explanation\n- **Details**: Contextual information (fields, IDs, reasons)\n- **Helpful hints**: Actionable guidance for resolution\n\n#### Performance Optimizations\n\n- **Batch size limits**: Default 100 records (prevents memory exhaustion)\n- **Single firewall query**: `WHERE id IN (...)` instead of N queries\n- **Bulk operations**: Single INSERT for multiple records (CREATE, UPSERT)\n- **O(1) lookups**: Map-based record lookup instead of Array.find()\n\n#### Configuration\n\nBatch operations are **auto-enabled** when corresponding write operations exist:\n\n```typescript\n// Auto-enabled - no configuration needed\ncreate: { access: { roles: ['recruiter'] } },\nupdate: { access: { roles: ['recruiter'] } }\n// create.batch and update.batch automatically available\n\n// Customize batch operations\ncreate: {\n access: { roles: ['recruiter'] },\n batch: {\n access: { roles: ['hiring-manager'] }, // Different access rules\n maxBatchSize: 50, // Lower limit\n allowFailFast: false // Disable failFast mode\n }\n}\n\n// Disable batch operations\ncreate: {\n access: { roles: ['recruiter'] },\n batch: false // Explicitly disable\n}\n```\n\n#### Security Layer Application\n\nBatch operations maintain **full security layer consistency**:\n\n1. **Firewall**: Auto-apply ownership fields, batch fetch with isolation\n2. **Access**: Operation-level for CREATE, per-record for UPDATE/DELETE\n3. **Guards**: Per-record field validation (same rules as single operations)\n4. **Masking**: Applied to success array (respects user permissions)\n5. **Audit**: Single timestamp for entire batch for consistency\n\n## Authentication\n\nAll endpoints require authentication. Include your auth token in the request header:\n\n```\nAuthorization: Bearer <your-token>\n```\n\nThe user's context (userId, roles, organizationId) is extracted from the token and used to:\n\n1. Apply firewall filters (data isolation)\n2. Check access permissions\n3. Set audit fields (createdBy, modifiedBy)\n\n## Error Responses\n\nAll errors use a flat structure with contextual fields:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": {\n \"required\": [\"hiring-manager\"],\n \"current\": [\"interviewer\"]\n },\n \"hint\": \"Contact an administrator to grant necessary permissions\"\n}\n```\n\nSee [Errors](/compiler/targets/hono-api/using-the-api/errors) for the complete reference of error codes by security layer."
|
|
203
203
|
},
|
|
204
204
|
"compiler/targets/hono-api/using-the-api/errors": {
|
|
205
205
|
"title": "Errors",
|
|
@@ -211,11 +211,11 @@ export const DOCS = {
|
|
|
211
211
|
},
|
|
212
212
|
"compiler/targets/hono-api/using-the-api/openapi": {
|
|
213
213
|
"title": "OpenAPI Spec",
|
|
214
|
-
"content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. Simple `z.object({...})` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: 'src/lib/api-types.gen.ts'
|
|
214
|
+
"content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every non-nullable column is listed, so generated SDKs treat them as guaranteed-present rather than optional.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input schemas\n\nActions defined with [`defineAction({ input: z.object(...) })`](/compiler/definitions/actions) get their full input schema lifted into the operation's `requestBody`. Simple `z.object({...})` shapes are extracted at compile time; for discriminated unions, refinements, recursive schemas, and bare-identifier references (`input: createPersonInput`), the compiler runs your action file through Zod 4's native `z.toJSONSchema()` during compilation so the OpenAPI request body and the MCP tool's `inputSchema` round-trip exactly what your Zod expression declares — no static translator to maintain.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n| `[\"api-types.gen.ts\", \"apps/web/src/lib/api-types.gen.ts\"]` | Write the same generated types to multiple paths in one compile |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. If your API project and SPA live in the same repo, prefer multiple `openapi.types` outputs over a second manual `codegen:api` step so one `quickback compile` keeps both copies in sync. Skipped automatically when `openapi.generate` is `false`.\n\nThe bundled Quickback CMS and Account SPAs do not import `api-types.gen.ts`. CMS is driven by `schema-registry.json`, and Account uses Better Auth plus small hand-written fetch helpers. Use `openapi.types` for your own colocated client apps.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```"
|
|
215
215
|
},
|
|
216
216
|
"compiler/targets/hono-api/using-the-api/query-params": {
|
|
217
217
|
"title": "Query Parameters",
|
|
218
|
-
"content": "The generated API supports filtering, pagination, sorting, field selection, search, and total count via query parameters on `GET` list endpoints.\n\n## Filter Operators\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### Examples\n\n```bash\n# Filter by status\nGET /api/v1/jobs?status=open\n\n# Range query\nGET /api/v1/jobs?salaryMin.gte=100000&salaryMax.lte=200000\n\n# Pattern matching\nGET /api/v1/jobs?title.like=Engineer\n\n# Multiple values\nGET /api/v1/jobs?department.in=Engineering,Design,Product\n```\n\n## Pagination\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `limit` | `50` | Number of records to return (min: 1, max: 100) |\n| `offset` | `0` | Number of records to skip |\n\n```bash\nGET /api/v1/jobs?limit=25&offset=50\n```\n\nThe default `limit` can be configured per-resource in your definition:\n\n```typescript\
|
|
218
|
+
"content": "The generated API supports filtering, pagination, sorting, field selection, search, and total count via query parameters on `GET` list endpoints.\n\n## Filter Operators\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### Examples\n\n```bash\n# Filter by status\nGET /api/v1/jobs?status=open\n\n# Range query\nGET /api/v1/jobs?salaryMin.gte=100000&salaryMax.lte=200000\n\n# Pattern matching\nGET /api/v1/jobs?title.like=Engineer\n\n# Multiple values\nGET /api/v1/jobs?department.in=Engineering,Design,Product\n```\n\n## Pagination\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `limit` | `50` | Number of records to return (min: 1, max: 100) |\n| `offset` | `0` | Number of records to skip |\n\n```bash\nGET /api/v1/jobs?limit=25&offset=50\n```\n\nThe default `limit` can be configured per-resource in your `read` definition:\n\n```typescript\nread: {\n access: { roles: [\"recruiter\"] },\n pageSize: 25, // Default limit\n maxPageSize: 100, // Maximum allowed limit\n},\n```\n\n### Response Shape\n\n```json\n{\n \"data\": [ /* records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 50,\n \"count\": 12\n }\n}\n```\n\n- `count` — number of records returned on this page\n- `total` — total matching records across all pages (only when `?total=true`, see below)\n\n## Sorting\n\nSort by one or more fields. Use the `-` prefix for descending order.\n\n### Multi-Sort (Recommended)\n\n```bash\n# Sort by status ascending, then createdAt descending\nGET /api/v1/jobs?sort=status,-createdAt\n\n# Single field descending\nGET /api/v1/jobs?sort=-createdAt\n\n# Multiple fields\nGET /api/v1/jobs?sort=department,-salaryMax,title\n```\n\n| Prefix | Direction |\n|--------|-----------|\n| (none) | Ascending |\n| `-` | Descending |\n\n### Legacy Format\n\nThe original `sort` + `order` format is still supported for backwards compatibility:\n\n```bash\nGET /api/v1/jobs?sort=title&order=asc\n```\n\n| Parameter | Values | Default | Description |\n|-----------|--------|---------|-------------|\n| `sort` | Any column name | `createdAt` | Field to sort by |\n| `order` | `asc`, `desc` | `desc` | Sort direction |\n\nWhen the multi-sort format is detected (comma or `-` prefix), the `order` parameter is ignored.\n\n## Field Selection\n\nSelect which columns to return using `?fields=`. Available on LIST and GET routes (not Views — they define their own field set).\n\n```bash\n# Return only id, title, and status\nGET /api/v1/jobs?fields=id,title,status\n\n# Combine with other query params\nGET /api/v1/jobs?fields=id,title,status&status=open&sort=-createdAt\n\n# Single record\nGET /api/v1/jobs/job_123?fields=id,title,salaryMin,salaryMax\n```\n\nAll columns are available including system columns (`id`, `organizationId`, `createdAt`, `modifiedAt`, etc.). Invalid field names are silently ignored. If no valid fields are provided, all columns are returned.\n\n**Security**: Masking still applies to selected fields. Requesting `?fields=ssn` will return the masked value, not the raw data.\n\n## Total Count\n\nGet the total number of matching records across all pages by adding `?total=true`. Available on LIST and VIEW routes.\n\n```bash\nGET /api/v1/jobs?status=open&total=true\n```\n\n```json\n{\n \"data\": [ /* 25 records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 0,\n \"count\": 25,\n \"total\": 142\n }\n}\n```\n\nThis is opt-in because it runs an additional `COUNT(*)` query. Only use it when you need the total (e.g., for pagination UI).\n\n## Search\n\nFull-text search across all text columns using `?search=`. Available on LIST and VIEW routes.\n\n```bash\n# Search across all text fields\nGET /api/v1/jobs?search=engineer\n\n# Combine with filters\nGET /api/v1/jobs?search=engineer&status=open\n```\n\nThe search generates an OR'd `LIKE` condition across all `text()` columns in your schema:\n\n```sql\nWHERE (title LIKE '%engineer%' OR department LIKE '%engineer%')\n```\n\nOnly columns defined with `text()` in your Drizzle schema are searchable. Non-text columns (integers, timestamps, UUIDs, blobs) are automatically excluded.\n\n## Complete Example\n\nCombine all query parameters together:\n\n```bash\nGET /api/v1/jobs?fields=id,title,status,salaryMin&status=open&salaryMin.gte=100000&search=engineer&sort=salaryMin,-createdAt&limit=10&offset=20&total=true\n```\n\nThis request:\n1. **Selects** only `id`, `title`, `status`, `salaryMin` fields\n2. **Filters** to open jobs with salaryMin >= 100000\n3. **Searches** text columns for \"engineer\"\n4. **Sorts** by salaryMin ascending, then createdAt descending\n5. **Paginates** with 10 results starting at offset 20\n6. **Counts** total matching records\n\n## Parameter Summary\n\n| Parameter | Applies To | Description |\n|-----------|-----------|-------------|\n| `limit` | LIST, VIEW | Page size (default: 50, max: 100) |\n| `offset` | LIST, VIEW | Skip N records |\n| `sort` | LIST, VIEW | Sort fields (comma-separated, `-` prefix for desc) |\n| `order` | LIST, VIEW | Legacy sort direction (`asc` or `desc`) |\n| `fields` | LIST, GET | Comma-separated column names to return |\n| `total` | LIST, VIEW | Set to `true` to include total count |\n| `search` | LIST, VIEW | Search text across all text columns |\n| `field=value` | LIST, VIEW | Filter by exact match |\n| `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |"
|
|
219
219
|
},
|
|
220
220
|
"compiler/targets/hono-api/using-the-api/views-api": {
|
|
221
221
|
"title": "Views API",
|
|
@@ -243,11 +243,11 @@ export const DOCS = {
|
|
|
243
243
|
},
|
|
244
244
|
"compiler/troubleshooting": {
|
|
245
245
|
"title": "Troubleshooting",
|
|
246
|
-
"content": "Common issues and their solutions. For cloud compiler specific issues, see [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting).\n\n## Compilation Issues\n\n### \"Feature must use defineTable()\"\n\nYour table file is missing the default export:\n\n```typescript\n// Wrong — no default export\nexport const applications = sqliteTable(\"applications\", { ... });\n\n// Correct — add defineTable default export\nexport const applications = sqliteTable(\"applications\", { ... });\nexport default defineTable(applications, { ... });\n```\n\n### \"File exports multiple tables with defineTable\"\n\nA single file can export multiple Drizzle tables, but only ONE can have a `defineTable()` default export. Split tables into separate files:\n\n```\nquickback/features/applications/\n├── applications.ts # defineTable(applications, { ... })\n└── candidates.ts # defineTable(candidates, { ... })\n```\n\n### Missing fields in generated API\n\nIf a field exists in your schema but doesn't appear in API responses:\n\n1. **Guards:** Check that the field is in `createable` (for POST) or `updatable` (for PATCH). Fields not listed are silently stripped.\n2. **Views:** If using views, the field must be in the view's `fields` array.\n3. **Masking:** The field may be present but masked (showing `[REDACTED]` or `***`). Check your masking config.\n\n### \"organizationId\" not auto-detected\n\nThe firewall auto-detects `organizationId` and `ownerId` columns by name. If your column uses a different name, declare the firewall explicitly:\n\n```typescript\nfirewall: [\n { field: 'orgId', equals: 'ctx.activeOrgId' },\n]\n```\n\nOr use `q.scope()` and override the SQL name:\n\n```typescript\ncolumns: {\n orgId: q.scope('organization', { sqlName: 'org_id' }),\n}\n```\n\n## Migration Issues\n\n### Columns persist after removal from schema\n\nQuickback (via Drizzle) does **not** generate DROP COLUMN migrations. If you remove a column from your schema, the database column will remain as an orphaned column. SQLite handles this gracefully — the column won't appear in API responses since Drizzle only selects defined columns.\n\nTo clean up, you'd need to manually create a migration.\n\n### Drizzle rename prompts in CI\n\nIf compilation fails with `drizzle-kit requested interactive rename input`, add explicit rename hints in your config. See [Drizzle rename prompts](/compiler/cloud-compiler/troubleshooting#drizzle-rename-prompts-in-ciheadless-compile).\n\n## Runtime Issues\n\n### 401 on all requests\n\n1. **Missing auth:** Ensure your request includes `Authorization: Bearer <token>` or the session cookie\n2. **Expired session:** Sessions last 7 days by default. Re-authenticate.\n3. **Wrong auth URL:** Check that `BETTER_AUTH_URL` matches your deployment URL\n\n### 403 Forbidden\n\n1. **Wrong role:** Check the `access` config for the endpoint — your role may not be listed\n2. **Wrong org:** You may be in a different organization than the record's `organizationId`\n3. **Firewall hiding:** If `errorMode: 'hide'` is set, firewall violations return 404 instead of 403\n\n### 400 Bad Request on create/update\n\n1. **Guard violation:** You're sending a field not in `createable` or `updatable`. Check the error's `details.fields`.\n2. **Missing required field:** A `.notNull()` column without a default is missing from your request body.\n3. **Immutable field:** You're trying to update a field marked as `immutable`.\n\n### Records missing from list\n\nRecords may be filtered by:\n1. **Firewall:** Only records matching your organization (and optionally owner) are returned\n2. **Soft delete:** Soft-deleted records are automatically excluded\n3. **Access conditions:** Record-level conditions may filter results\n\n### Recovering a previous `src/` tree\n\nThe CLI archives the previous `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` before each compile (most recent 3 retained). If a generator regression silently dropped a file you depended on, restore it from the latest archive:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/ ← latest\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n\n# Restore the whole tree (back-out a bad compile):\nrm -rf src\ncp -R quickback/.archives/src-2026-04-27T16-31-02-014 src\n\n# …or grep for what disappeared:\ngrep -r \"missingExportName\" quickback/.archives/src-2026-04-27T16-31-02-014/\n```\n\nAnything in `src/` not produced by the latest compile is removed on every compile — see [CLI → Compile Definitions](/compiler/cloud-compiler/cli#compile-definitions) for the full contract.\n\n## See Also\n\n- [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting) — CLI and authentication issues\n- [Errors](/compiler/targets/hono-api/using-the-api/errors) — Complete error code reference\n- [Firewall](/compiler/definitions/firewall) — Data isolation configuration\n- [Guards](/compiler/definitions/guards) — Field modification rules"
|
|
246
|
+
"content": "Common issues and their solutions. For cloud compiler specific issues, see [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting).\n\n## Compilation Issues\n\n### \"Feature must use defineTable()\"\n\nYour table file is missing the default export:\n\n```typescript\n// Wrong — no default export\nexport const applications = sqliteTable(\"applications\", { ... });\n\n// Correct — add defineTable default export\nexport const applications = sqliteTable(\"applications\", { ... });\nexport default defineTable(applications, { ... });\n```\n\n### \"File exports multiple tables with defineTable\"\n\nA single file can export multiple Drizzle tables, but only ONE can have a `defineTable()` default export. Split tables into separate files:\n\n```\nquickback/features/applications/\n├── applications.ts # defineTable(applications, { ... })\n└── candidates.ts # defineTable(candidates, { ... })\n```\n\n### Missing fields in generated API\n\nIf a field exists in your schema but doesn't appear in API responses:\n\n1. **Guards:** Check that the field is in `createable` (for POST) or `updatable` (for PATCH). Fields not listed are silently stripped.\n2. **Views:** If using views, the field must be in the view's `fields` array.\n3. **Masking:** The field may be present but masked (showing `[REDACTED]` or `***`). Check your masking config.\n\n### \"organizationId\" not auto-detected\n\nThe firewall auto-detects `organizationId` and `ownerId` columns by name. If your column uses a different name, declare the firewall explicitly:\n\n```typescript\nfirewall: [\n { field: 'orgId', equals: 'ctx.activeOrgId' },\n]\n```\n\nOr use `q.scope()` and override the SQL name:\n\n```typescript\ncolumns: {\n orgId: q.scope('organization', { sqlName: 'org_id' }),\n}\n```\n\n## Migration Issues\n\n### Columns persist after removal from schema\n\nQuickback (via Drizzle) does **not** generate DROP COLUMN migrations. If you remove a column from your schema, the database column will remain as an orphaned column. SQLite handles this gracefully — the column won't appear in API responses since Drizzle only selects defined columns.\n\nTo clean up, you'd need to manually create a migration.\n\n### Drizzle rename prompts in CI\n\nIf compilation fails with `drizzle-kit requested interactive rename input`, add explicit rename hints in your config. See [Drizzle rename prompts](/compiler/cloud-compiler/troubleshooting#drizzle-rename-prompts-in-ciheadless-compile).\n\n### Cloudflare D1 destructive migrations\n\nQuickback now adds a D1-specific safety pass around Drizzle-generated migrations for the `cloudflare-d1` provider:\n\n1. **Better Auth cleanup** for retired managed tables is stripped instead of shipped as raw `DROP TABLE` SQL.\n2. **Drop-only cleanup migrations** are reordered child-first when foreign keys require it.\n3. **All D1 migration directories** generated by the compiler are replayed against SQLite during compile, so a D1-breaking migration fails before deploy.\n\nIf `quickback compile` now fails with a D1 replay error, treat that as a real migration problem instead of a deploy-time surprise. The generated SQL needs manual intervention or a schema change that Drizzle can express more safely.\n\n## Runtime Issues\n\n### 401 on all requests\n\n1. **Missing auth:** Ensure your request includes `Authorization: Bearer <token>` or the session cookie\n2. **Expired session:** Sessions last 7 days by default. Re-authenticate.\n3. **Wrong auth URL:** Check that `BETTER_AUTH_URL` matches your deployment URL\n\n### 403 Forbidden\n\n1. **Wrong role:** Check the `access` config for the endpoint — your role may not be listed\n2. **Wrong org:** You may be in a different organization than the record's `organizationId`\n3. **Firewall hiding:** If `errorMode: 'hide'` is set, firewall violations return 404 instead of 403\n\n### 400 Bad Request on create/update\n\n1. **Guard violation:** You're sending a field not in `createable` or `updatable`. Check the error's `details.fields`.\n2. **Missing required field:** A `.notNull()` column without a default is missing from your request body.\n3. **Immutable field:** You're trying to update a field marked as `immutable`.\n\n### Records missing from list\n\nRecords may be filtered by:\n1. **Firewall:** Only records matching your organization (and optionally owner) are returned\n2. **Soft delete:** Soft-deleted records are automatically excluded\n3. **Access conditions:** Record-level conditions may filter results\n\n### Recovering a previous `src/` tree\n\nThe CLI archives the previous `src/` tree to `quickback/.archives/src-<ISO-timestamp>/` before each compile (most recent 3 retained). If a generator regression silently dropped a file you depended on, restore it from the latest archive:\n\n```bash\nls quickback/.archives/\n# src-2026-04-27T16-31-02-014/ ← latest\n# src-2026-04-27T16-29-44-882/\n# src-2026-04-27T16-12-19-301/\n\n# Restore the whole tree (back-out a bad compile):\nrm -rf src\ncp -R quickback/.archives/src-2026-04-27T16-31-02-014 src\n\n# …or grep for what disappeared:\ngrep -r \"missingExportName\" quickback/.archives/src-2026-04-27T16-31-02-014/\n```\n\nAnything in `src/` not produced by the latest compile is removed on every compile — see [CLI → Compile Definitions](/compiler/cloud-compiler/cli#compile-definitions) for the full contract.\n\n## See Also\n\n- [Cloud Compiler Troubleshooting](/compiler/cloud-compiler/troubleshooting) — CLI and authentication issues\n- [Errors](/compiler/targets/hono-api/using-the-api/errors) — Complete error code reference\n- [Firewall](/compiler/definitions/firewall) — Data isolation configuration\n- [Guards](/compiler/definitions/guards) — Field modification rules"
|
|
247
247
|
},
|
|
248
248
|
"index": {
|
|
249
249
|
"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 or PostgreSQL Row Level Security policies. Pair the output with the Quickback Stack for a complete Supabase alternative on Cloudflare.\n\n## Quick start\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 one of two targets:\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- **[Quickback for Supabase](/compiler/targets/supabase-rls)** — PostgreSQL Row Level Security policies for Supabase. Keep Supabase Auth, Storage, and Realtime; Quickback adds the security layer.\n\nThe same `defineTable()` definitions work for both targets.\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."
|
|
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 or PostgreSQL Row Level Security policies. Pair the output with the Quickback Stack for a complete 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 one of two targets:\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- **[Quickback for Supabase](/compiler/targets/supabase-rls)** — PostgreSQL Row Level Security policies for Supabase. Keep Supabase Auth, Storage, and Realtime; Quickback adds the security layer.\n\nThe same `defineTable()` definitions work for both targets.\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
251
|
},
|
|
252
252
|
"stack/account-ui/customization": {
|
|
253
253
|
"title": "Customization",
|
|
@@ -355,7 +355,7 @@ export const DOCS = {
|
|
|
355
355
|
},
|
|
356
356
|
"stack/auth/security": {
|
|
357
357
|
"title": "Authentication Security",
|
|
358
|
-
"content": "Quickback enforces secure authentication defaults out of the box. This page explains how cookie security, rate limiting, and cross-domain authentication work, plus how to configure them for your use case.\n\n## Cookie Security\n\nQuickback sets secure cookie defaults to protect against CSRF, XSS, and man-in-the-middle attacks.\n\n### Default Attributes\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n defaultCookieAttributes: {\n sameSite: 'lax', // CSRF protection\n secure: true, // HTTPS only\n httpOnly: true, // No JavaScript access\n }\n }\n})\n```\n\n**What each attribute does:**\n\n| Attribute | Value | Purpose |\n|-----------|-------|---------|\n| `sameSite` | `lax` | Blocks cookies on cross-site POST requests (CSRF protection) |\n| `secure` | `true` | Cookies only sent over HTTPS (prevents interception) |\n| `httpOnly` | `true` | JavaScript cannot access cookies via `document.cookie` (XSS mitigation) |\n\n### SameSite Options\n\n- **`lax` (recommended)**: Blocks cross-site POST requests but allows top-level navigation. Best balance of security and usability.\n- **`strict`**: Blocks cookies on all cross-site requests. More secure but may break legitimate flows (e.g., returning from payment provider).\n- **`none`**: Allows all cross-site requests. Required for cross-domain authentication (requires `secure: true`).\n\n### Development Override\n\nFor local development over HTTP, you can relax the `secure` flag:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n defaultCookieAttributes: {\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: true,\n }\n }\n})\n```\n\n**Warning**: Never use `secure: false` in production.\n\n---\n\n## Rate Limiting\n\nQuickback includes per-IP rate limiting by default to protect against brute-force attacks and abuse.\n\n### How It Works\n\n**Rate limits are applied per IP address**, not globally:\n\n```\n┌─────────────────────────────────────────────────┐\n│ IP: 192.168.1.1 │\n│ Endpoint: /sign-in/email │\n│ Limit: 10 requests per 60 seconds │\n│ │\n│ Request 1-10: ✅ Allowed │\n│ Request 11: ❌ 429 Too Many Requests │\n│ After 60s: Counter resets to 0 │\n└─────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────┐\n│ IP: 192.168.1.2 (different IP) │\n│ Endpoint: /sign-in/email │\n│ Independent counter: Not affected by 1.1 │\n│ Starts at 0 │\n└─────────────────────────────────────────────────┘\n```\n\n### Default Configuration\n\n```ts\nauth: defineAuth(\"better-auth\", {\n rateLimit: {\n enabled: true,\n window: 60, // 60 second window\n max: 100, // 100 requests per IP per window\n customRules: {\n \"/sign-in/email\": { window: 60, max: 10 },\n \"/sign-in/social\": { window: 60, max: 10 },\n \"/device/init\": { window: 60, max: 5 },\n \"/device/poll\": { window: 60, max: 30 },\n \"/device/token\": { window: 60, max: 10 },\n }\n }\n})\n```\n\n### Custom Rules by Endpoint\n\nSet different limits based on endpoint sensitivity:\n\n| Endpoint Type | Recommended Limit | Reasoning |\n|---------------|-------------------|-----------|\n| Sign-in | 10/min per IP | Prevent credential stuffing |\n| Device codes | 5/min per IP | Prevent device code enumeration |\n| Token exchange | 10/min per IP | Prevent token brute-force |\n| Polling | 30/min per IP | Allow reasonable polling (every 2s) |\n| General API | 100/min per IP | Balance abuse prevention and usability |\n\n### Why Per-IP?\n\n✅ **Per-IP** (what Quickback uses):\n- Prevents single attacker from brute-forcing\n- Doesn't penalize legitimate users when one IP is malicious\n- Standard for auth endpoints\n\n❌ **Global total** (not used):\n- Would allow distributed attacks to succeed\n- One attacker with many IPs could exhaust the limit for everyone\n- Not effective for security\n\n### Disabling Rate Limiting\n\nNot recommended, but you can disable for testing:\n\n```ts\nrateLimit: {\n enabled: process.env.NODE_ENV === 'production',\n window: 60,\n max: 1000, // Higher limit for development\n}\n```\n\n---\n\n## Cross-Domain Authentication\n\nFor applications spanning multiple subdomains (e.g., `account.example.com`, `api.example.com`, `dashboard.example.com`), Quickback provides dual-layer security.\n\n### The Problem\n\nBrowsers restrict cookies to exact domains by default. If your auth API is at `api.example.com`, cookies won't be sent to `dashboard.example.com`.\n\n### The Solution: Dual-Layer Protection\n\nQuickback uses two complementary security layers:\n\n#### 1. Cookie Domain (Browser-Level)\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: 'example.com' // All *.example.com can access cookies\n }\n }\n})\n```\n\n**Behavior**: Allows ALL subdomains to access the cookie (browser limitation per RFC 6265)\n- Cannot selectively allow only specific subdomains\n- All-or-nothing: either exact domain only, or all subdomains\n\n#### 2. Trusted Origins (Application-Level)\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n 'https://account.example.com',\n 'https://api.example.com',\n 'https://dashboard.example.com'\n ]\n})\n```\n\n**Behavior**: Better Auth validates request origins before processing auth operations\n- Granular whitelist of allowed origins\n- Blocks requests from untrusted subdomains even if they have the cookie\n- Prevents CSRF and unauthorized auth operations\n\n### Security Model\n\n```\n┌─────────────────────────────────────────────────┐\n│ Subdomain: evil.example.com │\n│ Has Cookie: ✓ (via crossSubDomainCookies) │\n│ In trustedOrigins: ✗ │\n│ Result: REQUEST BLOCKED by Better Auth │\n└─────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────┐\n│ Subdomain: account.example.com │\n│ Has Cookie: ✓ (via crossSubDomainCookies) │\n│ In trustedOrigins: ✓ │\n│ Result: REQUEST ALLOWED │\n└─────────────────────────────────────────────────┘\n```\n\n### Full Cross-Domain Configuration\n\n```ts\n\nexport default defineConfig({\n name: \"my-saas\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n ACCOUNT_URL: \"https://account.example.com\",\n BETTER_AUTH_URL: \"https://api.example.com\",\n }\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"organization\"],\n\n // Trusted origins (granular whitelist)\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://api.example.com\",\n \"https://dashboard.example.com\",\n \"http://localhost:3000\", // Development\n ],\n\n // Cookie configuration\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: \"example.com\",\n },\n defaultCookieAttributes: {\n secure: true,\n sameSite: \"none\", // Required for cross-domain\n httpOnly: true,\n }\n }\n })\n }\n})\n```\n\n**Important**: When using `sameSite: \"none\"`, you must also set `secure: true`. This is required by browsers.\n\n---\n\n## Environment Variables\n\nSet these in your Cloudflare Workers environment or `.env` file:\n\n### Required\n\n```bash\n# Better Auth secret (minimum 32 characters)\nBETTER_AUTH_SECRET=your-secret-key-min-32-chars\n\n# Base URL for Better Auth endpoints\nBETTER_AUTH_URL=https://api.example.com\n```\n\n### Optional (Cross-Domain)\n\n```bash\n# Enable cross-subdomain cookies\nCROSS_SUBDOMAIN_COOKIES=true\nCOOKIE_DOMAIN=example.com\n\n# Trusted origins (comma-separated)\nTRUSTED_ORIGINS=https://account.example.com,https://api.example.com\n\n# CORS allowed origins (typically matches trustedOrigins)\nALLOWED_ORIGINS=https://account.example.com,https://api.example.com\n```\n\n### Setting Secrets with Wrangler\n\nFor sensitive values like `BETTER_AUTH_SECRET`:\n\n```bash\nwrangler secret put BETTER_AUTH_SECRET\n# Paste your secret when prompted\n```\n\nFor non-secret vars, add to `wrangler.toml`:\n\n```toml\n[vars]\nBETTER_AUTH_URL = \"https://api.example.com\"\nCROSS_SUBDOMAIN_COOKIES = \"false\"\n```\n\n---\n\n## Security Best Practices\n\n### Single Domain (Recommended)\n\nFor most applications, use exact domain cookies:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\"https://app.example.com\"],\n advanced: {\n crossSubDomainCookies: {\n enabled: false // Default: exact domain only\n },\n defaultCookieAttributes: {\n sameSite: 'lax',\n secure: true,\n httpOnly: true,\n }\n }\n})\n```\n\n**Benefits**:\n- Maximum security (smallest cookie scope)\n- No cross-subdomain attack surface\n- Simpler configuration\n\n### Multi-Subdomain (When Needed)\n\nOnly enable cross-subdomain cookies if you need SSO across multiple subdomains:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://dashboard.example.com\",\n ],\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: \"example.com\",\n },\n defaultCookieAttributes: {\n sameSite: 'none', // Required for cross-domain\n secure: true,\n httpOnly: true,\n }\n }\n})\n```\n\n**Security requirements**:\n- Trust all subdomains equally (any compromised subdomain can steal cookies)\n- Use separate root domains for untrusted services\n- Always set `trustedOrigins` for granular control\n\n### CORS vs Trusted Origins\n\nThese serve different purposes and should typically match:\n\n| Setting | Purpose |\n|---------|---------|\n| `ALLOWED_ORIGINS` (CORS) | Controls which origins can make credentialed requests |\n| `trustedOrigins` (Better Auth) | Validates origins for auth operations + prevents open redirects |\n\n**Example**:\n\n```ts\ndatabase: defineDatabase(\"cloudflare-d1\", {\n vars: {\n ALLOWED_ORIGINS: \"https://account.example.com,https://api.example.com\"\n }\n}),\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://api.example.com\"\n ]\n})\n```\n\n### Checklist\n\nBefore deploying to production:\n\n- [ ] `BETTER_AUTH_SECRET` is set (minimum 32 random characters)\n- [ ] `secure: true` is enabled (HTTPS only)\n- [ ] `httpOnly: true` is enabled (XSS protection)\n- [ ] `sameSite: 'lax'` or `'strict'` unless cross-domain required\n- [ ] `trustedOrigins` includes only your domains\n- [ ] `ALLOWED_ORIGINS` matches `trustedOrigins`\n- [ ] Rate limiting is enabled (`rateLimit.enabled: true`)\n- [ ] Custom rate limits set for sensitive endpoints\n\n---\n\n## Deployment Considerations\n\n### Behind Proxy/Load Balancer\n\nIf your app is behind a proxy, ensure IP address headers are trusted:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n autoDetectIpAddress: true, // Uses X-Forwarded-For or CF-Connecting-IP\n})\n```\n\n**Cloudflare Workers**: IP automatically available via `CF-Connecting-IP` header\n\n**Other proxies**: Configure to trust `X-Forwarded-For` or `X-Real-IP`\n\n### Multiple Environments\n\nUse environment variables to configure different settings per environment:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: process.env.TRUSTED_ORIGINS?.split(',') || [],\n advanced: {\n crossSubDomainCookies: {\n enabled: process.env.CROSS_SUBDOMAIN_COOKIES === 'true',\n domain: process.env.COOKIE_DOMAIN,\n },\n defaultCookieAttributes: {\n sameSite: process.env.COOKIE_SAMESITE || 'lax',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: true,\n }\n }\n})\n```\n\n**Development** (`.dev.vars`):\n```bash\nTRUSTED_ORIGINS=http://localhost:3000,http://localhost:5173\nCROSS_SUBDOMAIN_COOKIES=false\nCOOKIE_SAMESITE=lax\n```\n\n**Production** (Wrangler secrets):\n```bash\nTRUSTED_ORIGINS=https://account.example.com,https://api.example.com\nCROSS_SUBDOMAIN_COOKIES=true\nCOOKIE_DOMAIN=example.com\nCOOKIE_SAMESITE=none\n```\n\n---\n\n## Further Reading\n\n- [Better Auth: Cookies Documentation](https://www.better-auth.com/docs/concepts/cookies)\n- [Better Auth: Security Guide](https://www.better-auth.com/docs/reference/security)\n- [OWASP: Cross-Site Request Forgery Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n- [MDN: SameSite Cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)"
|
|
358
|
+
"content": "Quickback enforces secure authentication defaults out of the box. This page explains how cookie security, rate limiting, and cross-domain authentication work, plus how to configure them for your use case.\n\n## Cookie Security\n\nQuickback sets secure cookie defaults to protect against CSRF, XSS, and man-in-the-middle attacks.\n\n### Default Attributes\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n defaultCookieAttributes: {\n sameSite: 'lax', // CSRF protection\n secure: true, // HTTPS only\n httpOnly: true, // No JavaScript access\n }\n }\n})\n```\n\n**What each attribute does:**\n\n| Attribute | Value | Purpose |\n|-----------|-------|---------|\n| `sameSite` | `lax` | Blocks cookies on cross-site POST requests (CSRF protection) |\n| `secure` | `true` | Cookies only sent over HTTPS (prevents interception) |\n| `httpOnly` | `true` | JavaScript cannot access cookies via `document.cookie` (XSS mitigation) |\n\n### SameSite Options\n\n- **`lax` (recommended)**: Blocks cross-site POST requests but allows top-level navigation. Best balance of security and usability.\n- **`strict`**: Blocks cookies on all cross-site requests. More secure but may break legitimate flows (e.g., returning from payment provider).\n- **`none`**: Allows all cross-site requests. Required for cross-domain authentication (requires `secure: true`).\n\n### Development Override\n\nFor local development over HTTP, you can relax the `secure` flag:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n defaultCookieAttributes: {\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: true,\n }\n }\n})\n```\n\n**Warning**: Never use `secure: false` in production.\n\n---\n\n## Rate Limiting\n\nQuickback includes per-IP rate limiting by default to protect against brute-force attacks and abuse.\n\n### How It Works\n\n**Rate limits are applied per IP address**, not globally:\n\n```\n┌─────────────────────────────────────────────────┐\n│ IP: 192.168.1.1 │\n│ Endpoint: /sign-in/email │\n│ Limit: 10 requests per 60 seconds │\n│ │\n│ Request 1-10: ✅ Allowed │\n│ Request 11: ❌ 429 Too Many Requests │\n│ After 60s: Counter resets to 0 │\n└─────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────┐\n│ IP: 192.168.1.2 (different IP) │\n│ Endpoint: /sign-in/email │\n│ Independent counter: Not affected by 1.1 │\n│ Starts at 0 │\n└─────────────────────────────────────────────────┘\n```\n\n### Default Configuration\n\n```ts\nauth: defineAuth(\"better-auth\", {\n rateLimit: {\n enabled: true,\n window: 60, // 60 second window\n max: 100, // 100 requests per IP per window\n customRules: {\n \"/sign-in/email\": { window: 60, max: 10 },\n \"/sign-in/social\": { window: 60, max: 10 },\n \"/device/init\": { window: 60, max: 5 },\n \"/device/poll\": { window: 60, max: 30 },\n \"/device/token\": { window: 60, max: 10 },\n }\n }\n})\n```\n\n### Custom Rules by Endpoint\n\nSet different limits based on endpoint sensitivity:\n\n| Endpoint Type | Recommended Limit | Reasoning |\n|---------------|-------------------|-----------|\n| Sign-in | 10/min per IP | Prevent credential stuffing |\n| Device codes | 5/min per IP | Prevent device code enumeration |\n| Token exchange | 10/min per IP | Prevent token brute-force |\n| Polling | 30/min per IP | Allow reasonable polling (every 2s) |\n| General API | 100/min per IP | Balance abuse prevention and usability |\n\n### Why Per-IP?\n\n✅ **Per-IP** (what Quickback uses):\n- Prevents single attacker from brute-forcing\n- Doesn't penalize legitimate users when one IP is malicious\n- Standard for auth endpoints\n\n❌ **Global total** (not used):\n- Would allow distributed attacks to succeed\n- One attacker with many IPs could exhaust the limit for everyone\n- Not effective for security\n\n### Disabling Rate Limiting\n\nNot recommended, but you can disable for testing:\n\n```ts\nrateLimit: {\n enabled: process.env.NODE_ENV === 'production',\n window: 60,\n max: 1000, // Higher limit for development\n}\n```\n\n---\n\n## Bearer Tokens and Cookie Precedence\n\nQuickback supports three bearer-token flavors alongside the standard browser session cookie:\n\n| Credential | Used by | Resolved by |\n|------------|---------|-------------|\n| Session cookie | Browser SPAs (CMS, Account, your app) | Better Auth session lookup |\n| Session-token bearer | API clients that grabbed `set-auth-token` | Better Auth `bearer` plugin |\n| JWT bearer | API clients that hit `/api/v1/token` | In-worker JWT fast-path (no DB hit) |\n| API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` / `?api_key=` |\n\nThese match Better Auth's own framing of bearer tokens as **an alternative to cookies, not a supplement** — a request uses one or the other.\n\n### Precedence: bearer always wins\n\nIf a request carries both `Authorization` and `Cookie` headers, the bearer wins universally and the cookie is dropped before session resolution:\n\n```\nRequest Resolved as\n────────────────────────────────────── ─────────────\nCookie only cookie session\nAuthorization: Bearer <jwt> JWT claims\nAuthorization: Bearer <api-key> API-key owner\nAuthorization: Bearer <session-token> bearer session\nCookie + Authorization: Bearer <token> bearer wins, cookie ignored\n```\n\nThis closes a class of silent-impersonation bugs where an ambient session cookie (multi-account browser tabs, a malicious extension, a misconfigured proxy injecting `Set-Cookie`) would otherwise override an explicit bearer credential. The decision is made before `getSession()` runs, so it applies to every code path in the auth middleware.\n\nThe api-key and JWT bearers also short-circuit before cookie resolution via dedicated fast-paths — they never touch the database for session lookup. Only session-token bearers reach `getSession()`, where Better Auth's `bearer` plugin resolves the `Authorization` header.\n\n### `requireSignature: true` is the secure default\n\nQuickback configures the Better Auth `bearer` plugin with `requireSignature: true` by default. This means:\n\n- The session token Better Auth emits via the `set-auth-token` response header is **signed server-side** with `BETTER_AUTH_SECRET`.\n- Unsigned bearer tokens are **rejected** at the plugin layer before any session lookup happens.\n- A session token leaked via a proxy access log, a browser dev-tools panel, or a misrouted `Referer` header **cannot** be replayed as a bearer token by an attacker — they would need the signing secret to forge a valid signature.\n\nBetter Auth's own default for this option is `false`. Quickback overrides it on the secure side. JWT bearers and agent-auth bearers are independently signed and unaffected by this setting.\n\n### Overriding the default\n\nIf a project genuinely needs unsigned bearers (e.g., a closed loopback service where signing is redundant), pass an explicit object:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n plugins: {\n bearer: { requireSignature: false },\n },\n})\n```\n\nUser-supplied options merge on top of the secure default, so any other [`bearer` plugin option](https://better-auth.com/docs/plugins/bearer) can be passed the same way.\n\n### Threat model and trade-offs\n\n| Threat | Mitigation |\n|--------|-----------|\n| Stolen session-token bearer replayed against the API | `requireSignature: true` blocks unsigned values |\n| Browser extension injects a victim's session cookie into an attacker's bearer-authed API call | Cookie stripped when `Authorization` is present |\n| Multi-account user has cookies for two identities and uses bearer for the second | Bearer identity wins; no ambiguity in audit log |\n| MCP / agent flow exposed to ambient browser cookies | `/mcp` and agent-auth routes are bearer-only (cookies dropped entirely, see [Agent Auth](/stack/auth/plugins/agent-auth)) |\n| Alg-confusion / forged JWT (alg=none, HS384, RS256) | Verifier pins HS256; signature math rejects all non-matching algs uniformly with 401 |\n\nFor a deeper walkthrough of the bearer flow itself, see the upstream [Better Auth bearer plugin docs](https://better-auth.com/docs/plugins/bearer).\n\n---\n\n## Cross-Domain Authentication\n\nFor applications spanning multiple subdomains (e.g., `account.example.com`, `api.example.com`, `dashboard.example.com`), Quickback provides dual-layer security.\n\n### The Problem\n\nBrowsers restrict cookies to exact domains by default. If your auth API is at `api.example.com`, cookies won't be sent to `dashboard.example.com`.\n\n### The Solution: Dual-Layer Protection\n\nQuickback uses two complementary security layers:\n\n#### 1. Cookie Domain (Browser-Level)\n\n```ts\nauth: defineAuth(\"better-auth\", {\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: 'example.com' // All *.example.com can access cookies\n }\n }\n})\n```\n\n**Behavior**: Allows ALL subdomains to access the cookie (browser limitation per RFC 6265)\n- Cannot selectively allow only specific subdomains\n- All-or-nothing: either exact domain only, or all subdomains\n\n#### 2. Trusted Origins (Application-Level)\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n 'https://account.example.com',\n 'https://api.example.com',\n 'https://dashboard.example.com'\n ]\n})\n```\n\n**Behavior**: Better Auth validates request origins before processing auth operations\n- Granular whitelist of allowed origins\n- Blocks requests from untrusted subdomains even if they have the cookie\n- Prevents CSRF and unauthorized auth operations\n\n### Security Model\n\n```\n┌─────────────────────────────────────────────────┐\n│ Subdomain: evil.example.com │\n│ Has Cookie: ✓ (via crossSubDomainCookies) │\n│ In trustedOrigins: ✗ │\n│ Result: REQUEST BLOCKED by Better Auth │\n└─────────────────────────────────────────────────┘\n\n┌─────────────────────────────────────────────────┐\n│ Subdomain: account.example.com │\n│ Has Cookie: ✓ (via crossSubDomainCookies) │\n│ In trustedOrigins: ✓ │\n│ Result: REQUEST ALLOWED │\n└─────────────────────────────────────────────────┘\n```\n\n### Full Cross-Domain Configuration\n\n```ts\n\nexport default defineConfig({\n name: \"my-saas\",\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\", {\n vars: {\n ACCOUNT_URL: \"https://account.example.com\",\n BETTER_AUTH_URL: \"https://api.example.com\",\n }\n }),\n auth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: [\"organization\"],\n\n // Trusted origins (granular whitelist)\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://api.example.com\",\n \"https://dashboard.example.com\",\n \"http://localhost:3000\", // Development\n ],\n\n // Cookie configuration\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: \"example.com\",\n },\n defaultCookieAttributes: {\n secure: true,\n sameSite: \"none\", // Required for cross-domain\n httpOnly: true,\n }\n }\n })\n }\n})\n```\n\n**Important**: When using `sameSite: \"none\"`, you must also set `secure: true`. This is required by browsers.\n\n---\n\n## Environment Variables\n\nSet these in your Cloudflare Workers environment or `.env` file:\n\n### Required\n\n```bash\n# Better Auth secret (minimum 32 characters)\nBETTER_AUTH_SECRET=your-secret-key-min-32-chars\n\n# Base URL for Better Auth endpoints\nBETTER_AUTH_URL=https://api.example.com\n```\n\n### Optional (Cross-Domain)\n\n```bash\n# Enable cross-subdomain cookies\nCROSS_SUBDOMAIN_COOKIES=true\nCOOKIE_DOMAIN=example.com\n\n# Trusted origins (comma-separated)\nTRUSTED_ORIGINS=https://account.example.com,https://api.example.com\n\n# CORS allowed origins (typically matches trustedOrigins)\nALLOWED_ORIGINS=https://account.example.com,https://api.example.com\n```\n\n### Setting Secrets with Wrangler\n\nFor sensitive values like `BETTER_AUTH_SECRET`:\n\n```bash\nwrangler secret put BETTER_AUTH_SECRET\n# Paste your secret when prompted\n```\n\nFor non-secret vars, add to `wrangler.toml`:\n\n```toml\n[vars]\nBETTER_AUTH_URL = \"https://api.example.com\"\nCROSS_SUBDOMAIN_COOKIES = \"false\"\n```\n\n---\n\n## Security Best Practices\n\n### Single Domain (Recommended)\n\nFor most applications, use exact domain cookies:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\"https://app.example.com\"],\n advanced: {\n crossSubDomainCookies: {\n enabled: false // Default: exact domain only\n },\n defaultCookieAttributes: {\n sameSite: 'lax',\n secure: true,\n httpOnly: true,\n }\n }\n})\n```\n\n**Benefits**:\n- Maximum security (smallest cookie scope)\n- No cross-subdomain attack surface\n- Simpler configuration\n\n### Multi-Subdomain (When Needed)\n\nOnly enable cross-subdomain cookies if you need SSO across multiple subdomains:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://dashboard.example.com\",\n ],\n advanced: {\n crossSubDomainCookies: {\n enabled: true,\n domain: \"example.com\",\n },\n defaultCookieAttributes: {\n sameSite: 'none', // Required for cross-domain\n secure: true,\n httpOnly: true,\n }\n }\n})\n```\n\n**Security requirements**:\n- Trust all subdomains equally (any compromised subdomain can steal cookies)\n- Use separate root domains for untrusted services\n- Always set `trustedOrigins` for granular control\n\n### CORS vs Trusted Origins\n\nThese serve different purposes and should typically match:\n\n| Setting | Purpose |\n|---------|---------|\n| `ALLOWED_ORIGINS` (CORS) | Controls which origins can make credentialed requests |\n| `trustedOrigins` (Better Auth) | Validates origins for auth operations + prevents open redirects |\n\n**Example**:\n\n```ts\ndatabase: defineDatabase(\"cloudflare-d1\", {\n vars: {\n ALLOWED_ORIGINS: \"https://account.example.com,https://api.example.com\"\n }\n}),\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: [\n \"https://account.example.com\",\n \"https://api.example.com\"\n ]\n})\n```\n\n### Checklist\n\nBefore deploying to production:\n\n- [ ] `BETTER_AUTH_SECRET` is set (minimum 32 random characters)\n- [ ] `secure: true` is enabled (HTTPS only)\n- [ ] `httpOnly: true` is enabled (XSS protection)\n- [ ] `sameSite: 'lax'` or `'strict'` unless cross-domain required\n- [ ] `trustedOrigins` includes only your domains\n- [ ] `ALLOWED_ORIGINS` matches `trustedOrigins`\n- [ ] Rate limiting is enabled (`rateLimit.enabled: true`)\n- [ ] Custom rate limits set for sensitive endpoints\n\n---\n\n## Deployment Considerations\n\n### Behind Proxy/Load Balancer\n\nIf your app is behind a proxy, ensure IP address headers are trusted:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n autoDetectIpAddress: true, // Uses X-Forwarded-For or CF-Connecting-IP\n})\n```\n\n**Cloudflare Workers**: IP automatically available via `CF-Connecting-IP` header\n\n**Other proxies**: Configure to trust `X-Forwarded-For` or `X-Real-IP`\n\n### Multiple Environments\n\nUse environment variables to configure different settings per environment:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n trustedOrigins: process.env.TRUSTED_ORIGINS?.split(',') || [],\n advanced: {\n crossSubDomainCookies: {\n enabled: process.env.CROSS_SUBDOMAIN_COOKIES === 'true',\n domain: process.env.COOKIE_DOMAIN,\n },\n defaultCookieAttributes: {\n sameSite: process.env.COOKIE_SAMESITE || 'lax',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: true,\n }\n }\n})\n```\n\n**Development** (`.dev.vars`):\n```bash\nTRUSTED_ORIGINS=http://localhost:3000,http://localhost:5173\nCROSS_SUBDOMAIN_COOKIES=false\nCOOKIE_SAMESITE=lax\n```\n\n**Production** (Wrangler secrets):\n```bash\nTRUSTED_ORIGINS=https://account.example.com,https://api.example.com\nCROSS_SUBDOMAIN_COOKIES=true\nCOOKIE_DOMAIN=example.com\nCOOKIE_SAMESITE=none\n```\n\n---\n\n## Further Reading\n\n- [Better Auth: Cookies Documentation](https://www.better-auth.com/docs/concepts/cookies)\n- [Better Auth: Security Guide](https://www.better-auth.com/docs/reference/security)\n- [OWASP: Cross-Site Request Forgery Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n- [MDN: SameSite Cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)"
|
|
359
359
|
},
|
|
360
360
|
"stack/auth/using-auth": {
|
|
361
361
|
"title": "Using Auth",
|
|
@@ -363,7 +363,7 @@ export const DOCS = {
|
|
|
363
363
|
},
|
|
364
364
|
"stack/cms/actions": {
|
|
365
365
|
"title": "Actions",
|
|
366
|
-
"content": "# Actions\n\nActions are custom operations defined in your feature files (e.g., `approve`, `void`, `post`, `applyPayment`). The CMS renders them as clickable buttons with auto-generated input forms — no UI code required.\n\n## Where Actions Appear\n\nActions show up in two places:\n\n### Row Action Menu (Table Mode)\n\nIn Table mode, the three-dot menu on each row includes a section for custom actions. Actions are separated from standard operations (view, edit, delete) by a divider.\n\n### Action Bar (Detail View)\n\nIn the record detail view, an \"Actions\" card displays all available actions as buttons. Each button shows the action name, and hovering reveals the description as a tooltip.\n\n## Action Dialog\n\nClicking an action opens a modal dialog with:\n\n1. **Header** — Action name with an icon (lightning bolt for standard, warning triangle for destructive, download for file responses)\n2. **Description** — The action's description text\n3. **Side effects warning** — If the action has `sideEffects: \"sync\"`, an amber warning banner appears: \"This action has synchronous side effects (e.g., GL entries).\"\n4. **Confirmation step** — If the action has `cms.confirm`, a confirmation message appears before the input form\n5. **Input fields** — Auto-generated from the action's `inputFields` schema\n6. **Execute button** — Submits the action. Shows \"Executing...\" while in progress.\n7. **Cancel button** — Closes the dialog without executing\n\n### Input Field Types\n\nThe dialog generates the appropriate input control for each field:\n\n| Zod Type | Input Control | Notes |\n|----------|--------------|-------|\n| `string` | Text input | Free-text entry |\n| `number` | Number input | Step 0.01, supports decimals |\n| `boolean` | Checkbox | With label text |\n| `array<string>` | Text input | Comma-separated values, split on save |\n\nRequired fields are marked with a red asterisk. Default values from the schema are pre-filled.\n\n### Example\n\nGiven this action definition:\n\n```typescript\nactions: {\n applyPayment: {\n description: \"Apply a payment to this invoice\",\n input: 'z.object({ amount: z.number(), reference: z.string().optional() })',\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'posted' } },\n },\n sideEffects: \"sync\",\n cms: {\n label: \"Apply Payment\",\n icon: \"dollar-sign\",\n confirm: \"This will create GL entries. Continue?\",\n category: \"payments\",\n successMessage: \"Payment applied successfully\",\n order: 1,\n },\n },\n}\n```\n\nThe CMS renders a dialog with:\n\n- A number input for `amount` (required)\n- A text input for `reference` (optional)\n- A sync side effects warning\n- A confirmation step with the custom message\n- Only visible to admins and owners\n- Only visible on records where `status === \"posted\"`\n\n## Access Filtering\n\nActions are filtered based on two criteria:\n\n### Role Check\n\nThe action's `access.roles` array is compared against the current user's role. If the user's role is not in the list, the action is hidden.\n\n### Record Condition\n\nThe action's `access.record` conditions are evaluated against the current record's data. Supported conditions:\n\n| Operator | Example | Meaning |\n|----------|---------|---------|\n| `equals` | `{ status: { equals: 'pending' } }` | Field must equal value |\n| `notEquals` | `{ status: { notEquals: 'void' } }` | Field must not equal value |\n| `in` | `{ status: { in: ['pending', 'draft'] } }` | Field must be one of values |\n\nAll conditions must pass for the action to be visible. This means \"approve\" actions naturally disappear after a record is approved, and \"void\" actions only appear on voidable records.\n\n## CMS Metadata\n\nActions can include an optional `cms` property for enhanced CMS rendering. Actions without `cms` render with default behavior.\n\n| Property | Type | Default | Purpose |\n|----------|------|---------|---------|\n| `label` | `string` | camelCase split | Display name override |\n| `icon` | `string` | `\"zap\"` | Lucide icon name |\n| `confirm` | `string \\| boolean` | `false` | `true` = generic confirm, string = custom message |\n| `destructive` | `boolean` | `false` | Red styling + requires confirmation |\n| `category` | `string` | none | Group actions under a header |\n| `hidden` | `boolean` | `false` | Hide from CMS entirely (API-only actions) |\n| `successMessage` | `string` | none | Toast message after success |\n| `onSuccess` | `\"refresh\" \\| \"redirect:list\" \\| \"close\"` | `\"refresh\"` | Behavior after successful execution |\n| `order` | `number` | `0` | Sort priority (lower = first) |\n\n### Example with CMS metadata\n\n```typescript\n// features/invoices/actions/post.ts\n\nexport default defineAction({\n description: \"Post this invoice to accounts receivable\",\n input: z.object({}),\n access: { roles: [\"owner\", \"admin\"], record: { status: { equals: \"draft\" } } },\n sideEffects: \"sync\",\n cms: {\n label: \"Post Invoice\",\n icon: \"send\",\n confirm: \"This will post the invoice to AR and create GL entries. Continue?\",\n category: \"lifecycle\",\n successMessage: \"Invoice posted successfully\",\n onSuccess: \"refresh\",\n order: 1,\n },\n async execute({ db, record }) {\n // ... post invoice\n return { ok: true };\n },\n});\n```\n\n### Hiding API-only actions\n\n```typescript\n// features/invoices/actions/internal-recalc.ts\n\nexport default defineAction({\n description: \"Recalculate internal totals\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n cms: { hidden: true }, // Never shown in CMS\n async execute({ db, record }) {\n // ... recalc totals\n return { ok: true };\n },\n});\n```\n\n## Destructive Actions\n\nActions are styled as destructive when either:\n\n- The action's `cms.destructive` is `true`\n- The action is named `void` or `delete` (legacy fallback)\n\nDestructive actions receive:\n\n- **Red text** in the row action menu\n- **Warning triangle icon** (unless overridden by `cms.icon`)\n- **Red execute button** in the dialog (using `bg-destructive` styling)\n- **Automatic confirmation step** (unless `cms.confirm` is explicitly `false`)\n\nThis provides a visual cue that the action has permanent consequences.\n\n## Standalone Actions\n\nActions with `path:` set are standalone — not tied to a specific record. They appear in a separate section and don't receive a `recordId` when executed. The CMS passes `null` as the record ID for standalone actions.\n\n## File Response Actions\n\nActions with `responseType: \"file\"` show a download icon instead of the lightning bolt. When executed, the response is treated as a file download rather than a JSON result.\n\n## Execution Flow\n\n1. User clicks action in row menu or action bar\n2. Dialog opens with description, inputs, and warnings\n3. If `cms.confirm` is set, user sees confirmation step first\n4. User fills in required fields\n5. User clicks \"Execute\" (or \"Confirm\" after confirmation step)\n6. CMS calls `client.executeAction(table, actionName, recordId, input)`\n7. On success: `cms.successMessage` shown as toast (if set), then `cms.onSuccess` behavior\n8. On error: error message displayed in dialog\n\n## Next Steps\n\n- **[Security](/stack/cms/security)** — Access conditions and role-based access\n- **[Table Views](/stack/cms/table-views)** — Where actions appear in the UI\n- **[Schema Format Reference](/stack/cms/schema-format)** — ActionMeta type definition"
|
|
366
|
+
"content": "# Actions\n\nActions are custom operations defined in your feature files (e.g., `approve`, `void`, `post`, `applyPayment`). The CMS renders them as clickable buttons with auto-generated input forms — no UI code required.\n\n## Where Actions Appear\n\nActions show up in two places:\n\n### Row Action Menu (Table Mode)\n\nIn Table mode, the three-dot menu on each row includes a section for custom actions. Actions are separated from standard operations (view, edit, delete) by a divider.\n\n### Action Bar (Detail View)\n\nIn the record detail view, an \"Actions\" card displays all available actions as buttons. Each button shows the action name, and hovering reveals the description as a tooltip.\n\n## Action Dialog\n\nClicking an action opens a modal dialog with:\n\n1. **Header** — Action name with an icon (lightning bolt for standard, warning triangle for destructive, download for file responses)\n2. **Description** — The action's description text\n3. **Side effects warning** — If the action has `sideEffects: \"sync\"`, an amber warning banner appears: \"This action has synchronous side effects (e.g., GL entries).\"\n4. **Confirmation step** — If the action has `cms.confirm`, a confirmation message appears before the input form\n5. **Input fields** — Auto-generated from the action's `inputFields` schema\n6. **Execute button** — Submits the action. Shows \"Executing...\" while in progress.\n7. **Cancel button** — Closes the dialog without executing\n\n### Input Field Types\n\nThe dialog generates the appropriate input control for each field:\n\n| Zod Type | Input Control | Notes |\n|----------|--------------|-------|\n| `string` | Text input | Free-text entry |\n| `number` | Number input | Step 0.01, supports decimals |\n| `boolean` | Checkbox | With label text |\n| `array<string>` | Text input | Comma-separated values, split on save |\n\nRequired fields are marked with a red asterisk. Default values from the schema are pre-filled.\n\n### Example\n\nGiven this action definition:\n\n```typescript\nactions: {\n applyPayment: {\n description: \"Apply a payment to this invoice\",\n input: 'z.object({ amount: z.number(), reference: z.string().optional() })',\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'posted' } },\n },\n sideEffects: \"sync\",\n cms: {\n label: \"Apply Payment\",\n icon: \"dollar-sign\",\n confirm: \"This will create GL entries. Continue?\",\n category: \"payments\",\n successMessage: \"Payment applied successfully\",\n order: 1,\n },\n },\n}\n```\n\nThe CMS renders a dialog with:\n\n- A number input for `amount` (required)\n- A text input for `reference` (optional)\n- A sync side effects warning\n- A confirmation step with the custom message\n- Only visible to admins and owners\n- Only visible on records where `status === \"posted\"`\n\n## Access Filtering\n\nActions are filtered based on two criteria:\n\n### Role Check\n\nThe action's `access.roles` array is compared against the current user's role. If the user's role is not in the list, the action is hidden.\n\n### Record Condition\n\nThe action's `access.record` conditions are evaluated against the current record's data. Supported conditions:\n\n| Operator | Example | Meaning |\n|----------|---------|---------|\n| `equals` | `{ status: { equals: 'pending' } }` | Field must equal value |\n| `notEquals` | `{ status: { notEquals: 'void' } }` | Field must not equal value |\n| `in` | `{ status: { in: ['pending', 'draft'] } }` | Field must be one of values |\n\nAll conditions must pass for the action to be visible. This means \"approve\" actions naturally disappear after a record is approved, and \"void\" actions only appear on voidable records.\n\n## CMS Metadata\n\nActions can include an optional `cms` property for enhanced CMS rendering. Actions without `cms` render with default behavior.\n\n| Property | Type | Default | Purpose |\n|----------|------|---------|---------|\n| `label` | `string` | camelCase split | Display name override |\n| `icon` | `string` | `\"zap\"` | Lucide icon name |\n| `confirm` | `string \\| boolean` | `false` | `true` = generic confirm, string = custom message |\n| `destructive` | `boolean` | `false` | Red styling + requires confirmation |\n| `category` | `string` | none | Group actions under a header |\n| `hidden` | `boolean` | `false` | Hide from CMS entirely (API-only actions) |\n| `placement` | `\"feature\" \\| \"tables\"` | none | Where standalone actions appear in multi-table features |\n| `tables` | `string[]` | none | Explicit table list when `placement` is `\"tables\"` |\n| `successMessage` | `string` | none | Toast message after success |\n| `onSuccess` | `\"refresh\" \\| \"redirect:list\" \\| \"close\"` | `\"refresh\"` | Behavior after successful execution |\n| `order` | `number` | `0` | Sort priority (lower = first) |\n\n### Example with CMS metadata\n\n```typescript\n// features/invoices/actions/post.ts\n\nexport default defineAction({\n description: \"Post this invoice to accounts receivable\",\n input: z.object({}),\n access: { roles: [\"owner\", \"admin\"], record: { status: { equals: \"draft\" } } },\n sideEffects: \"sync\",\n cms: {\n label: \"Post Invoice\",\n icon: \"send\",\n confirm: \"This will post the invoice to AR and create GL entries. Continue?\",\n category: \"lifecycle\",\n successMessage: \"Invoice posted successfully\",\n onSuccess: \"refresh\",\n order: 1,\n },\n async execute({ db, record }) {\n // ... post invoice\n return { ok: true };\n },\n});\n```\n\n### Hiding API-only actions\n\n```typescript\n// features/invoices/actions/internal-recalc.ts\n\nexport default defineAction({\n description: \"Recalculate internal totals\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n cms: { hidden: true }, // Never shown in CMS\n async execute({ db, record }) {\n // ... recalc totals\n return { ok: true };\n },\n});\n```\n\n## Destructive Actions\n\nActions are styled as destructive when either:\n\n- The action's `cms.destructive` is `true`\n- The action is named `void` or `delete` (legacy fallback)\n\nDestructive actions receive:\n\n- **Red text** in the row action menu\n- **Warning triangle icon** (unless overridden by `cms.icon`)\n- **Red execute button** in the dialog (using `bg-destructive` styling)\n- **Automatic confirmation step** (unless `cms.confirm` is explicitly `false`)\n\nThis provides a visual cue that the action has permanent consequences.\n\n## Standalone Actions\n\nActions with `path:` set are standalone — not tied to a specific record. They appear in a separate section and don't receive a `recordId` when executed. The CMS passes `null` as the record ID for standalone actions.\n\n### Placement in Multi-Table Features\n\nWhen a standalone action belongs to a feature with multiple tables, the CMS needs to know where to render it.\n\n- Use `cms.placement: \"feature\"` to show the action in the table toolbar for every table in that feature.\n- Use `cms.placement: \"tables\"` with `cms.tables` to show it only on specific tables.\n- Use `cms.hidden: true` to keep it API-only.\n\nSingle-table features and clearly table-scoped standalone paths are inferred automatically. Feature-root standalone actions in multi-table features should set placement explicitly.\n\n```typescript\ndefineAction({\n path: \"/chat/post-message\",\n method: \"POST\",\n access: { roles: [\"member\"] },\n cms: {\n label: \"Post Message\",\n placement: \"tables\",\n tables: [\"chatChannels\", \"chatMessages\"],\n },\n async execute() {\n return { ok: true };\n },\n});\n```\n\n## File Response Actions\n\nActions with `responseType: \"file\"` show a download icon instead of the lightning bolt. When executed, the response is treated as a file download rather than a JSON result.\n\n## Execution Flow\n\n1. User clicks action in row menu or action bar\n2. Dialog opens with description, inputs, and warnings\n3. If `cms.confirm` is set, user sees confirmation step first\n4. User fills in required fields\n5. User clicks \"Execute\" (or \"Confirm\" after confirmation step)\n6. CMS calls `client.executeAction(table, actionName, recordId, input)`\n7. On success: `cms.successMessage` shown as toast (if set), then `cms.onSuccess` behavior\n8. On error: error message displayed in dialog\n\n## Next Steps\n\n- **[Security](/stack/cms/security)** — Access conditions and role-based access\n- **[Table Views](/stack/cms/table-views)** — Where actions appear in the UI\n- **[Schema Format Reference](/stack/cms/schema-format)** — ActionMeta type definition"
|
|
367
367
|
},
|
|
368
368
|
"stack/cms/components": {
|
|
369
369
|
"title": "Components Reference",
|
|
@@ -371,7 +371,7 @@ export const DOCS = {
|
|
|
371
371
|
},
|
|
372
372
|
"stack/cms/connecting": {
|
|
373
373
|
"title": "Connecting",
|
|
374
|
-
"content": "# Connecting\n\nThe CMS supports two modes: **demo mode** for development and testing, and **live mode** for connecting to a real Quickback API.\n\n## Demo Mode\n\nWhen no `VITE_QUICKBACK_API_URL` is set, the CMS runs in demo mode:\n\n- Uses a **mock API client** backed by `localStorage`\n- Loads seed data from JSON files in `data/mock/`\n- Provides a **role switcher** in the header to test owner/admin/member access\n- Simulates authentication sessions without a real backend\n\nDemo mode is useful for prototyping your schema, testing guard behavior across roles, and verifying masking rules before deploying.\n\n```bash title=\".env.development\"\n# No VITE_QUICKBACK_API_URL — CMS runs in demo mode\n```\n\n### Mock Data\n\nPlace JSON files in `data/mock/` matching your table names:\n\n```\ndata/mock/\n contact.json # Array of contact records\n project.json # Array of project records\n invoice.json # Array of invoice records\n _meta.json # Mock session and org metadata\n```\n\nEach file contains an array of records. The mock client loads them on startup and persists changes to `localStorage`.\n\n### Role Switcher\n\nIn demo mode, the header displays a role switcher dropdown allowing you to switch between `owner`, `admin`, and `member` roles in real time. This lets you verify:\n\n- Which CRUD buttons appear per role\n- Which form fields are editable\n- Which masking rules apply\n- Which actions are available\n- Which views are accessible\n\n## Live Mode\n\nSet `VITE_QUICKBACK_API_URL` to connect to a real Quickback API:\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\n```\n\nIn live mode, the CMS:\n\n- Reads the **Better Auth session** from cookies\n- Fetches the user's **organization membership** and role\n- Makes real API calls to the Quickback backend for all CRUD operations\n- Applies server-side security (firewall, guards, masking) in addition to client-side UI filtering\n\n## API Client Interface\n\nThe CMS communicates with the backend through a standard interface:\n\n```typescript\ninterface IApiClient {\n list(table: string, params?: ListParams): Promise\n\n## How the Client is Created\n\nThe CMS auto-creates the API client based on configuration:\n\n1. **No `VITE_QUICKBACK_API_URL`** — Instantiates the mock client, loads seed data from `data/mock/`, and uses `localStorage` for persistence.\n2. **`VITE_QUICKBACK_API_URL` is set** — Instantiates the live client, reads the auth session cookie, and makes fetch requests to the Quickback API using the standard REST endpoints (`/api/v1/{table}`).\n\nThe client is provided via React context (`ApiClientContext`) and available throughout the component tree.\n\n## Embedded Mode (Recommended)\n\nSet `cms: true` in your config to embed the CMS directly in your compiled Worker:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\nWhen you run `quickback compile`, the CLI:\n1. Builds the CMS SPA from source and places assets in `src/apps/cms/`\n2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`\n3. Generates Worker routing to serve the CMS SPA\n\nRun `wrangler dev` and the CMS is served at `/cms/`. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app. Same origin — no CORS, auth cookies work naturally. On a custom domain, the CMS is served at root (`/`).\n\n### Custom CMS Domain\n\nOptionally serve the CMS on a separate subdomain:\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the Better Auth platform-admin tier) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:\n\n- **Account UI** hides the \"Go to CMS\" button for non-admins.\n- **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-admin. A non-admin who types the CMS URL directly cannot load the app.\n- **`/api/v1/schema`** returns `403 Admin access required` to non-admin callers, so schema metadata can't be scraped by hitting the API directly.\n- **`custom_view`
|
|
374
|
+
"content": "# Connecting\n\nThe CMS supports two modes: **demo mode** for development and testing, and **live mode** for connecting to a real Quickback API.\n\n## Demo Mode\n\nWhen no `VITE_QUICKBACK_API_URL` is set, the CMS runs in demo mode:\n\n- Uses a **mock API client** backed by `localStorage`\n- Loads seed data from JSON files in `data/mock/`\n- Provides a **role switcher** in the header to test owner/admin/member access\n- Simulates authentication sessions without a real backend\n\nDemo mode is useful for prototyping your schema, testing guard behavior across roles, and verifying masking rules before deploying.\n\n```bash title=\".env.development\"\n# No VITE_QUICKBACK_API_URL — CMS runs in demo mode\n```\n\n### Mock Data\n\nPlace JSON files in `data/mock/` matching your table names:\n\n```\ndata/mock/\n contact.json # Array of contact records\n project.json # Array of project records\n invoice.json # Array of invoice records\n _meta.json # Mock session and org metadata\n```\n\nEach file contains an array of records. The mock client loads them on startup and persists changes to `localStorage`.\n\n### Role Switcher\n\nIn demo mode, the header displays a role switcher dropdown allowing you to switch between `owner`, `admin`, and `member` roles in real time. This lets you verify:\n\n- Which CRUD buttons appear per role\n- Which form fields are editable\n- Which masking rules apply\n- Which actions are available\n- Which views are accessible\n\n## Live Mode\n\nSet `VITE_QUICKBACK_API_URL` to connect to a real Quickback API:\n\n```bash title=\".env.production\"\nVITE_QUICKBACK_API_URL=https://api.example.com\n```\n\nIn live mode, the CMS:\n\n- Reads the **Better Auth session** from cookies\n- Fetches the user's **organization membership** and role\n- Makes real API calls to the Quickback backend for all CRUD operations\n- Applies server-side security (firewall, guards, masking) in addition to client-side UI filtering\n\n## API Client Interface\n\nThe CMS communicates with the backend through a standard interface:\n\n```typescript\ninterface IApiClient {\n list(table: string, params?: ListParams): Promise\n\n## How the Client is Created\n\nThe CMS auto-creates the API client based on configuration:\n\n1. **No `VITE_QUICKBACK_API_URL`** — Instantiates the mock client, loads seed data from `data/mock/`, and uses `localStorage` for persistence.\n2. **`VITE_QUICKBACK_API_URL` is set** — Instantiates the live client, reads the auth session cookie, and makes fetch requests to the Quickback API using the standard REST endpoints (`/api/v1/{table}`).\n\nThe client is provided via React context (`ApiClientContext`) and available throughout the component tree.\n\n## Embedded Mode (Recommended)\n\nSet `cms: true` in your config to embed the CMS directly in your compiled Worker:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\nWhen you run `quickback compile`, the CLI:\n1. Builds the CMS SPA from source and places assets in `src/apps/cms/`\n2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`\n3. Generates Worker routing to serve the CMS SPA\n\nRun `wrangler dev` and the CMS is served at `/cms/`. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app. Same origin — no CORS, auth cookies work naturally. On a custom domain, the CMS is served at root (`/`).\n\n### Custom CMS Domain\n\nOptionally serve the CMS on a separate subdomain:\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the Better Auth platform-admin tier) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:\n\n- **Account UI** hides the \"Go to CMS\" button for non-admins.\n- **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-admin. A non-admin who types the CMS URL directly cannot load the app.\n- **`/api/v1/schema`** returns `403 Admin access required` to non-admin callers, so schema metadata can't be scraped by hitting the API directly.\n- **`custom_view` routes** are gated on `userRole: [\"admin\"]` rather than org membership, so saved views can't be listed or modified without admin rights.\n- **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource API endpoints (the ones generated for your features) are unaffected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.\n\nTo allow any authenticated user to access the CMS, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on multi-domain routing.\n\n## Multi-Tenant vs Single-Tenant\n\nThe CMS supports two authentication modes depending on your project's organization configuration.\n\n### Multi-Tenant (Default)\n\nIn multi-tenant mode, the CMS gates access behind organization membership:\n\n1. User logs in via Better Auth session\n2. CMS fetches the user's organization memberships\n3. If the user belongs to multiple organizations, an **org selector** is displayed\n4. Once an org is selected, the user's role within that org determines their CMS permissions\n\nThis is the default behavior for all Quickback projects.\n\n### Single-Tenant Mode\n\nWhen your project disables organizations (`features.organizations: false` in config), the compiler sets `singleTenant: true` in the schema registry. In this mode:\n\n- No org gate or org selector is shown\n- The user's role is read directly from `user.role` on the session\n- All data is unscoped (no `organizationId` filtering)\n\nSingle-tenant mode is useful for internal tools, personal projects, or apps that don't need multi-org isolation.\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Security](/stack/cms/security)** — How roles, guards, and masking work in the CMS"
|
|
375
375
|
},
|
|
376
376
|
"stack/cms/dashboard": {
|
|
377
377
|
"title": "Dashboard",
|
|
@@ -379,7 +379,7 @@ export const DOCS = {
|
|
|
379
379
|
},
|
|
380
380
|
"stack/cms": {
|
|
381
381
|
"title": "Quickback CMS",
|
|
382
|
-
"content": "# Quickback CMS\n\nA schema-driven admin interface that reads `schema-registry.json` generated by the Quickback compiler. Every table, column, action, view, and security rule is rendered automatically. Zero UI code per table.\n\n## Overview\n\nThe CMS generates its entire UI from your Quickback definitions. Define a table with columns, guards, masking, views, and actions in your feature files. Run the compiler. The CMS reads the resulting schema registry and renders a complete admin interface — data tables, inline editing, action dialogs, role-based access, and field masking — all without writing a single line of UI code.\n\n## Key Features\n\n- **Schema-driven** — Zero UI code per table. Add a table, recompile, and it appears in the CMS.\n- **Dashboard** — Stats grid and feature cards showing tables, columns, actions, views, and masked fields at a glance.\n- **Custom pages** — Split-panel layouts with drag-and-drop, matching engine, and page-level actions for workflows like reconciliation.\n- **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.\n- **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.\n- **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.\n- **Multi-tenant & single-tenant** — Org-scoped access by default, with single-tenant mode for simpler projects.\n- **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).\n- **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.\n- **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.\n- **Custom actions** — Action dialogs with auto-generated input forms, access filtering, CMS metadata (icons, categories, confirmations), and side effects warnings.\n- **Views** — Named column-level projections per role. \"All Fields\" plus custom views in the toolbar.\n- **Auto-form generation** — Create and edit forms built from guards (createable/updatable fields).\n- **Display column auto-detection** — FK labels resolved automatically from `name`, `title`, `label`, `code`, and other common patterns.\n\n## Architecture\n\nThe CMS sits at the end of the Quickback compilation pipeline:\n\n```\nQuickback Definitions (feature files)\n |\n v\n Compiler\n |\n v\n schema-registry.json\n |\n v\n CMS reads it\n |\n v\n Renders admin UI\n```\n\nYour feature definitions are the single source of truth. The compiler extracts all metadata — columns, types, guards, masking rules, views, actions, validation, and firewall config — into a static JSON file. The CMS consumes that file and renders the appropriate UI for each table.\n\n### How Embedded Serving Works\n\nWhen `cms: true` is set, the compiler builds the CMS SPA from source at compile time (with your project-specific env vars baked in) and outputs the assets to `src/apps/cms/`. It also configures `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nAll requests go through the Worker first. The Worker handles SPA routing — serving CMS at `/cms/` on the unified domain and at root (`/`) on a custom CMS domain. API paths (`/api/*`, `/auth/*`, etc.) are handled by Hono as normal.\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname-based routing.\n\n## Quick Start\n\n### 1. Enable CMS in config\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\n### 2. Compile\n\n```bash\nquickback compile\n```\n\nThe compiler generates `schema-registry.json` and copies CMS static assets to `src/apps/`. It also adds an `[assets]` section to `wrangler.toml` so Cloudflare serves the CMS SPA automatically.\n\n### 3. Run\n\n```bash\nnpm run dev\n```\n\nOpen your Worker URL in a browser — the CMS is served at the root. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app as normal. Everything runs on the same origin — no CORS configuration needed, auth cookies work naturally.\n\n### Optional: Custom CMS domain\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).\n\n### Access gate (admin-only by default)\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the user-table role from Better Auth's admin plugin) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:\n\n1. **Account UI link** — the \"Go to CMS\" button is hidden for non-admins.\n2. **CMS SPA shell** — the Worker returns `403 Admin access required` before serving `index.html` to a non-admin. Unauthenticated requests are redirected to the login page.\n3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === \"admin\"` and returns `403` otherwise.\n4. **`custom_view`
|
|
382
|
+
"content": "# Quickback CMS\n\nA schema-driven admin interface that reads `schema-registry.json` generated by the Quickback compiler. Every table, column, action, view, and security rule is rendered automatically. Zero UI code per table.\n\n## Overview\n\nThe CMS generates its entire UI from your Quickback definitions. Define a table with columns, guards, masking, views, and actions in your feature files. Run the compiler. The CMS reads the resulting schema registry and renders a complete admin interface — data tables, inline editing, action dialogs, role-based access, and field masking — all without writing a single line of UI code.\n\n## Key Features\n\n- **Schema-driven** — Zero UI code per table. Add a table, recompile, and it appears in the CMS.\n- **Dashboard** — Stats grid and feature cards showing tables, columns, actions, views, and masked fields at a glance.\n- **Custom pages** — Split-panel layouts with drag-and-drop, matching engine, and page-level actions for workflows like reconciliation.\n- **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.\n- **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.\n- **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.\n- **Multi-tenant & single-tenant** — Org-scoped access by default, with single-tenant mode for simpler projects.\n- **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).\n- **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.\n- **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.\n- **Custom actions** — Action dialogs with auto-generated input forms, access filtering, CMS metadata (icons, categories, confirmations), and side effects warnings.\n- **Views** — Named column-level projections per role. \"All Fields\" plus custom views in the toolbar.\n- **Auto-form generation** — Create and edit forms built from guards (createable/updatable fields).\n- **Display column auto-detection** — FK labels resolved automatically from `name`, `title`, `label`, `code`, and other common patterns.\n\n## Architecture\n\nThe CMS sits at the end of the Quickback compilation pipeline:\n\n```\nQuickback Definitions (feature files)\n |\n v\n Compiler\n |\n v\n schema-registry.json\n |\n v\n CMS reads it\n |\n v\n Renders admin UI\n```\n\nYour feature definitions are the single source of truth. The compiler extracts all metadata — columns, types, guards, masking rules, views, actions, validation, and firewall config — into a static JSON file. The CMS consumes that file and renders the appropriate UI for each table.\n\n### How Embedded Serving Works\n\nWhen `cms: true` is set, the compiler builds the CMS SPA from source at compile time (with your project-specific env vars baked in) and outputs the assets to `src/apps/cms/`. It also configures `wrangler.toml`:\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nAll requests go through the Worker first. The Worker handles SPA routing — serving CMS at `/cms/` on the unified domain and at root (`/`) on a custom CMS domain. API paths (`/api/*`, `/auth/*`, etc.) are handled by Hono as normal.\n\nSee [Multi-Domain Architecture](/compiler/config/domains) for details on hostname-based routing.\n\n## Quick Start\n\n### 1. Enable CMS in config\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n name: \"my-app\",\n cms: true,\n // ...providers\n});\n```\n\n### 2. Compile\n\n```bash\nquickback compile\n```\n\nThe compiler generates `schema-registry.json` and copies CMS static assets to `src/apps/`. It also adds an `[assets]` section to `wrangler.toml` so Cloudflare serves the CMS SPA automatically.\n\n### 3. Run\n\n```bash\nnpm run dev\n```\n\nOpen your Worker URL in a browser — the CMS is served at the root. API routes (`/api/*`, `/auth/*`, etc.) pass through to your Hono app as normal. Everything runs on the same origin — no CORS configuration needed, auth cookies work naturally.\n\n### Optional: Custom CMS domain\n\n```typescript\ncms: { domain: \"cms.example.com\" }\n```\n\nThis adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).\n\n### Access gate (admin-only by default)\n\nCMS access defaults to `access: \"admin\"` — only `user.role === \"admin\"` (the user-table role from Better Auth's admin plugin) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:\n\n1. **Account UI link** — the \"Go to CMS\" button is hidden for non-admins.\n2. **CMS SPA shell** — the Worker returns `403 Admin access required` before serving `index.html` to a non-admin. Unauthenticated requests are redirected to the login page.\n3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === \"admin\"` and returns `403` otherwise.\n4. **`custom_view` routes** — the CMS-internal saved-views table is gated on `userRole: [\"admin\"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.\n\nYour resource API endpoints (`/api/v1/<resource>`) are **not** affected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.\n\nTo allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\n### Optional: Skip SPA rebuild\n\nAfter the first compile, you can skip rebuilding the CMS SPA on subsequent compiles:\n\n```typescript\ncms: { build: false }\n```\n\nThis is useful when you're iterating on API features and don't need to rebuild the CMS UI each time — it saves significant compile time. Set `build: true` (or omit it) when you need to update the CMS assets.\n\n### Optional: Custom output directory\n\n```typescript\ncms: { outputDir: \"my-custom-path/cms\" }\n```\n\nThis changes where the compiled CMS assets are placed (relative to project root), instead of the default `src/apps/cms/`.\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — Understand the JSON format the compiler generates\n- **[Connecting](/stack/cms/connecting)** — Demo mode, live mode, CLI command, and auth modes\n- **[Dashboard](/stack/cms/dashboard)** — Stats grid and feature navigation\n- **[Table Views](/stack/cms/table-views)** — Browse and Data Table view modes\n- **[Custom Pages](/stack/cms/pages)** — Split-panel layouts, matching engine, and drag-drop\n- **[Inline Editing](/stack/cms/inline-editing)** — Spreadsheet-style editing and FK typeahead\n- **[Security](/stack/cms/security)** — How the CMS enforces all four security layers\n- **[Actions](/stack/cms/actions)** — Custom actions with input forms, access filtering, and CMS metadata\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types for schema-registry.json\n- **[Components Reference](/stack/cms/components)** — All CMS components and their props"
|
|
383
383
|
},
|
|
384
384
|
"stack/cms/inline-editing": {
|
|
385
385
|
"title": "Inline Editing",
|
|
@@ -391,27 +391,27 @@ export const DOCS = {
|
|
|
391
391
|
},
|
|
392
392
|
"stack/cms/record-layouts": {
|
|
393
393
|
"title": "Record Layouts",
|
|
394
|
-
"content": "# Record Layouts\n\nThe CMS record detail page groups fields into collapsible sections. By default, fields are auto-grouped by naming heuristics (Identity, Contact Info, Financial, etc.). With **record layouts**, you control the exact grouping.\n\nThere are two layers:\n\n1. **Code-defined layouts** — developers configure named layouts in `defineTable()`\n2. **User-created views** — end-users create and save custom views via the CMS UI\n\n## Code-Defined Layouts\n\nAdd a `layouts` property to your `defineTable()` config:\n\n```typescript\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n
|
|
394
|
+
"content": "# Record Layouts\n\nThe CMS record detail page groups fields into collapsible sections. By default, fields are auto-grouped by naming heuristics (Identity, Contact Info, Financial, etc.). With **record layouts**, you control the exact grouping.\n\nThere are two layers:\n\n1. **Code-defined layouts** — developers configure named layouts in `defineTable()`\n2. **User-created views** — end-users create and save custom views via the CMS UI\n\n## Code-Defined Layouts\n\nAdd a `layouts` property to your `defineTable()` config:\n\n```typescript\nexport default defineTable(contacts, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n create: { /* ... */ },\n update: { /* ... */ },\n delete: { /* ... */ },\n layouts: {\n default: {\n sections: [\n { label: \"Contact Info\", columns: 2, fields: [\"name\", \"email\", \"phone\", \"mobile\"] },\n { label: \"Address\", columns: 2, fields: [\"address1\", \"address2\", \"city\", \"state\", \"zip\"] },\n { label: \"Internal Notes\", collapsed: true, fields: [\"notes\", \"internalNotes\"] }\n ]\n },\n compact: {\n sections: [\n { label: \"Summary\", fields: [\"name\", \"status\", \"email\"] }\n ]\n }\n }\n});\n```\n\nEach layout has an ordered list of sections. Each section specifies:\n\n| Property | Type | Default | Description |\n|----------|------|---------|-------------|\n| `label` | string | required | Section header text |\n| `fields` | string[] | required | Column names to display |\n| `columns` | `1 \\| 2` | `1` | Number of columns for field layout |\n| `collapsed` | boolean | `false` | Whether the section starts collapsed |\n\nFields not assigned to any section are collected into an \"Other Fields\" section at the bottom.\n\n### Layout Switcher\n\nWhen a table has multiple named layouts, a dropdown appears in the record detail header. Selections persist per table using `localStorage`.\n\nIf only one layout is defined, it's used automatically without showing a dropdown.\n\n## User-Created Custom Views\n\nEnd-users can create their own record layouts via the CMS UI. These are stored in the database and can be shared with other organization members.\n\n### Creating a View\n\n1. Open any record detail page\n2. Click the **+ View** button in the header\n3. In the view builder dialog:\n - Name your view\n - Add sections and assign fields from a dropdown\n - Set columns (1 or 2) and collapsed state per section\n - Optionally share with your organization\n4. Click **Create View**\n\nThe new view appears in the layout dropdown alongside code-defined layouts.\n\n### Editing and Deleting Views\n\n- Click the **gear icon** next to the dropdown to edit the current custom view\n- Click the **trash icon** to delete it (with confirmation)\n- Code-defined layouts cannot be edited or deleted from the CMS\n\n### Access Control\n\n| Operation | Who Can Do It |\n|-----------|---------------|\n| Create a view | Any member, admin, or owner |\n| Edit/delete own views | The creator |\n| Edit/delete any view | Admins and owners |\n| View shared views | All organization members |\n\n### Setting Up the Custom View Feature\n\nTo enable user-created views, add a `customView` table to your Quickback project:\n\n```typescript\n// quickback/features/cms/custom-view.ts\n\nexport const customView = sqliteTable(\"custom_view\", {\n id: text(\"id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n tableName: text(\"table_name\").notNull(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n layoutConfig: text(\"layout_config\").notNull(),\n isShared: integer(\"is_shared\", { mode: \"boolean\" }).default(false),\n});\n\nexport default defineTable(customView, {\n displayColumn: \"name\",\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {\n access: { roles: [\"owner\", \"admin\", \"member\"] },\n },\n create: { access: { roles: [\"owner\", \"admin\", \"member\"] } },\n update: {\n access: {\n or: [\n { roles: [\"owner\", \"admin\"] },\n { roles: [\"member\"], record: { createdBy: { equals: \"$userId\" } } }\n ]\n }\n },\n delete: {\n access: {\n or: [\n { roles: [\"owner\", \"admin\"] },\n { roles: [\"member\"], record: { createdBy: { equals: \"$userId\" } } }\n ]\n },\n mode: \"hard\"\n },\n guards: {\n createable: [\"tableName\", \"name\", \"description\", \"layoutConfig\", \"isShared\"],\n updatable: [\"name\", \"description\", \"layoutConfig\", \"isShared\"]\n }\n});\n```\n\nCompile your project to generate the API endpoints. The CMS will automatically detect the `customView` table and enable the view builder UI.\n\n## Fallback Behavior\n\n| Scenario | Result |\n|----------|--------|\n| No `layouts` config, no custom views | Auto-grouping by naming heuristics |\n| `layouts` config defined | Uses \"default\" layout or first available |\n| Multiple layouts | Dropdown for switching, persisted per table |\n| Custom views created | Appear in dropdown below code-defined layouts |\n\n## Next Steps\n\n- **[Table Views](/stack/cms/table-views)** — Column projections for list views\n- **[Schema Format](/stack/cms/schema-format)** — Full TypeScript type reference\n- **[Database Schema](/compiler/definitions/schema)** — defineTable() configuration reference"
|
|
395
395
|
},
|
|
396
396
|
"stack/cms/schema-format": {
|
|
397
397
|
"title": "Schema Format Reference",
|
|
398
|
-
"content": "# Schema Format Reference\n\nThe schema registry is a JSON file with a well-defined structure. Below are the complete TypeScript type definitions used by both the compiler (to generate) and the CMS (to consume).\n\n## SchemaRegistry\n\nThe top-level type:\n\n```typescript\ninterface SchemaRegistry {\n generatedAt: string;\n generatedBy: string;\n version: string;\n singleTenant?: boolean;\n features: Record<string, string[]>;\n tables: Record<string, TableMeta>;\n tablesByFeature: Record<string, string[]>;\n pages: Record<string, PageMeta>;\n pagesByFeature: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `generatedAt` | ISO 8601 timestamp of when the registry was generated |\n| `generatedBy` | Always `\"quickback-compiler\"` |\n| `version` | Compiler version string |\n| `singleTenant` | When `true`, project has no organization layer (single-tenant mode) |\n| `features` | Map of feature name to array of source file names |\n| `tables` | Map of camelCase table name to full table metadata |\n| `tablesByFeature` | Map of feature name to array of table names in that feature |\n| `pages` | Map of page slug to full page metadata |\n| `pagesByFeature` | Map of feature name to array of page slugs in that feature |\n\n## TableMeta\n\nFull metadata for a single table:\n\n```typescript\ninterface TableMeta {\n name: string;\n dbName: string;\n feature: string;\n columns: ColumnMeta[];\n firewall: Record<string, unknown>;\n crud: Record<string, CrudConfig>;\n guards: GuardsConfig;\n masking: Record<string, MaskingRule>;\n views: Record<string, ViewConfig>;\n validation: Record<string, ValidationRule>;\n actions: ActionMeta[];\n displayColumn?: string;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n inputHints?: Record<string, string>;\n layouts?: Record<string, CmsLayout>;\n internal?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase table name (e.g., `\"accountCode\"`) |\n| `dbName` | Snake_case SQL table name (e.g., `\"account_code\"`) |\n| `feature` | Parent feature name (e.g., `\"accounting\"`) |\n| `columns` | Ordered array of column metadata |\n| `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |\n| `crud` | Per-operation (create, read, update, delete) access config |\n| `guards` | Field-level create/update/immutable/protected rules |\n| `masking` | Per-field masking rules keyed by column name |\n| `views` | Named column projections keyed by view name |\n| `validation` | Per-field validation rules keyed by column name |\n| `actions` | Array of action definitions for this table |\n| `displayColumn` | Column used as human-readable label (auto-detected or explicit) |\n| `defaultSort` | Default sort for CMS table list view (e.g., `{ field: \"createdAt\", order: \"desc\" }`) |\n| `inputHints` | Map of column name to preferred CMS input type (e.g., `\"richtext\"`, `\"select\"`, `\"textarea\"`, `\"checkbox\"`) |\n| `layouts` | Named record page layouts keyed by layout name (see CmsLayout below) |\n| `internal` | When `true`, table is hidden from CMS sidebar |\n\n## ColumnMeta\n\nMetadata for a single column:\n\n```typescript\ninterface ColumnMeta {\n name: string;\n dbName: string;\n type: \"text\" | \"integer\" | \"real\" | \"blob\";\n mode?: \"boolean\";\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase property name |\n| `dbName` | Snake_case SQL column name |\n| `type` | SQLite storage type |\n| `mode` | When `\"boolean\"`, an integer column represents true/false |\n| `primaryKey` | Whether this column is the primary key |\n| `notNull` | Whether the column has a NOT NULL constraint |\n| `defaultValue` | Static default value (strings, numbers, or booleans) |\n| `fkTarget` | Target table name for FK columns (e.g., `\"contact\"` for a `vendorId` column) |\n\n## CRUDConfig\n\nPer-operation access control:\n\n```typescript\ninterface CrudConfig {\n access?: AccessRule;\n mode?: string;\n}\n\ninterface AccessRule {\n roles?: string[];\n or?: Array<{\n roles?: string[];\n record?: Record<string, unknown>;\n }>;\n record?: Record<string, unknown>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `access.roles` | Array of roles allowed for this operation |\n| `access.or` | Alternative access conditions (any must match) |\n| `access.record` | Record-level conditions for access |\n| `mode` | Operation mode (e.g., `\"batch\"` for bulk create) |\n\n## GuardsConfig\n\nField-level control for create and update operations:\n\n```typescript\ninterface GuardsConfig {\n createable: string[];\n updatable: string[];\n immutable: string[];\n protected: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `createable` | Fields that can be set during record creation |\n| `updatable` | Fields that can be modified on existing records |\n| `immutable` | Fields that can be set on create but never changed |\n| `protected` | Fields only modifiable via named actions (field name to action names) |\n\n## ActionMeta\n\nMetadata for a custom action:\n\n```typescript\ninterface ActionMeta {\n name: string;\n description: string;\n inputFields: ActionInputField[];\n access?: {\n roles: string[];\n record?: Record<string, unknown>;\n };\n standalone?: boolean;\n path?: string;\n method?: string;\n responseType?: string;\n sideEffects?: string;\n cms?: CmsConfig;\n}\n\ninterface CmsConfig {\n label?: string;\n icon?: string;\n confirm?: string | boolean;\n destructive?: boolean;\n category?: string;\n hidden?: boolean;\n successMessage?: string;\n onSuccess?: 'refresh' | 'redirect:list' | 'close';\n order?: number;\n}\n\ninterface ActionInputField {\n name: string;\n type: string;\n required: boolean;\n default?: unknown;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Action identifier (e.g., `\"approve\"`, `\"applyPayment\"`) |\n| `description` | Human-readable description shown in dialog |\n| `inputFields` | Array of input field definitions |\n| `access.roles` | Roles allowed to execute this action |\n| `access.record` | Record conditions (e.g., `{ status: { equals: \"pending\" } }`) |\n| `standalone` | When `true`, action is not tied to a specific record |\n| `path` | Custom API path (overrides default) |\n| `method` | HTTP method (defaults to POST) |\n| `responseType` | `\"file\"` for download responses |\n| `sideEffects` | `\"sync\"` for actions with synchronous side effects |\n| `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, successMessage, onSuccess, order) |\n\n### ActionInputField\n\n| Field | Description |\n|-------|-------------|\n| `name` | Field identifier |\n| `type` | Zod type string: `\"string\"`, `\"number\"`, `\"boolean\"`, `\"array<string>\"` |\n| `required` | Whether the field must be provided |\n| `default` | Default value pre-filled in the form |\n\n## ViewConfig\n\nNamed column projection with access control:\n\n```typescript\ninterface ViewConfig {\n fields: string[];\n access: AccessRule;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `fields` | Array of column names to include in this view |\n| `access` | Role-based access rules (same shape as CrudConfig access) |\n\n## CmsLayout\n\nNamed record page layout with ordered sections:\n\n```typescript\ninterface CmsLayout {\n sections: CmsLayoutSection[];\n}\n\ninterface CmsLayoutSection {\n label: string;\n fields: string[];\n columns?: 1 | 2;\n collapsed?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `sections` | Ordered array of field sections |\n\n### CmsLayoutSection\n\n| Field | Description |\n|-------|-------------|\n| `label` | Section header text |\n| `fields` | Array of column names to display in this section |\n| `columns` | `1` (default) or `2` for two-column field layout |\n| `collapsed` | When `true`, section starts collapsed with a toggle to expand |\n\nFields not assigned to any section in the active layout are collected into an \"Other Fields\" section.\n\n## MaskingRule\n\nPer-field data masking:\n\n```typescript\ninterface MaskingRule {\n type: \"email\" | \"phone\" | \"ssn\" | \"redact\";\n show: {\n roles: string[];\n or?: string;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `type` | Masking pattern to apply |\n| `show.roles` | Roles that see the unmasked value |\n| `show.or` | Alternative condition for showing unmasked value |\n\n### Masking Patterns\n\n| Type | Input | Output |\n|------|-------|--------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | Any string | `------` |\n\n## ValidationRule\n\nPer-field validation constraints:\n\n```typescript\ninterface ValidationRule {\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n enum?: string[];\n email?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `minLength` | Minimum string length |\n| `maxLength` | Maximum string length |\n| `min` | Minimum numeric value |\n| `max` | Maximum numeric value |\n| `enum` | Array of allowed string values |\n| `email` | When `true`, validates email format |\n\n## PageMeta\n\nFull metadata for a custom page:\n\n```typescript\ninterface PageMeta {\n slug: string;\n title: string;\n description?: string;\n icon?: string;\n feature: string;\n access?: { roles: string[] };\n dataSources: Record<string, PageDataSource>;\n layout: PageLayout;\n matching?: PageMatching;\n pageActions?: Record<string, PageAction>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `slug` | URL-safe page identifier |\n| `title` | Display title |\n| `description` | Human-readable description |\n| `icon` | Icon name for sidebar |\n| `feature` | Parent feature name |\n| `access` | Role-based access control |\n| `dataSources` | Named data source bindings |\n| `layout` | Layout configuration |\n| `matching` | Matching/reconciliation rules |\n| `pageActions` | Actions triggered from the page |\n\n### PageDataSource\n\n```typescript\ninterface PageDataSource {\n table: string;\n defaultFilters?: Record<string, unknown>;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n displayColumns?: string[];\n}\n```\n\n### PageLayout\n\n```typescript\ninterface PageLayout {\n type: 'split-panel';\n panels: PagePanel[];\n}\n\ninterface PagePanel {\n id: string;\n title: string;\n dataSource: string;\n position: 'left' | 'right';\n features?: string[];\n}\n```\n\nPanel `features` can include `\"drag-source\"` and `\"drop-target\"` for drag-and-drop interactions.\n\n### PageMatching\n\n```typescript\ninterface PageMatching {\n enabled: boolean;\n rules: MatchingRule[];\n confidenceThreshold?: number;\n}\n\ninterface MatchingRule {\n name: string;\n weight: number;\n condition: {\n left: string;\n right: string;\n operator: 'abs-equals' | 'within-days' | 'fuzzy-match';\n value?: number;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `enabled` | Whether matching is active |\n| `rules` | Array of matching rules with weights (0-1) |\n| `confidenceThreshold` | Minimum score to display a match suggestion (0-1, default 0.5) |\n| `condition.left` | Left field reference (`dataSourceName.fieldName`) |\n| `condition.right` | Right field reference |\n| `condition.operator` | Comparison operator |\n| `condition.value` | Operator parameter (e.g., max days for `within-days`) |\n\n### PageAction\n\n```typescript\ninterface PageAction {\n table: string;\n action: string;\n inputMapping: Record<string, string>;\n label?: string;\n icon?: string;\n confirm?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `table` | Target table for the action |\n| `action` | Action name on that table |\n| `inputMapping` | Maps action input fields to data source field references (`\"dataSourceName.$fieldName\"`) |\n| `label` | Button label (defaults to action name) |\n| `icon` | Button icon name |\n| `confirm` | Confirmation prompt shown before execution |\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — How the registry is generated and used\n- **[Components Reference](/stack/cms/components)** — All CMS React components"
|
|
398
|
+
"content": "# Schema Format Reference\n\nThe schema registry is a JSON file with a well-defined structure. Below are the complete TypeScript type definitions used by both the compiler (to generate) and the CMS (to consume).\n\n## SchemaRegistry\n\nThe top-level type:\n\n```typescript\ninterface SchemaRegistry {\n generatedAt: string;\n generatedBy: string;\n version: string;\n singleTenant?: boolean;\n features: Record<string, string[]>;\n tables: Record<string, TableMeta>;\n tablesByFeature: Record<string, string[]>;\n featureActions: Record<string, ActionMeta[]>;\n pages: Record<string, PageMeta>;\n pagesByFeature: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `generatedAt` | ISO 8601 timestamp of when the registry was generated |\n| `generatedBy` | Always `\"quickback-compiler\"` |\n| `version` | Compiler version string |\n| `singleTenant` | When `true`, project has no organization layer (single-tenant mode) |\n| `features` | Map of feature name to array of source file names |\n| `tables` | Map of camelCase table name to full table metadata |\n| `tablesByFeature` | Map of feature name to array of table names in that feature |\n| `featureActions` | Map of feature name to standalone actions not attached to one table |\n| `pages` | Map of page slug to full page metadata |\n| `pagesByFeature` | Map of feature name to array of page slugs in that feature |\n\n## TableMeta\n\nFull metadata for a single table:\n\n```typescript\ninterface TableMeta {\n name: string;\n dbName: string;\n feature: string;\n columns: ColumnMeta[];\n firewall: Record<string, unknown>;\n crud: Record<string, CrudConfig>;\n create?: WriteOperationConfig | false;\n update?: WriteOperationConfig | false;\n delete?: WriteOperationConfig | false;\n upsert?: WriteOperationConfig | false;\n guards: GuardsConfig;\n masking: Record<string, MaskingRule>;\n views: Record<string, ViewConfig>;\n validation: Record<string, ValidationRule>;\n actions: ActionMeta[];\n displayColumn?: string;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n inputHints?: Record<string, string>;\n layouts?: Record<string, CmsLayout>;\n internal?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase table name (e.g., `\"accountCode\"`) |\n| `dbName` | Snake_case SQL table name (e.g., `\"account_code\"`) |\n| `feature` | Parent feature name (e.g., `\"accounting\"`) |\n| `columns` | Ordered array of column metadata |\n| `firewall` | Tenant isolation config (organization, owner, softDelete, exception) |\n| `crud` | Legacy normalized write config kept for backwards compatibility |\n| `create` / `update` / `delete` / `upsert` | Flat write-operation aliases mirroring the authored `defineTable(...)` DSL |\n| `guards` | Field-level create/update/immutable/protected rules |\n| `masking` | Per-field masking rules keyed by column name |\n| `views` | Named column projections keyed by view name |\n| `validation` | Per-field validation rules keyed by column name |\n| `actions` | Array of action definitions scoped to this table |\n| `displayColumn` | Column used as human-readable label (auto-detected or explicit) |\n| `defaultSort` | Default sort for CMS table list view (e.g., `{ field: \"createdAt\", order: \"desc\" }`) |\n| `inputHints` | Map of column name to preferred CMS input type (e.g., `\"richtext\"`, `\"select\"`, `\"textarea\"`, `\"checkbox\"`) |\n| `layouts` | Named record page layouts keyed by layout name (see CmsLayout below) |\n| `internal` | When `true`, table is hidden from CMS sidebar |\n\n## ColumnMeta\n\nMetadata for a single column:\n\n```typescript\ninterface ColumnMeta {\n name: string;\n dbName: string;\n type: \"text\" | \"integer\" | \"real\" | \"blob\";\n mode?: \"boolean\";\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | camelCase property name |\n| `dbName` | Snake_case SQL column name |\n| `type` | SQLite storage type |\n| `mode` | When `\"boolean\"`, an integer column represents true/false |\n| `primaryKey` | Whether this column is the primary key |\n| `notNull` | Whether the column has a NOT NULL constraint |\n| `defaultValue` | Static default value (strings, numbers, or booleans) |\n| `fkTarget` | Target table name for FK columns (e.g., `\"contact\"` for a `vendorId` column) |\n\n## CRUDConfig\n\nPer-operation access control:\n\n```typescript\ninterface CrudConfig {\n access?: AccessRule;\n mode?: string;\n}\n\ninterface WriteOperationConfig extends CrudConfig {\n defaults?: Record<string, unknown>;\n computed?: Record<string, unknown>;\n fields?: string[];\n maxBatchSize?: number;\n allowFailFast?: boolean;\n batch?: false | Record<string, unknown>;\n}\n\ninterface AccessRule {\n roles?: string[];\n or?: Array<{\n roles?: string[];\n record?: Record<string, unknown>;\n }>;\n record?: Record<string, unknown>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `access.roles` | Array of roles allowed for this operation |\n| `access.or` | Alternative access conditions (any must match) |\n| `access.record` | Record-level conditions for access |\n| `mode` | Operation mode (e.g., `\"batch\"` for bulk create) |\n| `defaults` / `computed` | Create-time defaults and computed field metadata |\n| `maxBatchSize` / `allowFailFast` | Batch-write controls when the config describes a batch operation |\n| `batch` | Nested batch config for the flat `create` / `update` / `delete` / `upsert` aliases |\n\n## GuardsConfig\n\nField-level control for create and update operations:\n\n```typescript\ninterface GuardsConfig {\n createable: string[];\n updatable: string[];\n immutable: string[];\n protected: Record<string, string[]>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `createable` | Fields that can be set during record creation |\n| `updatable` | Fields that can be modified on existing records |\n| `immutable` | Fields that can be set on create but never changed |\n| `protected` | Fields only modifiable via named actions (field name to action names) |\n\n## ActionMeta\n\nMetadata for a custom action:\n\n```typescript\ninterface ActionMeta {\n name: string;\n description: string;\n inputFields: ActionInputField[];\n access?: {\n roles: string[];\n record?: Record<string, unknown>;\n };\n standalone?: boolean;\n path?: string;\n method?: string;\n responseType?: string;\n sideEffects?: string;\n cms?: CmsConfig;\n}\n\ninterface CmsConfig {\n label?: string;\n icon?: string;\n confirm?: string | boolean;\n destructive?: boolean;\n category?: string;\n hidden?: boolean;\n placement?: 'feature' | 'tables';\n tables?: string[];\n successMessage?: string;\n onSuccess?: 'refresh' | 'redirect:list' | 'close';\n order?: number;\n}\n\ninterface ActionInputField {\n name: string;\n type: string;\n required: boolean;\n default?: unknown;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `name` | Action identifier (e.g., `\"approve\"`, `\"applyPayment\"`) |\n| `description` | Human-readable description shown in dialog |\n| `inputFields` | Array of input field definitions |\n| `access.roles` | Roles allowed to execute this action |\n| `access.record` | Record conditions (e.g., `{ status: { equals: \"pending\" } }`) |\n| `standalone` | When `true`, action is not tied to a specific record |\n| `path` | Custom API path (overrides default) |\n| `method` | HTTP method (defaults to POST) |\n| `responseType` | `\"file\"` for download responses |\n| `sideEffects` | `\"sync\"` for actions with synchronous side effects |\n| `cms` | Optional CMS rendering metadata (label, icon, confirm, destructive, category, hidden, placement, tables, successMessage, onSuccess, order) |\n\n### CmsConfig placement rules\n\n`placement` is only relevant for standalone actions in multi-table features:\n\n- `\"feature\"` shows the action in the toolbar for every table in the feature.\n- `\"tables\"` shows the action only for the tables listed in `tables`.\n\nIf the action is already unambiguously table-scoped, the compiler can infer placement and `placement` is optional.\n\n### ActionInputField\n\n| Field | Description |\n|-------|-------------|\n| `name` | Field identifier |\n| `type` | Zod type string: `\"string\"`, `\"number\"`, `\"boolean\"`, `\"array<string>\"` |\n| `required` | Whether the field must be provided |\n| `default` | Default value pre-filled in the form |\n\n## ViewConfig\n\nNamed column projection with access control:\n\n```typescript\ninterface ViewConfig {\n fields: string[];\n access: AccessRule;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `fields` | Array of column names to include in this view |\n| `access` | Role-based access rules (same shape as CrudConfig access) |\n\n## CmsLayout\n\nNamed record page layout with ordered sections:\n\n```typescript\ninterface CmsLayout {\n sections: CmsLayoutSection[];\n}\n\ninterface CmsLayoutSection {\n label: string;\n fields: string[];\n columns?: 1 | 2;\n collapsed?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `sections` | Ordered array of field sections |\n\n### CmsLayoutSection\n\n| Field | Description |\n|-------|-------------|\n| `label` | Section header text |\n| `fields` | Array of column names to display in this section |\n| `columns` | `1` (default) or `2` for two-column field layout |\n| `collapsed` | When `true`, section starts collapsed with a toggle to expand |\n\nFields not assigned to any section in the active layout are collected into an \"Other Fields\" section.\n\n## MaskingRule\n\nPer-field data masking:\n\n```typescript\ninterface MaskingRule {\n type: \"email\" | \"phone\" | \"ssn\" | \"redact\";\n show: {\n roles: string[];\n or?: string;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `type` | Masking pattern to apply |\n| `show.roles` | Roles that see the unmasked value |\n| `show.or` | Alternative condition for showing unmasked value |\n\n### Masking Patterns\n\n| Type | Input | Output |\n|------|-------|--------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | Any string | `------` |\n\n## ValidationRule\n\nPer-field validation constraints:\n\n```typescript\ninterface ValidationRule {\n minLength?: number;\n maxLength?: number;\n min?: number;\n max?: number;\n enum?: string[];\n email?: boolean;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `minLength` | Minimum string length |\n| `maxLength` | Maximum string length |\n| `min` | Minimum numeric value |\n| `max` | Maximum numeric value |\n| `enum` | Array of allowed string values |\n| `email` | When `true`, validates email format |\n\n## PageMeta\n\nFull metadata for a custom page:\n\n```typescript\ninterface PageMeta {\n slug: string;\n title: string;\n description?: string;\n icon?: string;\n feature: string;\n access?: { roles: string[] };\n dataSources: Record<string, PageDataSource>;\n layout: PageLayout;\n matching?: PageMatching;\n pageActions?: Record<string, PageAction>;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `slug` | URL-safe page identifier |\n| `title` | Display title |\n| `description` | Human-readable description |\n| `icon` | Icon name for sidebar |\n| `feature` | Parent feature name |\n| `access` | Role-based access control |\n| `dataSources` | Named data source bindings |\n| `layout` | Layout configuration |\n| `matching` | Matching/reconciliation rules |\n| `pageActions` | Actions triggered from the page |\n\n### PageDataSource\n\n```typescript\ninterface PageDataSource {\n table: string;\n defaultFilters?: Record<string, unknown>;\n defaultSort?: { field: string; order: 'asc' | 'desc' };\n displayColumns?: string[];\n}\n```\n\n### PageLayout\n\n```typescript\ninterface PageLayout {\n type: 'split-panel';\n panels: PagePanel[];\n}\n\ninterface PagePanel {\n id: string;\n title: string;\n dataSource: string;\n position: 'left' | 'right';\n features?: string[];\n}\n```\n\nPanel `features` can include `\"drag-source\"` and `\"drop-target\"` for drag-and-drop interactions.\n\n### PageMatching\n\n```typescript\ninterface PageMatching {\n enabled: boolean;\n rules: MatchingRule[];\n confidenceThreshold?: number;\n}\n\ninterface MatchingRule {\n name: string;\n weight: number;\n condition: {\n left: string;\n right: string;\n operator: 'abs-equals' | 'within-days' | 'fuzzy-match';\n value?: number;\n };\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `enabled` | Whether matching is active |\n| `rules` | Array of matching rules with weights (0-1) |\n| `confidenceThreshold` | Minimum score to display a match suggestion (0-1, default 0.5) |\n| `condition.left` | Left field reference (`dataSourceName.fieldName`) |\n| `condition.right` | Right field reference |\n| `condition.operator` | Comparison operator |\n| `condition.value` | Operator parameter (e.g., max days for `within-days`) |\n\n### PageAction\n\n```typescript\ninterface PageAction {\n table: string;\n action: string;\n inputMapping: Record<string, string>;\n label?: string;\n icon?: string;\n confirm?: string;\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `table` | Target table for the action |\n| `action` | Action name on that table |\n| `inputMapping` | Maps action input fields to data source field references (`\"dataSourceName.$fieldName\"`) |\n| `label` | Button label (defaults to action name) |\n| `icon` | Button icon name |\n| `confirm` | Confirmation prompt shown before execution |\n\n## Next Steps\n\n- **[Schema Registry](/stack/cms/schema-registry)** — How the registry is generated and used\n- **[Components Reference](/stack/cms/components)** — All CMS React components"
|
|
399
399
|
},
|
|
400
400
|
"stack/cms/schema-registry": {
|
|
401
401
|
"title": "Schema Registry",
|
|
402
|
-
"content": "# Schema Registry\n\nThe schema registry is a static JSON file generated by the Quickback compiler. It contains full metadata about every table in your project — columns, types, guards, masking rules, views, actions, validation, and firewall config. The CMS reads this file to render its entire UI.\n\n## Generation\n\nSchema registry generation is **enabled by default**. Run `quickback compile` and the compiler outputs `schema-registry.json` alongside your compiled API files.\n\nTo disable generation:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n schemaRegistry: { generate: false },\n // ... rest of your config\n});\n```\n\n## Output Shape\n\nThe top-level structure of `schema-registry.json`:\n\n```json\n{\n \"generatedAt\": \"2026-02-14T06:26:53.554Z\",\n \"generatedBy\": \"quickback-compiler\",\n \"version\": \"1.0.0\",\n \"singleTenant\": false,\n \"features\": { ... },\n \"tables\": { ... },\n \"tablesByFeature\": { ... },\n \"pages\": { ... },\n \"pagesByFeature\": { ... }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `generatedAt` | `string` | ISO timestamp of generation |\n| `generatedBy` | `string` | Always `\"quickback-compiler\"` |\n| `version` | `string` | Compiler version used |\n| `singleTenant` | `boolean?` | When `true`, no organization layer |\n| `features` | `Record<string, string[]>` | Feature name to file list mapping |\n| `tables` | `Record<string, TableMeta>` | Table name to full metadata |\n| `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |\n| `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |\n| `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |\n\n## TableMeta\n\nEach table entry contains everything the CMS needs to render its UI:\n\n```typescript\ninterface TableMeta {\n name: string; // camelCase table name (e.g., \"accountCode\")\n dbName: string; // SQL table name (e.g., \"account_code\")\n feature: string; // Parent feature name\n columns: ColumnMeta[]; // All columns including audit fields\n firewall: Record<string, unknown>; // Tenant isolation config\n crud: Record<string, CrudConfig>; //
|
|
402
|
+
"content": "# Schema Registry\n\nThe schema registry is a static JSON file generated by the Quickback compiler. It contains full metadata about every table in your project — columns, types, guards, masking rules, views, actions, validation, and firewall config. The CMS reads this file to render its entire UI.\n\n## Generation\n\nSchema registry generation is **enabled by default**. Run `quickback compile` and the compiler outputs `schema-registry.json` alongside your compiled API files.\n\nTo disable generation:\n\n```typescript title=\"quickback/quickback.config.ts\"\nexport default defineConfig({\n schemaRegistry: { generate: false },\n // ... rest of your config\n});\n```\n\n## Output Shape\n\nThe top-level structure of `schema-registry.json`:\n\n```json\n{\n \"generatedAt\": \"2026-02-14T06:26:53.554Z\",\n \"generatedBy\": \"quickback-compiler\",\n \"version\": \"1.0.0\",\n \"singleTenant\": false,\n \"features\": { ... },\n \"tables\": { ... },\n \"tablesByFeature\": { ... },\n \"featureActions\": { ... },\n \"pages\": { ... },\n \"pagesByFeature\": { ... }\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `generatedAt` | `string` | ISO timestamp of generation |\n| `generatedBy` | `string` | Always `\"quickback-compiler\"` |\n| `version` | `string` | Compiler version used |\n| `singleTenant` | `boolean?` | When `true`, no organization layer |\n| `features` | `Record<string, string[]>` | Feature name to file list mapping |\n| `tables` | `Record<string, TableMeta>` | Table name to full metadata |\n| `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |\n| `featureActions` | `Record<string, ActionMeta[]>` | Feature name to standalone actions not owned by one table |\n| `pages` | `Record<string, PageMeta>` | Page slug to full page metadata |\n| `pagesByFeature` | `Record<string, string[]>` | Feature name to page slug list |\n\n## TableMeta\n\nEach table entry contains everything the CMS needs to render its UI:\n\n```typescript\ninterface TableMeta {\n name: string; // camelCase table name (e.g., \"accountCode\")\n dbName: string; // SQL table name (e.g., \"account_code\")\n feature: string; // Parent feature name\n columns: ColumnMeta[]; // All columns including audit fields\n firewall: Record<string, unknown>; // Tenant isolation config\n crud: Record<string, CrudConfig>; // Legacy normalized write surface\n create?: WriteOperationConfig | false; // Flat create config\n update?: WriteOperationConfig | false; // Flat update config\n delete?: WriteOperationConfig | false; // Flat delete config\n upsert?: WriteOperationConfig | false; // Flat upsert config\n guards: {\n createable: string[]; // Fields allowed on create\n updatable: string[]; // Fields allowed on update\n immutable: string[]; // Fields locked after creation\n protected: Record<string, string[]>; // Fields only updatable via actions\n };\n masking: Record<string, MaskingRule>; // Per-field masking rules\n views: Record<string, ViewConfig>; // Named column projections\n validation: Record<string, ValidationRule>; // Per-field validation\n actions: ActionMeta[]; // Table-scoped actions for this table\n displayColumn?: string; // Human-readable label column\n internal?: boolean; // Hidden from CMS sidebar when true\n}\n```\n\n`create`, `update`, `delete`, and `upsert` mirror the preferred flat DSL from `defineTable(...)`. The legacy `crud` block is still emitted for backwards compatibility with older consumers.\n\n## Feature Actions\n\nStandalone actions do not always belong to a single table. When an action is attached to a multi-table feature root, the compiler emits it under `featureActions[featureName]` instead of duplicating it across every table.\n\n```typescript\ninterface SchemaRegistry {\n featureActions: Record<string, ActionMeta[]>;\n}\n```\n\nThe CMS uses `featureActions` for toolbar-style actions that apply to the feature as a whole. Use `cms.placement` on standalone actions to control whether they show for the whole feature or only selected tables.\n\n## ColumnMeta\n\nEach column in the `columns` array:\n\n```typescript\ninterface ColumnMeta {\n name: string; // Property name (camelCase)\n dbName: string; // SQL column name (snake_case)\n type: \"text\" | \"integer\" | \"real\" | \"blob\"; // SQLite type\n mode?: \"boolean\"; // When an integer represents a boolean\n primaryKey: boolean;\n notNull: boolean;\n defaultValue?: string | number | boolean;\n fkTarget?: string; // Target table name for FK columns\n}\n```\n\nThe compiler automatically includes the system columns (`id`, `organizationId`), the audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`), and the soft-delete pair (`deletedAt`, `deletedBy` — when soft delete is enabled) at the beginning of every table's column list.\n\n### fkTarget — FK Resolution\n\nColumns ending in `Id` may have a `fkTarget` property indicating which table they reference. This is resolved in priority order:\n\n1. **Explicit `references`** — from your `defineTable()` config (highest priority)\n2. **Drizzle `.references()`** — parsed from schema source code\n3. **Convention** — strip `Id` suffix, match table name directly\n\n```json\n{\n \"name\": \"vendorId\",\n \"type\": \"text\",\n \"fkTarget\": \"contact\"\n}\n```\n\nThe CMS uses `fkTarget` to render typeahead/lookup inputs that search the correct table instead of showing raw IDs.\n\n## Input Hints\n\nTables with `inputHints` configured in `defineTable()` include an `inputHints` map in their metadata:\n\n```json\n{\n \"name\": \"invoice\",\n \"inputHints\": {\n \"status\": \"select\",\n \"sortOrder\": \"radio\",\n \"isPartialPaymentDisabled\": \"checkbox\",\n \"headerMessage\": \"textarea\",\n \"description\": \"richtext\"\n }\n}\n```\n\nThe CMS reads these hints to render the appropriate form control for each field. The `\"richtext\"` hint renders a tiptap editor in edit mode and formatted HTML in view mode. See [Input Hints](/compiler/definitions/schema#input-hints) for the full list of supported values.\n\n## Display Column\n\nThe `displayColumn` field tells the CMS which column to use as a human-readable label for a record. This is used in:\n\n- FK typeahead dropdowns (showing names instead of IDs)\n- Record titles in detail views\n- Breadcrumb labels\n\n### Auto-Detection\n\nIf you don't explicitly set `displayColumn` in your resource config, the compiler auto-detects it by scanning column names in priority order:\n\n1. `name`\n2. `title`\n3. `label`\n4. `headline`\n5. `subject`\n6. `code`\n7. `displayName`\n8. `fullName`\n9. `description`\n\nThe first match wins. If no candidate matches, the table has no display column and the CMS falls back to showing IDs.\n\n### Explicit Config\n\nSet it explicitly in your table definition:\n\n```typescript\nexport default defineTable(contacts, {\n displayColumn: \"companyName\",\n // ...\n});\n```\n\n## FK Label Resolution\n\nWhen a table has foreign key columns (ending in `Id`), the API enriches list responses with `_label` fields. For example, a `roomTypeId` column gets a corresponding `roomType_label` field containing the display column value from the referenced table.\n\nThe CMS uses these `_label` fields to show human-readable names in table cells and FK typeahead dropdowns instead of raw UUIDs.\n\n```\nroomTypeId: \"rt_abc123\" → displayed as \"Master Bedroom\"\naccountCodeId: \"ac_xyz789\" → displayed as \"4100 - Revenue\"\n```\n\nThe FK target table is resolved from the `fkTarget` property on each column. For simple cases like `roomTypeId` → `roomType`, the compiler auto-detects it. For non-obvious mappings (e.g., `vendorId` → `contact`), use explicit [`references`](/compiler/definitions/schema#references) in your `defineTable()` config.\n\n## Pages\n\nWhen features include `definePage()` files (in `features/{name}/pages/`), the compiler includes them in the registry under two fields:\n\n- **`pages`** — Map of page slug to full `PageMeta` object (data sources, layout, matching rules, page actions)\n- **`pagesByFeature`** — Map of feature name to array of page slugs belonging to that feature\n\nThe CMS reads these fields to render custom pages in the sidebar and route to the page renderer. See [Custom Pages](/stack/cms/pages) for the full `definePage()` API.\n\n## Single-Tenant Mode\n\nWhen `singleTenant` is `true` in the registry (set when the project config has `features.organizations: false`), the CMS skips the organization gate and reads the user's role directly from `user.role` on the session instead of from organization membership.\n\n## Next Steps\n\n- **[Connecting](/stack/cms/connecting)** — Demo mode vs. live mode setup\n- **[Schema Format Reference](/stack/cms/schema-format)** — Full TypeScript types"
|
|
403
403
|
},
|
|
404
404
|
"stack/cms/security": {
|
|
405
405
|
"title": "Security",
|
|
406
|
-
"content": "# Security\n\nThe CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.\n\n## CMS Access (admin-only by default)\n\nThe CMS is restricted to Better Auth platform admins (`user.role === \"admin\"`) by default — non-admin authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nUnder the default `access: \"admin\"`, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't reach the CMS even by bypassing the SPA:\n\n1. **Account UI** — the \"Go to CMS\" button is hidden.\n2. **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.\n3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.\n4. **`custom_view`
|
|
406
|
+
"content": "# Security\n\nThe CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.\n\n## CMS Access (admin-only by default)\n\nThe CMS is restricted to Better Auth platform admins (`user.role === \"admin\"`) by default — non-admin authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:\n\n```typescript\ncms: { access: \"user\" }\n```\n\nUnder the default `access: \"admin\"`, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't reach the CMS even by bypassing the SPA:\n\n1. **Account UI** — the \"Go to CMS\" button is hidden.\n2. **CMS SPA shell** — the Worker checks `ctx.userRole === \"admin\"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.\n3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.\n4. **`custom_view` routes** — the CMS-internal saved-views table uses `userRole: [\"admin\"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.\n5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.\n\nYour resource API endpoints keep whatever `read`, `create`, `update`, `delete`, or `upsert` access rules you defined — they're the app's data API and unaffected by the CMS gate.\n\n## The Four Layers\n\nQuickback enforces security through four complementary layers:\n\n| Layer | Purpose | CMS Behavior |\n|-------|---------|-------------|\n| **Firewall** | Tenant isolation (org-scoped data) | Handled server-side. CMS cannot bypass it. |\n| **Operation Access** | Per-operation role requirements | Buttons hidden when role lacks permission |\n| **Guards** | Field-level create/update control | Form fields enabled/disabled per guard rules |\n| **Masking** | Sensitive field redaction | Masked values with lock icons per role |\n\n## Role-Based Access\n\nThe CMS header includes a **role switcher** (in demo mode) or reads the user's actual role from their organization membership (in live mode). The three roles are:\n\n- **owner** — Full access to all operations and data\n- **admin** — Elevated access, typically all write operations and most actions\n- **member** — Standard access with restrictions on sensitive data and destructive actions\n\n### Operation Button Visibility\n\nCreate, edit, and delete buttons are shown or hidden based on the current role's access:\n\n```typescript\nread: { access: { roles: ['member', 'admin', 'owner'] } },\ncreate: { access: { roles: ['admin', 'owner'] } },\nupdate: { access: { roles: ['admin', 'owner'] } },\ndelete: { access: { roles: ['owner'] } },\n```\n\nWith the config above:\n\n- **Members** see the table (read) but no Create, Edit, or Delete buttons\n- **Admins** see Create and Edit buttons but no Delete\n- **Owners** see all buttons\n\nThe row action menu also adapts — Edit and Delete entries only appear when the role has the corresponding permission.\n\n## Guards\n\nGuards control which fields appear in create and edit forms, and which cells are editable in Data Table mode.\n\n### Createable Fields\n\nFields listed in `guards.createable` appear in the create form. Fields not in this list are hidden from the form entirely:\n\n```typescript\nguards: {\n createable: ['name', 'email', 'phone', 'status'],\n}\n```\n\n### Updatable Fields\n\nFields listed in `guards.updatable` are editable in the edit form and in Data Table inline editing:\n\n```typescript\nguards: {\n updatable: ['name', 'email', 'phone'],\n}\n```\n\n### Immutable Fields\n\nFields in `guards.immutable` can be set during creation but cannot be changed afterward. In edit mode, they appear as disabled inputs with a lock icon:\n\n```typescript\nguards: {\n immutable: ['accountCode', 'type'],\n}\n```\n\n### Protected Fields\n\nFields in `guards.protected` can only be updated via specific actions. They appear as disabled inputs with the message \"Updated via actions only\":\n\n```typescript\nguards: {\n protected: {\n status: ['approve', 'void'], // Updated by approve or void actions\n balance: ['applyPayment'], // Updated by applyPayment action\n },\n}\n```\n\n## Masking\n\nMasking rules redact sensitive data based on the user's role. The CMS applies masking client-side for display and the API enforces it server-side in responses.\n\n### Masking Types\n\n| Type | Example Input | Masked Output |\n|------|--------------|---------------|\n| `email` | `john@acme.com` | `j***@acme.com` |\n| `phone` | `(555) 123-4567` | `***-***-4567` |\n| `ssn` | `123-45-6789` | `***-**-6789` |\n| `redact` | `Confidential notes` | `------` |\n\n### Configuration\n\n```typescript\nmasking: {\n email: { type: 'email', show: { roles: ['admin', 'owner'] } },\n phone: { type: 'phone', show: { roles: ['admin', 'owner'] } },\n ssn: { type: 'ssn', show: { roles: ['owner'] } },\n}\n```\n\nWith the above config:\n\n- **Members** see masked values for email, phone, and SSN\n- **Admins** see unmasked email and phone, but masked SSN\n- **Owners** see all values unmasked\n\n### Visual Indicator\n\nMasked fields display a lock icon next to the redacted value, making it clear that the field contains hidden data:\n\n```\nEmail: [lock] j***@acme.com\nSSN: [lock] ***-**-6789\n```\n\n## Views\n\nViews provide column-level projections per role. Only authorized views appear in the toolbar dropdown.\n\n```typescript\nread: {\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin', 'owner'] },\n },\n financial: {\n fields: ['id', 'name', 'balance', 'creditLimit', 'paymentTerms'],\n access: { roles: ['admin', 'owner'] },\n },\n },\n}\n```\n\nMembers only see the \"summary\" view option. Admins and owners see both \"summary\" and \"financial\". The \"All Fields\" option is always available.\n\n## Firewall\n\nThe firewall layer handles tenant isolation — ensuring users can only access data within their organization. This is enforced entirely server-side:\n\n- `organization_id` columns are filtered automatically by the API\n- `owner` predicates restrict records to the creating user\n- The CMS never sees data outside the user's organization scope\n\nThe CMS does not display firewall config in its UI because there is nothing for the user to control. Tenant isolation is transparent and automatic.\n\n## Actions\n\nAction visibility is controlled by access conditions on each action:\n\n```typescript\nactions: {\n approve: {\n access: {\n roles: ['admin', 'owner'],\n record: { status: { equals: 'pending' } },\n },\n cms: { destructive: true, confirm: true },\n },\n}\n```\n\nThe CMS evaluates both the role requirement and the record condition. In this example, the \"Approve\" action only appears for admins and owners, and only on records where `status === \"pending\"`.\n\nDestructive actions (`cms.destructive: true`, or named `void`/`delete`) receive special warning styling with red text and an alert icon. Actions with `cms.hidden: true` are hidden from the CMS entirely (API-only).\n\n## Next Steps\n\n- **[Actions](/stack/cms/actions)** — Action dialogs and input forms\n- **[Table Views](/stack/cms/table-views)** — View projections and toolbar\n- **[Inline Editing](/stack/cms/inline-editing)** — How guards affect editability"
|
|
407
407
|
},
|
|
408
408
|
"stack/cms/table-views": {
|
|
409
409
|
"title": "Table Views",
|
|
410
|
-
"content": "# Table Views\n\nThe CMS provides two view modes for every table: **Table** mode for browsing and navigating records, and **Data Table** mode for spreadsheet-style inline editing. Switch between them with the toolbar toggle.\n\n## Table Mode\n\nTable mode is the default browse experience:\n\n- **Click rows** to navigate to the record detail view\n- **Row action menus** (three-dot icon) with view, edit, delete, and custom actions\n- **Column headers** are sortable — click to toggle ascending/descending\n- **Search bar** for full-text search across all fields\n- **Responsive columns** that adapt to available space\n\nEach row shows the most relevant columns for the table. Foreign key columns display human-readable labels (resolved via `_label` fields) instead of raw UUIDs. Boolean columns render as colored Yes/No badges. Enum columns use color-coded pills.\n\n### Row Actions\n\nThe three-dot menu on each row provides:\n\n| Action | Visibility | Description |\n|--------|-----------|-------------|\n| View details | Always | Navigate to the record detail page |\n| Edit | When role has `update` access | Navigate to the edit form |\n| Custom actions | Filtered by role + record state | Run actions like approve, void, post |\n| Delete | When role has `delete` access | Delete with confirmation |\n\nActions are filtered by the current role's
|
|
410
|
+
"content": "# Table Views\n\nThe CMS provides two view modes for every table: **Table** mode for browsing and navigating records, and **Data Table** mode for spreadsheet-style inline editing. Switch between them with the toolbar toggle.\n\n## Table Mode\n\nTable mode is the default browse experience:\n\n- **Click rows** to navigate to the record detail view\n- **Row action menus** (three-dot icon) with view, edit, delete, and custom actions\n- **Column headers** are sortable — click to toggle ascending/descending\n- **Search bar** for full-text search across all fields\n- **Responsive columns** that adapt to available space\n\nEach row shows the most relevant columns for the table. Foreign key columns display human-readable labels (resolved via `_label` fields) instead of raw UUIDs. Boolean columns render as colored Yes/No badges. Enum columns use color-coded pills.\n\n### Row Actions\n\nThe three-dot menu on each row provides:\n\n| Action | Visibility | Description |\n|--------|-----------|-------------|\n| View details | Always | Navigate to the record detail page |\n| Edit | When role has `update` access | Navigate to the edit form |\n| Custom actions | Filtered by role + record state | Run actions like approve, void, post |\n| Delete | When role has `delete` access | Delete with confirmation |\n\nActions are filtered by the current role's write permissions and the action's access conditions. For example, an \"approve\" action that requires `status === \"pending\"` only appears on pending records.\n\n## Data Table Mode\n\nData Table mode provides an Excel/Google Sheets-like editing experience:\n\n- **Cell selection** with a blue focus ring\n- **Keyboard navigation** using arrow keys, Tab, Enter, and Escape\n- **Type-to-edit** — start typing to enter edit mode on the selected cell\n- **Row numbers** displayed in the leftmost column\n- **Hint bar** at the bottom showing keyboard shortcuts\n\n### Editable Fields\n\nWhich cells are editable is determined by the table's guards:\n\n- Fields in `guards.updatable` are editable\n- Fields in `guards.immutable` are read-only (shown with a disabled style)\n- Fields in `guards.protected` are read-only (marked \"Updated via actions only\")\n- Audit fields (`createdAt`, `createdBy`, `modifiedAt`, `modifiedBy`) are always read-only\n\nNon-editable cells can still be selected and copied, but they don't enter edit mode.\n\n### Cell Types\n\n| Column Type | Edit Control | Behavior |\n|-------------|-------------|----------|\n| Text | Text input | Free-text entry |\n| Number | Number input | Numeric entry with step controls |\n| Boolean | Yes/No dropdown | Toggle between Yes and No |\n| FK reference | Typeahead dropdown | Server-side search with debounced queries |\n| Enum | Select dropdown | Choose from allowed values |\n\n### Saving\n\nChanges are auto-saved when you:\n\n- Press **Enter** to confirm and move down\n- Press **Tab** to confirm and move to the next editable cell\n- **Click away** from the editing cell (blur)\n\nPress **Escape** to cancel an edit and revert to the previous value.\n\n## Views\n\nViews are named column projections defined in your table's resource config. They control which columns appear in the table based on the current role.\n\n### Toolbar\n\nThe toolbar shows a view dropdown when the table has views defined. Options include:\n\n- **All Fields** — Shows all columns (default)\n- Custom views — Only show the columns specified in the view config\n\nViews are filtered by role access. If a view's access rules require `admin` and the current user is a `member`, that view won't appear in the dropdown.\n\n### Example\n\nGiven this definition:\n\n```typescript\nread: {\n views: {\n summary: {\n fields: ['id', 'name', 'status'],\n access: { roles: ['member', 'admin'] },\n },\n full: {\n fields: ['id', 'name', 'status', 'ssn', 'internalNotes'],\n access: { roles: ['admin'] },\n },\n },\n}\n```\n\n- Members see: \"All Fields\" and \"summary\"\n- Admins see: \"All Fields\", \"summary\", and \"full\"\n- Owners see: \"All Fields\", \"summary\", and \"full\"\n\nWhen a view is selected, the CMS calls the `listView` API endpoint instead of the standard `list`, fetching only the projected columns.\n\n## Default Sort\n\nYou can set a default sort order for a table by adding `defaultSort` to your resource config:\n\n```typescript\nexport default defineTable(podcastEpisodes, {\n defaultSort: { field: \"createdAt\", order: \"desc\" },\n // ...\n});\n```\n\nWhen the CMS loads the table, it applies this sort automatically. Users can still click column headers to change the sort — `defaultSort` only sets the initial state.\n\n## Pagination\n\nThe bottom of every table view shows pagination controls:\n\n- **Page range indicator** — \"Showing 1-25 of 142\"\n- **Page buttons** — Navigate directly to a page, with ellipsis for large page counts\n- **Previous/Next** arrows\n\nThe default page size is 25 records. The CMS resets to page 1 when you change the search query or switch views.\n\n## Search\n\nThe search bar performs full-text search across all columns. Type a query and the CMS debounces the request, then fetches matching records from the API.\n\nSearch works in both Table and Data Table modes, and works with views (searching within the projected columns).\n\n## Next Steps\n\n- **[Inline Editing](/stack/cms/inline-editing)** — Deep dive into spreadsheet editing, FK typeahead, and keyboard shortcuts\n- **[Security](/stack/cms/security)** — How roles and guards affect the table UI\n- **[Actions](/stack/cms/actions)** — Custom actions in the row menu and detail view"
|
|
411
411
|
},
|
|
412
412
|
"stack": {
|
|
413
413
|
"title": "Quickback Stack",
|
|
414
|
-
"content": "**Quickback Stack** is the runtime services that surround your compiled API. While the [Quickback Compiler](/compiler) generates your routes and security policies, the Stack is everything else you need to ship a real application — auth, storage, realtime, queues, an admin UI, an account UI — all on your own Cloudflare account.\n\n## What you get\n\n| Component | Service | Purpose |\n|-----------|---------|---------|\n| [Auth](/stack/auth) | Better Auth | Email/OTP, passkeys, organizations, admin |\n| [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |\n| [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |\n| [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |\n| [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |\n| [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |\n| [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |\n| [Account UI](/stack/account-ui) | Embedded SPA | Login, profile, orgs, admin |\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Cloudflare Edge │\n├─────────────────────────────────────────────────────────────┤\n│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │\n│ │ Workers │ │ Durable │ │ KV │ │\n│ │ (API/CMS) │ │ Objects │ │ (Cache) │ │\n│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │\n│ │ │ │ │\n│ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐ │\n│ │ D1 │ │ Realtime │ │ R2 │ │\n│ │ (or Neon) │ │ (WebSocket)│ │ (Storage) │ │\n│ └─────────────┘ └─────────────┘ └─────────────┘ │\n│ │\n│ ┌─────────────┐ ┌─────────────────────────────────┐ │\n│ │ Queues │ │ Better Auth │ │\n│ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │\n│ └─────────────┘ └─────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Your account, your data\n\nEverything in Quickback Stack runs on your own Cloudflare account:\n\n- **Workers** — your deployments, your logs\n- **Storage** — your KV namespaces, your R2 buckets\n- **Secrets** — your API keys, in your Wrangler secrets\n\nQuickback provides the architecture and the code generation. You own the infrastructure.\n\n## Quick start\n\n```bash\
|
|
414
|
+
"content": "**Quickback Stack** is the runtime services that surround your compiled API. While the [Quickback Compiler](/compiler) generates your routes and security policies, the Stack is everything else you need to ship a real application — auth, storage, realtime, queues, an admin UI, an account UI — all on your own Cloudflare account.\n\n## What you get\n\n| Component | Service | Purpose |\n|-----------|---------|---------|\n| [Auth](/stack/auth) | Better Auth | Email/OTP, passkeys, organizations, admin |\n| [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |\n| [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |\n| [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |\n| [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |\n| [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |\n| [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |\n| [Account UI](/stack/account-ui) | Embedded SPA | Login, profile, orgs, admin |\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Cloudflare Edge │\n├─────────────────────────────────────────────────────────────┤\n│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │\n│ │ Workers │ │ Durable │ │ KV │ │\n│ │ (API/CMS) │ │ Objects │ │ (Cache) │ │\n│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │\n│ │ │ │ │\n│ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐ │\n│ │ D1 │ │ Realtime │ │ R2 │ │\n│ │ (or Neon) │ │ (WebSocket)│ │ (Storage) │ │\n│ └─────────────┘ └─────────────┘ └─────────────┘ │\n│ │\n│ ┌─────────────┐ ┌─────────────────────────────────┐ │\n│ │ Queues │ │ Better Auth │ │\n│ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │\n│ └─────────────┘ └─────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Your account, your data\n\nEverything in Quickback Stack runs on your own Cloudflare account:\n\n- **Workers** — your deployments, your logs\n- **Storage** — your KV namespaces, your R2 buckets\n- **Secrets** — your API keys, in your Wrangler secrets\n\nQuickback provides the architecture and the code generation. You own the infrastructure.\n\n## Quick start\n\n```bash\n# Scaffold + compile interactively\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n\n# Deploy to your Cloudflare account\nnpm i -g wrangler\nwrangler deploy\n```\n\n`start` handles scaffold, login (only when needed), and the first compile in one shot. The deploy step uses your own wrangler auth and ships everything to your Cloudflare account.\n\n## See also\n\n- [Quickback Compiler](/compiler) — the build tool that generates your API\n- [Quickback for Hono API](/compiler/targets/hono-api) — what the compiler outputs\n- [Definitions](/compiler/definitions) — the security model the Stack runs"
|
|
415
415
|
},
|
|
416
416
|
"stack/queues/handlers": {
|
|
417
417
|
"title": "Custom Queue Handlers",
|
|
@@ -427,11 +427,11 @@ export const DOCS = {
|
|
|
427
427
|
},
|
|
428
428
|
"stack/realtime/durable-objects": {
|
|
429
429
|
"title": "Realtime",
|
|
430
|
-
"content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n requiredRoles: [\"recruiter\", \"hiring-manager\"], // Who receives broadcasts\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually via the `createRealtime(env)` helper described below.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nThe `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ db, ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated users in the organization receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: { Authorization: `Bearer ${sessionToken}` },\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}&organizationId=${activeOrgId}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade — no HTTP round-trip.\n3. **API broadcasts** — After CRUD ops, the API calls the Broadcaster DO directly via its binding (in-process, no network hop).\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
|
|
430
|
+
"content": "Quickback can generate realtime notification helpers for broadcasting changes to connected clients. This enables live updates via WebSocket using Cloudflare Durable Objects.\n\nThe targeting model is shared across ws tickets, websocket attachment, and server-side broadcasts:\n\n- string target: historical `organizationId` shorthand\n- object target: `{ scopeKey?, organizationId?, userId? }`\n\nThat means the same mental model drives both `createRealtime()` and the generated Broadcaster filter path.\n\n## Enabling Realtime\n\nAdd `realtime` configuration to individual table definitions:\n\n```typescript\n// features/applications/applications.ts\n\nexport const applications = sqliteTable(\"applications\", {\n id: text(\"id\").primaryKey(),\n candidateId: text(\"candidate_id\").notNull(),\n jobId: text(\"job_id\").notNull(),\n stage: text(\"stage\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true, // Enable realtime for this table\n onInsert: true, // Broadcast on INSERT (default: true)\n onUpdate: true, // Broadcast on UPDATE (default: true)\n onDelete: true, // Broadcast on DELETE (default: true)\n requiredRoles: [\"recruiter\", \"hiring-manager\"], // Who receives broadcasts\n fields: [\"id\", \"candidateId\", \"stage\"], // Fields to include (optional)\n },\n // ... guards, crud\n});\n```\n\nWhen any table has realtime enabled, the compiler generates `src/lib/realtime.ts` with helper functions for sending notifications.\n\nAt the project level, `providers.database.config.realtime` can stay boolean or become object-shaped when you need relationship-authorized resource tickets:\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nThat tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.\n\n## When auto-broadcast fires (and when you call it manually)\n\nQuickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.\n\nEverywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually via the `createRealtime(env)` helper described below.\n\n| Mutation site | Auto-broadcast? | Why |\n|---|---|---|\n| Generated CRUD route (`POST /`, `PATCH /:id`, `DELETE /:id`) | Yes | The compiler emits the call after the write returns. |\n| Generated batch route (`/batch/...`) | Yes | Same pattern, emitted per record. |\n| `scoped.insert/update/delete` inside an action handler | No — manual | Scoped-db is a query-shape wrapper (firewall + soft-delete WHERE injection). It deliberately has no side-effects so explicit handlers can write multiple records, conditionally roll back, etc. without surprise broadcasts. |\n| `unsafeDb` writes in actions (or any custom route) | No — manual | Same reasoning — `unsafeDb` is the un-wrapped escape hatch. |\n| Queue consumers, cron jobs, webhook handlers | No — manual | These run outside the CRUD path entirely. |\n\nThe rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` directly, you also call `realtime.insert(...)` directly on the next line. Otherwise the cross-tab live-update you wired up in the SPA won't fire.\n\n## Generated Helper\n\nThe `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ db, ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // After creating a record\n await realtime.insert('applications', newApplication, ctx.activeOrgId!);\n\n // After updating a record\n await realtime.update('applications', newApplication, oldApplication, ctx.activeOrgId!);\n\n // After deleting a record\n await realtime.delete('applications', { id: applicationId }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\nFor explicit targeting, pass an object instead of the historical org string:\n\n```typescript\nawait realtime.broadcast(\"event-page-updated\", payload, {\n scopeKey: `events:${input.eventId}`,\n});\n\nawait realtime.broadcast(\"dm\", payload, {\n userId: recipientId,\n});\n```\n\n## Event Format\n\nQuickback broadcasts events in a structured JSON format for easy client-side handling.\n\n### Insert Event\n\n```typescript\nawait realtime.insert('applications', {\n id: 'app_123',\n candidateId: 'cnd_456',\n stage: 'applied'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"INSERT\",\n \"schema\": \"public\",\n \"new\": {\n \"id\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"applied\"\n },\n \"old\": null\n}\n```\n\n### Update Event\n\n```typescript\nawait realtime.update('applications',\n { id: 'app_123', stage: 'interview' }, // new\n { id: 'app_123', stage: 'screening' }, // old\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"UPDATE\",\n \"schema\": \"public\",\n \"new\": { \"id\": \"app_123\", \"stage\": \"interview\" },\n \"old\": { \"id\": \"app_123\", \"stage\": \"screening\" }\n}\n```\n\n### Delete Event\n\n```typescript\nawait realtime.delete('applications',\n { id: 'app_123' },\n ctx.activeOrgId!\n);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"eventType\": \"DELETE\",\n \"schema\": \"public\",\n \"new\": null,\n \"old\": { \"id\": \"app_123\" }\n}\n```\n\n## Custom Broadcasts\n\nFor arbitrary events that don't map to CRUD operations:\n\n```typescript\nawait realtime.broadcast('screening-complete', {\n applicationId: 'app_123',\n candidateId: 'cnd_456',\n stage: 'interview'\n}, ctx.activeOrgId!);\n```\n\nBroadcasts:\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\n## User-Specific Broadcasts\n\nTarget a specific user instead of the entire organization:\n\n```typescript\n// Only this user receives the notification\nawait realtime.insert('notifications', newNotification, ctx.activeOrgId!, {\n userId: ctx.userId\n});\n\n// Notify a hiring manager of a new application\nawait realtime.broadcast('application-received', {\n applicationId: 'app_123',\n jobId: 'job_789'\n}, ctx.activeOrgId!, {\n userId: hiringManagerId\n});\n```\n\n## Role-Based Filtering\n\nLimit which roles receive a broadcast using `targetRoles`:\n\n```typescript\n// Only hiring managers and recruiters receive this broadcast\nawait realtime.insert('applications', application, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager', 'recruiter']\n});\n\n// Interviewers only see applications assigned to them\nawait realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {\n targetRoles: ['hiring-manager']\n});\n```\n\nIf `targetRoles` is not specified, all authenticated subscribers in the chosen scope receive the broadcast.\n\n## Per-Role Field Masking\n\nApply different field masking based on the subscriber's role using `maskingConfig`:\n\n```typescript\nawait realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {\n maskingConfig: {\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n },\n});\n```\n\n**How masking works:**\n- Each subscriber receives a payload masked according to their role\n- Roles in the `show.roles` array see unmasked values\n- All other roles see the masked version\n- Masking is pre-computed per-role (O(roles) not O(subscribers))\n\n**Available mask types:**\n| Type | Example Output |\n|------|----------------|\n| `email` | `j***@y*********.com` |\n| `phone` | `******4567` |\n| `ssn` | `*****6789` |\n| `creditCard` | `**** **** **** 1111` |\n| `name` | `J***` |\n| `redact` | `[REDACTED]` |\n\n### Owner-Based Masking\n\nShow unmasked data to the record owner:\n\n```typescript\nmaskingConfig: {\n phone: {\n type: 'phone',\n show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked\n },\n}\n```\n\n## Client-Side Subscription\n\n### WebSocket Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. The client first obtains a short-lived ticket from the main API, then connects with it as a URL parameter. The Broadcaster verifies the ticket cryptographically at upgrade time — no HTTP round-trip needed.\n\n```typescript\n// 1. Get a ws-ticket from your API (requires session auth)\nconst response = await fetch('/broadcast/v1/ws-ticket', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ eventId: 'evt_123' }),\n});\nconst { wsTicket } = await response.json();\n\n// 2. Connect with ticket as URL param\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log('Connected and authenticated!');\n // No auth message needed — pre-authenticated at upgrade\n};\n```\n\nTickets expire after 60 seconds, so fetch a fresh one before each connection or reconnection.\n\n### Handling Messages\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n // Handle CRUD events\n if (msg.type === 'postgres_changes') {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n if (eventType === 'INSERT') {\n addRecord(table, newRecord);\n } else if (eventType === 'UPDATE') {\n updateRecord(table, newRecord);\n } else if (eventType === 'DELETE') {\n removeRecord(table, oldRecord.id);\n }\n }\n\n // Handle custom broadcasts\n if (msg.type === 'broadcast') {\n const { event, payload } = msg;\n\n if (event === 'screening-complete') {\n refreshApplication(payload.applicationId);\n } else if (event === 'interview-scheduled') {\n showInterviewNotification(payload.applicationId);\n }\n }\n};\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster DO runs inline in your main worker and uses `BETTER_AUTH_SECRET` (already required for auth) to sign and verify WebSocket tickets.\n\n| Variable | Description |\n|----------|-------------|\n| `BETTER_AUTH_SECRET` | Signs/verifies WebSocket tickets (already set for auth) |\n\nThe `BROADCASTER` binding is a `DurableObjectNamespace` — the compiler generates this in your `wrangler.toml` automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Architecture\n\n```\n 1. POST /ws-ticket\n┌───────────────────────────────────────────────┐ ┌─────────────────┐\n│ Quickback Worker │ ◄──│ Browser Client │\n│ │ ──►│ │\n│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘\n│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │\n│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...\n│ │ │ │\n└────────────────────────────────────┼──────────┘ │\n │◄──────────────────────┘\n WebSocket (verified at upgrade)\n```\n\n1. **Client gets a ticket** — `POST /broadcast/v1/ws-ticket` on the main API (session-authenticated). Returns a 60-second HMAC-signed ticket.\n2. **Client connects** — Opens WebSocket with `?ws_ticket=<ticket>`. The Durable Object verifies the ticket cryptographically at upgrade and attaches the socket to the ticket's `scopeKey`, `organizationId`, or `userId`.\n3. **API broadcasts** — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.\n\n## Best Practices\n\n### Broadcast After Commit\n\nAlways broadcast after the database operation succeeds:\n\n```typescript\n// Good - broadcast after successful insert\nconst [newApp] = await db.insert(applications).values(data).returning();\nawait realtime.insert('applications', newApp, ctx.activeOrgId!);\n\n// Bad - don't broadcast before confirming success\nawait realtime.insert('applications', data, ctx.activeOrgId!);\nawait db.insert(applications).values(data); // Could fail!\n```\n\n### Minimal Payloads\n\nOnly include necessary data in broadcasts:\n\n```typescript\n// Good - minimal payload\nawait realtime.update('applications',\n { id: record.id, stage: 'interview' },\n { id: record.id, stage: 'screening' },\n ctx.activeOrgId!\n);\n\n// Avoid - sending entire record with large content\nawait realtime.update('applications', fullRecord, oldRecord, ctx.activeOrgId!);\n```\n\n### Use Broadcasts for Complex Events\n\nFor events that don't map cleanly to CRUD:\n\n```typescript\n// Hiring pipeline stage completed\nawait realtime.broadcast('pipeline-stage-complete', {\n applicationId: application.id,\n stages: ['applied', 'screening', 'interview'],\n currentStage: 'offer',\n candidateId: application.candidateId\n}, ctx.activeOrgId!);\n```\n\n## Custom Event Namespaces\n\nFor complex applications with many custom events, you can define typed event namespaces using `defineRealtime`. This generates strongly-typed helper methods for your custom events.\n\n### Defining Event Namespaces\n\nCreate a file in `services/realtime/`:\n\n```typescript\n// services/realtime/screening.ts\n\nexport default defineRealtime({\n name: 'screening',\n events: ['started', 'progress', 'completed', 'failed'],\n description: 'Candidate screening pipeline events',\n});\n```\n\n### Generated Helper Methods\n\nAfter compilation, the `createRealtime()` helper includes your custom namespace:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const realtime = createRealtime(ctx.env);\n\n // Type-safe custom event methods\n await realtime.screening.started({\n applicationId: input.applicationId,\n }, ctx.activeOrgId!);\n\n // Progress updates\n await realtime.screening.progress({\n applicationId: input.applicationId,\n percent: 50,\n step: 'background-check',\n }, ctx.activeOrgId!);\n\n // Completion\n await realtime.screening.completed({\n applicationId: input.applicationId,\n result: 'passed',\n duration: 1234,\n }, ctx.activeOrgId!);\n\n return { success: true };\n};\n```\n\n### Event Format\n\nCustom namespace events use the `broadcast` type with namespaced event names:\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening:started\",\n \"payload\": {\n \"applicationId\": \"app_123\"\n }\n}\n```\n\n### Multiple Namespaces\n\nDefine multiple namespaces for different parts of your application:\n\n```typescript\n// services/realtime/notifications.ts\nexport default defineRealtime({\n name: 'notifications',\n events: ['interview-reminder', 'offer-update', 'application-received'],\n description: 'Recruitment notification events',\n});\n\n// services/realtime/presence.ts\nexport default defineRealtime({\n name: 'presence',\n events: ['joined', 'left', 'reviewing', 'idle'],\n description: 'Who is reviewing which candidate',\n});\n```\n\nUsage:\n```typescript\nconst realtime = createRealtime(ctx.env);\n\n// Notification events\nawait realtime.notifications['interview-reminder']({ ... }, ctx.activeOrgId!);\n\n// Presence events — who's reviewing which candidate\nawait realtime.presence.reviewing({ userId: ctx.userId, candidateId: 'cnd_456' }, ctx.activeOrgId!);\n```\n\n### Namespace vs Generic Broadcast\n\n| Use Case | Approach |\n|----------|----------|\n| One-off custom event | `realtime.broadcast('event-name', payload, orgId)` |\n| Repeated event patterns | `defineRealtime` namespace |\n| Type-safe events | `defineRealtime` namespace |\n| Event discovery | `defineRealtime` (appears in generated types) |"
|
|
431
431
|
},
|
|
432
432
|
"stack/realtime": {
|
|
433
433
|
"title": "Realtime",
|
|
434
|
-
"content": "Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:\n\n- **`/broadcast/v1/*` — server fan-out.** One DO instance per
|
|
434
|
+
"content": "Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:\n\n- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for \"tell every client in this shared scope that something changed.\" The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.\n- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).\n\nBoth share the same auth model and ride on the same compiled worker; they solve different problems.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────┐\n│ Quickback Worker │\n│ │\n│ ┌──────────┐ DO binding ┌────────────────────┐\n│ │ Hono API │ ──────────────► │ Broadcaster (DO) │\n│ │ │ │ WebSocket manager │\n│ └──────────┘ └─────────┬──────────┘\n│ │\n└─────────────────────────────────────────┼┘\n │ WebSocket\n │\n ┌────────▼─────────┐\n │ Browser Clients │\n │ (CMS, Account, │\n │ Admin, Custom) │\n └──────────────────┘\n```\n\nThe Broadcaster Durable Object runs **inline** in your main Quickback worker — no separate worker deployment needed. The API calls the DO directly via its binding (in-process, no network hop).\n\n1. **Quickback Worker** — Your compiled API with the Broadcaster DO class exported from the same worker.\n2. **Broadcaster (Durable Object)** — Manages WebSocket connections per subscription scope. One instance per `scopeKey`, organization, or user lane.\n3. **Browser Clients** — CMS, Account, Admin, and custom frontends connect via WebSocket on the same origin.\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Scope-aware fan-out | Routes by `scopeKey`, `organizationId`, or `userId` |\n| Role-based filtering | Only send events to users with matching roles |\n| Per-role masking | Different users see different field values based on their role |\n| User-specific targeting | Send events to a specific user within an org |\n| Resource-scoped tickets | Reuse authz relationship roles to mint scope-bound ws tickets |\n| Custom broadcasts | Arbitrary events beyond CRUD |\n| Custom namespaces | `defineRealtime()` for type-safe event helpers |\n| Ticket-based auth | HMAC-signed tickets verified at WebSocket upgrade — no HTTP round-trip |\n\n## Enabling Realtime\n\nAdd `realtime` to individual table definitions:\n\n```typescript\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n realtime: {\n enabled: true,\n onInsert: true,\n onUpdate: true,\n onDelete: true,\n requiredRoles: [\"recruiter\", \"hiring-manager\"],\n fields: [\"id\", \"candidateId\", \"stage\"],\n },\n});\n```\n\nAnd enable the realtime binding in your database config. The compiler generates the Durable Object class, helper functions, and wrangler bindings — all within your main worker.\n\n```typescript\nproviders: {\n database: defineDatabase(\"cloudflare-d1\", {\n realtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n },\n }),\n}\n```\n\nWith that config, `/broadcast/v1/ws-ticket` can authenticate the caller, verify the declared authz relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` channel.\n\n## Pages\n\n- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces\n- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling\n- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs"
|
|
435
435
|
},
|
|
436
436
|
"stack/realtime/partyserver-rooms": {
|
|
437
437
|
"title": "PartyServer Rooms",
|
|
@@ -439,7 +439,7 @@ export const DOCS = {
|
|
|
439
439
|
},
|
|
440
440
|
"stack/realtime/using-realtime": {
|
|
441
441
|
"title": "Using Realtime",
|
|
442
|
-
"content": "This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.\n\n## Connecting\n\nOpen a WebSocket connection to the realtime worker:\n\n```typescript\nconst ws = new WebSocket(\"wss://api.yourdomain.com/broadcast/v1/websocket\");\n```\n\n## Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. This is a two-step process:\n\n1. **Get a ticket** — Call the ws-ticket endpoint with your session auth\n2. **Connect with ticket** — Pass the ticket as a URL parameter when opening the WebSocket\n\nThis approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.\n\n### Step 1: Get a WebSocket Ticket\n\n```typescript\nconst response = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n \"Content-Type\": \"application/json\",\n },\n});\nconst { wsTicket, expiresIn } = await response.json();\n// expiresIn = 60 (seconds)\n```\n\nThe ticket is a short-lived (60-second) HMAC-signed token containing your userId,
|
|
442
|
+
"content": "This page covers connecting to the Quickback realtime system from client applications — authentication, subscribing to events, and handling messages.\n\n## Connecting\n\nOpen a WebSocket connection to the realtime worker:\n\n```typescript\nconst ws = new WebSocket(\"wss://api.yourdomain.com/broadcast/v1/websocket\");\n```\n\n## Authentication\n\nQuickback uses **ticket-based authentication** for WebSocket connections. This is a two-step process:\n\n1. **Get a ticket** — Call the ws-ticket endpoint with your session auth\n2. **Connect with ticket** — Pass the ticket as a URL parameter when opening the WebSocket\n\nThis approach is faster and more secure than in-band auth messages — the connection is authenticated at upgrade time with no HTTP round-trip from the Durable Object.\n\n### Step 1: Get a WebSocket Ticket\n\n```typescript\nconst response = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${sessionToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ eventId: \"evt_123\" }), // optional; used by resource-scoped wsTicket config\n});\nconst { wsTicket, expiresIn } = await response.json();\n// expiresIn = 60 (seconds)\n```\n\nThe ticket is a short-lived (60-second) HMAC-signed token containing your userId, roles, and the resolved subscription scope.\n\n### Step 2: Connect with Ticket\n\n```typescript\nconst ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n);\n\nws.onopen = () => {\n console.log(\"Connected and authenticated!\");\n // No auth message needed — connection is pre-authenticated\n};\n```\n\nIf the ticket is invalid or expired, the WebSocket upgrade is rejected with a 401 status.\n\n## Handling Messages\n\n### CRUD Events\n\nCRUD events use the `postgres_changes` type:\n\n```typescript\nws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n\n if (msg.type === \"postgres_changes\") {\n const { table, eventType, new: newRecord, old: oldRecord } = msg;\n\n switch (eventType) {\n case \"INSERT\":\n addRecord(table, newRecord);\n break;\n case \"UPDATE\":\n updateRecord(table, newRecord);\n break;\n case \"DELETE\":\n removeRecord(table, oldRecord.id);\n break;\n }\n }\n};\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"postgres_changes\",\n \"table\": \"applications\",\n \"schema\": \"public\",\n \"eventType\": \"INSERT\",\n \"new\": { \"id\": \"app_123\", \"candidateId\": \"cnd_456\", \"stage\": \"interview\" },\n \"old\": null\n}\n```\n\nFor UPDATE events, both `new` and `old` are populated. For DELETE events, only `old` is populated.\n\n### Custom Broadcasts\n\nCustom events use the `broadcast` type:\n\n```typescript\nif (msg.type === \"broadcast\") {\n const { event, payload } = msg;\n\n if (event === \"screening-complete\") {\n refreshApplication(payload.applicationId);\n } else if (event === \"screening:progress\") {\n updateProgressBar(payload.percent);\n }\n}\n```\n\n**Event payload:**\n\n```json\n{\n \"type\": \"broadcast\",\n \"event\": \"screening-complete\",\n \"payload\": {\n \"applicationId\": \"app_123\",\n \"candidateId\": \"cnd_456\",\n \"stage\": \"interview\"\n }\n}\n```\n\nCustom namespaces (from `defineRealtime()`) use the format `namespace:event` — e.g., `screening:started`, `screening:progress`.\n\n## Security\n\n### Role-Based Filtering\n\nEvents are only delivered to users whose role matches the broadcast's `targetRoles`. If a table's realtime config specifies `requiredRoles: [\"hiring-manager\", \"recruiter\"]`, only users with those roles receive the events.\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency.\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast — all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## Cloudflare Only\n\nRealtime requires Cloudflare Durable Objects and is only available with the Cloudflare runtime.\n\n## See Also\n\n- [Durable Objects Setup](/stack/realtime/durable-objects) — Configuration, event formats, masking, and custom namespaces\n- [Masking](/compiler/definitions/masking) — Field masking configuration"
|
|
443
443
|
},
|
|
444
444
|
"stack/storage": {
|
|
445
445
|
"title": "Storage",
|
|
@@ -463,7 +463,7 @@ export const DOCS = {
|
|
|
463
463
|
},
|
|
464
464
|
"stack/vector/embeddings": {
|
|
465
465
|
"title": "Automatic Embeddings",
|
|
466
|
-
"content": "Quickback can automatically generate embeddings for your data using Cloudflare Queues and Workers AI. When configured, INSERT and UPDATE operations automatically enqueue embedding jobs that are processed asynchronously.\n\n## Enabling Embeddings\n\nAdd an `embeddings` configuration to your resource definition:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n embeddings: {\n fields: ['description'], // Fields to concatenate and embed\n model: '@cf/baai/bge-base-en-v1.5', // Embedding model (optional)\n onInsert: true, // Auto-embed on create (default: true)\n onUpdate: ['description'], // Re-embed when these fields change\n embeddingColumn: 'embedding', // Column to store embedding\n metadata: ['department'], // Metadata for Vectorize index\n },\n\n crud: {\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } },\n },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `fields` | `string[]` | **Required** | Fields to concatenate and embed |\n| `model` | `string` | `'@cf/baai/bge-base-en-v1.5'` | Workers AI embedding model |\n| `onInsert` | `boolean` | `true` | Embed on INSERT operations |\n| `onUpdate` | `boolean \\| string[]` | `true` | Embed on UPDATE; array limits to specific fields |\n| `embeddingColumn` | `string` | `'embedding'` | Column to store the embedding vector |\n| `separator` | `string` | `' '` | Separator for joining multiple fields |\n| `metadata` | `string[]` | `[]` | Fields to include in Vectorize metadata |\n\n### onUpdate Options\n\n```typescript\n// Always re-embed on any update\nonUpdate: true\n\n// Never re-embed on update\nonUpdate: false\n\n// Only re-embed when specific fields change\nonUpdate: ['description', 'title']\n```\n\n## How It Works\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Main API Worker │\n│ │\n│ ┌─────────────────────┐ ┌────────────────────┐ │\n│ │ POST /jobs │ │ Queue Consumer │ │\n│ │ │ │ │ │\n│ │ 1. Auth middleware │ │ 1. Workers AI │ │\n│ │ 2. Firewall │ │ embed() │ │\n│ │ 3. Guards │ │ 2. D1 update() │ │\n│ │ 4. Insert to D1 │ │ 3. Vectorize │ │\n│ │ 5. Enqueue job ─────┼───▶│ upsert() │ │\n│ └─────────────────────┘ └────────────────────┘ │\n│ ▲ │\n│ ┌─────────────────┴──────────────────┐ │\n│ │ EMBEDDINGS_QUEUE │ │\n│ └────────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n1. **API Request** - POST/PATCH arrives and passes through auth, firewall, guards\n2. **Database Insert** - Record is created/updated in D1\n3. **Enqueue Job** - Embedding job is sent to Cloudflare Queue\n4. **Queue Consumer** - Processes job asynchronously:\n - Calls Workers AI to generate embedding\n - Updates D1 with embedding vector\n - Optionally upserts to Vectorize index\n\n## Security Model\n\n**Security is enforced at enqueue time, not consume time:**\n\n- Jobs are only enqueued after passing all security checks (auth, firewall, guards)\n- The queue consumer is an internal process that executes pre-validated jobs\n- If a user can't create a job posting, they can't trigger an embedding job\n\n## Generic Embeddings API\n\nIn addition to automatic embeddings on CRUD operations, Quickback generates a generic embeddings API endpoint that allows you to trigger embeddings on arbitrary content.\n\n### POST /api/v1/embeddings\n\nGenerate an embedding for any text content:\n\n```bash\ncurl -X POST https://your-api.workers.dev/api/v1/embeddings \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -d '{\n \"content\": \"Text to embed\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\",\n \"table\": \"jobs\",\n \"id\": \"job_123\"\n }'\n```\n\n#### Request Body\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `content` | `string` | Yes | Text to generate embedding for |\n| `model` | `string` | No | Embedding model (defaults to table config or `@cf/baai/bge-base-en-v1.5`) |\n| `table` | `string` | No | Table to store embedding back to |\n| `id` | `string` | Conditional | Record ID to update (required if `table` is specified) |\n\n#### Response\n\n```json\n{\n \"queued\": true,\n \"jobId\": \"550e8400-e29b-41d4-a716-446655440000\",\n \"table\": \"jobs\",\n \"id\": \"job_123\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n}\n```\n\n### GET /api/v1/embeddings/tables\n\nList tables that have embeddings configured:\n\n```bash\ncurl https://your-api.workers.dev/api/v1/embeddings/tables \\\n -H \"Cookie: better-auth.session_token=...\"\n```\n\nResponse:\n\n```json\n{\n \"tables\": [\n {\n \"name\": \"jobs\",\n \"embeddingColumn\": \"embedding\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n }\n ]\n}\n```\n\n### Authentication & Authorization\n\nThe generic embeddings API requires authentication and uses the `activeOrgId` from the user's context to enforce organization-level isolation. Embedding jobs are scoped to the user's current organization.\n\n### Use Cases\n\nThe generic embeddings API is useful for:\n\n- **Batch embedding**: Embed content without going through CRUD routes\n- **Re-embedding**: Force re-generation of embeddings for existing records\n- **Preview embeddings**: Test embedding generation before persisting\n- **External content**: Embed content that doesn't fit your defined schemas\n\n## Generated Files\n\nWhen embeddings are configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/queue-consumer.ts` | Queue consumer handler for processing embedding jobs |\n| `src/routes/embeddings.ts` | Generic embeddings API routes |\n| `wrangler.toml` | Queue producer/consumer bindings, AI binding |\n| `src/env.d.ts` | `EMBEDDINGS_QUEUE`, `AI` types |\n| `src/index.ts` | Exports `queue` handler, mounts `/api/v1/embeddings` |\n\n### wrangler.toml additions\n\n```toml\n# Embeddings Queue\n[[queues.producers]]\nqueue = \"your-app-embeddings-queue\"\nbinding = \"EMBEDDINGS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"your-app-embeddings-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n# Workers AI\n[ai]\nbinding = \"AI\"\n```\n\n## Multiple Fields\n\nEmbed multiple fields by concatenating them:\n\n```typescript\nembeddings: {\n fields: ['title', 'description', 'department'], // Joined with spaces by default\n // ...\n}\n```\n\nGenerated embedding text: `\"${title} ${description} ${department}\"`\n\n### Custom Separator\n\nUse `separator` to control how fields are joined. This is useful for sentence boundary detection:\n\n```typescript\nembeddings: {\n fields: ['title', 'description'],\n separator: '. ', // Join with period + space\n // ...\n}\n```\n\nGenerated code: `[result[0].title, result[0].description].filter(Boolean).join('. ')`\n\nThe `filter(Boolean)` ensures null or empty fields are excluded cleanly — no trailing separator when a field is absent.\n\n## Vectorize Integration\n\nIf you have a Vectorize index configured, embeddings are automatically upserted:\n\n```typescript\n// quickback.config.ts\nproviders: {\n database: {\n config: {\n vectorizeIndexName: 'jobs-embeddings', // Your Vectorize index\n vectorizeBinding: 'VECTORIZE',\n },\n },\n},\n```\n\nThe queue consumer will:\n1. Generate the embedding via Workers AI\n2. Store the vector in D1 (JSON string)\n3. Upsert to Vectorize with metadata\n\n### Vectorize Metadata\n\nInclude fields in Vectorize metadata for filtering:\n\n```typescript\nembeddings: {\n fields: ['description'],\n metadata: ['department', 'organizationId', 'status'],\n}\n```\n\nEnables queries like:\n```typescript\nconst results = await env.VECTORIZE.query(vector, {\n topK: 10,\n filter: { department: 'engineering' }\n});\n```\n\n## Schema Requirements\n\nYour schema must include the embedding column:\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 description: q.text().required(),\n department: q.text().optional(),\n status: q.text().required(),\n organizationId: q.scope(\"organization\"),\n\n // Embedding column — stores JSON array of floats\n embedding: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n crud: { list: {}, get: {}, create: {}, update: {}, delete: {} },\n});\n```\n\n## Supported Models\n\nAny Workers AI embedding model can be used:\n\n| Model | Dimensions | Notes |\n|-------|------------|-------|\n| `@cf/baai/bge-base-en-v1.5` | 768 | Default, good general-purpose |\n| `@cf/baai/bge-small-en-v1.5` | 384 | Faster, smaller |\n| `@cf/baai/bge-large-en-v1.5` | 1024 | Higher quality |\n\nSee [Workers AI Models](https://developers.cloudflare.com/workers-ai/models/) for the full list.\n\n## Deployment\n\nAfter compiling with embeddings:\n\n1. **Create the queue:**\n ```bash\n wrangler queues create your-app-embeddings-queue\n ```\n\n2. **Deploy the worker:**\n ```bash\n wrangler deploy\n ```\n\nThe single worker handles both HTTP requests and queue consumption.\n\n## Monitoring\n\nQueue metrics are available in the Cloudflare dashboard:\n- Messages enqueued\n- Messages processed\n- Retry count\n- Consumer lag\n\nCheck queue health:\n```bash\nwrangler queues list\nwrangler queues consumer your-app-embeddings-queue\n```\n\n## Error Handling\n\nFailed jobs are automatically retried (up to `max_retries`):\n\n```typescript\n// In queue consumer\ntry {\n const embedding = await env.AI.run(job.model, { text: job.content });\n // ...\n message.ack();\n} catch (error) {\n console.error('[Queue] Embedding job failed:', error);\n message.retry(); // Will retry up to 3 times\n}\n```\n\nAfter max retries, the message is dead-lettered (if configured) or dropped.\n\n## Similarity Search Service\n\nFor applications that need typed similarity search with classification, you can define embedding search configurations using `defineEmbedding`. This generates a service layer with typed search functions.\n\n### Defining Search Configurations\n\nCreate a file in `services/embeddings/`:\n\n```typescript\n// services/embeddings/job-similarity.ts\n\nexport default defineEmbedding({\n name: 'job-similarity',\n description: 'Find similar job postings by description content',\n\n // Source configuration\n source: 'jobs', // Table name\n vectorIndex: 'VECTORIZE', // Binding name\n model: '@cf/baai/bge-base-en-v1.5',\n\n // Search configuration\n search: {\n threshold: 0.60, // Minimum similarity (default: 0.60)\n limit: 10, // Max results (default: 10)\n classify: {\n DUPLICATE_POSTING: 0.90, // Score >= 0.90 = DUPLICATE_POSTING\n SIMILAR_ROLE: 0.85, // Score >= 0.85 = SIMILAR_ROLE\n RELATED: 0.75, // Score >= 0.75 = RELATED\n },\n filters: ['department', 'organizationId'], // Filterable fields\n },\n\n // Generation triggers (beyond CRUD)\n triggers: {\n onQueueMessage: 'embed_job', // Listen for queue messages\n },\n});\n```\n\n### Generated Service Layer\n\nAfter compilation, a `createEmbeddings()` helper is generated in `src/lib/embeddings.ts`:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const embeddings = createEmbeddings(ctx.env);\n\n // Search with automatic classification\n const similar = await embeddings.jobSimilarity.search(\n 'Senior Full-Stack Engineer with React and Node.js experience',\n {\n department: 'engineering',\n limit: 5,\n threshold: 0.70,\n }\n );\n\n // Returns: [{ id, score: 0.87, classification: 'SIMILAR_ROLE', metadata }]\n for (const match of similar) {\n console.log(`${match.classification}: ${match.id} (${match.score})`);\n }\n\n return { similar };\n};\n```\n\n### Classification Thresholds\n\nResults are automatically classified based on similarity score:\n\n| Classification | Default Threshold | Meaning |\n|----------------|-------------------|---------|\n| `DUPLICATE_POSTING` | >= 0.90 | Near-identical job posting |\n| `SIMILAR_ROLE` | >= 0.85 | Strongly similar role and requirements |\n| `RELATED` | >= 0.75 | Topically related position |\n| `NEW` | < 0.75 | No significant match |\n\nCustomize thresholds per use case:\n\n```typescript\nsearch: {\n classify: {\n DUPLICATE_POSTING: 0.95, // Stricter duplicate detection\n SIMILAR_ROLE: 0.88,\n RELATED: 0.70, // Broader \"related\" category\n },\n}\n```\n\n### Gray Zone Detection\n\nFor cases where automatic classification isn't sufficient, use gray zone detection to get matches that need semantic evaluation:\n\n```typescript\nconst results = await embeddings.jobSimilarity.findWithGrayZone(\n 'Some job description text',\n { min: 0.60, max: 0.85 }\n);\n\n// Returns structured results:\n// {\n// high_confidence: [...], // Score >= 0.85 (auto-classified)\n// gray_zone: [...] // 0.60 <= score < 0.85 (needs review)\n// }\n\n// Process high confidence matches automatically\nfor (const match of results.high_confidence) {\n await markAsDuplicate(match.id);\n}\n\n// Queue gray zone for manual review\nfor (const match of results.gray_zone) {\n await queueForReview(match.id, match.score);\n}\n```\n\n### Generate Embeddings Directly\n\nGenerate embeddings without searching:\n\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Get raw embedding vector\nconst vector = await embeddings.jobSimilarity.embed(\n 'Text to embed'\n);\n// Returns: number[] (768 dimensions for bge-base)\n```\n\n### Multiple Search Configurations\n\nDefine different configurations for different use cases:\n\n```typescript\n// services/embeddings/candidate-similarity.ts\nexport default defineEmbedding({\n name: 'candidate-similarity',\n description: 'Match candidates by resume content',\n source: 'candidates',\n search: {\n threshold: 0.65,\n limit: 20,\n classify: {\n DUPLICATE_POSTING: 0.92,\n SIMILAR_ROLE: 0.80,\n RELATED: 0.65,\n },\n filters: ['source'],\n },\n});\n\n// services/embeddings/application-match.ts\nexport default defineEmbedding({\n name: 'application-match',\n description: 'Match applications to similar job postings',\n source: 'applications',\n search: {\n threshold: 0.70,\n limit: 5,\n classify: {\n DUPLICATE_POSTING: 0.95,\n SIMILAR_ROLE: 0.90,\n RELATED: 0.80,\n },\n filters: ['jobId', 'organizationId'],\n },\n});\n```\n\nUsage:\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Different search behaviors for different content types\nconst similarJobs = await embeddings.jobSimilarity.search(text, opts);\nconst similarCandidates = await embeddings.candidateSimilarity.search(text, opts);\nconst matchingApplications = await embeddings.applicationMatch.search(text, opts);\n```\n\n### Table-Level vs Service-Level\n\n| Feature | Table-level (`defineTable`) | Service-level (`defineEmbedding`) |\n|---------|----------------------------|----------------------------------|\n| Auto-embed on INSERT | ✅ | ❌ |\n| Auto-embed on UPDATE | ✅ | ❌ |\n| Custom search functions | ❌ | ✅ |\n| Classification thresholds | ❌ | ✅ |\n| Gray zone detection | ❌ | ✅ |\n| Filterable searches | ❌ | ✅ |\n| Queue message triggers | ❌ | ✅ |\n\n**Use both together:**\n- `defineTable` with `embeddings` config for automatic embedding generation\n- `defineEmbedding` for typed search functions with classification"
|
|
466
|
+
"content": "Quickback can automatically generate embeddings for your data using Cloudflare Queues and Workers AI. When configured, INSERT and UPDATE operations automatically enqueue embedding jobs that are processed asynchronously.\n\n## Enabling Embeddings\n\nAdd an `embeddings` configuration to your resource definition:\n\n```typescript\n// quickback/features/jobs/jobs.ts\n\nexport default defineTable(jobs, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n\n embeddings: {\n fields: ['description'], // Fields to concatenate and embed\n model: '@cf/baai/bge-base-en-v1.5', // Embedding model (optional)\n onInsert: true, // Auto-embed on create (default: true)\n onUpdate: ['description'], // Re-embed when these fields change\n embeddingColumn: 'embedding', // Column to store embedding\n metadata: ['department'], // Metadata for Vectorize index\n },\n\n create: { access: { roles: ['recruiter'] } },\n update: { access: { roles: ['recruiter'] } },\n});\n```\n\n## Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `fields` | `string[]` | **Required** | Fields to concatenate and embed |\n| `model` | `string` | `'@cf/baai/bge-base-en-v1.5'` | Workers AI embedding model |\n| `onInsert` | `boolean` | `true` | Embed on INSERT operations |\n| `onUpdate` | `boolean \\| string[]` | `true` | Embed on UPDATE; array limits to specific fields |\n| `embeddingColumn` | `string` | `'embedding'` | Column to store the embedding vector |\n| `separator` | `string` | `' '` | Separator for joining multiple fields |\n| `metadata` | `string[]` | `[]` | Fields to include in Vectorize metadata |\n\n### onUpdate Options\n\n```typescript\n// Always re-embed on any update\nonUpdate: true\n\n// Never re-embed on update\nonUpdate: false\n\n// Only re-embed when specific fields change\nonUpdate: ['description', 'title']\n```\n\n## How It Works\n\n```\n┌─────────────────────────────────────────────────────────────────────┐\n│ Main API Worker │\n│ │\n│ ┌─────────────────────┐ ┌────────────────────┐ │\n│ │ POST /jobs │ │ Queue Consumer │ │\n│ │ │ │ │ │\n│ │ 1. Auth middleware │ │ 1. Workers AI │ │\n│ │ 2. Firewall │ │ embed() │ │\n│ │ 3. Guards │ │ 2. D1 update() │ │\n│ │ 4. Insert to D1 │ │ 3. Vectorize │ │\n│ │ 5. Enqueue job ─────┼───▶│ upsert() │ │\n│ └─────────────────────┘ └────────────────────┘ │\n│ ▲ │\n│ ┌─────────────────┴──────────────────┐ │\n│ │ EMBEDDINGS_QUEUE │ │\n│ └────────────────────────────────────┘ │\n└─────────────────────────────────────────────────────────────────────┘\n```\n\n1. **API Request** - POST/PATCH arrives and passes through auth, firewall, guards\n2. **Database Insert** - Record is created/updated in D1\n3. **Enqueue Job** - Embedding job is sent to Cloudflare Queue\n4. **Queue Consumer** - Processes job asynchronously:\n - Calls Workers AI to generate embedding\n - Updates D1 with embedding vector\n - Optionally upserts to Vectorize index\n\n## Security Model\n\n**Security is enforced at enqueue time, not consume time:**\n\n- Jobs are only enqueued after passing all security checks (auth, firewall, guards)\n- The queue consumer is an internal process that executes pre-validated jobs\n- If a user can't create a job posting, they can't trigger an embedding job\n\n## Generic Embeddings API\n\nIn addition to automatic embeddings on standard resource operations, Quickback generates a generic embeddings API endpoint that allows you to trigger embeddings on arbitrary content.\n\n### POST /api/v1/embeddings\n\nGenerate an embedding for any text content:\n\n```bash\ncurl -X POST https://your-api.workers.dev/api/v1/embeddings \\\n -H \"Content-Type: application/json\" \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -d '{\n \"content\": \"Text to embed\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\",\n \"table\": \"jobs\",\n \"id\": \"job_123\"\n }'\n```\n\n#### Request Body\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `content` | `string` | Yes | Text to generate embedding for |\n| `model` | `string` | No | Embedding model (defaults to table config or `@cf/baai/bge-base-en-v1.5`) |\n| `table` | `string` | No | Table to store embedding back to |\n| `id` | `string` | Conditional | Record ID to update (required if `table` is specified) |\n\n#### Response\n\n```json\n{\n \"queued\": true,\n \"jobId\": \"550e8400-e29b-41d4-a716-446655440000\",\n \"table\": \"jobs\",\n \"id\": \"job_123\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n}\n```\n\n### GET /api/v1/embeddings/tables\n\nList tables that have embeddings configured:\n\n```bash\ncurl https://your-api.workers.dev/api/v1/embeddings/tables \\\n -H \"Cookie: better-auth.session_token=...\"\n```\n\nResponse:\n\n```json\n{\n \"tables\": [\n {\n \"name\": \"jobs\",\n \"embeddingColumn\": \"embedding\",\n \"model\": \"@cf/baai/bge-base-en-v1.5\"\n }\n ]\n}\n```\n\n### Authentication & Authorization\n\nThe generic embeddings API requires authentication and uses the `activeOrgId` from the user's context to enforce organization-level isolation. Embedding jobs are scoped to the user's current organization.\n\n### Use Cases\n\nThe generic embeddings API is useful for:\n\n- **Batch embedding**: Embed content without going through CRUD routes\n- **Re-embedding**: Force re-generation of embeddings for existing records\n- **Preview embeddings**: Test embedding generation before persisting\n- **External content**: Embed content that doesn't fit your defined schemas\n\n## Generated Files\n\nWhen embeddings are configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/queue-consumer.ts` | Queue consumer handler for processing embedding jobs |\n| `src/routes/embeddings.ts` | Generic embeddings API routes |\n| `wrangler.toml` | Queue producer/consumer bindings, AI binding |\n| `src/env.d.ts` | `EMBEDDINGS_QUEUE`, `AI` types |\n| `src/index.ts` | Exports `queue` handler, mounts `/api/v1/embeddings` |\n\n### wrangler.toml additions\n\n```toml\n# Embeddings Queue\n[[queues.producers]]\nqueue = \"your-app-embeddings-queue\"\nbinding = \"EMBEDDINGS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"your-app-embeddings-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\n\n# Workers AI\n[ai]\nbinding = \"AI\"\n```\n\n## Multiple Fields\n\nEmbed multiple fields by concatenating them:\n\n```typescript\nembeddings: {\n fields: ['title', 'description', 'department'], // Joined with spaces by default\n // ...\n}\n```\n\nGenerated embedding text: `\"${title} ${description} ${department}\"`\n\n### Custom Separator\n\nUse `separator` to control how fields are joined. This is useful for sentence boundary detection:\n\n```typescript\nembeddings: {\n fields: ['title', 'description'],\n separator: '. ', // Join with period + space\n // ...\n}\n```\n\nGenerated code: `[result[0].title, result[0].description].filter(Boolean).join('. ')`\n\nThe `filter(Boolean)` ensures null or empty fields are excluded cleanly — no trailing separator when a field is absent.\n\n## Vectorize Integration\n\nIf you have a Vectorize index configured, embeddings are automatically upserted:\n\n```typescript\n// quickback.config.ts\nproviders: {\n database: {\n config: {\n vectorizeIndexName: 'jobs-embeddings', // Your Vectorize index\n vectorizeBinding: 'VECTORIZE',\n },\n },\n},\n```\n\nThe queue consumer will:\n1. Generate the embedding via Workers AI\n2. Store the vector in D1 (JSON string)\n3. Upsert to Vectorize with metadata\n\n### Vectorize Metadata\n\nInclude fields in Vectorize metadata for filtering:\n\n```typescript\nembeddings: {\n fields: ['description'],\n metadata: ['department', 'organizationId', 'status'],\n}\n```\n\nEnables queries like:\n```typescript\nconst results = await env.VECTORIZE.query(vector, {\n topK: 10,\n filter: { department: 'engineering' }\n});\n```\n\n## Schema Requirements\n\nYour schema must include the embedding column:\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 description: q.text().required(),\n department: q.text().optional(),\n status: q.text().required(),\n organizationId: q.scope(\"organization\"),\n\n // Embedding column — stores JSON array of floats\n embedding: q.text().optional(),\n },\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n read: {},\n create: {},\n update: {},\n delete: {},\n});\n```\n\n## Supported Models\n\nAny Workers AI embedding model can be used:\n\n| Model | Dimensions | Notes |\n|-------|------------|-------|\n| `@cf/baai/bge-base-en-v1.5` | 768 | Default, good general-purpose |\n| `@cf/baai/bge-small-en-v1.5` | 384 | Faster, smaller |\n| `@cf/baai/bge-large-en-v1.5` | 1024 | Higher quality |\n\nSee [Workers AI Models](https://developers.cloudflare.com/workers-ai/models/) for the full list.\n\n## Deployment\n\nAfter compiling with embeddings:\n\n1. **Create the queue:**\n ```bash\n wrangler queues create your-app-embeddings-queue\n ```\n\n2. **Deploy the worker:**\n ```bash\n wrangler deploy\n ```\n\nThe single worker handles both HTTP requests and queue consumption.\n\n## Monitoring\n\nQueue metrics are available in the Cloudflare dashboard:\n- Messages enqueued\n- Messages processed\n- Retry count\n- Consumer lag\n\nCheck queue health:\n```bash\nwrangler queues list\nwrangler queues consumer your-app-embeddings-queue\n```\n\n## Error Handling\n\nFailed jobs are automatically retried (up to `max_retries`):\n\n```typescript\n// In queue consumer\ntry {\n const embedding = await env.AI.run(job.model, { text: job.content });\n // ...\n message.ack();\n} catch (error) {\n console.error('[Queue] Embedding job failed:', error);\n message.retry(); // Will retry up to 3 times\n}\n```\n\nAfter max retries, the message is dead-lettered (if configured) or dropped.\n\n## Similarity Search Service\n\nFor applications that need typed similarity search with classification, you can define embedding search configurations using `defineEmbedding`. This generates a service layer with typed search functions.\n\n### Defining Search Configurations\n\nCreate a file in `services/embeddings/`:\n\n```typescript\n// services/embeddings/job-similarity.ts\n\nexport default defineEmbedding({\n name: 'job-similarity',\n description: 'Find similar job postings by description content',\n\n // Source configuration\n source: 'jobs', // Table name\n vectorIndex: 'VECTORIZE', // Binding name\n model: '@cf/baai/bge-base-en-v1.5',\n\n // Search configuration\n search: {\n threshold: 0.60, // Minimum similarity (default: 0.60)\n limit: 10, // Max results (default: 10)\n classify: {\n DUPLICATE_POSTING: 0.90, // Score >= 0.90 = DUPLICATE_POSTING\n SIMILAR_ROLE: 0.85, // Score >= 0.85 = SIMILAR_ROLE\n RELATED: 0.75, // Score >= 0.75 = RELATED\n },\n filters: ['department', 'organizationId'], // Filterable fields\n },\n\n // Generation triggers (beyond CRUD)\n triggers: {\n onQueueMessage: 'embed_job', // Listen for queue messages\n },\n});\n```\n\n### Generated Service Layer\n\nAfter compilation, a `createEmbeddings()` helper is generated in `src/lib/embeddings.ts`:\n\n```typescript\n\nexport const execute: ActionExecutor = async ({ ctx, input }) => {\n const embeddings = createEmbeddings(ctx.env);\n\n // Search with automatic classification\n const similar = await embeddings.jobSimilarity.search(\n 'Senior Full-Stack Engineer with React and Node.js experience',\n {\n department: 'engineering',\n limit: 5,\n threshold: 0.70,\n }\n );\n\n // Returns: [{ id, score: 0.87, classification: 'SIMILAR_ROLE', metadata }]\n for (const match of similar) {\n console.log(`${match.classification}: ${match.id} (${match.score})`);\n }\n\n return { similar };\n};\n```\n\n### Classification Thresholds\n\nResults are automatically classified based on similarity score:\n\n| Classification | Default Threshold | Meaning |\n|----------------|-------------------|---------|\n| `DUPLICATE_POSTING` | >= 0.90 | Near-identical job posting |\n| `SIMILAR_ROLE` | >= 0.85 | Strongly similar role and requirements |\n| `RELATED` | >= 0.75 | Topically related position |\n| `NEW` | < 0.75 | No significant match |\n\nCustomize thresholds per use case:\n\n```typescript\nsearch: {\n classify: {\n DUPLICATE_POSTING: 0.95, // Stricter duplicate detection\n SIMILAR_ROLE: 0.88,\n RELATED: 0.70, // Broader \"related\" category\n },\n}\n```\n\n### Gray Zone Detection\n\nFor cases where automatic classification isn't sufficient, use gray zone detection to get matches that need semantic evaluation:\n\n```typescript\nconst results = await embeddings.jobSimilarity.findWithGrayZone(\n 'Some job description text',\n { min: 0.60, max: 0.85 }\n);\n\n// Returns structured results:\n// {\n// high_confidence: [...], // Score >= 0.85 (auto-classified)\n// gray_zone: [...] // 0.60 <= score < 0.85 (needs review)\n// }\n\n// Process high confidence matches automatically\nfor (const match of results.high_confidence) {\n await markAsDuplicate(match.id);\n}\n\n// Queue gray zone for manual review\nfor (const match of results.gray_zone) {\n await queueForReview(match.id, match.score);\n}\n```\n\n### Generate Embeddings Directly\n\nGenerate embeddings without searching:\n\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Get raw embedding vector\nconst vector = await embeddings.jobSimilarity.embed(\n 'Text to embed'\n);\n// Returns: number[] (768 dimensions for bge-base)\n```\n\n### Multiple Search Configurations\n\nDefine different configurations for different use cases:\n\n```typescript\n// services/embeddings/candidate-similarity.ts\nexport default defineEmbedding({\n name: 'candidate-similarity',\n description: 'Match candidates by resume content',\n source: 'candidates',\n search: {\n threshold: 0.65,\n limit: 20,\n classify: {\n DUPLICATE_POSTING: 0.92,\n SIMILAR_ROLE: 0.80,\n RELATED: 0.65,\n },\n filters: ['source'],\n },\n});\n\n// services/embeddings/application-match.ts\nexport default defineEmbedding({\n name: 'application-match',\n description: 'Match applications to similar job postings',\n source: 'applications',\n search: {\n threshold: 0.70,\n limit: 5,\n classify: {\n DUPLICATE_POSTING: 0.95,\n SIMILAR_ROLE: 0.90,\n RELATED: 0.80,\n },\n filters: ['jobId', 'organizationId'],\n },\n});\n```\n\nUsage:\n```typescript\nconst embeddings = createEmbeddings(ctx.env);\n\n// Different search behaviors for different content types\nconst similarJobs = await embeddings.jobSimilarity.search(text, opts);\nconst similarCandidates = await embeddings.candidateSimilarity.search(text, opts);\nconst matchingApplications = await embeddings.applicationMatch.search(text, opts);\n```\n\n### Table-Level vs Service-Level\n\n| Feature | Table-level (`defineTable`) | Service-level (`defineEmbedding`) |\n|---------|----------------------------|----------------------------------|\n| Auto-embed on INSERT | ✅ | ❌ |\n| Auto-embed on UPDATE | ✅ | ❌ |\n| Custom search functions | ❌ | ✅ |\n| Classification thresholds | ❌ | ✅ |\n| Gray zone detection | ❌ | ✅ |\n| Filterable searches | ❌ | ✅ |\n| Queue message triggers | ❌ | ✅ |\n\n**Use both together:**\n- `defineTable` with `embeddings` config for automatic embedding generation\n- `defineEmbedding` for typed search functions with classification"
|
|
467
467
|
},
|
|
468
468
|
"stack/vector": {
|
|
469
469
|
"title": "Vector & AI",
|