@quickback-dev/cli 0.59.0 β 0.59.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +14 -1
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/schema.d.ts +10 -0
- package/dist/commands/schema.d.ts.map +1 -1
- package/dist/commands/schema.js +48 -16
- package/dist/commands/schema.js.map +1 -1
- package/dist/commands/schema.test.js +81 -1
- package/dist/commands/schema.test.js.map +1 -1
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +41 -21
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/file-loader.d.ts +10 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +41 -22
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/file-loader.test.js +20 -1
- package/dist/lib/file-loader.test.js.map +1 -1
- package/dist/lib/prepare-output.d.ts +2 -0
- package/dist/lib/prepare-output.d.ts.map +1 -1
- package/dist/lib/prepare-output.js +2 -2
- package/dist/lib/prepare-output.js.map +1 -1
- package/dist/lib/prepare-state-output.d.ts +33 -4
- package/dist/lib/prepare-state-output.d.ts.map +1 -1
- package/dist/lib/prepare-state-output.js +71 -12
- package/dist/lib/prepare-state-output.js.map +1 -1
- package/dist/lib/prepare-state-output.test.js +91 -11
- package/dist/lib/prepare-state-output.test.js.map +1 -1
- package/dist/lib/schema-sync/index.d.ts.map +1 -1
- package/dist/lib/schema-sync/index.js +39 -4
- package/dist/lib/schema-sync/index.js.map +1 -1
- package/dist/lib/schema-sync/index.test.js +89 -1
- package/dist/lib/schema-sync/index.test.js.map +1 -1
- package/dist/schema-engine/index.d.ts +1 -0
- package/dist/schema-engine/index.d.ts.map +1 -1
- package/dist/schema-engine/index.js +50 -0
- package/dist/schema-engine/index.js.map +3 -3
- package/dist/schema-engine/provider-dialects.d.ts +22 -0
- package/dist/schema-engine/provider-dialects.d.ts.map +1 -0
- package/dist/schema-engine/source-sync.d.ts +8 -0
- package/dist/schema-engine/source-sync.d.ts.map +1 -1
- package/dist/skill/SKILL.md +45 -0
- package/dist/skill/agents/quickback-specialist/AGENT.md +18 -1
- package/dist/skill/docs/changelog/index.md +28 -2
- package/dist/skill/docs/changelog/v0.1x.md +2 -2
- package/dist/skill/docs/configure/agents.md +19 -0
- package/dist/skill/docs/configure/index.md +1 -1
- package/dist/skill/docs/define/access.md +23 -820
- package/dist/skill/docs/define/actions/access.md +4 -4
- package/dist/skill/docs/define/areas.md +307 -4
- package/dist/skill/docs/define/authz-roles.md +164 -0
- package/dist/skill/docs/define/changesets.md +1 -1
- package/dist/skill/docs/define/fga.md +1 -1
- package/dist/skill/docs/define/firewall.md +3 -3
- package/dist/skill/docs/define/index.md +32 -3
- package/dist/skill/docs/define/masking.md +1 -1
- package/dist/skill/docs/define/permissions.md +1 -1
- package/dist/skill/docs/define/read.md +103 -1
- package/dist/skill/docs/define/relationships.md +313 -0
- package/dist/skill/docs/define/scopes.md +1 -1
- package/dist/skill/docs/platform/realtime/using-realtime.md +1 -1
- package/dist/skill/docs/platform/storage/r2.md +39 -0
- package/dist/skill/docs/platform/webhooks/inbound.md +17 -6
- package/dist/skill/docs/start/deploy-browser.md +118 -0
- package/dist/skill/docs/start/deploy-owner-access.md +62 -0
- package/dist/skill/docs/start/deploy.md +2 -0
- package/dist/skill/docs/tooling/cli.md +22 -0
- package/dist/skill/docs/tooling/output.md +64 -0
- package/package.json +1 -1
- package/src/skill/SKILL.md +45 -0
- package/src/skill/agents/quickback-specialist/AGENT.md +18 -1
- package/src/skill/docs/changelog/index.md +28 -2
- package/src/skill/docs/changelog/v0.1x.md +2 -2
- package/src/skill/docs/configure/agents.md +19 -0
- package/src/skill/docs/configure/index.md +1 -1
- package/src/skill/docs/define/access.md +23 -820
- package/src/skill/docs/define/actions/access.md +4 -4
- package/src/skill/docs/define/areas.md +307 -4
- package/src/skill/docs/define/authz-roles.md +164 -0
- package/src/skill/docs/define/changesets.md +1 -1
- package/src/skill/docs/define/fga.md +1 -1
- package/src/skill/docs/define/firewall.md +3 -3
- package/src/skill/docs/define/index.md +32 -3
- package/src/skill/docs/define/masking.md +1 -1
- package/src/skill/docs/define/permissions.md +1 -1
- package/src/skill/docs/define/read.md +103 -1
- package/src/skill/docs/define/relationships.md +313 -0
- package/src/skill/docs/define/scopes.md +1 -1
- package/src/skill/docs/platform/realtime/using-realtime.md +1 -1
- package/src/skill/docs/platform/storage/r2.md +39 -0
- package/src/skill/docs/platform/webhooks/inbound.md +17 -6
- package/src/skill/docs/start/deploy-browser.md +118 -0
- package/src/skill/docs/start/deploy-owner-access.md +62 -0
- package/src/skill/docs/start/deploy.md +2 -0
- package/src/skill/docs/tooling/cli.md +22 -0
- package/src/skill/docs/tooling/output.md +64 -0
package/dist/docs/content.js
CHANGED
|
@@ -43,11 +43,11 @@ export const DOCS = {
|
|
|
43
43
|
},
|
|
44
44
|
"changelog": {
|
|
45
45
|
"title": "Changelog",
|
|
46
|
-
"content": "The current release series. Older entries are archived by version range:\n\n- [v0.50 β v0.54](/changelog/v0.5x)\n- [v0.40 β v0.48](/changelog/v0.4x)\n- [v0.32 β v0.39](/changelog/v0.3x)\n- [v0.20 β v0.29](/changelog/v0.2x)\n- [v0.18 and earlier](/changelog/v0.1x)\n\n## Unreleased\n\n### BREAKING Β· Masking: sensitive columns now require an explicit decision\n\n**The compiler no longer decides whether to mask a column. It refuses to\ncompile until you do.**\n\nQuickback has always detected sensitive column names (`email`, `ssn`, `apiKey`,\n`stripeSecret`, `refreshToken`, β¦) and silently attached a default mask rule\nplus a warning. That was wrong in both directions: it broke list views nobody\nasked it to break, and it created a false sense of protection. Worse, only\n*some* surfaces read the auto-detected set β through v0.58.3 the HTTP response\npath applied **declared-only** masking while realtime and live views applied\ndetected-plus-declared, so an auto-detected secret was redacted over WebSocket\nand returned in **plaintext** on `GET /:id`, list, `POST` and `PATCH`, and\nstayed freely filterable and sortable. Making detection non-silent removes that\nwhole bug class by construction: the set of masked columns is now exactly the\nset you declared, so no two surfaces can disagree about it.\n\nEvery detected column must now carry an explicit decision in `masking`:\n\n```typescript\nmasking: {\n apiKey: { type: 'redact', show: { roles: ['admin'] } }, // yes, mask it\n email: false, // no, reviewed\n}\n```\n\n`false` is a new first-class answer meaning **reviewed β not sensitive here**:\nthe value is returned in full and the column stays freely `?filter=`-able,\n`?sort=`-able and `?search=`-able. An omitted key is not a decision.\n\n#### Migrating\n\nCompile the project. For each error, you get the resource name, every undecided\ncolumn, its suggested rule, and a paste-ready `masking` block with both answers\nper column β delete the wrong line from each pair:\n\n```\ncustomers: 2 columns match Quickback's sensitive-column patterns but carry no masking decision.\n ...\n masking: {\n email: { type: 'email', show: { or: 'owner', roles: ['admin'] } }, // mask it\n // email: false, // β¦or this instead: reviewed, not sensitive here\n },\n```\n\nTwo ways to resolve each column:\n\n1. **Mask it** β keep the suggested rule (or write your own). The value is\n redacted for callers outside `show.roles`, and only those roles may\n filter/sort/search it. Widen the query surface independently with\n `query: { roles: [...] }`; drop `or: 'owner'` if the table has no owner\n column.\n2. **Don't mask it** β `column: false`. Nothing changes about how the column\n behaves; you've recorded that somebody looked.\n\nA false positive (`cc` on an accounting table, `webhook` on a config row) costs\none line. That is the intended trade: the compiler asks about everything it\nrecognises rather than guessing.\n\nDetection itself is unchanged β same keyword table, same suffix matching, and\nthe suggested rule is still `show: { or: 'owner', roles: ['admin'] }`. It is\nnow a suggestion in an error message rather than a default that applies on its\nown. See [Masking](/define/masking).\n\n### Security fix: live views and realtime subscribe now evaluate `read.access`\n\nThe live-view materialize route (`GET /api/v1/views/:view/:rootId`) and the\nview-subscribe ws-ticket lane applied the firewall and masking but **never the\nrole gate**. A firewall is a tenant filter, not a role gate, so a same-org\nmember who was correctly `403`'d on `GET /<table>/:id` received the full row β\nand every included child row β through the view, and could subscribe to its\nlive deltas.\n\nEvery table on a [live view](/platform/realtime/live-views#security) surface (the\nroot *and* each included child) is now gated by its own `read: { access }`,\n**deny-on-any**: a root denial is a `403`, an included-table denial collapses to\n`404` with the firewall miss. Both entry points enforce it, and the gate lives\ninside the materializer so resync inherits it too.\n\nShapes the view path cannot decide now **fail closed at compile time** instead\nof silently passing: function-form access, `relationship:`/`fga:` arms, and a\n`record:` condition on an *included* table. A `record:` condition on the root\nis evaluated post-fetch against the materialized row, the same two-phase gate\n`GET /:id` uses.\n\n### Security fix: a team-only firewall no longer opens every tenant\n\nA resource whose **only** tenant predicate was team-scoped emitted no `WHERE`\nfilter at all when `ctx.activeTeamId` was absent, so every authenticated caller\ncould read, update and delete every tenant's rows.\n\nThe team predicate is rendered drop-when-absent β correct while an org arm still\nbounds the query (the teamless rest-of-org slice), but with team as the sole arm\n\"drop the team filter\" meant \"drop the entire tenant boundary\". The claim is\ngenuinely absent in ordinary setups: the Better Auth teams sub-plugin is opt-in,\nand the external auth provider never supplies it. Auto-detection also derives\nteam-only isolation for any table carrying a `teamId` and no `organizationId`,\nwith no explicit `firewall` block.\n\nAn absent claim now **denies** when team is the sole tenant arm. Soft-delete and\nliteral predicates are row filters, not tenant boundaries, so they don't count as\na co-existing arm. Team alongside org is unchanged.\n\nPaired with a compile-time gate: a team-only firewall on a project without the\nteams sub-plugin is now a build error rather than a resource that denies every\nrequest, since that claim can never be populated. See\n[Firewall](/define/firewall).\n\n### Security fixes: managed file storage\n\nThree scope-expansion holes in the managed file subsystem (`managed: true`):\n\n- **Removed organization members kept reading private files.** The files worker\n read `activeOrgId` straight off the session row; a session outlives\n membership, and a bucket with no `readRoles` had no second gate. Membership is\n now re-checked per request and a missing member row clears the organization\n before any org-scoped check.\n- **JWT claims were trusted as current.** The worker's JWT fast path took `orgId`\n and `role` from the signed token β a mint-time snapshot. Both are now\n re-derived from the database. The lookup only runs when a request carries an\n org claim, so user-scoped and public reads stay lookup-free.\n- **`writeScope: \"user\"` buckets bound nothing to the owner.** Keys come from a\n client-supplied path and the R2 write landed *before* the unique-key metadata\n insert could reject it, so a member who knew a peer's key overwrote their\n object β with no undo. Presigned uploads were worse: they signed a `PUT` URL\n and deleted the victim's metadata row. Both paths now check ownership first,\n and for presign that check runs *before signing*, since the URL is itself the\n write capability. The metadata row is also reserved before the R2 write, so a\n failed insert can no longer leave an overwrite behind.\n\nSee [File storage](/platform/storage/r2).\n\n## v0.58.1βv0.58.3 β July 28, 2026\n\n> No changelog entries were written for these three patch releases. Reconstructed\n> from git: compilation and generated-output hardening (`fc7d54fb`) and a\n> string-keyed batch FK visibility set that removes spurious `fkNotFound`\n> (`96f764ed`) in `0.58.1`; a CI deploy-serialization fix in `0.58.2`\n> (`2bf00e9c`). `0.58.3` was published from CI and has no bump commit in this\n> repository β its contents are not reconstructible from git history here.\n\n## v0.58.0 β July 28, 2026\n\n### `?include=<ownsRelation>` β the aggregate reader lands\n\n`read.include` now accepts **owns relation names** alongside FK columns:\n`?include=reactions` on a changeset root embeds the aggregate's owned child\nrows (pivot on the root PK, match the child's declared `fk`), landing in the\nsame top-level `included` map keyed by include token, then row PK. The child's\nfull security surface applies exactly as for FK embeds β pre-record-evaluable\n`read.access` (compile-enforced), firewall ANDed into the fetch on the\ncaller-claims handle, masking, and `fields[<token>]` sparse projection. The\n`?fields=` pivot guard follows the direction: an owns embed requires the\n**source PK** in the projection (an FK embed still requires the FK column).\nThis closes the changeset design's phase-2 reader β write the aggregate with\nthe changeset media type, read it back with `?include=`.\n\n### `afterCommit.reindex` + `afterCommit.notify` β the 06 fast-follows land\n\nThe two deliveries deferred out of afterCommit v1 now ship, riding the same\npost-commit dispatch seam (best-effort, `waitUntil`, never rolling back the\ncommitted changeset):\n\n- **`reindex: true`** re-enqueues the committed **root row** for embedding\n regeneration on the same at-least-once `EMBEDDINGS_QUEUE` lane the plain\n routes use β after the tx commits, so a rolled-back changeset produces no\n orphan jobs. Fail-closed: requires the root's `embeddings` block; honors\n `onInsert`/`onUpdate: false`; a field-watch array means \"always\" on the\n aggregate lane. The owns validator's embeddings warning now clears for a\n reindex-declaring root (owned children still warn β root row only).\n- **`notify`** sends a device push via the web-push provider (compile error\n without `push: { provider: 'web-push' }`). The audience is a\n `defineRealtimeDelivery` profile resolved with the **same disclosure\n gates as `broadcast`** β masked columns, `q.stamp` proven identity, and\n child-id enumeration are shared code, not a parallel set. Title/body/url/\n tag are `{key}` templates over a gate-checked payload map; an unmapped\n placeholder is a compile error, a null value at runtime pushes to nobody.\n Scope-keyed deliveries fan to `scope:<room>` subscription tags; user\n deliveries to the user's devices; roles AND-compose.\n\nA reindex- or notify-only `afterCommit` no longer requires realtime\ninfrastructure β the ws-infra gate now applies only to `broadcast`/`realtime`\nlanes.\n\n## v0.57.1 β July 28, 2026\n\n> No changelog entry was written for this release. Reconstructed from git: a\n> polish pass over `0.57.0` β `q.table` column initializers that cannot be\n> resolved now throw instead of dropping silently (`ace6cf17`), the scope-grant\n> gate distinguishes \"permission arm present\" from \"no arm at all\"\n> (`1b7a5773`), tenant-scope arrow endpoints and object-thunk references parse\n> again so authz analysis is restored (`ad53b924`), and the anchored fallback\n> fails closed (`48c70370`).\n\n## v0.57.0 β July 28, 2026\n\n### Typed scoped `db` on every Neon mode + write-side audit forbids\n\nThe action `db` is now schema-aware on **all** Neon connection modes, not just\nHyperdrive: http mode gets the same insert relaxation and typed reads with\n`.transaction` **blocked at the type level** (the neon-http driver throws at\nruntime β the type now says so instead of a 500), websocket mode gets the full\ninteractive-tx flavor. With D1 already typed, every supported provider's action\n`db` now carries the schema β including the `SealedValue` brand on `.sealed()`\ncolumns, so string-processing a sealed value is a compile error everywhere.\n\nOn every typed provider, the compiler-managed audit keys are now `?: never` in\n`.insert().values()` **and** the newly-typed `.update().set()`: the audit\nwrapper hard-stamps them from the verified caller, so a supplied value was\nalways discarded β now it's a compile error instead of a silent lie.\n`.set({ deletedAt })` stays allowed (the soft-delete signal).\n\n### Hard-stamp unification β one audit-actor contract\n\nThe scoped db's dead \"fill-if-absent\" actor lane is gone: on every wrapped\nhandle, `createdBy`/`modifiedBy` come from the verified principal, period (the\nraw client remains the documented escape for system writes that own their\nprovenance). Three attribution gaps closed with it: cron schedules' and queue\nhandlers' `withInternalContext` now hand out an **audit-wrapped** db, so\n`system:cron-<name>` / `system:queue-<name>` actually land on audit columns;\nupserts into encrypted/sealed tables now stamp `modifiedAt`/`modifiedBy` on the\n`onConflictDoUpdate` conflict branch like every other write; and an org-scoped\nchild table whose source can't accept the injected `organizationId` column now\nfails the compile instead of silently shipping without its tenant column.\n\n### Visible audit columns β `...q.audit()` / `...q.softDelete()` + canon validator\n\nThe compiler-managed audit quartet and soft-delete pair can now be **declared visibly**\nin authored feature files: q-DSL tables spread `...q.audit()` / `...q.softDelete()` into\nthe columns object (types flow through β `$infer` shows `createdAt`/`modifiedBy`/β¦ on the\nauthor's own table object), raw Drizzle tables declare the canonical lines literally.\n`quickback migrate visible-columns` codemods an existing project in one shot; emitted\noutput is unchanged either way (the spreads expand to the exact injector lines).\n\nWith visibility comes validation, **on by default**: every feature table must declare its\nmanaged columns visibly (`...q.audit()` / `...q.softDelete()` or the canonical literal\nlines β one `quickback migrate visible-columns` run), and every managed column that appears\nin authored source is checked against the canonical spec β insert-time default chains on\n`createdAt`/`modifiedAt` (+`$onUpdate`), nullable no-default actor columns, nullable\nno-default `deletedAt`, canonical SQL names, never `.encrypted()`/`.sealed()`. Divergence\n(silently accepted before) and missing declarations **fail the build**, with soft-delete\npresence pinned to `crud.delete.mode`. Opt out with\n`compiler.features.visibleAuditColumns: false`, which downgrades divergence to warnings and\nrestores invisible injection. Unknown spreads in a q-DSL columns object are now a compile\nerror instead of being silently dropped.\n\nAlso in this line: `q.table`'s `$insert` type is honest (required vs defaulted/stamped\ncolumns; audit keys are `?: never` β the wrapper hard-stamps them), `$infer` includes the\naudit columns, and the canonical column definitions collapsed into one shared spec\n(`constants/managed-columns.ts`) consumed by the injectors, meta augmentation, request\nvalidation, spread expansion, and the new validator.\n\n## v0.56.0βv0.56.11 β July 21β27, 2026\n\n> No changelog entries were written for the v0.56 line (twelve releases).\n> Reconstructed from git: feature-area follow-through β generated CRUD/changeset\n> routes claimed by an area prefix (`d33262e8`), feature-area transition route\n> adapters (`05d57940`), a fail-closed guard for generated routes under an area\n> prefix (`23f1f58d`), and a run of cross-feature resolution fixes\n> (`b6984a22`, `747dfad4`, `fb0cfb41`, `26bc569f`, `ae76e3e8`) β plus\n> relationship-proven `SESSION` parity for `q.stamp` (`b11fabfe`), an RLS\n> serial-sequence sweep with an audit-schema latch and `fga_tuples` backstop\n> (`299c93ee`), changeset trigger parity and `define-action` typing fixes\n> (`4c64edab`), and R2 files-migration scheduling gated on managed files\n> (`29b908f2`).\n\n## v0.55.1 β July 21, 2026\n\n### Feature areas β hierarchical authz grouping (`_area.ts`)\n\nA folder under `features/` carrying an `_area.ts` (`export default defineArea({...})`) is now\nan **area**: it declares a route prefix + admission lanes (the same shape as a project\nnamespace, incl. `mintScope`/`acceptScope`) and an authz vocabulary β relationships, composed\nroles, named gates, tenant anchors, scope kinds β that every feature inside the folder\nreferences by bare name. The vocabulary is visible to the area's subtree ONLY: the compiler\nchecks every reference channel (access roles/gates/scoped aliases, action `access`/`anchor`,\nfirewall `via`/`{ rule }`/`{ tenant }` arms, `ctx.scope.<kind>` accessors, auth-view tenant\nincludes, realtime handshake roles, table-level namespace lanes, and other `_area.ts` nodes)\nand fails the build on any outside reference. Root `authz` stays the global level, and root\nbodies may reference root-declared names only (no laundering an area name project-wide).\n\nFail-closed rules shipped with it: re-declaring an inherited name is a compile error (no\noverrides in v1); a descendant action whose path opts out of the area prefix must carry an\nexplicit `route: 'self'` marker; relative `path: './β¦'` resolves against the area prefix with\ndot segments rejected; foreign features can't claim paths (or table-level namespace prefixes)\nunder an area's prefix; nested areas may add vocabulary but not mount a second prefix under a\nmounted ancestor (unlinked parent/child admission never compiles); and area-tree projects\nmust declare `requires: ['feature-areas']` β the marker reaches the compiler through ANY CLI\nversion, so an area-unaware toolchain is rejected instead of silently dropping nested\nfeatures. Area projects also emit a reviewed audit artifact, `quickback/authz-manifest.json`\n(area tree, declared names, member features, area-gated vs self-gated actions, root-config\nnamespace consumers), and the generated `AGENTS.md` gains a feature-areas section.\n\nByte-parity guarantee: a flat root-authz project re-expressed as an area tree compiles to\nbyte-identical output (the emit-site key-order determinism pass from v2 step 0 makes the fold\norder provably irrelevant). See [Feature areas](/define/areas).\n\nOne cosmetic side effect of that determinism pass: the first recompile of an existing project\non this release may reorder generated relationship-table **import lines** (they are now\nemitted in sorted order instead of authz-map insertion order). The reordering is a one-time,\nbehavior-free diff.\n\n### Access rules: named gates (`authz.rules`) and tenant anchors (`authz.tenants`)\n\nTwo new root-`authz` blocks let you declare a row/role rule once and stamp it by name instead\nof copying predicates across files. A **named gate** in `authz.rules` bundles up to three\narms β `who` (roles), `record:` (record-aware predicates), and `firewall` lanes β under one\nname, referenced by bare name in any `access: { roles: [...] }` array (applies who + record)\nand as `{ rule: '<name>' }` in a resource's `firewall:` (splices the lanes into the top-level\nAND array β a reference can only *narrow* row admission, never widen it). A **tenant anchor**\nin `authz.tenants` names the tenant predicate (`{ column, equals }`, claim side locked to\nverified ctx claims) and is written `{ tenant: 'org' }` in firewalls β with an optional\nper-site column override β and `tenant: 'org'` in auth-view includes. Expansion happens at\ncompile time; emitted SQL is byte-identical to the inline spelling.\n\nEverything fails closed: gate/role/scoped-role/`+`/`:` name collisions, `+` hierarchy sugar\ninside rule bodies, `{ rule }` inside `all`/`any` groups, firewall-less gates referenced from\n`firewall:`, firewall-bearing gates on actions or in `masking.show`, and an access-side\nreference to a firewall-bearing gate whose lanes the resource doesn't also stamp are all\ncompile errors. Gates in `realtime.requiredRoles` lower to static who-roles at the handshake;\na declared non-empty list that lowers to nothing is a compile error, never a silent `[]`. A\nnew `AUTHZ_UNKNOWN_ROLE_NAME` warning flags reference-shaped names that resolve to nothing.\nSee [named gates](/define/access#named-gates-authzrules) Β·\n[`{ tenant }`](/define/firewall#named-tenant-anchors-tenant) Β·\n[`{ rule }`](/define/firewall#named-gate-references-rule).\n\n## v0.55.0 β July 17, 2026\n\n### Generated projects ship an `AGENTS.md`\n\nEvery compiled project now emits an `AGENTS.md` at its root β the file coding agents read first β weaving Quickback's security model and a *\"when to use what\"* decision guide into the output. An agent editing the features is steered to the right primitive: a **view** for a filtered read, a **transition** for a guarded state change, an **action** for custom logic, **guards**/**masking** for field-level control, **named invalidations** for realtime refresh β each with a `docs.quickback.dev` link. It also documents the access tiers (incl. `SESSION`/`SCOPED`), the `WHERE column = value` firewall model with the org-OR-scope `{ any: [...] }` pattern for non-org callers, and the fail-closed coherence guardrail (with the *\"never `exception: true` as a workaround\"* rule). Regenerated on every compile."
|
|
46
|
+
"content": "The current release series. Older entries are archived by version range:\n\n- [v0.50 β v0.54](/changelog/v0.5x)\n- [v0.40 β v0.48](/changelog/v0.4x)\n- [v0.32 β v0.39](/changelog/v0.3x)\n- [v0.20 β v0.29](/changelog/v0.2x)\n- [v0.18 and earlier](/changelog/v0.1x)\n\n## v0.59.1 β July 29, 2026\n\n### Fix: auth and features D1 bindings could collapse onto one name\n\nA project whose database config carried a single `binding` (e.g.\n`binding: 'DB'`) emitted **two** `[[d1_databases]]` entries bound to the same\nname, while the generated code still called `env.AUTH_DB`. Half the runtime\ntherefore reached a database with no auth tables.\n\nIn split mode β the default for `cloudflare-d1` β `binding` names the\n**features** database only; auth is a separate D1 with its own `authBinding`.\nThe service resolver was letting auth fall back to the generic `binding`, so one\nvalue drove both.\n\nIt went unnoticed because three places resolved the auth binding independently\nand only one carried that extra fallback, so the reserved-name validator\ncomputed `AUTH_DB`/`DB`, saw no clash, and passed while the wrangler emit\ncomputed `DB`/`DB`. All three now agree.\n\nA binding collision in split mode is also a **compile error** now rather than a\nsilently broken deploy, naming `authBinding` / `featuresBinding` and the\n`splitDatabases: false` single-database alternative as the fixes.\n\nNot introduced by v0.59.0 β the same behaviour is present in v0.58.3 and\nearlier. If you hit it, set `authBinding` explicitly or upgrade.\n\n## v0.59.0 β July 29, 2026\n\n### BREAKING Β· Masking: sensitive columns now require an explicit decision\n\n**The compiler no longer decides whether to mask a column. It refuses to\ncompile until you do.**\n\nQuickback has always detected sensitive column names (`email`, `ssn`, `apiKey`,\n`stripeSecret`, `refreshToken`, β¦) and silently attached a default mask rule\nplus a warning. That was wrong in both directions: it broke list views nobody\nasked it to break, and it created a false sense of protection. Worse, only\n*some* surfaces read the auto-detected set β through v0.58.3 the HTTP response\npath applied **declared-only** masking while realtime and live views applied\ndetected-plus-declared, so an auto-detected secret was redacted over WebSocket\nand returned in **plaintext** on `GET /:id`, list, `POST` and `PATCH`, and\nstayed freely filterable and sortable. Making detection non-silent removes that\nwhole bug class by construction: the set of masked columns is now exactly the\nset you declared, so no two surfaces can disagree about it.\n\nEvery detected column must now carry an explicit decision in `masking`:\n\n```typescript\nmasking: {\n apiKey: { type: 'redact', show: { roles: ['admin'] } }, // yes, mask it\n email: false, // no, reviewed\n}\n```\n\n`false` is a new first-class answer meaning **reviewed β not sensitive here**:\nthe value is returned in full and the column stays freely `?filter=`-able,\n`?sort=`-able and `?search=`-able. An omitted key is not a decision.\n\n#### Migrating\n\nCompile the project. For each error, you get the resource name, every undecided\ncolumn, its suggested rule, and a paste-ready `masking` block with both answers\nper column β delete the wrong line from each pair:\n\n```\ncustomers: 2 columns match Quickback's sensitive-column patterns but carry no masking decision.\n ...\n masking: {\n email: { type: 'email', show: { or: 'owner', roles: ['admin'] } }, // mask it\n // email: false, // β¦or this instead: reviewed, not sensitive here\n },\n```\n\nTwo ways to resolve each column:\n\n1. **Mask it** β keep the suggested rule (or write your own). The value is\n redacted for callers outside `show.roles`, and only those roles may\n filter/sort/search it. Widen the query surface independently with\n `query: { roles: [...] }`; drop `or: 'owner'` if the table has no owner\n column.\n2. **Don't mask it** β `column: false`. Nothing changes about how the column\n behaves; you've recorded that somebody looked.\n\nA false positive (`cc` on an accounting table, `webhook` on a config row) costs\none line. That is the intended trade: the compiler asks about everything it\nrecognises rather than guessing.\n\nDetection itself is unchanged β same keyword table, same suffix matching, and\nthe suggested rule is still `show: { or: 'owner', roles: ['admin'] }`. It is\nnow a suggestion in an error message rather than a default that applies on its\nown. See [Masking](/define/masking).\n\n### Security fix: live views and realtime subscribe now evaluate `read.access`\n\nThe live-view materialize route (`GET /api/v1/views/:view/:rootId`) and the\nview-subscribe ws-ticket lane applied the firewall and masking but **never the\nrole gate**. A firewall is a tenant filter, not a role gate, so a same-org\nmember who was correctly `403`'d on `GET /<table>/:id` received the full row β\nand every included child row β through the view, and could subscribe to its\nlive deltas.\n\nEvery table on a [live view](/platform/realtime/live-views#security) surface (the\nroot *and* each included child) is now gated by its own `read: { access }`,\n**deny-on-any**: a root denial is a `403`, an included-table denial collapses to\n`404` with the firewall miss. Both entry points enforce it, and the gate lives\ninside the materializer so resync inherits it too.\n\nShapes the view path cannot decide now **fail closed at compile time** instead\nof silently passing: function-form access, `relationship:`/`fga:` arms, and a\n`record:` condition on an *included* table. A `record:` condition on the root\nis evaluated post-fetch against the materialized row, the same two-phase gate\n`GET /:id` uses.\n\n### Security fix: a team-only firewall no longer opens every tenant\n\nA resource whose **only** tenant predicate was team-scoped emitted no `WHERE`\nfilter at all when `ctx.activeTeamId` was absent, so every authenticated caller\ncould read, update and delete every tenant's rows.\n\nThe team predicate is rendered drop-when-absent β correct while an org arm still\nbounds the query (the teamless rest-of-org slice), but with team as the sole arm\n\"drop the team filter\" meant \"drop the entire tenant boundary\". The claim is\ngenuinely absent in ordinary setups: the Better Auth teams sub-plugin is opt-in,\nand the external auth provider never supplies it. Auto-detection also derives\nteam-only isolation for any table carrying a `teamId` and no `organizationId`,\nwith no explicit `firewall` block.\n\nAn absent claim now **denies** when team is the sole tenant arm. Soft-delete and\nliteral predicates are row filters, not tenant boundaries, so they don't count as\na co-existing arm. Team alongside org is unchanged.\n\nPaired with a compile-time gate: a team-only firewall on a project without the\nteams sub-plugin is now a build error rather than a resource that denies every\nrequest, since that claim can never be populated. See\n[Firewall](/define/firewall).\n\n### Security fixes: managed file storage\n\nThree scope-expansion holes in the managed file subsystem (`managed: true`):\n\n- **Removed organization members kept reading private files.** The files worker\n read `activeOrgId` straight off the session row; a session outlives\n membership, and a bucket with no `readRoles` had no second gate. Membership is\n now re-checked per request and a missing member row clears the organization\n before any org-scoped check.\n- **JWT claims were trusted as current.** The worker's JWT fast path took `orgId`\n and `role` from the signed token β a mint-time snapshot. Both are now\n re-derived from the database. The lookup only runs when a request carries an\n org claim, so user-scoped and public reads stay lookup-free.\n- **`writeScope: \"user\"` buckets bound nothing to the owner.** Keys come from a\n client-supplied path and the R2 write landed *before* the unique-key metadata\n insert could reject it, so a member who knew a peer's key overwrote their\n object β with no undo. Presigned uploads were worse: they signed a `PUT` URL\n and deleted the victim's metadata row. Both paths now check ownership first,\n and for presign that check runs *before signing*, since the URL is itself the\n write capability. The metadata row is also reserved before the R2 write, so a\n failed insert can no longer leave an overwrite behind.\n\nSee [File storage](/platform/storage/r2).\n\n## v0.58.1βv0.58.3 β July 28, 2026\n\n> No changelog entries were written for these three patch releases. Reconstructed\n> from git: compilation and generated-output hardening (`fc7d54fb`) and a\n> string-keyed batch FK visibility set that removes spurious `fkNotFound`\n> (`96f764ed`) in `0.58.1`; a CI deploy-serialization fix in `0.58.2`\n> (`2bf00e9c`). `0.58.3` was published from CI and has no bump commit in this\n> repository β its contents are not reconstructible from git history here.\n\n## v0.58.0 β July 28, 2026\n\n### `?include=<ownsRelation>` β the aggregate reader lands\n\n`read.include` now accepts **owns relation names** alongside FK columns:\n`?include=reactions` on a changeset root embeds the aggregate's owned child\nrows (pivot on the root PK, match the child's declared `fk`), landing in the\nsame top-level `included` map keyed by include token, then row PK. The child's\nfull security surface applies exactly as for FK embeds β pre-record-evaluable\n`read.access` (compile-enforced), firewall ANDed into the fetch on the\ncaller-claims handle, masking, and `fields[<token>]` sparse projection. The\n`?fields=` pivot guard follows the direction: an owns embed requires the\n**source PK** in the projection (an FK embed still requires the FK column).\nThis closes the changeset design's phase-2 reader β write the aggregate with\nthe changeset media type, read it back with `?include=`.\n\n### `afterCommit.reindex` + `afterCommit.notify` β the 06 fast-follows land\n\nThe two deliveries deferred out of afterCommit v1 now ship, riding the same\npost-commit dispatch seam (best-effort, `waitUntil`, never rolling back the\ncommitted changeset):\n\n- **`reindex: true`** re-enqueues the committed **root row** for embedding\n regeneration on the same at-least-once `EMBEDDINGS_QUEUE` lane the plain\n routes use β after the tx commits, so a rolled-back changeset produces no\n orphan jobs. Fail-closed: requires the root's `embeddings` block; honors\n `onInsert`/`onUpdate: false`; a field-watch array means \"always\" on the\n aggregate lane. The owns validator's embeddings warning now clears for a\n reindex-declaring root (owned children still warn β root row only).\n- **`notify`** sends a device push via the web-push provider (compile error\n without `push: { provider: 'web-push' }`). The audience is a\n `defineRealtimeDelivery` profile resolved with the **same disclosure\n gates as `broadcast`** β masked columns, `q.stamp` proven identity, and\n child-id enumeration are shared code, not a parallel set. Title/body/url/\n tag are `{key}` templates over a gate-checked payload map; an unmapped\n placeholder is a compile error, a null value at runtime pushes to nobody.\n Scope-keyed deliveries fan to `scope:<room>` subscription tags; user\n deliveries to the user's devices; roles AND-compose.\n\nA reindex- or notify-only `afterCommit` no longer requires realtime\ninfrastructure β the ws-infra gate now applies only to `broadcast`/`realtime`\nlanes.\n\n## v0.57.1 β July 28, 2026\n\n> No changelog entry was written for this release. Reconstructed from git: a\n> polish pass over `0.57.0` β `q.table` column initializers that cannot be\n> resolved now throw instead of dropping silently (`ace6cf17`), the scope-grant\n> gate distinguishes \"permission arm present\" from \"no arm at all\"\n> (`1b7a5773`), tenant-scope arrow endpoints and object-thunk references parse\n> again so authz analysis is restored (`ad53b924`), and the anchored fallback\n> fails closed (`48c70370`).\n\n## v0.57.0 β July 28, 2026\n\n### Typed scoped `db` on every Neon mode + write-side audit forbids\n\nThe action `db` is now schema-aware on **all** Neon connection modes, not just\nHyperdrive: http mode gets the same insert relaxation and typed reads with\n`.transaction` **blocked at the type level** (the neon-http driver throws at\nruntime β the type now says so instead of a 500), websocket mode gets the full\ninteractive-tx flavor. With D1 already typed, every supported provider's action\n`db` now carries the schema β including the `SealedValue` brand on `.sealed()`\ncolumns, so string-processing a sealed value is a compile error everywhere.\n\nOn every typed provider, the compiler-managed audit keys are now `?: never` in\n`.insert().values()` **and** the newly-typed `.update().set()`: the audit\nwrapper hard-stamps them from the verified caller, so a supplied value was\nalways discarded β now it's a compile error instead of a silent lie.\n`.set({ deletedAt })` stays allowed (the soft-delete signal).\n\n### Hard-stamp unification β one audit-actor contract\n\nThe scoped db's dead \"fill-if-absent\" actor lane is gone: on every wrapped\nhandle, `createdBy`/`modifiedBy` come from the verified principal, period (the\nraw client remains the documented escape for system writes that own their\nprovenance). Three attribution gaps closed with it: cron schedules' and queue\nhandlers' `withInternalContext` now hand out an **audit-wrapped** db, so\n`system:cron-<name>` / `system:queue-<name>` actually land on audit columns;\nupserts into encrypted/sealed tables now stamp `modifiedAt`/`modifiedBy` on the\n`onConflictDoUpdate` conflict branch like every other write; and an org-scoped\nchild table whose source can't accept the injected `organizationId` column now\nfails the compile instead of silently shipping without its tenant column.\n\n### Visible audit columns β `...q.audit()` / `...q.softDelete()` + canon validator\n\nThe compiler-managed audit quartet and soft-delete pair can now be **declared visibly**\nin authored feature files: q-DSL tables spread `...q.audit()` / `...q.softDelete()` into\nthe columns object (types flow through β `$infer` shows `createdAt`/`modifiedBy`/β¦ on the\nauthor's own table object), raw Drizzle tables declare the canonical lines literally.\n`quickback migrate visible-columns` codemods an existing project in one shot; emitted\noutput is unchanged either way (the spreads expand to the exact injector lines).\n\nWith visibility comes validation, **on by default**: every feature table must declare its\nmanaged columns visibly (`...q.audit()` / `...q.softDelete()` or the canonical literal\nlines β one `quickback migrate visible-columns` run), and every managed column that appears\nin authored source is checked against the canonical spec β insert-time default chains on\n`createdAt`/`modifiedAt` (+`$onUpdate`), nullable no-default actor columns, nullable\nno-default `deletedAt`, canonical SQL names, never `.encrypted()`/`.sealed()`. Divergence\n(silently accepted before) and missing declarations **fail the build**, with soft-delete\npresence pinned to `crud.delete.mode`. Opt out with\n`compiler.features.visibleAuditColumns: false`, which downgrades divergence to warnings and\nrestores invisible injection. Unknown spreads in a q-DSL columns object are now a compile\nerror instead of being silently dropped.\n\nAlso in this line: `q.table`'s `$insert` type is honest (required vs defaulted/stamped\ncolumns; audit keys are `?: never` β the wrapper hard-stamps them), `$infer` includes the\naudit columns, and the canonical column definitions collapsed into one shared spec\n(`constants/managed-columns.ts`) consumed by the injectors, meta augmentation, request\nvalidation, spread expansion, and the new validator.\n\n## v0.56.0βv0.56.11 β July 21β27, 2026\n\n> No changelog entries were written for the v0.56 line (twelve releases).\n> Reconstructed from git: feature-area follow-through β generated CRUD/changeset\n> routes claimed by an area prefix (`d33262e8`), feature-area transition route\n> adapters (`05d57940`), a fail-closed guard for generated routes under an area\n> prefix (`23f1f58d`), and a run of cross-feature resolution fixes\n> (`b6984a22`, `747dfad4`, `fb0cfb41`, `26bc569f`, `ae76e3e8`) β plus\n> relationship-proven `SESSION` parity for `q.stamp` (`b11fabfe`), an RLS\n> serial-sequence sweep with an audit-schema latch and `fga_tuples` backstop\n> (`299c93ee`), changeset trigger parity and `define-action` typing fixes\n> (`4c64edab`), and R2 files-migration scheduling gated on managed files\n> (`29b908f2`).\n\n## v0.55.1 β July 21, 2026\n\n### Feature areas β hierarchical authz grouping (`_area.ts`)\n\nA folder under `features/` carrying an `_area.ts` (`export default defineArea({...})`) is now\nan **area**: it declares a route prefix + admission lanes (the same shape as a project\nnamespace, incl. `mintScope`/`acceptScope`) and an authz vocabulary β relationships, composed\nroles, named gates, tenant anchors, scope kinds β that every feature inside the folder\nreferences by bare name. The vocabulary is visible to the area's subtree ONLY: the compiler\nchecks every reference channel (access roles/gates/scoped aliases, action `access`/`anchor`,\nfirewall `via`/`{ rule }`/`{ tenant }` arms, `ctx.scope.<kind>` accessors, auth-view tenant\nincludes, realtime handshake roles, table-level namespace lanes, and other `_area.ts` nodes)\nand fails the build on any outside reference. Root `authz` stays the global level, and root\nbodies may reference root-declared names only (no laundering an area name project-wide).\n\nFail-closed rules shipped with it: re-declaring an inherited name is a compile error (no\noverrides in v1); a descendant action whose path opts out of the area prefix must carry an\nexplicit `route: 'self'` marker; relative `path: './β¦'` resolves against the area prefix with\ndot segments rejected; foreign features can't claim paths (or table-level namespace prefixes)\nunder an area's prefix; nested areas may add vocabulary but not mount a second prefix under a\nmounted ancestor (unlinked parent/child admission never compiles); and area-tree projects\nmust declare `requires: ['feature-areas']` β the marker reaches the compiler through ANY CLI\nversion, so an area-unaware toolchain is rejected instead of silently dropping nested\nfeatures. Area projects also emit a reviewed audit artifact, `quickback/authz-manifest.json`\n(area tree, declared names, member features, area-gated vs self-gated actions, root-config\nnamespace consumers), and the generated `AGENTS.md` gains a feature-areas section.\n\nByte-parity guarantee: a flat root-authz project re-expressed as an area tree compiles to\nbyte-identical output (the emit-site key-order determinism pass from v2 step 0 makes the fold\norder provably irrelevant). See [Feature areas](/define/areas).\n\nOne cosmetic side effect of that determinism pass: the first recompile of an existing project\non this release may reorder generated relationship-table **import lines** (they are now\nemitted in sorted order instead of authz-map insertion order). The reordering is a one-time,\nbehavior-free diff.\n\n### Access rules: named gates (`authz.rules`) and tenant anchors (`authz.tenants`)\n\nTwo new root-`authz` blocks let you declare a row/role rule once and stamp it by name instead\nof copying predicates across files. A **named gate** in `authz.rules` bundles up to three\narms β `who` (roles), `record:` (record-aware predicates), and `firewall` lanes β under one\nname, referenced by bare name in any `access: { roles: [...] }` array (applies who + record)\nand as `{ rule: '<name>' }` in a resource's `firewall:` (splices the lanes into the top-level\nAND array β a reference can only *narrow* row admission, never widen it). A **tenant anchor**\nin `authz.tenants` names the tenant predicate (`{ column, equals }`, claim side locked to\nverified ctx claims) and is written `{ tenant: 'org' }` in firewalls β with an optional\nper-site column override β and `tenant: 'org'` in auth-view includes. Expansion happens at\ncompile time; emitted SQL is byte-identical to the inline spelling.\n\nEverything fails closed: gate/role/scoped-role/`+`/`:` name collisions, `+` hierarchy sugar\ninside rule bodies, `{ rule }` inside `all`/`any` groups, firewall-less gates referenced from\n`firewall:`, firewall-bearing gates on actions or in `masking.show`, and an access-side\nreference to a firewall-bearing gate whose lanes the resource doesn't also stamp are all\ncompile errors. Gates in `realtime.requiredRoles` lower to static who-roles at the handshake;\na declared non-empty list that lowers to nothing is a compile error, never a silent `[]`. A\nnew `AUTHZ_UNKNOWN_ROLE_NAME` warning flags reference-shaped names that resolve to nothing.\nSee [named gates](/define/authz-roles#named-gates-authzrules) Β·\n[`{ tenant }`](/define/firewall#named-tenant-anchors-tenant) Β·\n[`{ rule }`](/define/firewall#named-gate-references-rule).\n\n## v0.55.0 β July 17, 2026\n\n### Generated projects ship an `AGENTS.md`\n\nEvery compiled project now emits an `AGENTS.md` at its root β the file coding agents read first β weaving Quickback's security model and a *\"when to use what\"* decision guide into the output. An agent editing the features is steered to the right primitive: a **view** for a filtered read, a **transition** for a guarded state change, an **action** for custom logic, **guards**/**masking** for field-level control, **named invalidations** for realtime refresh β each with a `docs.quickback.dev` link. It also documents the access tiers (incl. `SESSION`/`SCOPED`), the `WHERE column = value` firewall model with the org-OR-scope `{ any: [...] }` pattern for non-org callers, and the fail-closed coherence guardrail (with the *\"never `exception: true` as a workaround\"* rule). Regenerated on every compile."
|
|
47
47
|
},
|
|
48
48
|
"changelog/v0.1x": {
|
|
49
49
|
"title": "v0.18 and earlier",
|
|
50
|
-
"content": "## v0.18.1 β May 18, 2026\n\n### Account SPA β teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams β `organization({ teams: { enabled: true } })` β the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) β splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) β member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header β calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** β `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` β synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates β `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu β `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` β `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` β `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` β `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** β full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** β single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 β the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced β and the Teams tab is hidden β keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 β May 17, 2026\n\n### `config.apps` β mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack β API, account, and product UI β onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior β `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` β the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames β an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label β `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 β May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", β¦)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry β a path to ship third-party plugins (`@better-auth-kit/audit`, β¦), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod β typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 β May 14, 2026\n\n### `quickback start` β interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact β sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking β the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 β May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 β May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens β Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 β May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 β May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently β no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security β Bearer Tokens and Cookie Precedence](/platform/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](/define/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](/define/firewall#relationship-based-scoping-via) and [Access β Relationship-based authorization](/define/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 title=\"features/applications/actions/advance.ts\"\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\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 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](/define/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](/platform/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](/platform/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](/platform/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](/configure/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](/api/errors#database).\n\n---\n\n## v0.10.5 β April 28, 2026\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\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\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](/define/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables, through the per-file discovery rules above: `actions/<name>.ts` binds to the feature's primary table, `actions/<table>/<name>.ts` binds to the sibling table file of that name.\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> **Correction.** As originally published, this entry listed three discovery modes β colocated `defineActions(<table>, β¦)` inside the table file, a bundled `actions.ts`, and `actions/<table>.ts` β plus a universal `_feature.ts` slot. All four were retired by the one-file-per-action change in this same release (see the entry above) and are rejected at load time today. The shape stated here is the surviving one.\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) β the first match in the schema source becomes the predicate field. Owner scope accepts `userId` **in this release**.\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> **Superseded in v0.21.0 β do not follow the two paragraphs above.** The owner\n> convention was inverted: `ownerId` is the auto-detected owner column (the\n> compiler firewalls reads with `WHERE ownerId = ctx.userId` and auto-stamps the\n> column on insert) and `userId` is **not** auto-detected on feature tables β it\n> is a Better Auth convention on Better Auth's own tables (`session`, `account`,\n> `member`, `passkey`), and on a feature table it usually means *a user this row\n> references* (member, contact, invitee) rather than *the row's owner*. If\n> `userId` is the only candidate column the compiler raises an error; alongside a\n> detected isolation column it raises a warning. Two escapes: rename the column to\n> `ownerId`, or declare `firewall: { owner: { column: \"userId\" } }` explicitly.\n> The two paragraphs above describe v0.10.5 behaviour only β see\n> *Auto-firewall column swap* under v0.21.0.\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()`](/define/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](/define/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](/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](/configure#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](/define/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](/configure/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](/ui/account/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](/define/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](/configure).\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> **Retired syntax.** The `defineActions(<table>, {β¦})` wrapper below was retired by the one-file-per-action change in v0.10.5 β the canonical shape is one `actions/<name>.ts` per action with `export default defineAction({β¦})`. `unsafe: true` / `rawDb` are unchanged. Kept as the record of what shipped.\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](/define/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](/api/actions#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](/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)."
|
|
50
|
+
"content": "## v0.18.1 β May 18, 2026\n\n### Account SPA β teams, active-team picker, permission-aware UI\n\nThe Account SPA's organization surface is now feature-parity with Better Auth's `organization` plugin for the basic team workflow, and replaces the long-standing hardcoded `role === 'owner' || 'admin'` checks with `checkRolePermission` so projects that ship custom roles get a UI that respects them.\n\n#### Teams (opt-in)\n\nWhen the BA config enables teams β `organization({ teams: { enabled: true } })` β the compiler emits `VITE_ENABLE_ORG_TEAMS=true` and the Account SPA exposes a Teams tab on each organization:\n\n- **Teams index** (`/$slug/teams`) β splits into \"Your teams\" (from `listUserTeams`) and \"Other teams\" so non-admins land on what's relevant. Create / rename / delete from the list, gated on `team:create` / `team:update` / `team:delete`.\n- **Team detail** (`/$slug/teams/$teamId`) β member roster with add / remove, joining `listTeamMembers` against the org's full member list for display.\n- **Active-team picker** in the org header β calls `setActiveTeam` and exposes the choice via `OrganizationContext.activeTeamId` so downstream routes (and the BA `session.activeTeamId` server-side) stay in sync.\n- **Team-aware invites** β `InviteMemberDialog` shows an optional team picker when teams are on and forwards `teamId` to `inviteMember`, so accepting the invite drops the new member straight into the right team.\n\nTeams are loaded once by the `$slug` layout (`listTeams` + `listUserTeams`) and exposed via `OrganizationContext.teams` / `userTeamIds` / `refreshTeams`, so individual team routes don't re-fetch the list.\n\n#### Permission-aware UI via `checkRolePermission`\n\n`OrganizationContext.isOwnerOrAdmin` is gone. Routes now read `can(resource, action)` from context, which delegates to `authClient.organization.checkRolePermission` β synchronous, no roundtrip, and aware of any custom roles registered via the BA `ac` option. Multi-role users (BA stores multiple roles comma-separated) are handled by checking each role; the action is allowed if any role grants it.\n\nMigrated sites:\n\n- `$slug.tsx` tab gates β `can('invitation', 'create')`, `can('organization', 'update')`\n- `members.tsx` action menu β `can('member', 'update' | 'delete')`; the owner-hierarchy guard (non-owners can't touch owner-role members) is preserved as a client-side mirror of BA's server enforcement\n- `invitations.tsx` β `can('invitation', 'create' | 'cancel')` gates the Invite button, resend, and cancel separately\n- `settings.tsx` β `can('organization', 'update')` for the form, `can('organization', 'delete')` for the danger zone (was owner-only)\n- `teams.tsx` / `teams.$teamId.tsx` β `can('team', 'create' | 'update' | 'delete')`\n\nProjects on the default three-role hierarchy see no behaviour change; projects that defined `admin`/`member` overrides via BA's access-control API now get a UI that matches what the server will actually authorize.\n\n#### Editable slug + metadata on organization settings\n\nThe `$slug/settings.tsx` form now edits two more `organization.update` fields:\n\n- **URL slug** β full debounced `checkSlug` flow (mirroring the create-org form); on rename, the SPA navigates to `/${newSlug}/settings` and the layout re-fetches with the new slug.\n- **Metadata** β single `Record<string, any> | null` JSON textarea, parsed on submit with inline error messaging. Empty clears the field.\n\nSlug rename is non-breaking for the SPA itself, but every external link / bookmark that references the old slug becomes a 404 β the form warns about this before saving.\n\n#### Auth client wiring\n\nWhen `VITE_ENABLE_ORG_TEAMS=true`, the SPA's `organizationClient(...)` is instantiated with `teams: { enabled: true }` so the team APIs are typed end-to-end. When the flag is off, team methods aren't surfaced β and the Teams tab is hidden β keeping the bundle and UI honest about what the server actually supports.\n\n---\n\n## v0.18.0 β May 17, 2026\n\n### `config.apps` β mount user-authored SPAs on dedicated hostnames\n\nThe compiler now generates per-hostname Worker middleware for arbitrary user SPAs alongside the built-in CMS and Account UIs. Previously the only way to host a product app next to a Quickback API was a second Worker; `config.apps` brings the full stack β API, account, and product UI β onto one deployment with same-origin auth.\n\n```ts\napps: {\n www: {\n domain: \"www.example.com\",\n aliasDomains: [\"example.com\"], // apex serves the same SPA\n },\n}\n```\n\nEach entry binds one or more hostnames to a directory under `src/apps/<name>/` and inherits the Account-domain pass-through behavior β `/api/`, `/auth/`, `/admin/`, `/storage/`, and `/health` route to Hono so the SPA fetches its API without CORS. The compiler:\n\n- emits a `custom_domain = true` route in `wrangler.toml` for the primary hostname and every alias\n- adds each hostname to Better Auth's `TRUSTED_ORIGINS` (when `trustedOrigins` is left unset)\n- widens the CSP `connect-src` to cover the SPA-baked origins\n- folds the new hostnames into shared-parent detection for `crossSubDomainCookies`\n\nDrop the prebuilt SPA bundle at `quickback/apps/<name>/` β the existing source-apps passthrough copies it byte-for-byte into `src/apps/<name>/`. The compiler doesn't build the SPA; it only emits routing for whatever's already there. The names `cms`, `account`, and `public` are reserved; hostname collisions with `cms.domain` / `account.domain` / `account.adminDomain` or between two `apps[*]` entries fail at compile time.\n\nWhen `cms` and `account` are both configured, the multi-domain catchall now explicitly skips app hostnames β an API miss on an app host returns the standard 404 JSON via `app.notFound` instead of stray-serving a sibling SPA's HTML shell.\n\n### Cross-subdomain cookie inference handles apex aliases\n\nThe shared-parent detection that drives `advanced.crossSubDomainCookies` previously reduced any hostname by stripping the leftmost label β `'example.com'` collapsed to `'com'`, which broke equality against sibling subdomains. Apex hostnames (exactly two dot-segments) are now treated as already being the parent, so apex aliases (`example.com` listed alongside `www.example.com`) coexist cleanly with `auth.example.com` / `cms.example.com` and the compiler still emits `crossSubDomainCookies: { enabled: true, domain: '.example.com' }`.\n\n---\n\n## v0.17.2 β May 15, 2026\n\n### `customPlugins` escape hatch on `defineAuth(\"better-auth\", β¦)`\n\nThe Better Auth provider now accepts `customPlugins` alongside the named-plugin registry β a path to ship third-party plugins (`@better-auth-kit/audit`, β¦), unregistered built-ins, or one-off project-local plugins without forking the compiler.\n\nEach entry is an explicit import descriptor:\n\n```ts\nauth: defineAuth(\"better-auth\", {\n emailAndPassword: { enabled: true },\n plugins: { passkey: true, organization: true },\n customPlugins: [\n // (1) Project-local plugin file at quickback/plugins/long-session.ts\n { from: \"./plugins/long-session\", export: \"longSessionPlugin\" },\n // (2) Third-party npm package\n {\n from: \"@better-auth-kit/audit\",\n export: \"auditPlugin\",\n args: { events: [\"sign-in\"] },\n dependencies: { \"@better-auth-kit/audit\": \"^1.0.0\" },\n },\n ],\n}),\n```\n\n`from` is either a relative path under `./plugins/` (the CLI auto-uploads matching files from `quickback/plugins/`; the compiler copies them into `src/plugins/<name>.ts` and rewrites the emitted import) or a bare npm specifier (emitted verbatim; declare `dependencies` so the package lands in the generated `package.json`). Omit `args` to emit the symbol uncalled (plugin instance); provide `args` to emit a JSON-serialized factory call.\n\nThe descriptor is validated with Zod β typos in `from`/`export`, paths that escape `./plugins/`, and references to files the CLI didn't ship all fail at compile time with a targeted message.\n\n---\n\n## v0.17.1 β May 14, 2026\n\n### `quickback start` β interactive onboarding\n\n```bash\nmkdir my-app && cd my-app\nnpx @quickback-dev/cli start\n```\n\n`start` walks new users through template selection, scaffolds the project on disk, and only prompts for an account when it's ready to compile. Cancelling at the login prompt leaves the scaffold intact β sign in and run `quickback compile` whenever you're ready.\n\nThe same deferred-auth flow applies to `quickback create`. Scaffolding and (optional) Cloudflare D1 setup run before authentication, so you can preview the project on disk before committing to an account.\n\n### Named views on the free tier\n\nThe `todos` template now ships a `dashboard` named view, exposing a projected response at `GET /api/v1/todos/views/dashboard`. Named views support per-view access rules and per-view field selection while inheriting the table's firewall and masking β the canonical way to ship list-view payloads that are cheaper to fetch and easier to cache than a full collection read.\n\n### `quickback init` removed\n\nFolded into `start` and `create`. The legacy command name prints a deprecation notice pointing at its replacements.\n\n### Minor\n\n- `quickback whoami` reads the stored tier from your credentials.\n- Pro upsell copy in `quickback login` is shown only when the server returns an explicit free-tier subscription.\n- Bare scaffolds (`cloudflare`, `empty`) report accurately when there are no features to generate migrations for.\n\n---\n\n## v0.16.10 β May 14, 2026\n\n### D1-specific safety pass on generated migrations\n\nThe `cloudflare-d1` provider now runs a post-generation pass over every Drizzle migration directory (auth, features, webhooks, audit) before the compile finishes. Better Auth cleanup for retired managed tables is stripped from raw `DROP TABLE` statements. Drop-only cleanup migrations are reordered child-first when foreign-key dependencies require it. Every generated D1 migration directory is replayed against SQLite during compile, so a D1-breaking migration fails at compile time rather than at `wrangler d1 migrations apply`.\n\n---\n\n## v0.16.9 β May 13, 2026\n\n### Resource-scoped realtime tickets\n\n`providers.database.config.realtime` accepts an object form for projects whose WebSocket subscribers aren't org members:\n\n```ts\nrealtime: {\n wsTicket: {\n role: \"attendee\",\n requestField: \"eventId\",\n scopeTable: \"events\",\n },\n}\n```\n\nThe generated `/broadcast/v1/ws-ticket` route authenticates the caller, evaluates the declared relationship role against the request, and mints a short-lived WebSocket ticket scoped to the resolved resource. `realtime: true` continues to enable the org-scoped broadcaster.\n\n### Unified broadcast targeting\n\nThe realtime helper and Broadcaster now route by `scopeKey || organizationId || userId`. String targets remain shorthand for `organizationId`; explicit targets can scope a broadcast to a resource or a single user:\n\n```ts\nawait realtime.broadcast(\"event-page-updated\", payload, { scopeKey: \"events:evt_123\" });\nawait realtime.broadcast(\"dm\", payload, { userId: recipientId });\n```\n\nWebSocket tickets are Quickback-minted (signed with `BETTER_AUTH_SECRET`), not Better Auth tokens β Better Auth remains the front-door auth check; Quickback signs the upgrade ticket after authorization succeeds.\n\n---\n\n## v0.16.8 β May 13, 2026\n\n### One auth transport per request\n\nGenerated middleware treats `Cookie`, `Authorization: Bearer`, and `x-api-key` as distinct auth methods and rejects mixed requests with `400 AUTH_METHOD_CONFLICT`. Query-string API keys (`?api_key=` / `?key=`) are no longer accepted. Machine-to-machine auth is explicit; precedence rules between transports are gone.\n\n### Cookie-backed CSRF gate\n\nGenerated apps now block cross-site `POST` / `PUT` / `PATCH` / `DELETE` requests from cookie-relying callers. The middleware skips explicit `Authorization` clients, requires a trusted `Origin` or `Referer`, and blocks `Sec-Fetch-Site: cross-site`. This matters most for cross-subdomain session setups where `SameSite=None` is intentional.\n\n### First-class Wrangler observability\n\n`providers.runtime.config.observability` now supports nested `logs` / `traces` blocks for `headSamplingRate`, `destinations`, `persist`, and `logs.invocationLogs`, emitting matching `[observability]`, `[observability.logs]`, and `[observability.traces]` TOML.\n\n---\n\n## v0.16.7 β May 12, 2026\n\n### Bearer wins over cookie\n\nA request carrying both `Authorization` and a session `Cookie` resolves entirely from the bearer; the cookie is dropped before `getSession()` runs. All three Bearer flavors (API key, JWT, session-token) now behave consistently β no more silent cookie precedence on session-token bearers.\n\n### Bearer plugin defaults to `requireSignature: true`\n\nBetter Auth's `bearer` plugin defaults to unsigned tokens; Quickback now emits `bearer({ requireSignature: true })`. Tokens emitted in the CORS-exposed `set-auth-token` header are server-signed with `BETTER_AUTH_SECRET` and verified on every request. Projects that genuinely need unsigned bearers can override via `providers.auth.config.plugins.bearer`.\n\nSee [Authentication Security β Bearer Tokens and Cookie Precedence](/platform/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](/define/relationships#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](/define/firewall#relationship-based-scoping-via) and [Access β Relationship-based authorization](/define/relationships).\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 title=\"features/applications/actions/advance.ts\"\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\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 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](/define/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](/platform/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](/platform/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](/platform/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](/configure/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](/api/errors#database).\n\n---\n\n## v0.10.5 β April 28, 2026\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\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\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](/define/actions).\n\n### Multi-table actions per feature\n\nOne feature directory can own actions on multiple tables, through the per-file discovery rules above: `actions/<name>.ts` binds to the feature's primary table, `actions/<table>/<name>.ts` binds to the sibling table file of that name.\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> **Correction.** As originally published, this entry listed three discovery modes β colocated `defineActions(<table>, β¦)` inside the table file, a bundled `actions.ts`, and `actions/<table>.ts` β plus a universal `_feature.ts` slot. All four were retired by the one-file-per-action change in this same release (see the entry above) and are rejected at load time today. The shape stated here is the surviving one.\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) β the first match in the schema source becomes the predicate field. Owner scope accepts `userId` **in this release**.\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> **Superseded in v0.21.0 β do not follow the two paragraphs above.** The owner\n> convention was inverted: `ownerId` is the auto-detected owner column (the\n> compiler firewalls reads with `WHERE ownerId = ctx.userId` and auto-stamps the\n> column on insert) and `userId` is **not** auto-detected on feature tables β it\n> is a Better Auth convention on Better Auth's own tables (`session`, `account`,\n> `member`, `passkey`), and on a feature table it usually means *a user this row\n> references* (member, contact, invitee) rather than *the row's owner*. If\n> `userId` is the only candidate column the compiler raises an error; alongside a\n> detected isolation column it raises a warning. Two escapes: rename the column to\n> `ownerId`, or declare `firewall: { owner: { column: \"userId\" } }` explicitly.\n> The two paragraphs above describe v0.10.5 behaviour only β see\n> *Auto-firewall column swap* under v0.21.0.\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()`](/define/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](/define/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](/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](/configure#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](/define/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](/configure/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](/ui/account/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](/define/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](/configure).\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> **Retired syntax.** The `defineActions(<table>, {β¦})` wrapper below was retired by the one-file-per-action change in v0.10.5 β the canonical shape is one `actions/<name>.ts` per action with `export default defineAction({β¦})`. `unsafe: true` / `rawDb` are unchanged. Kept as the record of what shipped.\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](/define/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](/api/actions#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](/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)."
|
|
51
51
|
},
|
|
52
52
|
"changelog/v0.2x": {
|
|
53
53
|
"title": "v0.20 β v0.29",
|
|
@@ -67,7 +67,7 @@ export const DOCS = {
|
|
|
67
67
|
},
|
|
68
68
|
"configure/agents": {
|
|
69
69
|
"title": "AI Agent Readiness",
|
|
70
|
-
"content": "Every compiled Quickback Worker advertises itself to AI agents and MCP clients β no user wiring required. One config flag controls the whole discovery surface.\n\n## What the compiler generates\n\nWhen `agents` is enabled (the default), the Worker serves:\n\n| Route | What it is |\n|-------|-----------|\n| `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |\n| `GET /llms.txt` | Agent-facing summary of the API β project name, authentication, resource list, endpoint conventions β derived from your own config. |\n| `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |\n| `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata. When the `oauthProvider` plugin is enabled it **delegates to Better Auth's real OAuth 2.1 surface** (`/oauth2/authorize`, `/oauth2/token`, `/oauth2/register` dynamic client registration, PKCE); otherwise it advertises only the truthful token-mint subset. |\n| `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |\n| `GET /.well-known/mcp.json` | MCP Server Card β discoverable metadata for the MCP server below. |\n| `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |\n\n## Default behavior\n\n```ts title=\"quickback.config.ts\"\nimport { defineConfig } from '@quickback/compiler';\n\nexport default defineConfig({\n name: 'my-api',\n // β¦\n // agents: true is the default β no need to write it.\n});\n```\n\nRun `quickback compile` and every endpoint above ships in the Worker.\n\n## Opting out\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: false, // disables everything\n});\n```\n\n## Fine-grained control\n\nPass an object to toggle individual surfaces:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: {\n robotsTxt: true, // default\n llmsTxt: true, // default\n mcp: true, // default\n oauthDiscovery: true, // default\n apiCatalog: true, // default\n allowAiCrawlers: true, // default β flip to false to Disallow in robots.txt\n },\n});\n```\n\n`mcp` also accepts an object for an authenticated-only MCP surface:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: {\n mcp: { requireAuth: true }, // /mcp challenges anonymous callers β interactive OAuth\n },\n});\n```\n\nSee [Interactive OAuth](#interactive-oauth-requireauth) below.\n\n## The MCP server\n\n### Tools\n\nEvery operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's `operationId` (e.g. `listCustomers`, `createInvoice`, `sendInvoice`). Each tool's `inputSchema` is a JSON Schema combining the request body with every parameter in the operation's **mounted** path β including the `:params` contributed by a namespace prefix (e.g. `/scope/:scopeId/...`), so a standalone or namespace action is always callable, not just record-based ones. Nested `z.object` inputs are preserved as nested objects rather than flattened, so the model sees each field's real type.\n\n`tools/call` re-enters the same Hono app via `app.request(...)` β so **every existing middleware runs exactly as it would for a direct REST call**: authentication, firewall, access control, guards, masking. No bypass.\n\n### Access-filtered `tools/list`\n\n`tools/list` only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (`roles`, `userRole`, `or` / `and` combinators) and `tools/list` filters against `ctx` before responding:\n\n- **Unauthenticated callers** see only tools whose access declares the `PUBLIC` pseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up).\n- **Authenticated callers** see tools whose role gate intersects their `ctx.roles` or `ctx.userRole`. Platform-operator endpoints don't appear for callers outside the required user roles.\n- **Function-form access** (escape hatch) is opaque at list time β surfaced to any authenticated caller, then evaluated for real on `tools/call`.\n- **Record predicates** are dropped from the list-time check (no record yet) and applied normally on the actual call.\n\nThis is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate β `tools/call` still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.\n\nThe unauthenticated `GET /mcp` discovery payload returns server info only; it does **not** enumerate tool names. Inventory is exclusively available via the access-filtered `tools/list`.\n\n### Authentication\n\nMCP clients pass their credentials through the standard `Authorization: Bearer <jwt>` header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards `/api/v1/*` validates it.\n\nMint a JWT from an authenticated session:\n\n```bash\ncurl -X POST https://my-api.example.com/api/v1/token \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\"\n```\n\n### Interactive OAuth (`requireAuth`)\n\nStatically pasting a Bearer token works, but it isn't how an MCP connector wants to authenticate β it expects to **launch a sign-in flow**. By default `/mcp` serves an anonymous session (the access-filtered public tool list), and a connector that never sees an auth challenge never offers to sign in. Set `agents.mcp.requireAuth: true` to turn `/mcp` into an authenticated-only endpoint:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: { mcp: { requireAuth: true } },\n});\n```\n\nThis does three things:\n\n1. **Force-enables the `oauthProvider` + `bearer` Better Auth plugins** β so `/oauth2/authorize`, `/oauth2/token`, and `/oauth2/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist for a connector to discover, with PKCE.\n2. **Challenges unauthenticated `/mcp` requests** with `401` and a `WWW-Authenticate: Bearer resource_metadata=\"β¦/.well-known/oauth-protected-resource\"` header ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) Β§5.1). This is the signal MCP connectors use to start OAuth.\n3. **Makes the root `/.well-known/oauth-authorization-server` doc delegate to Better Auth's real metadata**, so discovery resolves to working `/oauth2/*` endpoints instead of a hand-rolled stub.\n\nThe full handshake a connector runs:\n\n```text\nPOST /mcp (no token)\n β 401 + WWW-Authenticate: resource_metadata=\"β¦/.well-known/oauth-protected-resource\"\nGET /.well-known/oauth-protected-resource β authorization_servers: [<origin>]\nGET /.well-known/oauth-authorization-server β authorize/token/register + PKCE\nPOST /oauth2/register β dynamic client registration\nGET /oauth2/authorize?code_challenge=β¦ β redirect to your Account login β consent\nPOST /oauth2/token (code + code_verifier) β access token\nPOST /mcp (Bearer access token) β authenticated tool list\n```\n\nThe login and consent screens are served by your [Account SPA](/ui/account) (`ACCOUNT_URL/login`, `ACCOUNT_URL/consent`), so users sign in with whatever methods you already enabled (Google, GitHub, email, passkey). No connector-specific configuration is required β adding the server URL is enough.\n\n### Split authorization server / resource server (multi-app SSO)\n\nBy default a Worker is both the authorization server (AS) and the resource server β it issues *and* verifies its own OAuth tokens. For multi-app SSO you can run **one canonical AS** and **many resource servers** (each hosting its own `/mcp`) that share a single auth database (the same D1, e.g. via `crossSubDomainCookies` on a shared parent domain). Two config fields wire it up β both under `auth.config.oauth`:\n\n**On each resource server** β point discovery at the external AS and verify its tokens:\n\n```ts\nauth: {\n config: {\n oauth: {\n enabled: true,\n issuerUrl: \"https://auth.example.com/auth/v1\", // the canonical AS\n },\n },\n},\nagents: { mcp: { requireAuth: true } },\n```\n\n`issuerUrl` makes `/.well-known/oauth-protected-resource` advertise the AS (not this Worker), and the generated middleware verifies incoming `Bearer` access tokens against the **shared JWKS** (`iss` must equal `issuerUrl`, `aud` must equal this Worker's `/mcp`, plus `exp` + live-session binding). Because the auth DB is shared, the resource server reads the AS's signing keys and the session row directly β no cross-Worker HTTP call.\n\n**On the authorization server** β register the resource audiences it may mint tokens for ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707) resource indicators):\n\n```ts\nauth: {\n config: {\n oauth: {\n enabled: true,\n audiences: [\n \"https://crm.example.com/mcp\",\n \"https://billing.example.com/mcp\",\n ],\n },\n },\n},\n```\n\n`audiences` is an array β list every federated resource server. The AS's own origin (and `/mcp`) is always included automatically, so you only list the *other* servers; a token requested with `resource=https://crm.example.com/mcp` is then minted with that audience instead of rejected.\n\n### Connecting clients\n\n**Claude Desktop** β add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n\n```json\n{\n \"mcpServers\": {\n \"my-api\": {\n \"url\": \"https://my-api.example.com/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <jwt>\"\n }\n }\n }\n}\n```\n\n**Cursor** β use the same config shape under `.cursor/mcp.json`.\n\n**Quick sanity check with curl:**\n\n```bash\n# List available tools\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n\n# Call a tool\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"listCustomers\",\"arguments\":{\"limit\":10}}}'\n```\n\n### Transport\n\nThe server speaks the **Streamable HTTP** MCP transport β JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.\n\nThe MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.\n\n## Verification\n\nAfter you deploy, scan both the REST and MCP surfaces:\n\n```bash\n# Agent-readiness scan (external)\nopen https://isitagentready.com/?url=https://my-api.example.com\n\n# MCP Inspector (official tool)\nnpx @modelcontextprotocol/inspector https://my-api.example.com/mcp\n```"
|
|
70
|
+
"content": "Every compiled Quickback Worker advertises itself to AI agents and MCP clients β no user wiring required. One config flag controls the whole discovery surface.\n\n## What the compiler generates\n\nWhen `agents` is enabled (the default), the Worker serves:\n\n| Route | What it is |\n|-------|-----------|\n| `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |\n| `GET /llms.txt` | Agent-facing summary of the API β project name, authentication, resource list, endpoint conventions β derived from your own config. |\n| `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |\n| `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata. When the `oauthProvider` plugin is enabled it **delegates to Better Auth's real OAuth 2.1 surface** (`/oauth2/authorize`, `/oauth2/token`, `/oauth2/register` dynamic client registration, PKCE); otherwise it advertises only the truthful token-mint subset. |\n| `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |\n| `GET /.well-known/mcp.json` | MCP Server Card β discoverable metadata for the MCP server below. |\n| `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |\n\n## Default behavior\n\n```ts title=\"quickback.config.ts\"\nimport { defineConfig } from '@quickback/compiler';\n\nexport default defineConfig({\n name: 'my-api',\n // β¦\n // agents: true is the default β no need to write it.\n});\n```\n\nRun `quickback compile` and every endpoint above ships in the Worker.\n\n## Opting out\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: false, // disables everything\n});\n```\n\n## Fine-grained control\n\nPass an object to toggle individual surfaces:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: {\n robotsTxt: true, // default\n llmsTxt: true, // default\n mcp: true, // default\n oauthDiscovery: true, // default\n apiCatalog: true, // default\n allowAiCrawlers: true, // default β flip to false to Disallow in robots.txt\n },\n});\n```\n\n`mcp` also accepts an object for an authenticated-only MCP surface:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: {\n mcp: { requireAuth: true }, // /mcp challenges anonymous callers β interactive OAuth\n },\n});\n```\n\nSee [Interactive OAuth](#interactive-oauth-requireauth) below.\n\n## The MCP server\n\n### Tools\n\nEvery operation in your generated OpenAPI spec becomes one MCP tool. The tool name is the operation's `operationId` (e.g. `listCustomers`, `createInvoice`, `sendInvoice`). Each tool's `inputSchema` is a JSON Schema combining the request body with every parameter in the operation's **mounted** path β including the `:params` contributed by a namespace prefix (e.g. `/scope/:scopeId/...`), so a standalone or namespace action is always callable, not just record-based ones. Nested `z.object` inputs are preserved as nested objects rather than flattened, so the model sees each field's real type.\n\n`tools/call` re-enters the same Hono app via `app.request(...)` β so **every existing middleware runs exactly as it would for a direct REST call**: authentication, firewall, access control, guards, masking. No bypass.\n\n### Access-filtered `tools/list`\n\n`tools/list` only returns tools the calling identity could actually invoke. Each generated tool entry carries the operation's access metadata (`roles`, `userRole`, `or` / `and` combinators) and `tools/list` filters against `ctx` before responding:\n\n- **Unauthenticated callers** see only tools whose access declares the `PUBLIC` pseudo-role, or operations that have no security requirement at all (e.g. sign-in / sign-up).\n- **Authenticated callers** see tools whose role gate intersects their `ctx.roles` or `ctx.userRole`. Platform-operator endpoints don't appear for callers outside the required user roles.\n- **Function-form access** (escape hatch) is opaque at list time β surfaced to any authenticated caller, then evaluated for real on `tools/call`.\n- **Record predicates** are dropped from the list-time check (no record yet) and applied normally on the actual call.\n\nThis is recon-mitigation, not a security boundary. Hiding a tool from the list never weakens the underlying gate β `tools/call` still runs the full middleware chain and rejects unauthorized invocations the same way a direct REST call would.\n\nThe unauthenticated `GET /mcp` discovery payload returns server info only; it does **not** enumerate tool names. Inventory is exclusively available via the access-filtered `tools/list`.\n\n### Request limits\n\nUnless `requireAuth` is set, `/mcp` accepts anonymous POSTs, so both the body\nand the JSON-RPC batch array are attacker-controlled. Two limits apply:\n\n| Limit | Value | Behaviour when exceeded |\n| --- | --- | --- |\n| Request body | 1 MiB | `413` with JSON-RPC error `-32600` |\n| Batch elements | 50 | `413` with `-32600`; split the batch |\n\nThe body is read through a byte counter rather than buffered whole, so an\noversized request is cut off mid-stream instead of being materialized first.\nA size rejection is deliberately distinct from `-32700` *Parse error* β a\nclient told \"parse error\" would retry the same oversized body.\n\nBatches are dispatched in waves of 8 rather than all at once. Every element\nbecomes its own internal request through the full middleware chain, so peak\nconcurrency stays flat regardless of how large a batch is submitted.\n\n### Authentication\n\nMCP clients pass their credentials through the standard `Authorization: Bearer <jwt>` header. The generated MCP handler forwards the header verbatim into the internal request, and the same JWT middleware that guards `/api/v1/*` validates it.\n\nMint a JWT from an authenticated session:\n\n```bash\ncurl -X POST https://my-api.example.com/api/v1/token \\\n -H \"Cookie: better-auth.session_token=...\" \\\n -H \"Content-Type: application/json\"\n```\n\n### Interactive OAuth (`requireAuth`)\n\nStatically pasting a Bearer token works, but it isn't how an MCP connector wants to authenticate β it expects to **launch a sign-in flow**. By default `/mcp` serves an anonymous session (the access-filtered public tool list), and a connector that never sees an auth challenge never offers to sign in. Set `agents.mcp.requireAuth: true` to turn `/mcp` into an authenticated-only endpoint:\n\n```ts title=\"quickback.config.ts\"\nexport default defineConfig({\n // β¦\n agents: { mcp: { requireAuth: true } },\n});\n```\n\nThis does three things:\n\n1. **Force-enables the `oauthProvider` + `bearer` Better Auth plugins** β so `/oauth2/authorize`, `/oauth2/token`, and `/oauth2/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist for a connector to discover, with PKCE.\n2. **Challenges unauthenticated `/mcp` requests** with `401` and a `WWW-Authenticate: Bearer resource_metadata=\"β¦/.well-known/oauth-protected-resource\"` header ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) Β§5.1). This is the signal MCP connectors use to start OAuth.\n3. **Makes the root `/.well-known/oauth-authorization-server` doc delegate to Better Auth's real metadata**, so discovery resolves to working `/oauth2/*` endpoints instead of a hand-rolled stub.\n\nThe full handshake a connector runs:\n\n```text\nPOST /mcp (no token)\n β 401 + WWW-Authenticate: resource_metadata=\"β¦/.well-known/oauth-protected-resource\"\nGET /.well-known/oauth-protected-resource β authorization_servers: [<origin>]\nGET /.well-known/oauth-authorization-server β authorize/token/register + PKCE\nPOST /oauth2/register β dynamic client registration\nGET /oauth2/authorize?code_challenge=β¦ β redirect to your Account login β consent\nPOST /oauth2/token (code + code_verifier) β access token\nPOST /mcp (Bearer access token) β authenticated tool list\n```\n\nThe login and consent screens are served by your [Account SPA](/ui/account) (`ACCOUNT_URL/login`, `ACCOUNT_URL/consent`), so users sign in with whatever methods you already enabled (Google, GitHub, email, passkey). No connector-specific configuration is required β adding the server URL is enough.\n\n### Split authorization server / resource server (multi-app SSO)\n\nBy default a Worker is both the authorization server (AS) and the resource server β it issues *and* verifies its own OAuth tokens. For multi-app SSO you can run **one canonical AS** and **many resource servers** (each hosting its own `/mcp`) that share a single auth database (the same D1, e.g. via `crossSubDomainCookies` on a shared parent domain). Two config fields wire it up β both under `auth.config.oauth`:\n\n**On each resource server** β point discovery at the external AS and verify its tokens:\n\n```ts\nauth: {\n config: {\n oauth: {\n enabled: true,\n issuerUrl: \"https://auth.example.com/auth/v1\", // the canonical AS\n },\n },\n},\nagents: { mcp: { requireAuth: true } },\n```\n\n`issuerUrl` makes `/.well-known/oauth-protected-resource` advertise the AS (not this Worker), and the generated middleware verifies incoming `Bearer` access tokens against the **shared JWKS** (`iss` must equal `issuerUrl`, `aud` must equal this Worker's `/mcp`, plus `exp` + live-session binding). Because the auth DB is shared, the resource server reads the AS's signing keys and the session row directly β no cross-Worker HTTP call.\n\n**On the authorization server** β register the resource audiences it may mint tokens for ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707) resource indicators):\n\n```ts\nauth: {\n config: {\n oauth: {\n enabled: true,\n audiences: [\n \"https://crm.example.com/mcp\",\n \"https://billing.example.com/mcp\",\n ],\n },\n },\n},\n```\n\n`audiences` is an array β list every federated resource server. The AS's own origin (and `/mcp`) is always included automatically, so you only list the *other* servers; a token requested with `resource=https://crm.example.com/mcp` is then minted with that audience instead of rejected.\n\n### Connecting clients\n\n**Claude Desktop** β add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n\n```json\n{\n \"mcpServers\": {\n \"my-api\": {\n \"url\": \"https://my-api.example.com/mcp\",\n \"headers\": {\n \"Authorization\": \"Bearer <jwt>\"\n }\n }\n }\n}\n```\n\n**Cursor** β use the same config shape under `.cursor/mcp.json`.\n\n**Quick sanity check with curl:**\n\n```bash\n# List available tools\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}'\n\n# Call a tool\ncurl -X POST https://my-api.example.com/mcp \\\n -H \"Authorization: Bearer $JWT\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"listCustomers\",\"arguments\":{\"limit\":10}}}'\n```\n\n### Transport\n\nThe server speaks the **Streamable HTTP** MCP transport β JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.\n\nThe MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.\n\n## Verification\n\nAfter you deploy, scan both the REST and MCP surfaces:\n\n```bash\n# Agent-readiness scan (external)\nopen https://isitagentready.com/?url=https://my-api.example.com\n\n# MCP Inspector (official tool)\nnpx @modelcontextprotocol/inspector https://my-api.example.com/mcp\n```"
|
|
71
71
|
},
|
|
72
72
|
"configure/auth": {
|
|
73
73
|
"title": "Auth & JWT",
|
|
@@ -83,7 +83,7 @@ export const DOCS = {
|
|
|
83
83
|
},
|
|
84
84
|
"configure": {
|
|
85
85
|
"title": "Configuration",
|
|
86
|
-
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\nimport { defineConfig, defineRuntime, defineDatabase, defineAuth } from \"@quickback/compiler\";\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n auth: {\n // Required for \"+\" role expansion in access rules (e.g. roles: [\"member+\"]).\n // Lowest β highest. Omit if you always list roles explicitly.\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ββ Project ββ\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ββ Embedded UIs (CMS / Account) ββ\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** β the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // β lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template. `\"hono\"` is the only accepted value. |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\nEvery optional top-level key the config accepts is listed below. You never have to memorize them β after your first compile, the [discoverable options block](#discoverable-options-block) lists each one (minus the ones you've set) right inside your `quickback.config.ts`. This table is the human reference; follow the links for detailed pages.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) β see [Domains](/configure/domains) |\n| `contract` | `{ version?: \"v1\" \\| \"v2\" }` | Public API/auth contract version. Omit for the backward-compatible v1 default; select v2 for `/api/v2/*` and `/auth/v2/*` across generated routes, Better Auth, OpenAPI, MCP, and discovery. |\n| `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias β see [Domains](/configure/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`/`profileUrl`, `domain`) β see [Access](/define/access#role-hierarchy) and [Delegated principals](#delegated-principals-contract-v2) |\n| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `rules`, `tenants`, `permissions`, `arrows`) β see [Access](/define/access#centrally-defined-access-rules) and [Permissions](/define/permissions). `rules` = named gates (who + `record:` + firewall lanes under one name); `tenants` = named tenant anchors (`{ column, equals }`, referenced as `{ tenant: '<name>' }` in firewalls and `tenant: '<name>'` in auth-view includes). Root `authz` is the GLOBAL vocabulary level β names scoped to one concept belong in that concept's [feature area](/define/areas) (`_area.ts`), and root bodies may reference root-declared names only |\n| `requires` | `string[]` | Capability floor (fail-closed guard). Declare `['feature-areas']` when the project uses `features/**/_area.ts` β an area-unaware CLI/compiler then refuses the compile instead of silently dropping nested features. See [Feature areas](/define/areas#the-capability-floor-requires-feature-areas) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` β see [Pinned Organization Mode](/configure/single-tenant) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) β see [CMS](/ui/admin) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) β see [Account UI](/ui/account) |\n| `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix β see [Domains](/configure/domains) |\n| `agents` | `boolean \\| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) β see [Agents](/configure/agents) |\n| `security` | `object \\| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) β see [Security Headers](/configure/security) |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'`, `types`) β see [OpenAPI](/api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) β see [Schema Registry](/ui/admin/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) β see [Caching & ETags](/api/caching) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) β see [Email Configuration](#email-configuration) |\n| `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) β see [Bindings](/configure/bindings) |\n| `compiler` | `object` | Compiler internals β `features.auditFields: false`, `migrations.renames` (headless CI), Neon `migrations.foreignKeys`, `securityContracts`, `injectId`, `routes` |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) β see [Custom Dependencies](#custom-dependencies) |\n| `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) β see [Variables](/configure/variables) |\n| `preset` | `string` | Inherit defaults from a named preset |\n\n## Public contract version\n\nQuickback defaults to the existing v1 HTTP contract. New applications can opt\ninto v2 explicitly:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n contract: { version: \"v2\" },\n providers: cloudflare({}),\n});\n```\n\nThe selection is atomic: feature routes move to `/api/v2/*`, Better Auth moves\nto `/auth/v2/*`, and generated OpenAPI, MCP tool calls, OAuth discovery,\n`llms.txt`, schema/embeddings routes, and dedicated-domain `/v2/*` shortcuts\nuse the same version. When CMS or Account is enabled, Quickback also bakes\nthose paths into the SPA build and injects them at runtime, so CRUD, schema,\nlive-view, and authentication requests use the selected contract. Quickback\ndoes not expose a mixed v1/v2 surface from one compiled Worker. Omitting\n`contract` remains byte-compatible with v1 projects.\n\nV2 also makes action input-schema fidelity a compile gate. The CLI must\nsuccessfully harvest `z.toJSONSchema(action.input)` for every authored action;\npartial or missing harvests fail with the exact action file keys, bundle or\nevaluation phase, and underlying local error. Dependencies are resolved from\nthe generated runtime's `build.outputDir/node_modules` before unrelated\nancestor installs, so an isolated `quickback/` definition tree can use a\nsibling `src/` runtime without a workspace-root symlink. The compiler enforces\nthe same invariant at its shared input boundary, including\n`POST /compile?complete=false`, so validation-only or raw API calls cannot\nbypass it. V1 retains the historical best-effort static-schema fallback.\n\nThe version selection also moves the event and read surfaces:\n\n| Surface | v1 (pinned) | v2 (flagship) |\n|---|---|---|\n| Realtime data frames (`/broadcast/*`) | raw frames, byte-stable | CloudEvents 1.0 envelopes at DO egress ([realtime](/platform/realtime)) |\n| Outbound webhook signing | Standard Webhooks headers **plus** legacy `X-Webhook-*` | Standard Webhooks **only** |\n| `?include=` FK-graph embedding | not available | available where a resource/view allowlists it |\n| Bare `?fields=` / `fields[<fk>]=` unknown names | silent drop / n/a | 400 on both |\n\nSee [API Contract](/platform/api-contract) for the full v1 β v2 matrix and\nmigration sequencing.\n\n## Delegated principals (contract v2)\n\n`auth.principals` defines non-account authority such as an event pass or a\nshort-lived event session. It is available only with all three of:\n\n- `contract: { version: \"v2\" }`\n- the Cloudflare runtime\n- Neon with `connectionMode: \"hyperdrive\"`\n\nEach principal type owns an exact Authorization scheme. `Bearer` is reserved\nfor Quickback account authentication, including case variants, and two\nprincipal types cannot share a scheme.\n\n```typescript\nexport default defineConfig({\n name: \"attend-v2\",\n template: \"hono\",\n contract: { version: \"v2\" },\n auth: {\n principals: {\n event_pass: {\n scheme: \"EventPass\",\n authenticate: {\n module: \"./event-pass-proof\",\n export: \"authenticateEventPass\",\n },\n lookup: {\n table: {\n module: \"../features/event-access/event-access\",\n export: \"eventAccess\",\n sqlName: \"event_access\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n event_delegate: {\n scheme: \"EventSession\",\n authenticate: {\n module: \"./event-session-proof\",\n export: \"authenticateEventSession\",\n },\n lookup: {\n table: {\n module: \"../features/event-sessions/event-sessions\",\n export: \"eventSessions\",\n sqlName: \"event_sessions\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n sessionId: { field: \"id\", column: \"id\" },\n familyId: { field: \"familyId\", column: \"family_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"hyperdrive\",\n hyperdrive: { id: \"<32-character-hyperdrive-id>\" },\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThe `authenticate.module` path is relative to generated\n`src/lib/principal-auth.ts`. Put project proof hooks under `quickback/lib`; the\ncompiler stages them into `src/lib` even if no action imports them. A hook has\none job: prove the presented credential and return its stable digest.\n\n```typescript\n// quickback/lib/event-session-proof.ts\nexport async function authenticateEventSession({ credential, env, request }: {\n credential: string;\n env: Env;\n request: Request;\n}): Promise<{ digest: string } | null> {\n const valid = await verifySignedEventSession(credential, env, request);\n return valid ? { digest: await sha256(credential) } : null;\n}\n```\n\nThe hook receives no `db`, and it must not implement row authorization or\nbusiness behavior. Quickback performs exactly one narrow, unique digest lookup\nunder a lookup-only RLS principal. A digest must be 16β512 non-whitespace\ncharacters; resolved identity strings must be 1β512 characters and serialized\nclaims are limited to 4096 characters. A lookup must resolve exactly one active\nrow or authentication fails.\n\nOn success, actions receive `ctx.principal`:\n\n```typescript\n{\n type: \"event_delegate\",\n actor: { type: \"event_delegate\", id: \"person_123\" },\n session: { id: \"session_123\", familyId: \"family_123\" },\n claims: { eventId: \"event_123\", personId: \"person_123\" },\n}\n```\n\nQuickback never synthesizes `userId`, `activeOrgId`, `activeTeamId`, or\nmembership roles from a delegated credential. Use `principals` in an access\narm to admit it. Values inside one arm are ANDed; sibling `or` arms are ORed:\n\n```typescript\naccess: {\n or: [\n { roles: [\"AUTHENTICATED\"] },\n { principals: [\"event_delegate\"], record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n } },\n ],\n}\n```\n\nAn Authorization header cannot be combined with `x-api-key` or a Better Auth\nsession cookie. Quickback recognizes only Better Auth's exact session cookie\nnames for this conflict check, so analytics and preference cookies remain\nharmless.\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Neon Foreign Key Migrations\n\nUse `compiler.migrations.foreignKeys` when a Neon relationship cannot be\nexpressed in one generated Drizzle schema fileβfor example, a feature table\nthat references a Better Auth table, or a composite integrity relationship\nbetween independently authored feature modules.\n\n```typescript\nexport default defineConfig({\n // ...\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", { connectionMode: \"hyperdrive\" }),\n auth: defineAuth(\"better-auth\"),\n },\n compiler: {\n migrations: {\n foreignKeys: [\n {\n name: \"person_account_links_user_fk\",\n source: {\n schema: \"app\",\n table: \"person_account_links\",\n columns: [\"user_id\"],\n },\n target: {\n schema: \"auth\",\n table: \"users\",\n columns: [\"id\"],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n {\n name: \"event_access_grants_consumed_family_fk\",\n source: {\n schema: \"app\",\n table: \"event_access_grants\",\n columns: [\n \"consumed_by_family_id\",\n \"id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n target: {\n schema: \"app\",\n table: \"event_session_families\",\n columns: [\n \"id\",\n \"source_grant_id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n ],\n },\n },\n});\n```\n\nAll identifiers must be lowercase Postgres identifiers of at most 63\ncharacters. Source and target tuples must be nonempty and have equal arity;\ncolumn order is significant. Supported actions are `\"no action\"`,\n`\"restrict\"`, `\"cascade\"`, `\"set null\"`, and `\"set default\"`.\n\nConstraint names and source tuples must be unique in the config. On replay,\nQuickback verifies that an existing same-named constraint has the exact target,\nordered columns, and referential actions. It fails instead of silently\naccepting an ambiguous definition. Existing rows are validated during\nmigration, so clean up orphans before deploying.\n\nThis API is for database integrity, not business behavior. Keep authorization,\nstate transitions, event-pass consumption, and other business rules in the API\naction layer.\n\n## Disable Audit Field Injection\n\nQuickback manages four **audit columns** (`createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`) on every feature table, plus two **soft-delete columns** (`deletedAt`, `deletedBy`) on tables whose resource uses soft delete (the default delete mode). The audit columns drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nYou declare them in the table's `columns` object with `...q.audit()` and `...q.softDelete()`. The compiler validates every managed column against its canonical shape and fails the compile when one is missing, diverges, or is present on a hard-delete table β run `quickback migrate visible-columns` to adopt the declarations on an existing project. Set `compiler.features.visibleAuditColumns: false` to downgrade those checks to warnings and keep the pre-v0.57.0 silent-injection behavior.\n\nTo opt out of the managed columns entirely, project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema β Audit Fields](/define/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces β they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` and `/auth/v1/*` for the default contract, or `/api/v2/*` and\n `/auth/v2/*` when `contract.version` is `\"v2\"`\n- `/storage/*` β R2 file storage\n- `/health`, `/openapi.json` β monitoring/discovery\n- `/account/*`, `/cms/*` β bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime; `/broadcast/v2/*` under `contract.version: 'v2'`), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling β `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ β backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** β the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/{version}/users` | `/api/{version}/users` | `{version}` is the selected `v1` or `v2`; the rewriter prepends `/api` |\n| `https://auth.example.com/{version}/sign-in/email` | `/auth/{version}/sign-in/email` | Same selected version with `/auth` |\n| `https://api.example.com/api/{version}/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/{version}/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception β monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/{version}/users` | feature route | Works for the selected version whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/{version}/sign-in/email` | Better Auth | Works for the selected version whether `auth.domain` is set or not |\n| `https://quickback.example.com/{version}/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when β₯2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker β no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Admin UI](/ui/admin) in your compiled Worker. It reads your schema registry and renders a complete admin interface β zero UI code per table.\n\n```typescript\n// Simple β embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier β sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | β | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/ui/admin/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/define/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool β debugging a tenant's data, running cross-tenant queries, supporting a customer β that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` β appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/define/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table β every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/ui/account) in your compiled Worker. Provides login, signup, profile management, organization management, and admin β all built from your config at compile time.\n\nFor post-signup logic β auto-provisioning a workspace, gating signup, setting an active organization β drop a file in `quickback/hooks/`. See [Auth Hooks](/ui/account/hooks).\n\n```typescript\n// Simple β embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA β the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application β where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config β so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` β the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication β both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login β adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication β adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration β false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | β | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | β | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config β no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) β uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES β requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n- Types the binding with Cloudflare's native `SendEmail` / `EmailSendResult`\n contract (`{ email, name }`, `replyTo`, and `contentId` on Workers). The REST\n helper remains a separate `{ address, name }` / `reply_to` / `content_id`\n contract.\n- Anchors each authentication delivery to `executionCtx.waitUntil(...)`. The\n background promise records a structured generic failure and stays rejected;\n outside a Worker request, the callback returns the observed promise for the\n caller to await. Every Cloudflare Email callback is wired through that shared\n scheduler exactly once, so no auth action can bypass failure observation or\n double-schedule the send. Provider error bodies are never written to\n generated logs.\n\nβ¦whenever any auth surface needs to send mail β `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins β or you set the top-level `email: {β¦}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/configure/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/configure/providers) β Runtime, database, and auth options\n- [Variables](/configure/variables) β Environment variables and flags\n- [Output](/tooling/output) β Generated file structure\n- [Pinned Organization Mode](/configure/single-tenant) β Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/configure/domains) β Custom domains, hostname routing, and cross-subdomain auth"
|
|
86
|
+
"content": "The `quickback.config.ts` file configures your Quickback project. It defines which providers to use, which features to enable, and how the compiler generates code.\n\n```typescript\nimport { defineConfig, defineRuntime, defineDatabase, defineAuth } from \"@quickback/compiler\";\n\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n auth: {\n // Required for \"+\" role expansion in access rules (e.g. roles: [\"member+\"]).\n // Lowest β highest. Omit if you always list roles explicitly.\n roleHierarchy: [\"member\", \"admin\", \"owner\"],\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\n## Discoverable options block\n\nAfter your first `quickback compile`, the file gets a managed block bracketed by sentinel comments:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n // [quickback:options-start]\n // ββ Project ββ\n //\n // Primary custom domain (auto-inferred from cms/account/api domains if unset).\n // domain: \"example.com\",\n //\n // ββ Embedded UIs (CMS / Account) ββ\n //\n // Login/signup/profile/orgs SPA. Set `true` for default, or object to customize.\n // account: {\n // fileUploads: false, // show the avatar upload UI on the profile page\n // auth: { passkey: false, emailOTP: false, ... },\n // ...\n // },\n //\n // ... every other option Quickback supports\n // [quickback:options-end]\n});\n```\n\nThis block is **regenerated on every compile** β the compiler is the source of truth, so newly added options surface automatically when you upgrade Quickback (no CLI bump needed).\n\n**To enable an option**, copy the line you care about *above* the `[quickback:options-start]` sentinel and uncomment it:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n providers: cloudflare({}),\n\n account: {\n fileUploads: true, // β lifted out of the managed block\n },\n\n // [quickback:options-start]\n // ... account is now omitted from this block on next compile\n // [quickback:options-end]\n});\n```\n\nQuickback notices that `account` is set above the marker and drops it from the managed block on the next compile to avoid duplicate definitions. Anything outside the marker block is yours and never touched.\n\nIf you ever want to opt out of the auto-managed block, run:\n\n```bash\nquickback compile --no-sync-config\n```\n\n## Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | `string` | Project name |\n| `template` | `\"hono\"` | Application template. `\"hono\"` is the only accepted value. |\n| `providers` | `object` | Runtime, database, and auth provider configuration |\n\n## Optional Fields\n\nEvery optional top-level key the config accepts is listed below. You never have to memorize them β after your first compile, the [discoverable options block](#discoverable-options-block) lists each one (minus the ones you've set) right inside your `quickback.config.ts`. This table is the human reference; follow the links for detailed pages.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) β see [Domains](/configure/domains) |\n| `contract` | `{ version?: \"v1\" \\| \"v2\" }` | Public API/auth contract version. Omit for the backward-compatible v1 default; select v2 for `/api/v2/*` and `/auth/v2/*` across generated routes, Better Auth, OpenAPI, MCP, and discovery. |\n| `api` | `object` | Dedicated hostname for the selected feature API contract (`/api/v1/*` or `/api/v2/*`); additive alias β see [Domains](/configure/domains) |\n| `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, delegated `principals`, `loginUrl`/`profileUrl`, `domain`) β see [Access](/define/access#role-hierarchy) and [Delegated principals](#delegated-principals-contract-v2) |\n| `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `rules`, `tenants`, `permissions`, `arrows`) β see [Access](/define/authz-roles#centrally-defined-access-rules) and [Permissions](/define/permissions). `rules` = named gates (who + `record:` + firewall lanes under one name); `tenants` = named tenant anchors (`{ column, equals }`, referenced as `{ tenant: '<name>' }` in firewalls and `tenant: '<name>'` in auth-view includes). Root `authz` is the GLOBAL vocabulary level β names scoped to one concept belong in that concept's [feature area](/define/areas) (`_area.ts`), and root bodies may reference root-declared names only |\n| `requires` | `string[]` | Capability floor (fail-closed guard). Declare `['feature-areas']` when the project uses `features/**/_area.ts` β an area-unaware CLI/compiler then refuses the compile instead of silently dropping nested features. See [Feature areas](/define/areas#the-capability-floor-requires-feature-areas) |\n| `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |\n| `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` β see [Pinned Organization Mode](/configure/single-tenant) |\n| `cms` | `boolean \\| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) β see [CMS](/ui/admin) |\n| `account` | `boolean \\| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) β see [Account UI](/ui/account) |\n| `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix β see [Domains](/configure/domains) |\n| `agents` | `boolean \\| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) β see [Agents](/configure/agents) |\n| `security` | `object \\| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) β see [Security Headers](/configure/security) |\n| `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \\| 'swagger'`, `types`) β see [OpenAPI](/api/openapi) |\n| `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) β see [Schema Registry](/ui/admin/schema-registry) |\n| `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) β see [Caching & ETags](/api/caching) |\n| `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) β see [Email Configuration](#email-configuration) |\n| `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) β see [Bindings](/configure/bindings) |\n| `compiler` | `object` | Compiler internals β `features.auditFields: false`, `migrations.renames` (headless CI), Neon `migrations.foreignKeys`, `securityContracts`, `injectId`, `routes` |\n| `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) β see [Custom Dependencies](#custom-dependencies) |\n| `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) β see [Variables](/configure/variables) |\n| `preset` | `string` | Inherit defaults from a named preset |\n\n## Public contract version\n\nQuickback defaults to the existing v1 HTTP contract. New applications can opt\ninto v2 explicitly:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n contract: { version: \"v2\" },\n providers: cloudflare({}),\n});\n```\n\nThe selection is atomic: feature routes move to `/api/v2/*`, Better Auth moves\nto `/auth/v2/*`, and generated OpenAPI, MCP tool calls, OAuth discovery,\n`llms.txt`, schema/embeddings routes, and dedicated-domain `/v2/*` shortcuts\nuse the same version. When CMS or Account is enabled, Quickback also bakes\nthose paths into the SPA build and injects them at runtime, so CRUD, schema,\nlive-view, and authentication requests use the selected contract. Quickback\ndoes not expose a mixed v1/v2 surface from one compiled Worker. Omitting\n`contract` remains byte-compatible with v1 projects.\n\nV2 also makes action input-schema fidelity a compile gate. The CLI must\nsuccessfully harvest `z.toJSONSchema(action.input)` for every authored action;\npartial or missing harvests fail with the exact action file keys, bundle or\nevaluation phase, and underlying local error. Dependencies are resolved from\nthe generated runtime's `build.outputDir/node_modules` before unrelated\nancestor installs, so an isolated `quickback/` definition tree can use a\nsibling `src/` runtime without a workspace-root symlink. The compiler enforces\nthe same invariant at its shared input boundary, including\n`POST /compile?complete=false`, so validation-only or raw API calls cannot\nbypass it. V1 retains the historical best-effort static-schema fallback.\n\nThe version selection also moves the event and read surfaces:\n\n| Surface | v1 (pinned) | v2 (flagship) |\n|---|---|---|\n| Realtime data frames (`/broadcast/*`) | raw frames, byte-stable | CloudEvents 1.0 envelopes at DO egress ([realtime](/platform/realtime)) |\n| Outbound webhook signing | Standard Webhooks headers **plus** legacy `X-Webhook-*` | Standard Webhooks **only** |\n| `?include=` FK-graph embedding | not available | available where a resource/view allowlists it |\n| Bare `?fields=` / `fields[<fk>]=` unknown names | silent drop / n/a | 400 on both |\n\nSee [API Contract](/platform/api-contract) for the full v1 β v2 matrix and\nmigration sequencing.\n\n## Delegated principals (contract v2)\n\n`auth.principals` defines non-account authority such as an event pass or a\nshort-lived event session. It is available only with all three of:\n\n- `contract: { version: \"v2\" }`\n- the Cloudflare runtime\n- Neon with `connectionMode: \"hyperdrive\"`\n\nEach principal type owns an exact Authorization scheme. `Bearer` is reserved\nfor Quickback account authentication, including case variants, and two\nprincipal types cannot share a scheme.\n\n```typescript\nexport default defineConfig({\n name: \"attend-v2\",\n template: \"hono\",\n contract: { version: \"v2\" },\n auth: {\n principals: {\n event_pass: {\n scheme: \"EventPass\",\n authenticate: {\n module: \"./event-pass-proof\",\n export: \"authenticateEventPass\",\n },\n lookup: {\n table: {\n module: \"../features/event-access/event-access\",\n export: \"eventAccess\",\n sqlName: \"event_access\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n event_delegate: {\n scheme: \"EventSession\",\n authenticate: {\n module: \"./event-session-proof\",\n export: \"authenticateEventSession\",\n },\n lookup: {\n table: {\n module: \"../features/event-sessions/event-sessions\",\n export: \"eventSessions\",\n sqlName: \"event_sessions\",\n },\n digest: { field: \"digest\", column: \"digest\" },\n actorId: { field: \"personId\", column: \"person_id\" },\n sessionId: { field: \"id\", column: \"id\" },\n familyId: { field: \"familyId\", column: \"family_id\" },\n claims: {\n eventId: { field: \"eventId\", column: \"event_id\" },\n personId: { field: \"personId\", column: \"person_id\" },\n },\n status: { field: \"status\", column: \"status\", allow: [\"active\"] },\n },\n },\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", {\n connectionMode: \"hyperdrive\",\n hyperdrive: { id: \"<32-character-hyperdrive-id>\" },\n }),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThe `authenticate.module` path is relative to generated\n`src/lib/principal-auth.ts`. Put project proof hooks under `quickback/lib`; the\ncompiler stages them into `src/lib` even if no action imports them. A hook has\none job: prove the presented credential and return its stable digest.\n\n```typescript\n// quickback/lib/event-session-proof.ts\nexport async function authenticateEventSession({ credential, env, request }: {\n credential: string;\n env: Env;\n request: Request;\n}): Promise<{ digest: string } | null> {\n const valid = await verifySignedEventSession(credential, env, request);\n return valid ? { digest: await sha256(credential) } : null;\n}\n```\n\nThe hook receives no `db`, and it must not implement row authorization or\nbusiness behavior. Quickback performs exactly one narrow, unique digest lookup\nunder a lookup-only RLS principal. A digest must be 16β512 non-whitespace\ncharacters; resolved identity strings must be 1β512 characters and serialized\nclaims are limited to 4096 characters. A lookup must resolve exactly one active\nrow or authentication fails.\n\nOn success, actions receive `ctx.principal`:\n\n```typescript\n{\n type: \"event_delegate\",\n actor: { type: \"event_delegate\", id: \"person_123\" },\n session: { id: \"session_123\", familyId: \"family_123\" },\n claims: { eventId: \"event_123\", personId: \"person_123\" },\n}\n```\n\nQuickback never synthesizes `userId`, `activeOrgId`, `activeTeamId`, or\nmembership roles from a delegated credential. Use `principals` in an access\narm to admit it. Values inside one arm are ANDed; sibling `or` arms are ORed:\n\n```typescript\naccess: {\n or: [\n { roles: [\"AUTHENTICATED\"] },\n { principals: [\"event_delegate\"], record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n } },\n ],\n}\n```\n\nAn Authorization header cannot be combined with `x-api-key` or a Better Auth\nsession cookie. Quickback recognizes only Better Auth's exact session cookie\nnames for this conflict check, so analytics and preference cookies remain\nharmless.\n\n## Custom Dependencies\n\nAdd third-party npm packages to the generated `package.json` using `build.dependencies`. This is useful when your action handlers import external libraries.\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n template: \"hono\",\n build: {\n dependencies: {\n \"fast-xml-parser\": \"^4.5.0\",\n \"lodash-es\": \"^4.17.21\",\n },\n },\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"cloudflare-d1\"),\n auth: defineAuth(\"better-auth\"),\n },\n});\n```\n\nThese are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.\n\n## Headless Migration Rename Hints\n\nWhen `drizzle-kit generate` detects a potential rename, it normally prompts for confirmation. Cloud/CI compiles are non-interactive, so you must provide explicit rename hints.\n\nAdd hints in `compiler.migrations.renames`:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n migrations: {\n renames: {\n // Keys are NEW names, values are OLD names\n tables: {\n events_v2: \"events\",\n },\n columns: {\n events: {\n summary_text: \"summary\",\n },\n },\n },\n },\n },\n});\n```\n\nRules:\n- `tables`: `new_table_name -> old_table_name`\n- `columns.<table>`: `new_column_name -> old_column_name`\n- Keys must match the names in your current schema (the new names)\n- Validation fails fast for malformed rename config, unsupported keys, or conflicting legacy/new rename paths.\n\n## Neon Foreign Key Migrations\n\nUse `compiler.migrations.foreignKeys` when a Neon relationship cannot be\nexpressed in one generated Drizzle schema fileβfor example, a feature table\nthat references a Better Auth table, or a composite integrity relationship\nbetween independently authored feature modules.\n\n```typescript\nexport default defineConfig({\n // ...\n providers: {\n runtime: defineRuntime(\"cloudflare\"),\n database: defineDatabase(\"neon\", { connectionMode: \"hyperdrive\" }),\n auth: defineAuth(\"better-auth\"),\n },\n compiler: {\n migrations: {\n foreignKeys: [\n {\n name: \"person_account_links_user_fk\",\n source: {\n schema: \"app\",\n table: \"person_account_links\",\n columns: [\"user_id\"],\n },\n target: {\n schema: \"auth\",\n table: \"users\",\n columns: [\"id\"],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n {\n name: \"event_access_grants_consumed_family_fk\",\n source: {\n schema: \"app\",\n table: \"event_access_grants\",\n columns: [\n \"consumed_by_family_id\",\n \"id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n target: {\n schema: \"app\",\n table: \"event_session_families\",\n columns: [\n \"id\",\n \"source_grant_id\",\n \"organization_id\",\n \"event_id\",\n \"event_person_id\",\n ],\n },\n onDelete: \"restrict\",\n onUpdate: \"restrict\",\n },\n ],\n },\n },\n});\n```\n\nAll identifiers must be lowercase Postgres identifiers of at most 63\ncharacters. Source and target tuples must be nonempty and have equal arity;\ncolumn order is significant. Supported actions are `\"no action\"`,\n`\"restrict\"`, `\"cascade\"`, `\"set null\"`, and `\"set default\"`.\n\nConstraint names and source tuples must be unique in the config. On replay,\nQuickback verifies that an existing same-named constraint has the exact target,\nordered columns, and referential actions. It fails instead of silently\naccepting an ambiguous definition. Existing rows are validated during\nmigration, so clean up orphans before deploying.\n\nThis API is for database integrity, not business behavior. Keep authorization,\nstate transitions, event-pass consumption, and other business rules in the API\naction layer.\n\n## Disable Audit Field Injection\n\nQuickback manages four **audit columns** (`createdAt`, `modifiedAt`, `createdBy`, `modifiedBy`) on every feature table, plus two **soft-delete columns** (`deletedAt`, `deletedBy`) on tables whose resource uses soft delete (the default delete mode). The audit columns drive record-provenance queries and the CMS audit panel; the soft-delete pair drives soft-delete filtering.\n\nYou declare them in the table's `columns` object with `...q.audit()` and `...q.softDelete()`. The compiler validates every managed column against its canonical shape and fails the compile when one is missing, diverges, or is present on a hard-delete table β run `quickback migrate visible-columns` to adopt the declarations on an existing project. Set `compiler.features.visibleAuditColumns: false` to downgrade those checks to warnings and keep the pre-v0.57.0 silent-injection behavior.\n\nTo opt out of the managed columns entirely, project-wide:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n compiler: {\n features: {\n auditFields: false, // skip audit-field injection globally\n },\n },\n providers: { /* ... */ },\n});\n```\n\nWhen disabled, you're responsible for supplying these columns yourself if you want soft delete, audit trails, or modifiedAt-based optimistic concurrency. See the [Schema β Audit Fields](/define/schema#audit-fields) section for the full list and what each field drives.\n\n## Security Contract Reports and Signing\n\nAfter generation, Quickback verifies machine-checkable security contracts for Hono routes and RLS SQL.\n\nIt also emits a report artifact and signature artifact by default:\n\n- `reports/security-contracts.report.json`\n- `reports/security-contracts.report.sig.json`\n\nYou can configure output paths and signing behavior:\n\n```typescript\nexport default defineConfig({\n // ...\n compiler: {\n securityContracts: {\n failMode: \"error\", // or \"warn\"\n report: {\n path: \"reports/security-contracts.report.json\",\n signature: {\n enabled: true,\n required: true,\n keyEnv: \"QUICKBACK_SECURITY_REPORT_SIGNING_KEY\",\n keyId: \"prod-k1\",\n path: \"reports/security-contracts.report.sig.json\",\n },\n },\n },\n },\n});\n```\n\nIf `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: \"warn\"`).\n\n## Hostname architecture (v0.33+)\n\nA modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. By default, everything lives under a single unified backend hostname (auto-inferred as `quickback.{baseDomain}` from your other configured subdomains, or overridable via `config.domain`). For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces β they're additive aliases, never replacements.\n\n### The unified backend contract\n\nWhen any subdomain is configured (`account.domain`, `cms.domain`, `auth.domain`, `api.domain`, `apps.<n>.domain`), the compiler always emits a unified backend host where **every compiler-emitted backend route** is reachable:\n\n- `/api/v1/*` and `/auth/v1/*` for the default contract, or `/api/v2/*` and\n `/auth/v2/*` when `contract.version` is `\"v2\"`\n- `/storage/*` β R2 file storage\n- `/health`, `/openapi.json` β monitoring/discovery\n- `/account/*`, `/cms/*` β bundled SPAs (when enabled)\n- `/broadcast/v1/*` (realtime; `/broadcast/v2/*` under `contract.version: 'v2'`), `/mcp` (MCP), etc.\n\nThe unified hostname is `quickback.{baseDomain}` by default (where baseDomain is extracted from your first configured subdomain). Override with `config.domain` if you prefer a different name.\n\nThis contract is forward-pointing: it gives a stable URL pattern for future management tooling β `https://quickback.{baseDomain}/...` will always reach a Quickback backend regardless of how the operator splits their surfaces.\n\n### Dedicated hostnames (optional, additive)\n\nFor branding or operational separation, you can opt specific surfaces onto their own hostnames:\n\n```ts\n{\n // Bundled SPAs on their own hosts (already-shipped pattern):\n cms: { domain: 'cms.example.com' },\n account: { domain: 'account.example.com' },\n\n // v0.33+ β backend surfaces on their own hosts:\n auth: { domain: 'auth.example.com' },\n api: { domain: 'api.example.com' },\n\n // User SPAs (existing pattern):\n apps: {\n www: { domain: 'app.example.com' },\n },\n}\n```\n\nOn a dedicated hostname, **the hostname IS the namespace** β the path drops the prefix that matches the hostname:\n\n| URL on dedicated host | Internally rewritten to | Notes |\n|---|---|---|\n| `https://api.example.com/{version}/users` | `/api/{version}/users` | `{version}` is the selected `v1` or `v2`; the rewriter prepends `/api` |\n| `https://auth.example.com/{version}/sign-in/email` | `/auth/{version}/sign-in/email` | Same selected version with `/auth` |\n| `https://api.example.com/api/{version}/users` | (unchanged) | Long form also accepted |\n| `https://api.example.com/auth/{version}/sign-in` | **404** | Auth doesn't live on the API hostname |\n| `https://api.example.com/health` | (unchanged) | Explicit exception β monitoring agents expect `/health` everywhere |\n\nDual-reach is preserved on the unified host:\n\n| URL on unified host | Handler | Notes |\n|---|---|---|\n| `https://quickback.example.com/api/{version}/users` | feature route | Works for the selected version whether `api.domain` is set or not |\n| `https://quickback.example.com/auth/{version}/sign-in/email` | Better Auth | Works for the selected version whether `auth.domain` is set or not |\n| `https://quickback.example.com/{version}/users` | **404** | Shortcut only applies on dedicated hostnames |\n\nEach dedicated hostname also:\n\n- Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically\n- Joins `trustedOrigins` for CORS\n- Joins the cross-subdomain cookie inference (auto-enables `crossSubDomainCookies` when β₯2 same-parent subdomains are configured, so `auth.example.com` and `app.example.com` can share session cookies)\n- Joins CSP `connect-src` so SPAs can fetch from it\n\n### Why two URL shapes (Shape 1 vs Shape 2)\n\nIf you only want Better Auth to **advertise** itself on a different URL (e.g. so verification emails link to `auth.example.com` instead of the unified host), set the `BETTER_AUTH_URL` env var on the Worker β no code change required. BA generates outgoing URLs against that value. This is sufficient when the goal is branding email/OAuth callback URLs without changing where requests actually land.\n\n`auth.domain` (Shape 1, above) is the heavier option: it binds an actual hostname to the Worker, configures CORS/cookies/CSP for it, and adds the path-shortcut rewriter. Use it when you want the dedicated hostname as a real ingress, not just a label.\n\n## CMS Configuration\n\nEmbed the [Admin UI](/ui/admin) in your compiled Worker. It reads your schema registry and renders a complete admin interface β zero UI code per table.\n\n```typescript\n// Simple β embed CMS at root\ncms: true,\n\n// With custom domain\ncms: { domain: \"cms.example.com\" },\n\n// With access control (only admins can access CMS)\ncms: { domain: \"cms.example.com\", access: \"admin\" },\n\n// Cross-tenant DB-admin tier β sysadmins see every tenant's data\ncms: { domain: \"cms.example.com\", sysadmin: true },\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `domain` | `string` | β | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |\n| `access` | `\"user\" \\| \"admin\"` | `\"admin\"` | Controls who can access the CMS. When `\"admin\"`, platform control-plane users (`user.role === \"appmanager\"`) can enter; when `sysadmin` mode is also on, `user.role === \"sysadmin\"` is admitted too. The gate is enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to callers outside those roles) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/ui/admin/connecting) for the full enforcement model. |\n| `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === \"sysadmin\"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's \"All organizations\" sentinel. The CMS HTML gate admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Off by default. See [`SYSADMIN` pseudo-role](/define/access#sysadmin--cross-tenant-db-admin-tier). |\n\n### Sysadmin tier (`cms.sysadmin: true`)\n\nQuickback's default model assumes every CMS user belongs to at least one organization (`member` row in the auth DB). For platforms that need a Supabase-style cross-tenant DB-admin tool β debugging a tenant's data, running cross-tenant queries, supporting a customer β that's a poor fit: a sysadmin without `member` rows would dead-end, and auto-filling their active org from \"first membership\" silently scopes them to a tenant they have no relationship with.\n\n`cms: { sysadmin: true }` introduces a separate role tier:\n\n- **Role**: `user.role === \"sysadmin\"` (set on the Better Auth user table). Distinct from `\"appmanager\"` β appmanagers keep platform control-plane access (CMS shell, Better Auth admin surfaces, support tooling), while sysadmins get true cross-tenant data access. `ADMIN` is now a rejected legacy pseudo-role; use `userRole: [\"appmanager\"]` for control-plane gates and `roles: [\"SYSADMIN\"]` for cross-tenant access.\n- **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === \"sysadmin\") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/define/firewall#sysadmin-escape-hatch).\n- **Org listing**: a `GET /auth/v1/admin/list-organizations` endpoint selects directly from the auth-schema `organization` table β every row, every tenant. Sits under Better Auth's admin URL namespace (sibling of `/auth/v1/admin/list-users`) so the URL shape matches BA convention; the handler is Quickback-emitted and gated to `user.role === \"sysadmin\"` only. For the membership-bound caller's-orgs listing, use BA's own `/auth/v1/organization/list`.\n- **CMS SPA**: when the user is a sysadmin, the header switcher loads from the cross-tenant endpoint, defaults to \"All organizations\" (which omits `?organizationId=` and reaches the firewall escape), and pins selected tenants via `?organizationId=` on every API call. Org admins keep the existing membership-based switcher.\n- **CMS HTML gate**: admits `userRole === \"sysadmin\"` alongside `\"appmanager\"`. Org admins are not locked out when you set `cms.access: \"user\"`; `cms.access: \"admin\"` is specifically the platform control-plane gate.\n\nOff by default. Projects that don't enable it get zero behavior change; setting `cms.sysadmin: true` and granting a user `user.role = \"sysadmin\"` is the only way to unlock the cross-tenant view.\n\n## Account UI Configuration\n\nEmbed the [Account UI](/ui/account) in your compiled Worker. Provides login, signup, profile management, organization management, and admin β all built from your config at compile time.\n\nFor post-signup logic β auto-provisioning a workspace, gating signup, setting an active organization β drop a file in `quickback/hooks/`. See [Auth Hooks](/ui/account/hooks).\n\n```typescript\n// Simple β embed Account UI with defaults\naccount: true,\n\n// Full configuration\naccount: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"My Company\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: true,\n admin: true,\n },\n},\n```\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `domain` | `string` | Custom domain for Account UI (e.g., `auth.example.com`) |\n| `adminDomain` | `string` | Custom domain for admin-only access (e.g., `admin.example.com`). Serves the same Account SPA β the client-side router handles admin routing. |\n| `appUrl` | `string` | URL of the tenant's main application β where users are redirected after login. Baked into the Account SPA as `VITE_QUICKBACK_APP_URL`. Independent from `domain`. |\n| `name` | `string` | App display name shown on login, profile, and email templates |\n| `companyName` | `string` | Company name for branding |\n| `tagline` | `string` | App tagline shown on login page |\n| `description` | `string` | App description |\n\n### Auth Feature Flags\n\nControl which authentication features are exposed. Disabled features are excluded from the Account UI bundle at compile time (routes removed before the Vite build, keeping bundle sizes minimal) **and** enforced on the server side via the Better Auth config β so \"signup off\" actually closes `POST /auth/v1/sign-up/email`, not just the SPA's signup screen.\n\n`account.auth.*` is a shorthand for `providers.auth.config` β the compiler maps each flag onto the Better Auth server config before any code is generated. You can write either side directly; setting both incompatibly (e.g. `account.auth.signup: false` and `emailAndPassword.disableSignUp: false`) fails the compile with a precise error rather than picking a silent winner.\n\n| Flag | Type | Default | Maps to (server) | Description |\n|------|------|---------|------------------|-------------|\n| `auth.password` | `boolean` | `true` | `emailAndPassword.enabled` | Email/password authentication β both server endpoint and UI |\n| `auth.emailOTP` | `boolean` | `false` | adds `emailOtp` plugin | Email one-time password login β adds plugin server-side, surfaces UI |\n| `auth.passkey` | `boolean` | `false` | adds `passkey` plugin | WebAuthn/FIDO2 passkey authentication β adds plugin server-side, surfaces UI |\n| `auth.signup` | `boolean` | `true` | `emailAndPassword.disableSignUp` (inverted) | Self-service account registration β false hides the UI **and** rejects the server endpoint with 403 |\n| `auth.organizations` | `boolean` | `true` | UI surface only | Organization management UI (dashboard, invitations, roles). Server-side organization support stays on regardless; set `features.pinnedOrganizationId` when you want one fixed org with no switching UI |\n| `auth.admin` | `boolean` | `false` | UI surface only | Admin panel for user management in the Account SPA. The Better Auth admin plugin is compiler-managed separately from this UI toggle |\n| `auth.emailVerification` | `boolean` | `false` | `emailAndPassword.requireEmailVerification` | Require email verification before sessions are issued. False = sessions usable immediately after signup |\n\n## Trusted Origins\n\nList of origins allowed to make cross-origin requests to your API. Required when your CMS, Account UI, or frontend app run on different domains.\n\n```typescript\ntrustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://app.example.com\",\n],\n```\n\n## Local Development\n\nConfigure local development URLs. These are automatically added to the trusted origins list for CORS and Better Auth, so authentication works out of the box during local development.\n\n```typescript\ndev: {\n port: 8787, // wrangler dev port (default: 8787)\n api: \"http://localhost:8787\", // API backend URL\n cms: \"http://localhost:8787/cms\", // CMS URL (path on same worker)\n account: \"http://localhost:8787/account\", // Account URL (path on same worker)\n},\n```\n\nIf you run a SPA standalone on its own Vite dev server, set its URL here so CORS allows it:\n\n```typescript\ndev: {\n port: 8787,\n api: \"http://localhost:8787\",\n account: \"http://localhost:5173\", // standalone Account dev server\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `port` | `number` | `8787` | Local dev server port (sets `[dev].port` in wrangler.toml) |\n| `api` | `string` | `http://localhost:{port}` | API backend URL |\n| `cms` | `string` | β | CMS dev URL (added to trusted origins if set) |\n| `account` | `string` | β | Account dev URL (added to trusted origins if set) |\n\n## Email Configuration\n\nConfigure email delivery for authentication emails (verification, password reset, invitations).\n\n> **Cloudflare Email Sending is now in public beta** and is Quickback's default transport for Cloudflare deploys. The Workers `send_email` binding is zero-config β no API keys, no third-party accounts. AWS SES remains supported as an explicit opt-in (`email.provider: 'aws-ses'`) for non-Cloudflare runtimes or existing SES setups.\n\n```typescript\n// Cloudflare Email Service (default) β uses send_email binding, no API keys needed\nemail: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n\n// AWS SES β requires AWS credentials set as Wrangler secrets\nemail: {\n provider: \"aws-ses\",\n region: \"us-east-2\",\n from: \"noreply@example.com\",\n fromName: \"My App\",\n},\n```\n\n| Field | Type | Default | Description |\n|-------|------|---------|-------------|\n| `provider` | `\"cloudflare\" \\| \"aws-ses\"` | `\"cloudflare\"` | Email transport |\n| `from` | `string` | `\"noreply@example.com\"` | Sender email address |\n| `fromName` | `string` | `\"{name} \\| Account Services\"` | Sender display name |\n| `region` | `string` | `\"us-east-2\"` | AWS SES region (aws-ses only) |\n\n### Auto-wiring\n\nFor the Cloudflare provider (the default), the compiler automatically:\n- Emits `[[send_email]] EMAIL` into `wrangler.toml`\n- Generates `src/lib/cloudflare-email.ts`\n- Wires `sendResetPassword`, `sendVerificationEmail`, `sendInvitationEmail`, etc. into Better Auth\n- Types the binding with Cloudflare's native `SendEmail` / `EmailSendResult`\n contract (`{ email, name }`, `replyTo`, and `contentId` on Workers). The REST\n helper remains a separate `{ address, name }` / `reply_to` / `content_id`\n contract.\n- Anchors each authentication delivery to `executionCtx.waitUntil(...)`. The\n background promise records a structured generic failure and stays rejected;\n outside a Worker request, the callback returns the observed promise for the\n caller to await. Every Cloudflare Email callback is wired through that shared\n scheduler exactly once, so no auth action can bypass failure observation or\n double-schedule the send. Provider error bodies are never written to\n generated logs.\n\nβ¦whenever any auth surface needs to send mail β `emailAndPassword.enabled`, the `emailOtp` / `magicLink` / `organization` plugins β or you set the top-level `email: {β¦}` config. You don't need to add `bindings.sendEmail` by hand for the standard cases.\n\n> **Cloudflare Email Routing setup is required.** The binding alone does not deliver mail. Enable Email Routing on the sending zone and add at least one verified destination address ([Cloudflare docs](https://developers.cloudflare.com/email-routing/get-started/)). Otherwise sends fail at runtime even with the binding present and the `/auth/v1/ses/status` check passing locally.\n\n## Multi-Domain Example\n\nA complete config with CMS, Account UI, and Admin on separate subdomains:\n\n```typescript\nexport default {\n name: \"my-app\",\n template: \"hono\",\n cms: { domain: \"cms.example.com\", access: \"admin\" },\n account: {\n domain: \"auth.example.com\",\n adminDomain: \"admin.example.com\",\n name: \"My App\",\n companyName: \"Example Inc.\",\n auth: {\n password: true,\n emailOTP: false,\n passkey: true,\n organizations: false,\n admin: true,\n },\n },\n email: {\n from: \"noreply@example.com\",\n fromName: \"My App\",\n },\n trustedOrigins: [\n \"https://auth.example.com\",\n \"https://admin.example.com\",\n \"https://cms.example.com\",\n \"https://example.com\",\n ],\n providers: {\n runtime: { name: \"cloudflare\", config: {\n routes: [{ pattern: \"api.example.com\", custom_domain: true }],\n }},\n database: { name: \"cloudflare-d1\", config: { binding: \"DB\" } },\n auth: { name: \"better-auth\", config: { plugins: [\"admin\"] } },\n },\n};\n```\n\nThis produces a single Cloudflare Worker serving five domains. See [Multi-Domain Architecture](/configure/domains) for details on hostname routing, cross-subdomain cookies, and the unified fallback domain.\n\n---\n\nSee the sub-pages for detailed reference on each section:\n- [Providers](/configure/providers) β Runtime, database, and auth options\n- [Variables](/configure/variables) β Environment variables and flags\n- [Output](/tooling/output) β Generated file structure\n- [Pinned Organization Mode](/configure/single-tenant) β Fixed-org deployments without org switching UI\n- [Multi-Domain Architecture](/configure/domains) β Custom domains, hostname routing, and cross-subdomain auth"
|
|
87
87
|
},
|
|
88
88
|
"configure/providers": {
|
|
89
89
|
"title": "Providers",
|
|
@@ -103,11 +103,11 @@ export const DOCS = {
|
|
|
103
103
|
},
|
|
104
104
|
"define/access": {
|
|
105
105
|
"title": "Access - Role & Condition-Based Access Control",
|
|
106
|
-
"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\nimport { sqliteTable, text } from 'drizzle-orm/sqlite-core';\nimport { defineTable } from '@quickback/compiler';\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 // ββ quickback:audit (compiler-managed β edits are validated, not merged) ββ\n createdAt: text('created_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()),\n modifiedAt: text('modified_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()).$onUpdate(() => new Date().toISOString()),\n createdBy: text('created_by'),\n modifiedBy: text('modified_by'),\n deletedAt: text('deleted_at'),\n deletedBy: text('deleted_by'),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest β highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time β `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `SESSION`, `SCOPED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix β they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Custom org roles\n\nYou're not limited to Better Auth's built-in `owner` / `admin` / `member` β\nany lowercase role name you reference in an access tree (`\"recruiter\"`,\n`\"hiring-manager\"`, `\"support\"`, β¦) is a custom org-membership role, matched\nagainst `ctx.roles` like the built-ins.\n\nAs of v0.46, custom roles declared in access trees are **auto-registered\nwith the Better Auth organization plugin**, so members can actually be\nprovisioned into them: `invite-member` and `update-member-role` accept them\n(previously they rejected custom roles with `400 ROLE_NOT_FOUND`).\nAuto-registered roles carry member-equivalent Better Auth permissions β\nregistration is about assignability; your access trees remain the\nauthorization model. If you pass your own `roles` / `ac` to the organization\nplugin options, those win and auto-registration is skipped.\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic β user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column β independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused β get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" β not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND β the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix β user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships seven reserved UPPERCASE markers. Six are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none β explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` (a full session **or** a scope principal β the wrapper over `SESSION` βͺ `SCOPED`) |\n| `SESSION` | required | none | a full Better Auth session **only** β `ctx.authenticated && !ctx.principal && !ctx.scopePrincipal` |\n| `SCOPED` | required | none | a sessionless scope principal **only** β `ctx.authenticated && ctx.scopePrincipal === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | a real signed-in user β `ctx.authenticated` AND **not** a scope principal (`!ctx.scopePrincipal`) AND (`ctx.userRole` unset OR `=== \"user\"`). A sessionless scope caller does **not** satisfy `USER` (use `SCOPED` / `scope:<kind>:<role>`); `AUTHENTICATED` is the marker that admits both flavors. |\n| `ADMIN` | required | reserved legacy marker β compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list β they're OR'd together.\n\n#### `PUBLIC` β unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks β anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node β reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** β data is scoped by the firewall (organization, owner, team)\n- **Tree semantics:** `PUBLIC` admits anonymous callers from anywhere in the access tree, not just a flat `roles` list. An `or:` arm containing `PUBLIC` admits anonymous callers past the authentication gate; an `and:` group admits them only when *every* arm does. The access, org, and firewall layers still evaluate the full tree afterwards. (Before v0.46 the emitted auth gate only honored `PUBLIC` in a flat `roles` list β a nested `PUBLIC` arm incorrectly answered `401`.)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** β using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.\n\n`?organizationId=` is an account/public addressing surface. A request using a\nconfigured delegated principal cannot use it to acquire account organization\nauthority: the generated route returns `403 CROSS_TENANT_FORBIDDEN` and never\nadds `activeOrgId` or account roles to the delegated `AppContext`. Delegated\nscope continues to come only from the verified principal claims and database\nRLS policy.\n\n```typescript\n// quickback/features/listings/listings.ts\nimport { q, defineTable } from '@quickback/compiler';\n\n// Public listing page β anyone can browse, but scoped to an org\nexport const listings = q.table('listings', {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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 authenticated caller (the wrapper)\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in caller 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`AUTHENTICATED` is the **wrapper over two auth flavors** β it admits both a full Better Auth session **and** a sessionless scope principal (a scope-token holder, e.g. an event attendee who isn't an org member; see [Scopes](/define/scopes)). It excludes only *external delegated* principals (`ctx.principal`, admitted via `principals:`). When you need to distinguish the two flavors, use `SESSION` or `SCOPED` below; when either is fine, use `AUTHENTICATED`.\n\n#### `SESSION` β a full session only\n\nUse `roles: [\"SESSION\"]` when a route must admit **only** a full Better Auth session and **not** a sessionless scope principal. This is `AUTHENTICATED` minus scope-token callers.\n\n```typescript\n// Account settings β a real logged-in user, never a scope-token attendee\nread: { access: { roles: [\"SESSION\"] } }\n```\n\n#### `SCOPED` β a scope principal only\n\nUse `roles: [\"SCOPED\"]` for a route that is specifically for **sessionless scope-token callers** (a principal-only surface β e.g. a shared event link or kiosk token with no account). It admits any scope principal regardless of *which* scope; for a **specific** scoped role, use the `scope:<kind>:<role>` form instead (e.g. `scope:event:attendee` β see [Scopes](/define/scopes)).\n\n```typescript\n// Principal-only event surface β a scope token, no account required\nread: { access: { roles: [\"SCOPED\"] } }\n```\n\n> **Firewall coherence:** if an access surface admits a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) but the resource firewall can't filter that caller, the compiler **fails the build** β the caller would reach the handler yet see zero rows (a silent `200 + []`). Give the firewall a way to filter them: a `ctx.scope.<kind>` arm inside an `{ any: [...] }` group (compose org **or** scope β see [Firewall](/define/firewall)), a `via:` relationship, or `firewall: [{ exception: true }]`.\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 owner** β the role marker is the access half of the pair, the firewall is the row-filter half.\n\nThe owner column is `ownerId`. Name the column `ownerId` and the firewall is auto-derived (`WHERE ownerId = ctx.userId`, plus auto-stamping on insert); `userId` is **not** auto-detected on feature tables and must be declared explicitly. See [Firewall β `ownerId` vs `userId`](/define/firewall#ownerid-vs-userid).\n\n```typescript\n// quickback/features/todos/todos.ts\nimport { q, defineTable } from '@quickback/compiler';\n\n// \"My todos\" β each caller sees only their own rows\nexport const todos = q.table('todos', {\n id: q.id(),\n title: q.text().required(),\n done: q.bool().default(false).required(),\n ownerId: q.text().required(),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(todos, {\n firewall: [{ field: 'ownerId', 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 the firewall doesn't scope by owner, the compiler throws:\n\n```text\nResource \"todos\" uses roles: [\"USER\"] but the firewall does not scope by\nownerId. Add an ownerId column (auto-scoped) or an explicit owner predicate\n(firewall: [{ field: \"ownerId\", equals: \"ctx.userId\" }, ...]). If the column\nis named userId, declare it explicitly:\nfirewall: [{ field: \"userId\", equals: \"ctx.userId\" }]. If you want any\nsigned-in user to read all records, use roles: [\"AUTHENTICATED\"] instead.\n```\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically β appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` β legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` β cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins β the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top β so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/configure#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\n// (\"+\" requires auth.roleHierarchy in quickback.config.ts β see Role Hierarchy above)\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## Centrally defined access rules\n\nInstead of repeating the same `roles: [...]` expression across every feature, define it **once** in `authz.roles` and reference it by name everywhere. This is the recommended way to manage access as your app grows: one source of truth per rule, changed in one place.\n\nNamed roles (and named gates, tenant anchors, scope kinds) can be declared at **two levels**:\nat root `authz` in `quickback.config.ts` (visible everywhere), or inside a\n[feature area](/define/areas)'s `_area.ts` (visible to that area's\nsubtree only β a feature outside the area referencing the name is a compile error, and root\n`authz` bodies may reference root-declared names only). Declare each name in exactly one\nplace: re-declaring an inherited name is a compile error.\n\n```typescript\n// quickback.config.ts β define ONCE\nexport default defineConfig({\n // ...providers...\n authz: {\n roles: {\n // Compose from BA roles, pseudo-roles, and other named rules:\n staff: { roles: ['admin', 'member'] },\n // Boolean combinators:\n eventStaff: { or: [{ roles: ['staff'] }, { via: 'organizerOf' }] },\n // Relationship-backed (see below):\n attendee: { via: 'attendeeOf' },\n },\n },\n});\n```\n\n```typescript\n// any feature β REFERENCE by bare name\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const agendaItems = q.table('agendaItems', {\n id: q.id(),\n title: q.text().required(),\n startsAt: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(agendaItems, {\n read: { access: { roles: ['eventStaff'] } },\n update: { access: { roles: ['eventStaff'] } },\n});\n\n// features/events/actions/checkIn.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Check a guest in to the event and record the arrival time.\",\n input: z.object({ guestId: z.string() }),\n access: { roles: ['eventStaff', 'attendee'] },\n async execute({ db, input, ctx }) { /* ... */ },\n});\n```\n\n### Rule shapes\n\nEach entry in `authz.roles` is one of four shapes:\n\n| Shape | Meaning |\n|---|---|\n| `{ roles: ['admin', 'member'] }` | Composition β matches any of the listed roles (BA, pseudo, or other named rules) |\n| `{ or: [ruleA, ruleB] }` | Matches if **any** sub-rule matches |\n| `{ and: [ruleA, ruleB] }` | Matches only if **all** sub-rules match |\n| `{ via: 'relationshipName' }` | Caller proves a declared relationship β see [Relationship-based authorization](#relationship-based-authorization) below |\n\nRules compose freely β a rule may reference another rule by name (cycles are a compile error).\n\n### Where references resolve\n\nA named rule works in the `roles: [...]` array of every access surface. The compiler expands it at build time:\n\n| Surface | |\n|---|---|\n| `crud.*.access` | β |\n| `read.access` / `read.views.*.access` | β |\n| `masking.<field>.show` | β for role/composite rules; relationship (`via`) rules refused at compile (v1) |\n| `actions.<name>.access` | β |\n| `realtime.requiredRoles` | β β relationship arms fail closed at the WS handshake and are enforced by the row-stream firewall |\n\nNames that **aren't** declared in `authz.roles` β Better Auth roles, pseudo-roles like `AUTHENTICATED` β pass through untouched, so you can mix named rules and raw roles in the same array.\n\n### Beyond roles: named permissions\n\nFor access that traverses the data graph (FK hops, SpiceDB-style permission composition), see [`authz.permissions` + `authz.arrows`](/define/permissions) β the same define-once-reference-by-name model, one level richer than `authz.roles`.\n\n## Named gates (`authz.rules`)\n\n`authz.roles` centralizes the *who*. A **gate** (`authz.rules.<name>`) bundles a full access rule β *who* + an optional row predicate (`record:`) + optional [firewall lanes](/define/firewall#named-gate-references-rule) β under ONE name, declared once:\n\n```typescript\n// quickback.config.ts\nauthz: {\n tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } },\n rules: {\n // who + record: \"org staff, but only rows still active\"\n activeStaff: {\n who: { roles: ['member', 'admin', 'owner'] },\n record: { status: { equals: 'active' } },\n },\n // who + firewall: an org-OR-event-scope row gate, declared ONCE\n eventRow: {\n who: { roles: ['owner', 'admin', 'member'] },\n firewall: [{ any: [\n { tenant: 'org' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] }],\n },\n },\n}\n```\n\n{/* doc-compile: skip β cross-fence dependency: the `eventRow` gate is declared in the `quickback.config.ts` fence directly above. Named refs are expanded once at the compiler's normalization seam with the project's authz config in hand, and the gate compiles each fence as an isolated project against a fixed harness config, so `{ rule: 'eventRow' }` can never resolve here. */}\n```typescript\n// any feature β the gate name works like a role name\nexport default defineTable(eventLinks, {\n firewall: [{ rule: 'eventRow' }], // firewall stamp\n read: { access: { roles: ['eventRow'] } }, // access stamp\n});\n```\n\n### The two-stamp contract\n\nOne shared name, two independent stamps β **a single reference never applies both**:\n\n- An **access-position reference** (the bare name in any `roles: [...]` array) applies the gate's `who` + `record` arms **only**. It expands exactly like an inline rule: a who-only gate splices as the flat role list; a who+record gate as `{ and: [who, { record }] }`.\n- A **firewall reference** (`firewall: [{ rule: '<name>' }]`) applies the gate's `firewall` lanes **only**, spliced into the resource's top-level AND array. The `who` of a gate referenced only from `firewall:` is **not consulted** β that is the documented contract, not a silent drop. Firewall-who is legitimately *wider* than access-who (e.g. the firewall admits scope-token holders to rows while read access stays staff-only).\n\nBoth directions are enforced fail-closed at compile time:\n\n| You wrote | Compiler says |\n|---|---|\n| Access reference to a firewall-bearing gate, but the resource's `firewall:` doesn't reference it | **Error** β the row lanes would silently not apply |\n| `firewall: [{ rule }]` naming a gate with no `firewall` arm | **Error** β a who/record-only gate would splice zero lanes |\n| A firewall-bearing gate referenced from an **action's** access or from `masking.show` | **Error, unconditional** β no firewall array exists at those sites (nested `show.or` / `show.and` arms included) |\n| A who-less (firewall-only) gate referenced from an access position | **Error** β row lanes can't masquerade as a who-grant |\n| A gate's `record:` field is not a column of the referencing table | **Error, per reference** β a missing field evaluates against `undefined` at runtime (`notEquals`/`notIn` would silently *grant*) |\n| A spliced gate's firewall lane filters on a column the stamped table doesn't have | **Error, per reference** β the lane could never scope rows there |\n\n### Naming rules\n\nRule names share the reference namespace with roles, so the compiler rejects (at declaration time) a rule name that collides with an `authz.roles` entry, a reserved/provider role, **any scoped-role name** (bare sugar like `attendee` or the canonical `scope:<kind>:<role>` spelling), or a name containing `+` or `:` (the `scope:` prefix always means a token-verified scope principal β a colon-named rule could capture references meant for one).\n\nInside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned β write the expanded list (`['member', 'admin', 'owner']`), because `+` expansion runs at resource sites only and a `member+` inside a body would silently never match. Roles may not reference rules (the dependency arrow is one-way), and gates never nest.\n\n### Typo safety\n\nA `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule β a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.\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. These are the `{ via: '...' }` rule shape from [Centrally defined access rules](#centrally-defined-access-rules) above.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\nimport { defineConfig } from '@quickback/compiler';\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#### Supported relationship-role surfaces\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| **Standalone** `actions.<name>.access` `roles: ['guest']` | β Supported | Inline gate; the surface exposes `resource.column` as a path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | β Supported | Inline lookup uses the already-loaded, firewalled record |\n| Namespace `via` lanes | β Supported | Hoisted middleware resolves once and can hydrate `ctx.<exposeAs>` |\n| `masking.<field>.show` `roles: ['guest']` | Build-time refusal | Use a relationship-gated view for field projection; per-row async masking is not approximated |\n\nRelationship roles are therefore available across CRUD, reads, standalone\nactions, record-based actions, and namespace mounts. Masking is the one\ndifferent execution surface: list masking must stay synchronous and batched, so\nthe compiler rejects a relationship-bearing `masking.show` rule and points to a\nrelationship-gated view instead. It never drops the relationship arm or turns\nit into a broader role grant.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface β either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the current compiler stops with a clear build error; an action can never ship with a relationship rule it has no key to evaluate.\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // β v0.19+: load matching event row\n exposeAs: 'event', // β onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first β `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed β `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies β 403.\n3. **Tenant stamping from the matched row** β for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** β no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** β `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped β the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped β so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT β¦ FROM guests WHERE β¦` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"List the caller's chat inbox for one event they attend.\",\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed β the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace β see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // β¦ domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n{/* doc-compile: skip β project-config prerequisite: `roles: [\"SYSADMIN\"]` requires `cms: { sysadmin: true }` in quickback.config.ts (documented above under SYSADMIN), and the gate compiles every fence against one fixed harness config that does not set it. */}\n```ts\n// features/admin/actions/crossTenantReport.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Report activity across every tenant for a date range (sysadmin only).\",\n path: '/admin/cross-tenant-report',\n input: z.object({ since: z.string(), until: z.string() }),\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['SYSADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` β they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // β row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // β who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern β \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" β is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` β a flat per-user table.\n- **A standalone action that walks the relationship table itself** β see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\nimport { z } from 'zod';\nimport { eq, and, inArray } from 'drizzle-orm';\nimport { defineAction } from '../.quickback/define-action';\nimport { events } from '../../events/events';\nimport { guests } from '../../guests/guests';\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-backed rules in `masking.show` (use a relationship-gated view\n for field projection; action access is fully supported).\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate β `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` β declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* β external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and β as of v0.25 β at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together β at the namespace or via `access.or` β when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it β no addition to `quickback.config.ts` needed.\n\n{/* doc-compile: skip β cross-fence dependency: `namespace.via: 'attendeeOf'` must resolve against `authz.relationships`, which is declared in the `quickback.config.ts` fence in the next section. The gate compiles each fence as an isolated project against a fixed harness config, so the lane can never be declared here. */}\n```typescript\n// features/events/events.ts\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const events = q.table('events', {\n id: q.id(),\n name: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(events, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/postAnnouncement.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Post an announcement to everyone attending the event.\",\n path: '/event/:eventId/announcements',\n method: 'POST',\n input: z.object({ body: z.string().max(2000) }),\n // No `via:` gate boilerplate β the namespace already ran the resolver, so\n // `access` only names roles and ctx.event is typed inside execute().\n access: { roles: ['admin', 'member'] },\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration β `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate β regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feedMoments.ts (in one feature)\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Publish a moment to the event's live feed.\",\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ caption: z.string().max(280), photoId: z.string().optional() }),\n access: { roles: ['admin', 'member'] },\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Record the caller's RSVP for the event.\",\n path: '/event/:eventId/respond',\n method: 'POST',\n input: z.object({ response: z.enum(['yes', 'no', 'maybe']) }),\n access: { roles: ['admin', 'member'] },\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) β first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match β `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL β these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** β that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" β the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** β passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** β passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration β they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken β relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes β so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\nA namespace can also fold the scope machinery into this same gate: `mintScope: true` **mints** a scope token on a matched userId lane, and `acceptScope: '<kind>'` **accepts** an already-minted scope claim as proof of entry β one handler under the prefix serves both a Better-Auth user and a sessionless scope principal. See [Scopes β `acceptScope`](/define/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` β the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or β as of v0.26 β an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted β set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine β the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error β the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default β narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate β namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime β that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes β runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feedMoments.ts\"\n// One-line flip per namespace-scoped action:\nimport { z } from 'zod';\nimport { defineAction } from '../.quickback/define-action.event-scope';\n// ββββββββ¬βββββββ\n// kebab(namespaceName)\n\nexport default defineAction({\n description: \"Publish a moment to the event's live feed.\",\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // β string\n ctx.event.startsAt // β Date β autocomplete works\n ctx.event.organizerId // β narrows on the field's declared type\n\n ctx.event.idd // β TS2339 β typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` β `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged β `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23βv0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" β switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking β same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces β say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\nβββ define-action.ts # generic β standard fallback\nβββ define-action.interview-scope.ts # ctx.interview typed\nβββ define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough β every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.\n\n## Read & Write Configuration\n\nReads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/define/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'`](/define/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`mode` on the single-record path is inherited by `DELETE /batch` unless `batch` names its own β so `mode: \"hard\"` above makes the whole resource hard-delete. That changes the schema: a hard-delete table must **not** declare `deletedAt` / `deletedBy` (via `...q.softDelete()` or literal Drizzle lines), and the firewall drops its `isNull(deletedAt)` predicate. See [Soft-delete fields](/define/schema#soft-delete-fields).\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)"
|
|
106
|
+
"content": "Define who can perform read and write operations and under what conditions.\n\n## Which primitive do I need?\n\nStart here. **Most apps need only the first row** β this page, and nothing below it.\n\n| The rule you're expressing | Use | Where |\n|---|---|---|\n| \"Anyone in the org, with this role\" | `roles: ['member+']` / `['admin+']` | this page |\n| \"Any signed-in caller\" | `roles: ['AUTHENTICATED']` | [below](#authenticated--any-authenticated-caller-the-wrapper) |\n| \"Only the caller's own rows\" | `roles: ['USER']` + an `ownerId` firewall | [below](#user--per-user-records) |\n| \"Anyone at all, signed in or not\" | `roles: ['PUBLIC']` | [below](#public--unauthenticated-access) |\n| \"Platform operators, regardless of org\" | `userRole: ['appmanager']` | [below](#userrole-vs-roles) |\n| The same expression, repeated across many features | `authz.roles` / `authz.rules` | [Named rules](/define/authz-roles) |\n| \"The caller has a row in *my* table linking them to this record\" | `authz.relationships` | [Relationships](/define/relationships) |\n| A permission *graph* β derived, inherited, share links | FGA | [FGA](/define/fga) |\n\n## Basic Usage\n\n```typescript\n// features/applications/applications.ts\nimport { sqliteTable, text } from 'drizzle-orm/sqlite-core';\nimport { defineTable } from '@quickback/compiler';\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 // ββ quickback:audit (compiler-managed β edits are validated, not merged) ββ\n createdAt: text('created_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()),\n modifiedAt: text('modified_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()).$onUpdate(() => new Date().toISOString()),\n createdBy: text('created_by'),\n modifiedBy: text('modified_by'),\n deletedAt: text('deleted_at'),\n deletedBy: text('deleted_by'),\n});\n\nexport default defineTable(applications, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n guards: { createable: [\"candidateId\", \"jobId\", \"notes\"], updatable: [\"notes\"] },\n read: {\n access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\", \"interviewer\"] },\n },\n create: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n update: { access: { roles: [\"owner\", \"hiring-manager\", \"recruiter\"] } },\n delete: { access: { roles: [\"owner\", \"hiring-manager\"] } },\n});\n```\n\n## Role Hierarchy\n\nIf your project uses a tiered role system (e.g., `member` < `admin` < `owner`), you can define a hierarchy in your config and use the `+` suffix to mean \"this role and above\":\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n name: \"my-app\",\n auth: {\n roleHierarchy: ['member', 'admin', 'owner'], // lowest β highest\n },\n // ...\n});\n```\n\nThen in your resource definitions:\n\n```typescript\nread: { access: { roles: [\"member+\"] } }, // member, admin, owner\ncreate: { access: { roles: [\"admin+\"] } }, // admin, owner\ndelete: { access: { roles: [\"owner\"] } }, // owner only (no +)\n```\n\nThe `+` suffix expands at compile time β `\"member+\"` becomes `[\"member\", \"admin\", \"owner\"]` in the generated code. You can mix hierarchical and exact roles: `roles: [\"member+\", \"finance\"]` expands to `[\"member\", \"admin\", \"owner\", \"finance\"]`.\n\n- Roles without `+` are exact matches (no expansion)\n- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `SESSION`, `SCOPED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix β they're terminal markers\n- Using `+` with a role not in the hierarchy throws a compile error\n- Using `+` without configuring `auth.roleHierarchy` throws a compile error\n\n## Custom org roles\n\nYou're not limited to Better Auth's built-in `owner` / `admin` / `member` β\nany lowercase role name you reference in an access tree (`\"recruiter\"`,\n`\"hiring-manager\"`, `\"support\"`, β¦) is a custom org-membership role, matched\nagainst `ctx.roles` like the built-ins.\n\nAs of v0.46, custom roles declared in access trees are **auto-registered\nwith the Better Auth organization plugin**, so members can actually be\nprovisioned into them: `invite-member` and `update-member-role` accept them\n(previously they rejected custom roles with `400 ROLE_NOT_FOUND`).\nAuto-registered roles carry member-equivalent Better Auth permissions β\nregistration is about assignability; your access trees remain the\nauthorization model. If you pass your own `roles` / `ac` to the organization\nplugin options, those win and auto-registration is skipped.\n\n## Configuration Options\n\n```typescript\ninterface Access {\n // Org-membership roles (OR logic β user needs at least one)\n // Matched against ctx.roles. Use \"role+\" suffix for hierarchy expansion.\n roles?: string[];\n\n // User-table role (OR logic). Matched against ctx.userRole from the\n // user.role column β independent of org membership. See userRole below.\n userRole?: string[];\n\n // Record-level conditions\n record?: {\n [field: string]: FieldCondition;\n };\n\n // Combinators\n or?: Access[];\n and?: Access[];\n}\n```\n\n## `userRole` vs `roles`\n\n`roles` and `userRole` check **two different fields** and are often confused β get this wrong and you'll grant access too broadly.\n\n| Primitive | Checks | Source | Example values |\n|-----------|--------|--------|----------------|\n| `roles` | `ctx.roles` | Org membership roles | `\"owner\"`, `\"admin\"`, `\"member\"` |\n| `userRole` | `ctx.userRole` | The `user.role` column (Better Auth / platform control-plane roles) | `\"user\"`, `\"appmanager\"`, `\"sysadmin\"` |\n\nIn multi-tenant mode, **`roles: [\"admin\"]` means \"org admin\" β not a platform-wide role.** An org-admin of Acme Corp has no elevated rights across other orgs. If you want platform control-plane operators through regardless of org membership (CMS, Better Auth admin surfaces, support tooling), use `userRole: [\"appmanager\"]`. If you need true cross-tenant data-plane access, use `roles: [\"SYSADMIN\"]` (with `cms: { sysadmin: true }`).\n\nPinned organization mode does not change this split. `roles` still come from organization membership in the pinned org, while `userRole` still comes from Better Auth's `user.role` column.\n\n### When to use `userRole`\n\n```typescript\n// Platform control-plane users can see SSNs on every customer record, regardless of org\nmasking: {\n ssn: { type: 'ssn', show: { userRole: ['appmanager'] } },\n}\n\n// Platform ops (user.role === 'appmanager') OR the org owner can refund\naccess: {\n or: [\n { userRole: ['appmanager'] },\n { roles: ['owner'] },\n ],\n}\n\n// CMS-internal resource: only platform control-plane users\nread: { access: { userRole: ['appmanager'] } },\ncreate: { access: { userRole: ['appmanager'] } },\nupdate: { access: { userRole: ['appmanager'] } },\ndelete: { access: { userRole: ['appmanager'] } },\n```\n\nWhen `roles` and `userRole` both appear in a single `Access` node, they're combined with AND β the user must satisfy both. Use `or:` to express \"one or the other\".\n\n`userRole` doesn't expand with the `+` hierarchy suffix β user-table roles are flat (typically just `\"user\"`, `\"appmanager\"`, and `\"sysadmin\"`). If you've added custom user-table roles via Better Auth, list them explicitly.\n\n### Pseudo-roles\n\nQuickback ships seven reserved UPPERCASE markers. Six are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).\n\n| Role | Auth gate | Compile-time requirement | Runtime check |\n|------|-----------|-------------------------|---------------|\n| `PUBLIC` | bypassed | none β explicit opt-in for unauthenticated access | always passes (auth skipped) |\n| `AUTHENTICATED` | required | none | `ctx.authenticated === true` (a full session **or** a scope principal β the wrapper over `SESSION` βͺ `SCOPED`) |\n| `SESSION` | required | none | a full Better Auth session **only** β `ctx.authenticated && !ctx.principal && !ctx.scopePrincipal` |\n| `SCOPED` | required | none | a sessionless scope principal **only** β `ctx.authenticated && ctx.scopePrincipal === true` |\n| `USER` | required | resource firewall **must** scope by `userId` | a real signed-in user β `ctx.authenticated` AND **not** a scope principal (`!ctx.scopePrincipal`) AND (`ctx.userRole` unset OR `=== \"user\"`). A sessionless scope caller does **not** satisfy `USER` (use `SCOPED` / `scope:<kind>:<role>`); `AUTHENTICATED` is the marker that admits both flavors. |\n| `ADMIN` | required | reserved legacy marker β compiler rejects it | `false` |\n| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === \"sysadmin\"` |\n\nYou can mix pseudo-roles with real roles in the same list β they're OR'd together.\n\n#### `PUBLIC` β unauthenticated access\n\nUse `roles: [\"PUBLIC\"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.\n\n```typescript\naccess: { roles: [\"PUBLIC\"] }\n```\n\n**Important:**\n- `PUBLIC` skips authentication and role checks β anyone can call the endpoint\n- **`PUBLIC` is the explicit, uppercase opt-in for unauthenticated access.** It works on every access node β reads, top-level writes (`create`/`update`/`delete`/`upsert`), views, and actions. The compiler trusts the marker; row-level safety comes from the firewall, masking, and (for token-gated endpoints like RSVP confirm, magic-link redemption, List-Unsubscribe-Post, webhook ingest) your handler's own validation. Anonymous write endpoints typically pair `roles: [\"PUBLIC\"]` with `firewall: { exception: true }` on the resource so the row predicate doesn't reject every unauthenticated caller.\n- **Firewall still applies** β data is scoped by the firewall (organization, owner, team)\n- **Tree semantics:** `PUBLIC` admits anonymous callers from anywhere in the access tree, not just a flat `roles` list. An `or:` arm containing `PUBLIC` admits anonymous callers past the authentication gate; an `and:` group admits them only when *every* arm does. The access, org, and firewall layers still evaluate the full tree afterwards. (Before v0.46 the emitted auth gate only honored `PUBLIC` in a flat `roles` list β a nested `PUBLIC` arm incorrectly answered `401`.)\n- Every `PUBLIC` action invocation is **mandatory audit logged** to the security audit table (IP address, input, result, timing)\n- The wildcard `\"*\"` is **not supported** β using it throws a compile-time error\n- Tables with no isolation columns and any `PUBLIC` route do not require `firewall: [{ exception: true }]`\n\nFor org-scoped tables, `PUBLIC` routes still filter by organization. Since the user isn't authenticated, the organization ID must be passed as a query parameter:\n\n```\nGET /api/v1/listings?organizationId=org_abc123\n```\n\nThe firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.\n\n`?organizationId=` is an account/public addressing surface. A request using a\nconfigured delegated principal cannot use it to acquire account organization\nauthority: the generated route returns `403 CROSS_TENANT_FORBIDDEN` and never\nadds `activeOrgId` or account roles to the delegated `AppContext`. Delegated\nscope continues to come only from the verified principal claims and database\nRLS policy.\n\n```typescript\n// quickback/features/listings/listings.ts\nimport { q, defineTable } from '@quickback/compiler';\n\n// Public listing page β anyone can browse, but scoped to an org\nexport const listings = q.table('listings', {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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 authenticated caller (the wrapper)\n\nUse `roles: [\"AUTHENTICATED\"]` for endpoints that any logged-in caller 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`AUTHENTICATED` is the **wrapper over two auth flavors** β it admits both a full Better Auth session **and** a sessionless scope principal (a scope-token holder, e.g. an event attendee who isn't an org member; see [Scopes](/define/scopes)). It excludes only *external delegated* principals (`ctx.principal`, admitted via `principals:`). When you need to distinguish the two flavors, use `SESSION` or `SCOPED` below; when either is fine, use `AUTHENTICATED`.\n\n#### `SESSION` β a full session only\n\nUse `roles: [\"SESSION\"]` when a route must admit **only** a full Better Auth session and **not** a sessionless scope principal. This is `AUTHENTICATED` minus scope-token callers.\n\n```typescript\n// Account settings β a real logged-in user, never a scope-token attendee\nread: { access: { roles: [\"SESSION\"] } }\n```\n\n#### `SCOPED` β a scope principal only\n\nUse `roles: [\"SCOPED\"]` for a route that is specifically for **sessionless scope-token callers** (a principal-only surface β e.g. a shared event link or kiosk token with no account). It admits any scope principal regardless of *which* scope; for a **specific** scoped role, use the `scope:<kind>:<role>` form instead (e.g. `scope:event:attendee` β see [Scopes](/define/scopes)).\n\n```typescript\n// Principal-only event surface β a scope token, no account required\nread: { access: { roles: [\"SCOPED\"] } }\n```\n\n> **Firewall coherence:** if an access surface admits a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) but the resource firewall can't filter that caller, the compiler **fails the build** β the caller would reach the handler yet see zero rows (a silent `200 + []`). Give the firewall a way to filter them: a `ctx.scope.<kind>` arm inside an `{ any: [...] }` group (compose org **or** scope β see [Firewall](/define/firewall)), a `via:` relationship, or `firewall: [{ exception: true }]`.\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 owner** β the role marker is the access half of the pair, the firewall is the row-filter half.\n\nThe owner column is `ownerId`. Name the column `ownerId` and the firewall is auto-derived (`WHERE ownerId = ctx.userId`, plus auto-stamping on insert); `userId` is **not** auto-detected on feature tables and must be declared explicitly. See [Firewall β `ownerId` vs `userId`](/define/firewall#ownerid-vs-userid).\n\n```typescript\n// quickback/features/todos/todos.ts\nimport { q, defineTable } from '@quickback/compiler';\n\n// \"My todos\" β each caller sees only their own rows\nexport const todos = q.table('todos', {\n id: q.id(),\n title: q.text().required(),\n done: q.bool().default(false).required(),\n ownerId: q.text().required(),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(todos, {\n firewall: [{ field: 'ownerId', 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 the firewall doesn't scope by owner, the compiler throws:\n\n```text\nResource \"todos\" uses roles: [\"USER\"] but the firewall does not scope by\nownerId. Add an ownerId column (auto-scoped) or an explicit owner predicate\n(firewall: [{ field: \"ownerId\", equals: \"ctx.userId\" }, ...]). If the column\nis named userId, declare it explicitly:\nfirewall: [{ field: \"userId\", equals: \"ctx.userId\" }]. If you want any\nsigned-in user to read all records, use roles: [\"AUTHENTICATED\"] instead.\n```\n\nWhen the Better Auth admin plugin is enabled, `USER` matches `user.role === \"user\"` specifically β appmanagers and sysadmins are excluded. If the same route should serve both, express it explicitly with `or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }]`.\n\n#### `ADMIN` β legacy reserved marker (compile-time error)\n\n`roles: [\"ADMIN\"]` is no longer supported. The compiler fails hard on any use of `ADMIN` so platform and tenant roles can't be confused.\n\n```typescript\n// Platform control-plane audit log\nread: { access: { userRole: [\"appmanager\"] } }\n```\n\nUse one of these instead:\n\n- `userRole: [\"appmanager\"]` for platform control-plane access\n- `roles: [\"admin\"]` for org-membership admin access\n- `roles: [\"SYSADMIN\"]` for true cross-tenant access\n\n#### `SYSADMIN` β cross-tenant DB-admin tier\n\nUse `roles: [\"SYSADMIN\"]` for endpoints that should only be reachable by platform sysadmins β the cross-tenant DB-admin tier introduced in v0.15.0. Compiles to `ctx.userRole === \"sysadmin\"`. **Requires `cms: { sysadmin: true }` on the project config**; without that flag, using `SYSADMIN` fails the compile so the role can't sit as dead code.\n\n```typescript\n// Cross-tenant audit dashboard, sysadmin-only\nread: { access: { roles: [\"SYSADMIN\"] } }\n```\n\n`SYSADMIN` is distinct from `userRole: [\"appmanager\"]`. Appmanager is the platform control-plane tier (CMS shell, Better Auth admin surfaces, support tooling); sysadmin is the cross-tenant data-plane tier. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top β so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'appmanager'`; appmanagers still go through the firewall like everyone else.\n\nThis separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/configure#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's \"All organizations\" sentinel.\n\n#### Mixing pseudo-roles with real roles\n\nPseudo-roles and lowercase real roles compose with OR:\n\n```typescript\n// Record owner OR a platform control-plane user can read\nread: { access: { or: [{ roles: [\"USER\"] }, { userRole: [\"appmanager\"] }] } }\n\n// Org owner OR sysadmin\ndelete: { access: { or: [{ roles: [\"owner\"] }, { roles: [\"SYSADMIN\"] }] } }\n```\n\n> Note: `userRole: [\"appmanager\"]` never bypasses a `userId` firewall scope. If you need cross-user visibility, expose a separate route with `firewall: { exception: true }` or a `SYSADMIN`-gated cross-tenant surface.\n\n#### Quick reference\n\n```typescript\n// Unauthenticated public\naccess: { roles: [\"PUBLIC\"] }\n\n// Any signed-in user, no scoping\naccess: { roles: [\"AUTHENTICATED\"] }\n\n// Per-user records (requires userId firewall scope)\naccess: { roles: [\"USER\"] }\n\n// Platform control-plane\naccess: { userRole: [\"appmanager\"] }\n\n// Cross-tenant DB-admin tier\naccess: { roles: [\"SYSADMIN\"] }\n\n// Org-membership roles with hierarchy expansion\n// (\"+\" requires auth.roleHierarchy in quickback.config.ts β see Role Hierarchy above)\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## 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'`](/define/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## 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)"
|
|
107
107
|
},
|
|
108
108
|
"define/actions/access": {
|
|
109
109
|
"title": "Action Access",
|
|
110
|
-
"content": "## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name β see [Centrally defined access rules](/define/
|
|
110
|
+
"content": "## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name β see [Centrally defined access rules](/define/authz-roles#centrally-defined-access-rules).\n\n[Named gates](/define/authz-roles#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array β a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.\n\n**A firewall-bearing gate on an action is a compile error.** An action has no firewall array β there is no row query for the gate's lanes to constrain before execution β so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\nBoth standalone and record-based actions support relationship roles directly in\n`access.roles`. Declare the relationship under `authz.relationships`, name it\nunder `authz.roles`, and use that name like any organization or pseudo-role.\n\nFor a standalone action, optional `loads` / `exposeAs` fields can hydrate the\nmatched resource onto `ctx`:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"List the caller's chat inbox for one event they attend.\",\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT β¦ FROM guests WHERE β¦` needed.\n },\n});\n```\n\nThe standalone action's surface (path params + input fields) must expose the\nrelationship's `resource.column`. A missing key is a compile error, so the\nresolver can never be skipped silently. See [Access β standalone\nactions](/define/relationships#standalone-actions-surface-keys-and-loads--exposeas-v019)\nfor the full mechanism.\n\nFor a record-based action, Quickback already has the firewalled record in\nscope. It emits an inline relationship match against that record before\n`execute()` runs:\n\n```typescript\n// features/sessions/actions/comment.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { comments } from \"../comments\";\n\nexport default defineAction({\n description: \"Add a comment to a session the caller is a guest of.\",\n input: z.object({ text: z.string().max(2000) }),\n access: { roles: ['guest', 'admin'] },\n async execute({ db, record, input }) {\n // The route loaded `record` through its firewall, then verified guestOf\n // against record.eventId. Only domain logic remains here.\n return db.insert(comments).values({\n sessionId: record.id,\n text: input.text,\n });\n },\n});\n```\n\nSimple role arms are checked before the record lookup to preserve ID-probe\nresistance. Relationship arms run only after the record has been loaded through\nthe firewall, because the record supplies the relationship key. No manual\nlookup or firewall exception is required.\n\nSee [Access β relationship\nauthorization](/define/relationships)\nfor the full surface matrix, namespace hoisting, and tenant-context stamping."
|
|
111
111
|
},
|
|
112
112
|
"define/actions/defining": {
|
|
113
113
|
"title": "Defining Actions",
|
|
@@ -131,19 +131,23 @@ export const DOCS = {
|
|
|
131
131
|
},
|
|
132
132
|
"define/areas": {
|
|
133
133
|
"title": "Feature Areas - Hierarchical Authz Grouping",
|
|
134
|
-
"content": "Group related features under one **area** folder. The area's `_area.ts` file declares a route\nprefix, admission lanes, and an authorization vocabulary β relationships, roles, rules, tenant\nanchors, scope kinds β that every feature **inside the folder** inherits by name. Features\noutside the folder cannot reference any of it: the compiler fails the build.\n\n> Naming note: this concept is an **area**. `domain` in Quickback always means a DNS custom\n> domain (see [custom domains](/configure/domains)).\n\n## Why\n\nCross-cutting authz for a concept like a project, an event, or a location used to live in the\nroot `quickback.config.ts` and was wired to its consumers by a path-prefix string across a flat\nfeature list. An area makes the grouping **structural**: the folder *is* the boundary, the\n`_area.ts` *is* the single declaration site, and the compiler enforces that the vocabulary\nnever leaks outside the subtree.\n\n## Layout\n\n```\nquickback/features/\nβββ workspace/ β AREA (has _area.ts)\nβ βββ _area.ts β defineArea({...})\nβ βββ projects.ts β the area folder may itself be a feature\nβ βββ project_collaborators.ts\nβ βββ tasks/ β child feature\nβ β βββ tasks.ts\nβ β βββ actions/addTask.ts\nβ βββ chat/ β child feature\nβ βββ actions/postMessage.ts\nβββ billing/ β flat feature (unchanged)\n```\n\nReserved sub-directories (`actions/`, `lib/`, `pages/`) are never child features. A directory\n**without** `_area.ts` is a leaf feature β its unreserved subdirectories are not loaded, and a\nsubdirectory containing `defineTable(...)` / `defineAction(...)` **fails the compile** (silent\nroute/table disappearance after a mis-move is the failure mode areas must never introduce).\nFeature leaf names stay globally unique β they key `src/features/<name>/` in the output, so\nmoving a feature into an area changes nothing about its generated identity.\n\n## `_area.ts`\n\n```typescript\n// features/workspace/_area.ts\nimport { defineArea } from '@quickback/compiler';\n\nexport default defineArea({\n // Namespace identity β drives the emitted routes file name and errors.\n name: 'projectScope',\n\n // Inherited route mount + admission gate. Optional: an area with no\n // prefix contributes shared vocabulary only. A prefix REQUIRES at least\n // one `via` lane (a mounted prefix with no gate would be ungated).\n prefix: '/project/:projectId',\n via: ['collaboratorOf', { roles: ['admin', 'owner'] }],\n mintScope: true,\n acceptScope: 'project',\n\n // Area-owned vocabulary β the EXACT same shapes as the root authz blocks.\n relationships: {\n collaboratorOf: {\n from: 'project_collaborators',\n subject: { column: 'collaboratorUserId', equals: 'ctx.userId' },\n resource: { column: 'projectId' },\n where: { status: 'active' },\n loads: 'projects',\n exposeAs: 'project',\n },\n },\n roles: {\n projectStaff: { or: [{ via: 'collaboratorOf' }, { roles: ['admin', 'owner'] }] },\n },\n scopes: {\n project: {\n requestField: 'projectId',\n roles: { collaborator: { via: 'collaboratorOf', subject: 'both' } },\n },\n },\n // Named gates + tenant anchors work too β same shapes as authz.rules /\n // authz.tenants, visible to this subtree only.\n});\n```\n\nA descendant feature references everything by bare name β no imports, no root declaration:\n\n{/* doc-compile: skip β cross-fence dependency: the relative `path: './tasks/add'` and the `projectStaff` role both resolve against the `_area.ts` in the fence directly above, and the area is the whole point of the example. The gate compiles each fence as an isolated project, so this feature has no ancestor area to inherit a prefix from. */}\n```typescript\n// features/workspace/tasks/actions/addTask.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Add a task to the project the area gate already proved.\",\n path: './tasks/add', // relative β /project/:projectId/tasks/add\n input: z.object({ title: z.string().min(1) }),\n access: { roles: ['projectStaff'] }, // resolves against the area\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n```\n\n## The visibility contract\n\nAn area's names are visible to **its own subtree only** (the area folder, its features, and\nnested areas). The compiler checks **every** reference channel β access `roles:` arrays\n(including named gates and both spellings of scoped roles: bare aliases and\n`scope:<kind>:<role>`), action `access` and `anchor:`, firewall `via:` arms,\n`ctx.scope.<kind>` accessors, `{ rule }` and `{ tenant }` firewall references, auth-view\n`tenant:` includes, `realtime.requiredRoles`, table-level `namespace.via` lanes, and other\n`_area.ts` nodes. Referencing an area name from outside is always a compile error:\n\n```\nFeature \"billing\" ... references role \"projectStaff\" declared by area \"projectScope\"\n(features/workspace/_area.ts), but this site is not inside that area. ... move the\nreferencing code under the declaring area, or lift the declaration to root authz if it\nis genuinely global.\n```\n\nTwo structural rules keep the fold sound:\n\n- **No overrides (v1).** Re-declaring an inherited name β in any class, including scope kinds,\n scoped-role aliases, and namespace names β is a compile error. Declare each name in exactly\n one place. (`overrides:` marker syntax is reserved for a future release.)\n- **Declaration-site rule.** Root `authz` bodies (roles, rules, tenants, scopes, namespaces)\n may reference **root-declared names only** β a root definition is visible everywhere and\n would launder an area name out of its subtree. An area's bodies may reference root βͺ\n ancestors βͺ self.\n\nOne deliberate exception: root-config **namespace-identity wiring** β today exactly\n`realtime.wsTicket.namespace` β may name an area's namespace. It attaches the area's complete\ngate (its full lane set) and constructs no new grant. Such consumers are listed in the\nmanifest under the owning area.\n\n## Containment and the `route: 'self'` marker\n\nThe area's prefix is an audited surface:\n\n- A feature **outside** the area may not declare an action path (or a table-level\n `namespace` prefix) under the area's prefix β compile error.\n- A project-level `authz.namespaces` entry the area does **not** own β root-declared, or\n another area's β may not carve a prefix at or under the area's prefix. Namespace claiming\n is longest-prefix-wins, so such an entry would silently re-gate the area's descendant\n actions with its own `via` lanes β compile error. (A *descendant* feature's table-level\n namespace inside the prefix is legal; the manifest attributes its claimed actions to that\n namespace, not to the area.)\n- A **descendant** action whose absolute path is *outside* the prefix opts out of the area's\n admission gate and is gated solely by its own `access:`. That must be explicit:\n mark the action `route: 'self'`, or the compile fails (a typo'd prefix must never silently\n self-gate). The marker is equally rejected where it is dead β on in-prefix actions and in\n features outside any mounted area. Every self-gated action is listed in the manifest.\n\nRelative paths (`path: './β¦'`) resolve against the area prefix. Dot segments (`.` / `..`) are\nrejected outright β the resolved route must stay under the prefix.\n\n## Nested areas\n\nAreas nest to arbitrary depth. A nested area may declare additional **vocabulary** freely. A\nnested area may **not** mount its own `prefix` under an ancestor that already mounts one:\nper-level nested admission is *unlinked* (a caller related to child instance S under parent A\nwould be admitted at `/a/A/s/S` even when S belongs to parent B), and Quickback refuses to\ncompile an unlinked gate. Mount one prefix per chain, or keep the nested area\nvocabulary-only.\n\n## The capability floor: `requires: ['feature-areas']`\n\nAn area-tree project **must** declare the marker in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n // ...\n requires: ['feature-areas'],\n});\n```\n\nAny CLI β including one that predates areas β passthrough-executes the config, so the marker\nalways reaches the compiler. A current compiler that sees the marker but no `areas` payload\nrejects the compile with an upgrade message instead of silently compiling a project whose\nnested features an old CLI never loaded (which would otherwise generate destructive\nmigrations). In the other direction, a current CLI refuses output from a compiler that\npredates areas.\n\n## The authz manifest\n\nArea projects emit `quickback/authz-manifest.json` on every compile β the audit inventory the\nflat config can no longer answer from one file: the area tree, every folded name and its\ndeclaring file, per-area member features, `areaGatedActions` vs `selfGatedActions`, and any\nroot-config namespace consumers. Review it in PRs the way you review the security reports;\nthe generated `AGENTS.md` also gains a feature-areas section so coding agents place new\nfeatures correctly.\n\n## What belongs at root\n\nRoot `authz` remains the home for genuinely global vocabulary β names used across areas or by\nflat features. Everything scoped to one concept belongs in that concept's `_area.ts`. When in\ndoubt: if only one folder's features reference it, it belongs in that folder's area."
|
|
134
|
+
"content": "Group related features under one **area** folder. The area's `_area.ts` file declares a route\nprefix, admission lanes, and an authorization vocabulary β relationships, roles, rules, tenant\nanchors, scope kinds β that every feature **inside the folder** inherits by name. Features\noutside the folder cannot reference any of it: the compiler fails the build.\n\n> Naming note: this concept is an **area**. `domain` in Quickback always means a DNS custom\n> domain (see [custom domains](/configure/domains)).\n\n## Do you need one?\n\nAn area is [rung 3](/define#the-authorization-ladder) β reach for it only when a subtree shares\na URL prefix **and** a per-row admission gate. Most apps never need one.\n\n| You want | Use |\n|---|---|\n| Every row scoped to the caller's tenant | Nothing β `organizationId: q.scope('organization')` already does it. **Not an area.** |\n| Routes grouped under a shared path, no per-row gate | A `path` on each feature |\n| A shared role/rule vocabulary, no route prefix | Root [`authz.roles`](/define/authz-roles#centrally-defined-access-rules) β or an area with no `prefix` |\n| Everything under `/project/:projectId` gated by \"is the caller on this project?\", with the project row hydrated onto `ctx` | **An area** |\n\n## Why\n\nCross-cutting authz for a concept like a project, an event, or a location used to live in the\nroot `quickback.config.ts` and was wired to its consumers by a path-prefix string across a flat\nfeature list. An area makes the grouping **structural**: the folder *is* the boundary, the\n`_area.ts` *is* the single declaration site, and the compiler enforces that the vocabulary\nnever leaks outside the subtree.\n\n## Layout\n\n```\nquickback/features/\nβββ project/ β AREA (has _area.ts)\nβ βββ _area.ts β defineArea({...})\nβ βββ projects.ts β the area folder may itself be a feature\nβ βββ project_collaborators.ts\nβ βββ tasks/ β child feature\nβ β βββ tasks.ts\nβ β βββ actions/addTask.ts\nβ βββ chat/ β child feature\nβ βββ actions/postMessage.ts\nβββ billing/ β flat feature (unchanged)\n```\n\nThe gate here is `collaboratorOf` β a row in *your* `project_collaborators` table. That's what\nmakes it an area: the answer isn't in `ctx.roles` already.\n\nReserved sub-directories (`actions/`, `lib/`, `pages/`) are never child features. A directory\n**without** `_area.ts` is a leaf feature β its unreserved subdirectories are not loaded, and a\nsubdirectory containing `defineTable(...)` / `defineAction(...)` **fails the compile** (silent\nroute/table disappearance after a mis-move is the failure mode areas must never introduce).\nFeature leaf names stay globally unique β they key `src/features/<name>/` in the output, so\nmoving a feature into an area changes nothing about its generated identity.\n\n## `_area.ts`\n\n```typescript\n// features/project/_area.ts\nimport { defineArea } from '@quickback/compiler';\n\nexport default defineArea({\n // Namespace identity β drives the emitted routes file name and errors.\n name: 'projectScope',\n\n // Inherited route mount + admission gate. Optional: an area with no\n // prefix contributes shared vocabulary only. A prefix REQUIRES at least\n // one `via` lane (a mounted prefix with no gate would be ungated).\n prefix: '/project/:projectId',\n via: ['collaboratorOf', { roles: ['admin', 'owner'] }],\n mintScope: true,\n acceptScope: 'project',\n\n // Area-owned vocabulary β the EXACT same shapes as the root authz blocks.\n relationships: {\n collaboratorOf: {\n from: 'project_collaborators',\n subject: { column: 'collaboratorUserId', equals: 'ctx.userId' },\n resource: { column: 'projectId' },\n where: { status: 'active' },\n loads: 'projects',\n exposeAs: 'project',\n },\n },\n roles: {\n projectStaff: { or: [{ via: 'collaboratorOf' }, { roles: ['admin', 'owner'] }] },\n },\n scopes: {\n project: {\n requestField: 'projectId',\n roles: { collaborator: { via: 'collaboratorOf', subject: 'both' } },\n },\n },\n // Named gates + tenant anchors work too β same shapes as authz.rules /\n // authz.tenants, visible to this subtree only.\n});\n```\n\nA descendant feature references everything by bare name β no imports, no root declaration:\n\n{/* doc-compile: skip β cross-fence dependency: the relative `path: './tasks/add'` and the `projectStaff` role both resolve against the `_area.ts` in the fence directly above, and the area is the whole point of the example. The gate compiles each fence as an isolated project, so this feature has no ancestor area to inherit a prefix from. */}\n```typescript\n// features/project/tasks/actions/addTask.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Add a task to the project the area gate already proved.\",\n path: './tasks/add', // relative β /project/:projectId/tasks/add\n input: z.object({ title: z.string().min(1) }),\n access: { roles: ['projectStaff'] }, // resolves against the area\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n```\n\n## The visibility contract\n\nAn area's names are visible to **its own subtree only** (the area folder, its features, and\nnested areas). The compiler checks **every** reference channel β access `roles:` arrays\n(including named gates and both spellings of scoped roles: bare aliases and\n`scope:<kind>:<role>`), action `access` and `anchor:`, firewall `via:` arms,\n`ctx.scope.<kind>` accessors, `{ rule }` and `{ tenant }` firewall references, auth-view\n`tenant:` includes, `realtime.requiredRoles`, table-level `namespace.via` lanes, and other\n`_area.ts` nodes. Referencing an area name from outside is always a compile error:\n\n```\nFeature \"billing\" ... references role \"projectStaff\" declared by area \"projectScope\"\n(features/project/_area.ts), but this site is not inside that area. ... move the\nreferencing code under the declaring area, or lift the declaration to root authz if it\nis genuinely global.\n```\n\nTwo structural rules keep the fold sound:\n\n- **No overrides (v1).** Re-declaring an inherited name β in any class, including scope kinds,\n scoped-role aliases, and namespace names β is a compile error. Declare each name in exactly\n one place. (`overrides:` marker syntax is reserved for a future release.)\n- **Declaration-site rule.** Root `authz` bodies (roles, rules, tenants, scopes, namespaces)\n may reference **root-declared names only** β a root definition is visible everywhere and\n would launder an area name out of its subtree. An area's bodies may reference root βͺ\n ancestors βͺ self.\n\nOne deliberate exception: root-config **namespace-identity wiring** β today exactly\n`realtime.wsTicket.namespace` β may name an area's namespace. It attaches the area's complete\ngate (its full lane set) and constructs no new grant. Such consumers are listed in the\nmanifest under the owning area.\n\n## Containment and the `route: 'self'` marker\n\nThe area's prefix is an audited surface:\n\n- A feature **outside** the area may not declare an action path (or a table-level\n `namespace` prefix) under the area's prefix β compile error.\n- A project-level `authz.namespaces` entry the area does **not** own β root-declared, or\n another area's β may not carve a prefix at or under the area's prefix. Namespace claiming\n is longest-prefix-wins, so such an entry would silently re-gate the area's descendant\n actions with its own `via` lanes β compile error. (A *descendant* feature's table-level\n namespace inside the prefix is legal; the manifest attributes its claimed actions to that\n namespace, not to the area.)\n- A **descendant** action whose absolute path is *outside* the prefix opts out of the area's\n admission gate and is gated solely by its own `access:`. That must be explicit:\n mark the action `route: 'self'`, or the compile fails (a typo'd prefix must never silently\n self-gate). The marker is equally rejected where it is dead β on in-prefix actions and in\n features outside any mounted area. Every self-gated action is listed in the manifest.\n\nRelative paths (`path: './β¦'`) resolve against the area prefix. Dot segments (`.` / `..`) are\nrejected outright β the resolved route must stay under the prefix.\n\n## Nested areas\n\nAreas nest to arbitrary depth. A nested area may declare additional **vocabulary** freely. A\nnested area may **not** mount its own `prefix` under an ancestor that already mounts one:\nper-level nested admission is *unlinked* (a caller related to child instance S under parent A\nwould be admitted at `/a/A/s/S` even when S belongs to parent B), and Quickback refuses to\ncompile an unlinked gate. Mount one prefix per chain, or keep the nested area\nvocabulary-only.\n\n## The capability floor: `requires: ['feature-areas']`\n\nAn area-tree project **must** declare the marker in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n // ...\n requires: ['feature-areas'],\n});\n```\n\nAny CLI β including one that predates areas β passthrough-executes the config, so the marker\nalways reaches the compiler. A current compiler that sees the marker but no `areas` payload\nrejects the compile with an upgrade message instead of silently compiling a project whose\nnested features an old CLI never loaded (which would otherwise generate destructive\nmigrations). In the other direction, a current CLI refuses output from a compiler that\npredates areas.\n\n## The authz manifest\n\nArea projects emit `quickback/authz-manifest.json` on every compile β the audit inventory the\nflat config can no longer answer from one file: the area tree, every folded name and its\ndeclaring file, per-area member features, `areaGatedActions` vs `selfGatedActions`, and any\nroot-config namespace consumers. Review it in PRs the way you review the security reports;\nthe generated `AGENTS.md` also gains a feature-areas section so coding agents place new\nfeatures correctly.\n\n## What belongs at root\n\nRoot `authz` remains the home for genuinely global vocabulary β names used across areas or by\nflat features. Everything scoped to one concept belongs in that concept's `_area.ts`. When in\ndoubt: if only one folder's features reference it, it belongs in that folder's area.\n\n## Namespace mounts (hoisted relationship middleware)\n\nWhen several standalone actions share a path prefix and the same relationship gate β `/event/:eventId/announce`, `/event/:eventId/cancel`, `/event/:eventId/respond` β declaring the gate per-action means writing the same `roles: ['attendee']` over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).\n\nNamespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; `ctx.<exposeAs>` is hydrated by the middleware before the action's `execute()` runs. With the per-namespace helper (v0.27+, [below](#narrow-ctxexposeas-typing-v027)), that field is also statically typed as the loaded row.\n\n### When to use roles vs. relationships\n\nA user is authorized for a row when **any** of the following is true:\n\n- they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or\n- they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or\n- they have **team membership** matching the row's `teamId`.\n\nUse **relationships** when membership is specific to *this row* β external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use **roles / team** when staff at your org/team should see everything in their scope by default.\n\nThe two compose at the action level (`access.or` accepts both relationship-roles and tenant roles) and β as of v0.25 β at the namespace level too: `namespace.via` accepts an array of lanes, first match wins.\n\n> **Rule of thumb.** If the answer is *\"yes if you work here,\"* reach for org/team roles. If the answer is *\"yes if you have something to do with **this** row,\"* reach for a per-row relationship. Reach for both together β at the namespace or via `access.or` β when an action should let either side in.\n\nTwo declaration sites depending on whether the participating actions live in one feature or many:\n\n### Single feature: `defineTable({ namespace })` (v0.23+)\n\nUse when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it β no addition to `quickback.config.ts` needed.\n\n{/* doc-compile: skip β cross-fence dependency: `namespace.via: 'attendeeOf'` must resolve against `authz.relationships`, which is declared in the `quickback.config.ts` fence in the next section. The gate compiles each fence as an isolated project against a fixed harness config, so the lane can never be declared here. */}\n```typescript\n// features/events/events.ts\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const events = q.table('events', {\n id: q.id(),\n name: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(events, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n namespace: {\n prefix: '/event/:eventId', // absolute URL path\n via: 'attendeeOf', // relationship gate (must exist in authz.relationships)\n },\n});\n\n// features/events/actions/postAnnouncement.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Post an announcement to everyone attending the event.\",\n path: '/event/:eventId/announcements',\n method: 'POST',\n input: z.object({ body: z.string().max(2000) }),\n // No `via:` gate boilerplate β the namespace already ran the resolver, so\n // `access` only names roles and ctx.event is typed inside execute().\n access: { roles: ['admin', 'member'] },\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n```\n\nThe compiler emits one `app.use(...)` on the events feature's Hono app. Every standalone action in `features/events/actions/` whose path starts with `/event/:eventId/` joins the namespace automatically.\n\nMulti-lane via (v0.25+) and bulk-grant lanes (v0.26+) work identically on the table-level declaration β `via:` accepts the same shapes documented below for the project-level form.\n\n### Cross-feature: `authz.namespaces` (v0.24+)\n\nUse when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },\n },\n}\n```\n\nWith the namespace declared, any standalone action whose `path:` matches the prefix joins the gate β regardless of which feature owns it:\n\n```typescript\n// features/feeds/actions/feedMoments.ts (in one feature)\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Publish a moment to the event's live feed.\",\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ caption: z.string().max(280), photoId: z.string().optional() }),\n access: { roles: ['admin', 'member'] },\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n\n// features/rsvp/actions/respond.ts (in a different feature)\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Record the caller's RSVP for the event.\",\n path: '/event/:eventId/respond',\n method: 'POST',\n input: z.object({ response: z.enum(['yes', 'no', 'maybe']) }),\n access: { roles: ['admin', 'member'] },\n async execute({ db, input, ctx }) { /* β¦ */ },\n});\n```\n\nThe compiler emits one synthetic `src/routes/__namespace-event-scope.routes.ts` that imports each contributing feature's `actions` map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.\n\n### Multi-lane via (v0.25+) β first match wins\n\nWhen more than one relationship can authorize a caller for the namespaced resource, pass `via:` as an array. The middleware tries each lane in declaration order and stops at the first match β `ctx.<exposeAs>` is hydrated from whichever lane fired.\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n // Named per-event organizers (potentially EXTERNAL β these users may\n // not be a member of the event's org. That's the point: lets you grant\n // event-level access to freelancers / partner staff without adding\n // them to the org's member list.)\n organizerOf: {\n from: 'eventOrganizers',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf', 'organizerOf'],\n },\n },\n}\n```\n\nAll relationship lanes in a namespace **must agree on `loads:` + `exposeAs:`** β that's what guarantees `ctx.event` has the same shape regardless of which lane matched. The compiler rejects heterogeneous lanes at parse time.\n\n### Bulk-grant lanes (v0.26+)\n\nRelationship lanes cover \"specifically connected to this row.\" Bulk-grant lanes cover \"anyone with this role / team membership in the row's tenant\" β the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.\n\n```typescript\nnamespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: [\n 'attendeeOf',\n 'organizerOf',\n { roles: ['admin', 'owner'] }, // org-role bulk grant\n { team: true }, // active-team-membership bulk grant\n ],\n },\n}\n```\n\nEach bulk-grant lane:\n\n- **`{ roles: [...] }`** β passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the \"company admin sees everything\" case.\n- **`{ team: true }`** β passes when `ctx.activeTeamId` is set. The loads-table firewall does the actual `events.teamId === ctx.activeTeamId` check during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.\n\nBoth bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration β they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. **At least one relationship lane is required** alongside bulk-grant lanes in v0.26 (to anchor `loads:` + `exposeAs:`).\n\nWhen a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken β relationship names, role names, and `\"team-membership\"` for `{ team: true }` lanes β so a developer debugging an unexpected 403 sees the full surface they need to satisfy.\n\nA namespace can also fold the scope machinery into this same gate: `mintScope: true` **mints** a scope token on a matched userId lane, and `acceptScope: '<kind>'` **accepts** an already-minted scope claim as proof of entry β one handler under the prefix serves both a Better-Auth user and a sessionless scope principal. See [Scopes β `acceptScope`](/define/scopes#acceptscope--accept-an-incoming-scope-claim-as-proof-of-entry).\n\n### Discovery is path-prefix-only\n\nActions opt in by matching `path:` against a declared namespace prefix. There's no `namespace: 'foo'` field on `defineAction` β the path string is the discoverable surface, consistent with how `path:` already determines an action's URL.\n\n### Requirements (enforced at compile time)\n\nBoth forms share the same shape checks:\n\n- **`via:` accepts one of three shapes.** A single relationship name (v0.23+), an array of relationship names (v0.25+, first match wins), or β as of v0.26 β an array mixing relationship names with bulk-grant guards (`{ roles: [...] }`, `{ team: true }`).\n- **Every relationship lane must declare `loads + exposeAs`.** Without `loads` there's nothing for the middleware to hydrate; the namespace gate would be indistinguishable from a per-action access rule.\n- **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.\n- **Bulk-grant lanes inherit `loads:` + `exposeAs:` from sibling relationship lanes.** Pure bulk-grant namespaces (no relationship lane at all) are also accepted β set `loads:` + `exposeAs:` directly on the namespace declaration so hydration has somewhere to anchor.\n- **`prefix:` must contain at least one `:param` segment** (e.g. `/event/:eventId`). The middleware reads the relationship key from `c.req.param()` because no request body has been parsed at middleware time.\n- **One declaration per namespace name.** The same name in both `defineTable({ namespace })` and `authz.namespaces` is rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.\n\nProject-level only:\n\n- **Ambiguous prefixes** like `/a/:x` and `/a/:y` (same shape, different `:param` names) are rejected. Strict super/sub-set relationships (`/event/:e` vs `/event/:e/admin`) are fine β the harvester routes each action to the longest matching prefix.\n- **Unused namespace** emits a `[quickback:authz]` warning when no action's path matches the declared prefix. Not a hard error β the namespace may be staged ahead of the actions.\n\n### What namespace actions get for free\n\nInside a namespace action's `execute()`:\n\n- `ctx.<exposeAs>` is populated by the middleware with the loaded resource row. Statically `any` by default β narrowed to `typeof <loadsTable>.$inferSelect` when the action's import points at the per-namespace helper (see [below](#narrow-ctxexposeas-typing-v027)).\n- Tenant context (`ctx.activeOrgId` / `ctx.activeTeamId`) is stamped from the matched relationship row when its `from` table carries those columns. Downstream scoped queries work without further setup.\n- The action's own `access:` block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate β namespace handles entry, per-action gates further.\n\n### Narrow `ctx.<exposeAs>` typing (v0.27+)\n\nThe namespace middleware hydrates `ctx.<exposeAs>` at runtime β that's been true since v0.23. The static type of that field, though, is `any` via the `AppContext` index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.\n\nv0.27 emits one **per-namespace `defineAction` helper** alongside the standard `<feature>/.quickback/define-action.ts`. Importing from the narrowed helper retypes `ctx.<exposeAs>` inside `execute({ ctx })` to the loaded row's `$inferSelect` shape. Nothing else changes β runtime behavior, action discovery, and the `path:` namespace match are identical.\n\n```ts title=\"features/feeds/actions/feedMoments.ts\"\n// One-line flip per namespace-scoped action:\nimport { z } from 'zod';\nimport { defineAction } from '../.quickback/define-action.event-scope';\n// ββββββββ¬βββββββ\n// kebab(namespaceName)\n\nexport default defineAction({\n description: \"Publish a moment to the event's live feed.\",\n path: '/event/:eventId/feed-moments',\n method: 'POST',\n input: z.object({ body: z.string() }),\n access: { roles: ['attendee'] },\n async execute({ ctx, input }) {\n ctx.event.id // β string\n ctx.event.startsAt // β Date β autocomplete works\n ctx.event.organizerId // β narrows on the field's declared type\n\n ctx.event.idd // β TS2339 β typo caught at compile time\n },\n});\n```\n\nThe compiler emits one helper per `(feature, namespace)` pair where the feature owns at least one action whose `path:` falls under the namespace prefix. Filename is `define-action.<kebab(namespaceName)>.ts` β `eventScope` becomes `define-action.event-scope.ts`. Helpers live next to the standard `define-action.ts` in `<feature>/.quickback/`, so the relative import is the same shape as every other action file in your project.\n\n#### Opt-in, not breaking\n\nActions that keep their existing `import { defineAction } from '../.quickback/define-action'` continue to compile unchanged β `ctx.<exposeAs>` is `any` via the `AppContext` index signature, which is exactly the v0.23βv0.26 behavior. You flip imports per action at your own pace.\n\n#### Compile-time advisory\n\nWhen `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:\n\n```text\n[quickback:typing] action \"feedMoments\" in feature \"feeds\" lives under\n namespace \"eventScope\" β switch its import to\n `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.\n (Runtime behavior is unchanged; the narrowed helper only refines TS types.)\n```\n\nNon-blocking β same `[quickback:typing]` family as `[quickback:authz]`. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).\n\n#### Multi-namespace features\n\nA single feature can contribute actions to several namespaces β say, an `interviews` feature with actions under both `interviewScope` and `eventScope`. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.\n\n```text\nsrc/features/interviews/.quickback/\nβββ define-action.ts # generic β standard fallback\nβββ define-action.interview-scope.ts # ctx.interview typed\nβββ define-action.event-scope.ts # ctx.event typed\n```\n\n#### Why per-namespace and not per-action\n\nA `defineAction` helper that's narrow to *one* exposed key (the namespace's `exposeAs`) is enough β every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project."
|
|
135
135
|
},
|
|
136
136
|
"define/arrows": {
|
|
137
137
|
"title": "Arrows",
|
|
138
138
|
"content": "A relationship answers *\"does the caller have a row linking them to this\nresource?\"* An **arrow** answers a different question: *\"the caller has\nauthority over **another** object β does that authority **flow across a\nforeign key** to this one?\"* An event's announcements inherit the authority\nof the event's organization; a folder's documents inherit the authority of\nthe folder; a child section inherits the authority of its ancestors.\n\nAn arrow is a declared **FK hop**: it names a foreign-key column on a `from`\ntable and the `to` table that FK resolves to. Referenced from a permission,\nit resolves the row's FK to its target object and requires a permission\n**there** β SpiceDB's `relation->permission`, lowered to SQL. Two emit\nshapes: a single FK hop lowers to a subquery; a self-referential hop\n(`folder.parentId -> folder`) lowers to a depth-bounded `WITH RECURSIVE` CTE.\n\n## Declaring arrows\n\nArrows live in `quickback.config.ts` under `authz.arrows`, alongside\n`authz.relationships` and `authz.permissions`:\n\n```typescript\n// quickback.config.ts\nimport { defineConfig } from '@quickback/compiler';\n\nexport default defineConfig({\n // ...providers...\n authz: {\n arrows: {\n // single FK hop: an event row β the organization that owns it\n eventOrg: { from: 'event', fk: 'organizationId', to: 'organization' },\n // self-referential hierarchy: a folder β its parent folder\n folderTree: { from: 'folder', fk: 'parentId', to: 'folder', recursive: true },\n },\n permissions: {\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n // org admins of an event's org inherit access to the event\n 'event:view': { anyOf: ['organizerOf', { arrowRef: 'eventOrg', permission: 'org:admin' }] },\n // anyone who can administer an ancestor folder can read this folder\n 'folder:read': { anyOf: [{ arrowRef: 'folderTree', permission: 'org:admin' }] },\n },\n },\n});\n```\n\n| Field | Meaning |\n|---|---|\n| `from` | Source table the FK column lives on. |\n| `fk` | Foreign-key column on `from`. **For a non-recursive arrow this is the tenant column** the claim binds against (see below); for a recursive arrow it is the recursion pointer (`parentId`). |\n| `to` | Target table the FK resolves to. A self-hop has `from === to`. |\n| `recursive?` | Forces the recursive-CTE lowering. When `from === to` the compiler auto-detects recursion even if this is omitted. Default `false`. |\n| `maxDepth?` | Per-arrow recursion bound (positive integer). Ignored for non-recursive arrows. Default is the global bound, `8`. |\n| `tenantColumn?` | The tenant column the seed of a **recursive** arrow binds the org claim against β defaults to `organizationId`. Set it when the hierarchy table spells the column differently (e.g. `organisationId`). Ignored for non-recursive arrows. |\n\n## Referencing an arrow from a permission\n\nAn arrow is never used directly. It is a **leaf** inside a\n[permission](/define/permissions) expression, written as\n`{ arrowRef: '<name>', permission: '<perm-at-target>' }`:\n\n```typescript\n'event:view': { anyOf: ['organizerOf', { arrowRef: 'eventOrg', permission: 'org:admin' }] },\n```\n\nRead it as: *\"`event:view` holds if the caller is an `organizerOf` the\nevent, **or** if β hopping across `eventOrg` to the event's organization β\nthe caller has `org:admin` **there**.\"* The `permission` named on the leaf is\nthe permission required **at the target object**, and it participates in the\npermission composition graph (resolution + cycle detection) exactly like a\n`{ permissionRef }`.\n\n**M2 target restriction.** The target permission must reduce to\n**org-membership roles** (`admin` / `owner` / `member`) β directly or\nthrough a `permissionRef` / `anyOf` / `allOf` of org roles. That's what lets\nthe hop bind to the caller's verified active-org claim (`ctx.activeOrgId`).\nA target permission that references a relation, a scoped role, a pseudo-role,\na `not`, or a nested arrow is a **compile error** in M2 (never a silent\nallow) β those richer targets are a documented fast-follow. So\n`org:admin = anyOf(role('admin'), role('owner'))` is the canonical target.\n\n## Using the permission in a firewall\n\nThe permission that contains the arrow is referenced from a resource's\n[`firewall`](/define/firewall) with a `{ field, permission }`\narm, like any other named permission. `field` is the resource-side column the\nlowered subquery constrains:\n\n```typescript\n// features/event-documents/event-documents.ts\nfirewall: {\n all: [\n { field: 'eventId', permission: 'event:view' },\n { field: 'deletedAt', isNull: true },\n ],\n}\n```\n\nThe arrow arm of `event:view` lowers to an FK-hop subquery on `eventId`; the\nrelationship arms (`organizerOf`) lower to relationship subqueries; the\n`anyOf` OR's them under the null-safe empty-guard (`anyGuarded`) so an absent\nclaim **denies** rather than reading the whole table.\n\n## Emit shape 1 β non-recursive (FK-hop subquery)\n\nFor `eventOrg = { from: 'event', fk: 'organizationId', to: 'organization' }`\nwith target permission `org:admin`, an `{ arrowRef: 'eventOrg' }` arm on a\nresource constrained by `eventId` lowers to:\n\n```sql\nWHERE event_documents.eventId IN (\n SELECT event.id FROM event\n WHERE event.organizationId = ? -- ? = ctx.activeOrgId (signed claim)\n )\n```\n\nIn Drizzle terms:\n\n```typescript\ninArray(event_documents.eventId,\n db.select({ x: event.id }).from(event)\n .where(eq(event.organizationId, ctx.activeOrgId!)))\n```\n\nThe seed of every non-recursive hop binds the **`fk` column** to the active-org\nclaim β so for a non-recursive arrow, **`fk` is the org/tenant column on\n`from`**, not an unrelated FK. (A self-FK hierarchy is the recursive case\nbelow; that's where `fk` is a recursion pointer and the tenant column is\nseparate.)\n\n## Emit shape 2 β recursive (bounded `WITH RECURSIVE` CTE)\n\nA self-referential arrow expresses **inherited authority down a hierarchy**:\na row is visible if the caller controls it directly **or** controls any of\nits ancestors. For `folderTree = { from: 'folder', fk: 'parentId', to: 'folder', recursive: true }`\nthe arrow lowers to a recursive CTE bounded by `maxDepth`:\n\n```sql\nWITH RECURSIVE __arrow_closure(id, depth) AS (\n -- seed: the folders the caller directly controls (tenant-constrained)\n SELECT folder.id, 0 FROM folder\n WHERE folder.organizationId = ? -- ? = ctx.activeOrgId\n UNION ALL\n -- step: walk parent β child, RE-constraining tenancy on every walked row\n SELECT folder.id, c.depth + 1\n FROM folder JOIN __arrow_closure c ON folder.parentId = c.id\n WHERE c.depth < 8 AND folder.organizationId = ?\n)\nSELECT id FROM __arrow_closure\n```\n\nBoth D1 (SQLite) and Neon (Postgres) speak `WITH RECURSIVE`, so the same\narrow is valid on either provider. Drizzle interpolates the column/table\n**objects** (dialect-correct identifiers) and binds the claim as a\n**parameter** β never string-concatenated, so an arrow is never an injection\nsurface (the FK column and tables are compile-time identifiers; the only\nruntime value is the signed org claim).\n\n## Tenant isolation semantics\n\nArrows are tenant-safe by construction. Three guarantees, all enforced at\nthe SQL level:\n\n- **The seed is tenant-constrained.** The CTE root (and the non-recursive\n hop's `WHERE`) binds the tenant column to `ctx.activeOrgId`. A caller only\n ever seeds the closure with rows in their own org.\n- **The recursive arm re-constrains tenancy on *every* walked row** β not\n just the seed. The step is `JOIN __arrow_closure c ON folder.parentId = c.id`\n **`AND folder.organizationId = ctx.activeOrgId`**. A row that was reparented\n under an in-tenant parent but whose **own** org differs is excluded. This is\n defense-in-depth: cross-org inheritance must never happen, and the SQL\n enforces it regardless of what the write path allows. Strict per-row\n tenancy is the correct default for an org-membership arrow.\n- **A missing claim fails closed.** When `ctx.activeOrgId` is null (anonymous\n or cross-tenant caller), the subquery short-circuits to `sql\\`1 = 0\\`` β\n a deny, never an unconstrained read and never an `undefined` bind.\n\n## Bounded recursion\n\nRecursion is **always** finite. The recursive arm's `WHERE c.depth < maxDepth`\ncaps the walk so a deep or cyclic hierarchy can never run away. The bound is\nresolved with this precedence:\n\n1. Per-permission override β `authz.permissionMaxDepth['<perm>']`.\n2. Per-arrow `maxDepth`.\n3. The global default, **8**.\n\n```typescript\nauthz: {\n arrows: {\n sectionTree: { from: 'sections', fk: 'parentId', to: 'sections', recursive: true, maxDepth: 6 },\n },\n permissions: {\n 'section:inTree': { anyOf: [{ arrowRef: 'sectionTree', permission: 'org:admin' }] },\n },\n // optional: raise the bound for one permission without touching the arrow\n permissionMaxDepth: { 'section:inTree': 16 },\n}\n```\n\nAn author who **explicitly opts out** of the bound β `unbounded: true` β\nwith no token-closure path is a **compile error**: there is no safe finite\nSQL for unbounded recursion, so the compiler refuses to emit a\nnon-terminating CTE. The fix is to set a `maxDepth`. Quickback never silently\nallows an unbounded traversal.\n\n## Worked example β q-events\n\nThe `q-events` example ships both shapes.\n\nA **recursive** self-FK on the `sections` feature. `sections.parentId`\npoints back at `sections`; access to an ancestor section confers access to\nall descendants:\n\n```typescript\n// quickback.config.ts\nauthz: {\n arrows: {\n sectionTree: { from: 'sections', fk: 'parentId', to: 'sections', recursive: true, maxDepth: 6 },\n },\n permissions: {\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n 'section:inTree': { anyOf: [{ arrowRef: 'sectionTree', permission: 'org:admin' }] },\n },\n}\n\n// features/sections/sections.ts β the permission arm rides alongside the org scope\nfirewall: {\n all: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'id', permission: 'section:inTree' }, // emits the tenant-gated WITH RECURSIVE CTE\n { field: 'deletedAt', isNull: true },\n ],\n}\n```\n\nThe org `equals` arm and the recursive arrow's per-row tenant re-constraint\nare belt-and-suspenders β both pin the closure to the caller's org. The arrow\nadds the *ancestor-authority* dimension on top of the flat org scope.\n\n## Reference\n\n```typescript\n// authz.arrows.<name>\ninterface ArrowDefinition {\n from: string; // source table the FK lives on\n fk: string; // FK column (non-recursive: the tenant column; recursive: the parent pointer)\n to: string; // target table the FK resolves to (self-hop: from === to)\n recursive?: boolean; // force the recursive-CTE lowering (auto when from === to)\n maxDepth?: number; // per-arrow recursion bound (default 8)\n tenantColumn?: string; // recursive-seed tenant column override (default 'organizationId')\n}\n\n// referenced from a permission as a leaf:\n{ arrowRef: '<arrowName>', permission: '<permissionAtTarget>' }\n\n// per-permission depth override (overrides per-arrow maxDepth + the global 8):\nauthz.permissionMaxDepth?: Record<string, number>\n```\n\n- Every `{ arrowRef }` in a permission must name a declared `authz.arrows[*]`\n entry, and the arrow's `fk` / `to` are checked against the real schema at\n compile time.\n- The target `permission` must reduce to org-membership roles in M2.\n- See [Permissions](/define/permissions) for the expression DSL\n the arrow leaf lives in, and [Firewall β named permissions](/define/firewall#named-permissions-permission)\n for how the resulting `{ permission }` arm sits inside a firewall. The\n compile-time analyzer reports the subquery / CTE depth of every arrow-bearing\n permission β see [Diagnostics](/define/diagnostics)."
|
|
139
139
|
},
|
|
140
|
+
"define/authz-roles": {
|
|
141
|
+
"title": "Named Access Rules - authz.roles & authz.rules",
|
|
142
|
+
"content": "**[Rung 2](/define#the-authorization-ladder).** Once the same role expression appears\nacross many features, give it a name and declare it once. If you only have a couple of\nrepeats, inline them β stay on [rung 1](/define/access).\n\n## Centrally defined access rules\n\nInstead of repeating the same `roles: [...]` expression across every feature, define it **once** in `authz.roles` and reference it by name everywhere. This is the recommended way to manage access as your app grows: one source of truth per rule, changed in one place.\n\nNamed roles (and named gates, tenant anchors, scope kinds) can be declared at **two levels**:\nat root `authz` in `quickback.config.ts` (visible everywhere), or inside a\n[feature area](/define/areas)'s `_area.ts` (visible to that area's\nsubtree only β a feature outside the area referencing the name is a compile error, and root\n`authz` bodies may reference root-declared names only). Declare each name in exactly one\nplace: re-declaring an inherited name is a compile error.\n\n```typescript\n// quickback.config.ts β define ONCE\nexport default defineConfig({\n // ...providers...\n authz: {\n roles: {\n // Compose from BA roles, pseudo-roles, and other named rules:\n staff: { roles: ['admin', 'member'] },\n // Boolean combinators:\n eventStaff: { or: [{ roles: ['staff'] }, { via: 'organizerOf' }] },\n // Relationship-backed (see below):\n attendee: { via: 'attendeeOf' },\n },\n },\n});\n```\n\n```typescript\n// any feature β REFERENCE by bare name\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const agendaItems = q.table('agendaItems', {\n id: q.id(),\n title: q.text().required(),\n startsAt: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(agendaItems, {\n read: { access: { roles: ['eventStaff'] } },\n update: { access: { roles: ['eventStaff'] } },\n});\n\n// features/events/actions/checkIn.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Check a guest in to the event and record the arrival time.\",\n input: z.object({ guestId: z.string() }),\n access: { roles: ['eventStaff', 'attendee'] },\n async execute({ db, input, ctx }) { /* ... */ },\n});\n```\n\n### Rule shapes\n\nEach entry in `authz.roles` is one of four shapes:\n\n| Shape | Meaning |\n|---|---|\n| `{ roles: ['admin', 'member'] }` | Composition β matches any of the listed roles (BA, pseudo, or other named rules) |\n| `{ or: [ruleA, ruleB] }` | Matches if **any** sub-rule matches |\n| `{ and: [ruleA, ruleB] }` | Matches only if **all** sub-rules match |\n| `{ via: 'relationshipName' }` | Caller proves a declared relationship β see [Relationship-based authorization](#relationship-based-authorization) below |\n\nRules compose freely β a rule may reference another rule by name (cycles are a compile error).\n\n### Where references resolve\n\nA named rule works in the `roles: [...]` array of every access surface. The compiler expands it at build time:\n\n| Surface | |\n|---|---|\n| `crud.*.access` | β |\n| `read.access` / `read.views.*.access` | β |\n| `masking.<field>.show` | β for role/composite rules; relationship (`via`) rules refused at compile (v1) |\n| `actions.<name>.access` | β |\n| `realtime.requiredRoles` | β β relationship arms fail closed at the WS handshake and are enforced by the row-stream firewall |\n\nNames that **aren't** declared in `authz.roles` β Better Auth roles, pseudo-roles like `AUTHENTICATED` β pass through untouched, so you can mix named rules and raw roles in the same array.\n\n### Beyond roles: named permissions\n\nFor access that traverses the data graph (FK hops, SpiceDB-style permission composition), see [`authz.permissions` + `authz.arrows`](/define/permissions) β the same define-once-reference-by-name model, one level richer than `authz.roles`.\n\n## Named gates (`authz.rules`)\n\n`authz.roles` centralizes the *who*. A **gate** (`authz.rules.<name>`) bundles a full access rule β *who* + an optional row predicate (`record:`) + optional [firewall lanes](/define/firewall#named-gate-references-rule) β under ONE name, declared once:\n\n```typescript\n// quickback.config.ts\nauthz: {\n tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } },\n rules: {\n // who + record: \"org staff, but only rows still active\"\n activeStaff: {\n who: { roles: ['member', 'admin', 'owner'] },\n record: { status: { equals: 'active' } },\n },\n // who + firewall: an org-OR-event-scope row gate, declared ONCE\n eventRow: {\n who: { roles: ['owner', 'admin', 'member'] },\n firewall: [{ any: [\n { tenant: 'org' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] }],\n },\n },\n}\n```\n\n{/* doc-compile: skip β cross-fence dependency: the `eventRow` gate is declared in the `quickback.config.ts` fence directly above. Named refs are expanded once at the compiler's normalization seam with the project's authz config in hand, and the gate compiles each fence as an isolated project against a fixed harness config, so `{ rule: 'eventRow' }` can never resolve here. */}\n```typescript\n// any feature β the gate name works like a role name\nexport default defineTable(eventLinks, {\n firewall: [{ rule: 'eventRow' }], // firewall stamp\n read: { access: { roles: ['eventRow'] } }, // access stamp\n});\n```\n\n### The two-stamp contract\n\nOne shared name, two independent stamps β **a single reference never applies both**:\n\n- An **access-position reference** (the bare name in any `roles: [...]` array) applies the gate's `who` + `record` arms **only**. It expands exactly like an inline rule: a who-only gate splices as the flat role list; a who+record gate as `{ and: [who, { record }] }`.\n- A **firewall reference** (`firewall: [{ rule: '<name>' }]`) applies the gate's `firewall` lanes **only**, spliced into the resource's top-level AND array. The `who` of a gate referenced only from `firewall:` is **not consulted** β that is the documented contract, not a silent drop. Firewall-who is legitimately *wider* than access-who (e.g. the firewall admits scope-token holders to rows while read access stays staff-only).\n\nBoth directions are enforced fail-closed at compile time:\n\n| You wrote | Compiler says |\n|---|---|\n| Access reference to a firewall-bearing gate, but the resource's `firewall:` doesn't reference it | **Error** β the row lanes would silently not apply |\n| `firewall: [{ rule }]` naming a gate with no `firewall` arm | **Error** β a who/record-only gate would splice zero lanes |\n| A firewall-bearing gate referenced from an **action's** access or from `masking.show` | **Error, unconditional** β no firewall array exists at those sites (nested `show.or` / `show.and` arms included) |\n| A who-less (firewall-only) gate referenced from an access position | **Error** β row lanes can't masquerade as a who-grant |\n| A gate's `record:` field is not a column of the referencing table | **Error, per reference** β a missing field evaluates against `undefined` at runtime (`notEquals`/`notIn` would silently *grant*) |\n| A spliced gate's firewall lane filters on a column the stamped table doesn't have | **Error, per reference** β the lane could never scope rows there |\n\n### Naming rules\n\nRule names share the reference namespace with roles, so the compiler rejects (at declaration time) a rule name that collides with an `authz.roles` entry, a reserved/provider role, **any scoped-role name** (bare sugar like `attendee` or the canonical `scope:<kind>:<role>` spelling), or a name containing `+` or `:` (the `scope:` prefix always means a token-verified scope principal β a colon-named rule could capture references meant for one).\n\nInside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned β write the expanded list (`['member', 'admin', 'owner']`), because `+` expansion runs at resource sites only and a `member+` inside a body would silently never match. Roles may not reference rules (the dependency arrow is one-way), and gates never nest.\n\n### Typo safety\n\nA `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule β a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.\n\n## Outgrown this?\n\nIf the answer depends on a row in one of *your* domain tables (\"is this caller a\ncollaborator on this project?\") rather than on org membership, that's\n[rung 3 β Relationships](/define/relationships)."
|
|
143
|
+
},
|
|
140
144
|
"define/bundles": {
|
|
141
145
|
"title": "Bundles",
|
|
142
146
|
"content": "## Overview\n\nClient bootstrap screens want many small lists in one request. Hand-written\n\"bundle\" endpoints all repeat the same 150 lines: a `Promise.all` of selects\nshaped byte-identically to the CRUD list endpoints they replace, a\n`sections: string[]` subset filter, a copy-pasted SHA-1 ETag +\n`ifNoneMatch β notModified` short-circuit, a `Server-Timing` header, and\nhand-re-derived per-slice masking. `defineBundle` generates all of it.\n\n```typescript\n// features/events/actions/getOverviewBundle.ts\nimport { defineBundle, list, custom } from \"../.quickback/define-bundle\";\n\nexport default defineBundle({\n path: \"/event/:eventId/overview-bundle\",\n description: \"Console Overview bootstrap\",\n access: { roles: [\"member\", \"admin\"] },\n etag: true, // default true\n serverTiming: \"overview\", // optional\n sections: {\n guests: list(\"guests\", {\n columns: [\"id\", \"status\", \"modifiedAt\", \"createdAt\", \"displayName\"],\n where: { eventId: \"$ctx.event.id\" },\n orderBy: [{ createdAt: \"desc\" }],\n limit: 500,\n }),\n tickets: list(\"supportTickets\", { where: { eventId: \"$ctx.event.id\" }, orderBy: [{ modifiedAt: \"desc\" }], limit: 100 }),\n counts: custom(async ({ db, ctx }) => ({ open: 0 })), // computed slice β author owns masking\n },\n});\n```\n\n## Semantics\n\n- **Generated POST action** with input `{ sections?: string[], ifNoneMatch?: string }`,\n mounted through the standard standalone pipeline β auth, access, org/team\n preconditions, rate limits, OpenAPI, MCP tools, security contracts all\n apply.\n- **`list()` sections run through the scoped db** β the org firewall and\n soft-delete filter apply by construction β and the target table's REAL\n mask function is applied (the same read projection the CRUD list endpoint\n runs), so masked columns are safe to include. Every list slice lands as\n `{ data: rows }` (the per-resource cache-seed contract).\n- **`sections` filter**: omitted/empty = all. An un-wanted list section\n returns `{ data: [] }` (drop-in compatible with existing clients);\n un-wanted `custom` sections are absent.\n- **All sections run in one `Promise.all`.**\n- **ETag**: SHA-1 hex over `{ scopeSeed: <path params>, userId, payload }`.\n An `ifNoneMatch` match returns `{ success: true, etag, notModified: true }`\n with **no sections**. The digest is also exported as `sha1Hex` from\n `lib/etag` so remaining hand-written reads can delete their copies.\n- **`custom()` sections** receive the full action context and are embedded\n verbatim under the section name β the author owns masking there.\n\n## Compile-time validation (fail-closed)\n\n- Unknown section tables error, listing candidates.\n- `columns` / `where` / `orderBy` must name declared columns\n (compiler-injected audit columns like `createdAt`/`modifiedAt` are allowed).\n- `where` values are literals or the strict substitution allowlist\n (`$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id`) β always\n parameterized. Anything richer belongs in a `custom()` section.\n- Section names may not shadow the response envelope\n (`success`, `etag`, `notModified`, `sections`).\n- **A bundle must never widen read access**: its `access.roles` must be a\n subset of every list section table's `read.access` roles β a violation is\n a compile error, not a warning."
|
|
143
147
|
},
|
|
144
148
|
"define/changesets": {
|
|
145
149
|
"title": "Changesets β aggregate writes",
|
|
146
|
-
"content": "A **changeset** writes a parent row and its owned relations β junction\nmemberships, normalized phones/emails, line items β in **one request**,\nreplacing the hand-rolled multi-table action. You declare the one fact the\ncompiler was missing β which relations are **compositions** (owned by this\nroot) vs **references** (independent entities) β and the compiler generates\nthe whole write path.\n\nChangesets are a **contract v2** capability (`contract: { version: \"v2\" }`).\nDeclaring `owns` on a v1-pinned project is a compile error.\n\n## Declaring the boundary β `owns`\n\n{/* doc-compile: skip β two reasons. (1) Project-config prerequisite: `owns` is a contract-v2 capability (stated two paragraphs above) and needs `contract: { version: \"v2\" }`; the gate's harness config pins v1. (2) The fence is the `owns` boundary only β columns/firewall/guards/masking/read are elided, and it names three sibling tables (`tasks`, `people`, `taskChecklistItems`) it deliberately does not repeat. */}\n```ts title=\"quickback/features/projects/projects.ts\"\nexport default feature(\"projects\", {\n // ...columns, firewall, guards, masking, read...\n create: { access: { roles: [\"admin\", \"owner\"] } },\n update: { access: { roles: [\"admin\", \"owner\"] } },\n\n owns: {\n tasks: {\n table: \"tasks\", // camelCase table name β a defineTable in this project\n fk: \"projectId\", // FK on the CHILD pointing at this root's PK\n refs: { // client-supplied pointers at INDEPENDENT entities\n assigneeId: \"people\",\n reviewerId: \"people\", // nullable refs may be omitted or null\n },\n inherit: [\"organizationId\"], // parent columns copied onto every inserted child\n owns: { // grandchildren β structural nesting, depth-capped\n checklist: { table: \"taskChecklistItems\", fk: \"taskId\", inherit: [\"organizationId\"] },\n },\n },\n },\n});\n```\n\n| Key | Meaning |\n|---|---|\n| `table` | The owned child β **must** be a `defineTable`/`feature()` in the project. String literal, never an identifier. Auth tables can never be owned. |\n| `fk` | The spine: the child column pointing at this root. **Compiler-stamped** on inserts; a client-supplied value is rejected. |\n| `refs` | Columns pointing at independent entities. Client-supplied, **existence-checked inside the caller's tenant** (the referenced table's firewall is ANDed) β on inserts **and** patches. The referenced row is never written through. |\n| `inherit` | Tenant/denorm columns copied verbatim from the (firewall-verified) parent row onto every inserted child. Compiler-stamped; client values rejected. |\n| `owns` | Nested owned relations. Max 3 levels of nesting (the aggregate spans at most 4 tables). |\n\nA child's [`q.stamp`](/define/schema#qstamp--proven-principal-identity-columns) identity columns are a **fourth, disjoint** source, sitting alongside `fk`/`inherit`/`refs`. On a changeset **insert** the engine stamps them from the **caller's proven scope claim** (`ctx.scope.<kind>.<claim>`) β *not* from the parent row β but only when the caller is a scope-only principal; an org-admitted caller keeps their client value (org-firewall-bounded). The contrast is exact: `inherit` copies **tenant** columns from the firewall-verified *parent*, `q.stamp` copies **identity** from the proven *token*. A required claim absent on a scope principal fails the op with **403** β emitted *before* the ref-existence checks, so a claim-less caller cannot probe which rows exist. A `refs` key may not alias a `q.stamp` column (a column is compiler-stamped **or** a client ref, never both). On a changeset **patch** op the stamp column is **immutable** β a client value for it is rejected (400) like any systemManaged column, matching the plain update path. Because the stamp lives inside the changeset handler, a **keyed** (`Idempotency-Key`) replay neither re-writes nor re-stamps; a keyless retry re-writes and re-stamps.\n\n**Owning a relation is not a write grant.** Every changeset op is admitted by\nthe **child table's own crud declaration**: `insert` requires `create:` on the\nchild, `patch` requires `update:`, `delete` requires `delete:` (soft mode only\nin v1) β each with its own `access`. There is no per-relation access override:\naccess is declared exactly once, on the child.\n\n### `routes: false` β changeset admission without a raw route\n\nWidening a child's access for changeset use must not silently open its raw\nCRUD surface. The `create`, `update`, and `delete` op configs accept\n`routes: false` (`upsert`/`put` does not): the access stays declared (it is\nthe changeset admission gate) while the raw HTTP route β and its\nauto-promoted batch variant β is never mounted, documented, or counted in\nthe operations manifest.\n\n```ts title=\"quickback/features/projects/tasks.ts\"\nupdate: { access: { roles: [\"member\", \"admin\", \"owner\"] }, routes: false },\n```\n\n## The wire contract\n\nOne blessed path β **RFC 5789 media-type dispatch** on the routes you already\nhave. No subpath.\n\n- `PATCH /api/v2/<resource>/:id` with\n `Content-Type: application/vnd.quickback.changeset+json` β apply a changeset\n to an existing root. Plain `application/json` keeps the flat-column PATCH.\n- `POST /api/v2/<resource>` with the same media type β create the root and its\n children in one changeset.\n\n```jsonc\n// PATCH /api/v2/projects/prj_1 (Content-Type: application/vnd.quickback.changeset+json)\n{\n \"patch\": { \"name\": \"Renamed\" }, // sparse ROOT patch (optional)\n \"tasks\": {\n \"insert\": [\n {\n \"lid\": \"t1\", // client correlation id\n \"title\": \"Ship it\",\n \"assigneeId\": \"per_9\", // ref β tenant-checked\n \"checklist\": { \"insert\": [{ \"label\": \"QA pass\" }] } // grandchild, FKs onto t1's minted id\n }\n ],\n \"patch\": [{ \"id\": \"tsk_2\", \"state\": \"done\" }],\n \"delete\": [\"tsk_3\"]\n }\n}\n```\n\n```jsonc\n// Response\n{\n \"success\": true,\n \"root\": { \"id\": \"prj_1\", \"name\": \"Renamed\", /* masked through the root's masking */ },\n \"created\": { \"t1\": \"tsk_9aβ¦\", \"/tasks/insert/0/checklist/insert/0\": \"tci_44β¦\" },\n \"meta\": { \"ops\": 4, \"transactional\": false }\n}\n```\n\n- Inserts/patches apply parent-first (document order); deletes apply\n children-first.\n- `lid` correlates a minted id in `created`; entries without a `lid` key on\n their JSON Pointer. A nested insert's FK comes from its parent op's minted\n id β an unresolvable parent lid is a pointer-carrying **400**, never a\n silent re-parent onto the root.\n- `Prefer: return=minimal` omits `root` from the response. v1 representation\n is **root-row-only** (re-read through the root's masking) β nested aggregate\n reads are the phase-2 `?include=` reader; use [`defineView`\n includes](/define/read) today.\n\n### Headers\n\n| Header | Behavior |\n|---|---|\n| `If-Match` | Optimistic concurrency against the **root revision** β the root's `updatedAt` (or the injected `modifiedAt` audit column). Accepted value forms: `W/\"<revision>\"`, `\"<revision>\"`, or the bare revision value, where `<revision>` is the raw value of the revision column as returned in the root row. **Do not echo `GET /:id`'s `ETag` header into `If-Match`** β that ETag is the contract layer's body-hash ETag, not this revision, and will always **412**. Compared inside the transaction; mismatch β **412**. Every accepted changeset touches the revision. A root with no revision column answers `If-Match` with **428 PRECONDITION_UNSUPPORTED** β never silently ignored; the POST variant always answers 428 (no pre-existing revision to match). |\n\n`If-Match` is honored with the **identical comparator on the plain\n`application/json` write lanes** too: single-record `PATCH`, `PUT`, and\n`DELETE` compare the supplied revision against the fetched row (mismatch β\n**412**), and `PATCH`/`PUT` additionally pin the revision into the write's\n`WHERE` (compare-and-swap), so a concurrent writer between the fetch and the\nwrite surfaces as **412** on every provider β including the transaction-less\nD1 / Neon-HTTP lanes. A `PUT` with `If-Match` against a missing row is a\n**412** (RFC 9110: no current representation), never a silent create. Tables\nwith no revision column, and every **batch** endpoint (`If-Match` is a\nsingle-resource precondition), answer **428 PRECONDITION_UNSUPPORTED**. A\nsupplied precondition is **never silently ignored** anywhere.\n| `Idempotency-Key` | The standard write-retry key. Claims are principal-scoped β a replayed key from a different principal is a 422, never a cached-body leak. |\n| `Prefer` | `return=representation` (default) or `return=minimal`. |\n\n### Errors\n\nRFC 9457 `application/problem+json`. The failing op is identified by a JSON\nPointer in the `pointer` extension (`/tasks/insert/0/assigneeId`). On\n**non-transactional providers** the error also carries an `ops` extension\nlisting the outcomes of ops applied before the failure β the honest committed\nprefix. On **transactional providers** the rollback erased every applied op,\nso the error carries **no `ops` extension** (advertising rolled-back ids would\npoint clients at rows that no longer exist). **Outcome entries carry only\n`{ pointer, status, id? }` β never child field values** (v1 deliberately\nwithholds nested child representation, so errors cannot become an\nunmasked-child side channel).\n\n## The security model β \"owning a relation is not a backdoor\"\n\nThe **root op** runs the root table's full single-record gate stack, in order:\nauth β cross-tenant guard β the root's own `update` (PATCH) / `create` (POST)\naccess β **always, including child-only bodies; there is no child-only bypass\nlane** β firewall fetch (reveal β 403 / hide β 404, byte-consistent with the\nplain handler) β `requireSelf` β root body schema + ownership guard + guards.\nThe POST variant runs the root's full create pipeline (org validation, FK\nexistence checks, defaults/computed, ownership stamping).\n\nEvery **child op** then pays:\n\n1. **Admission** β declared relation, declared op kind (unknown keys are 400s).\n2. **The child's own access** β the pre-record role gate runs **before any row\n fetch** (no 404-vs-403 ID probing under the aggregate); `record:`\n predicates are evaluated against the fetched row on patch/delete and\n against the submitted input on insert.\n3. **systemManaged rejection** β client data carrying `fk`, any `inherit`\n column, or an ownership column is **rejected** with the op's pointer, never\n stripped or stamped-over. (The child's *plain-CRUD* guards are unaffected β\n a junction may keep its FK createable for its raw route; the same field in\n a changeset op is rejected because the changeset supplies it structurally.)\n4. **The child's column body schema** β q-authored children pay the same Zod\n types/enums/lengths backstop their plain POST/PATCH enforces (strict,\n guards-aware, with the compiler-stamped columns omitted). Drizzle-authored\n children have no Zod on their plain routes either, so none applies here β\n parity, not an omission.\n5. **The child's guards** β `createable`/`updatable` validation.\n6. **The child's firewall** β every patch/delete WHERE is\n `spine FK = parent id AND child firewall AND id`, same-feature or\n cross-feature alike. Inserts derive tenant columns only from the\n firewall-verified parent row.\n7. **Tenant-scoped `refs` checks** β each non-null ref must exist inside the\n referenced table's firewall, on **inserts and patches alike** (re-pointing\n a ref pays the same check; only columns present in the op's data are\n checked).\n8. **Server-minted child ids** β a client-supplied child primary key on an\n insert is rejected (like the plain POST's strict body schema), unless the\n project is configured for client-provided ids (`generateId: false`).\n\nChild `delete` ops stamp the **fixed `deletedAt`** audit column β exactly what\nthe plain DELETE route stamps (the audit wrapper then auto-stamps\n`deletedBy`). An `isNull` firewall arm on any other column (e.g.\n`archivedAt`) is a read-scoping predicate, never the soft-delete stamp.\n\n### Handler triggers fire β the changeset is a first-party write\n\nEvery root and owned-child op writes through the **same audit-wrapped `db`\nchokepoint** the plain CRUD routes and actions use β not a raw Drizzle handle.\nSo a child's declared [`handler:` triggers](/define/triggers#handler-triggers-handler)\nfire on the changeset exactly as they do on the child's own route: `beforeInsert`\n/ `beforeUpdate` / `beforeDelete` run at the write (a throw becomes the same\n`TRIGGER_REJECTED` and β on a transactional provider β rolls the whole aggregate\nback), and `afterInsert` / `afterUpdate` run once per affected row. Audit\nstamping (`createdBy` / `modifiedBy`) rides the same chokepoint. The only gap is\n`afterDelete`, which the soft-delete stamp can't see β identical to the plain\nDELETE route's own limitation. (`sql:` triggers fire on every path regardless,\nas always.) This is the parity the trigger docs promise: a generated\ncontract-v2 changeset is a compiler write surface, not one of the\nqueue/cron/raw-SQL bypasses that skip handler hooks.\n\nCompile-time, fail-closed (everything throws, nothing normalizes silently):\n\n- **Per-arm tenant coverage**: every column arm of the child's *resolved*\n firewall β including **every branch of an `any:` OR** β must be satisfiable\n by `fk`/`inherit`. Covering one arm of an OR is not coverage. This runs over\n the post-expansion firewall, so lanes spliced from\n [`authz.rules`](/define/access#centrally-defined-access-rules)\n gates and `{ tenant }` anchors are checked too.\n- Children firewalled through a **subquery arm** (`via:`, `{ permission }`,\n arrows) cannot be owned in v1 β even when the arm arrives through a gate\n splice.\n- `refs` keys must be **disjoint** from `{fk} βͺ inherit βͺ ownership columns` β\n a column is either compiler-stamped or a client ref, never both (blocks\n ownership-column injection through a ref).\n- **Relationship / FGA access arms are compile errors** on the changeset lane\n β on the root's `update`/`create` access and on every admitted child op's\n access. Those arms are decided by inline route code the changeset engine\n does not emit in v1; rather than silently widen (or silently 403) the gate,\n the compiler refuses. Use roles/record predicates, or keep the write in an\n authored action. (Function-form access is refused for the same reason.)\n- **Envelope-encrypted roots cannot ride the changeset in v1** β the response\n path does not run the decrypt-then-mask prepare helper, so the returned root\n would carry sealed ciphertext. The compiler refuses rather than degrade\n silently. (Sealed-mode columns are unaffected β plain routes return those\n as-is too.)\n- **Relation names `insert`, `patch`, `delete`, and `lid` are rejected** β\n the wire parser reserves those payload keys, so such a relation would be\n silently unreachable on the wire.\n- One aggregate root per table, acyclic graph, bounded depth, declared child\n ops only, soft-delete children only, contract v2 only.\n\n## `afterCommit` β emit a realtime signal after the changeset commits\n\nA changeset that must notify live views declares **`afterCommit`** on the\naggregate root β a declarative broadcast, **not** a hand-rolled\n`try { realtime.* } catch {}` tail. It fires **one aggregate-level CloudEvent**\nstrictly **after** the transaction commits, riding the existing\n[named-invalidation / Broadcaster egress](/platform/realtime/named-invalidations)\n(so it inherits the CloudEvents envelope + AsyncAPI description for free).\n\n{/* doc-compile: skip β project-config prerequisites this fence cannot carry: `owns` needs `contract: { version: \"v2\" }`, and the `broadcast` event `attendRealtime.mobileBundleChanged.travelUpdated` plus its `thisEvent` delivery profile must be declared in a realtime registry under `services/realtime/`. Columns/firewall/read/crud are elided to `// ...` and the owned child table is not repeated. */}\n```ts title=\"quickback/features/travel/lodging-reservations.ts\"\nexport default defineTable(lodgingReservations, {\n // ...firewall / read / crud ...\n owns: { occupants: { table: \"lodgingReservationGuests\", fk: \"reservationId\",\n inherit: [\"eventId\", \"organizationId\"] } },\n afterCommit: {\n broadcast: {\n travelChanged: {\n event: \"attendRealtime.mobileBundleChanged.travelUpdated\", // registry.event.variant\n delivery: \"thisEvent\", // MUST be in the event's `deliveries` allowlist\n payload: {\n eventId: \"root.eventId\", // a committed root column\n reservationId: \"rootId\", // the root pk\n occupantIds: \"affectedIds\", // ids of child rows touched this changeset\n },\n },\n },\n },\n});\n```\n\n- **One event per aggregate**, not one per touched child. The payload carries\n an **affected-ids / changed-paths** roll-up derived from the applied ops\n (`affectedIds` = child ids, `changedPaths` = JSON pointers) β **ids and\n pointers only, never child field values**.\n- **`delivery` is required and fail-closed.** The audience lives on a named\n [delivery profile](/platform/realtime/named-invalidations); it must appear in the\n referenced event's `deliveries` allowlist. There is **no default selection**,\n so an event permitting a narrow AND a wide room can never silently fan a\n changeset frame to the wider one.\n- **Payload sources:** `root.<col>` (a committed root column), `rootId`,\n `affectedIds`, `changedPaths`. Every payload key the variant declares must be\n mapped; unknown sources / undeclared keys are compile errors.\n- **Best-effort:** a broadcast failure never rolls back the committed changeset\n (`console.warn`, dispatched on `waitUntil`).\n- **Root-row frame:** `afterCommit: { realtime: true }` additionally emits the\n root row (postgres_changes-style) on the table's own `realtime` room. The row\n rides unmasked **with the table's `MASKING_CONFIG`** so the Broadcaster masks\n per-subscriber-role at fanout β the same discipline plain CRUD realtime uses.\n\n### Fail-closed disclosure gates\n\nBecause a broadcast payload is **not** masked at fanout (only the root-row frame\nis), afterCommit fails the build rather than leak:\n\n- A **masked `root.<col>`** may ride a broadcast only to a role-only delivery\n whose roles β the column's unmask roles (same app-role namespace). A\n **scope-keyed** delivery or an **empty unmask set** (`show: { or: 'owner' }`)\n **always** throws.\n- **`affectedIds` / `rootId` / `changedPaths`** carry firewalled row IDs\n (existence/enumeration). They may ride a scope-keyed delivery (bounded to one\n scope-instance room); a role-only / org-wide delivery throws unless you\n acknowledge with `disclosesChildIds: true`.\n\n### `q.scope` verified vs `q.stamp` proven β the \"stamp then emit\" rule\n\nWhen a changeset [stamps a proven identity](/define/schema#qstamp--proven-principal-identity-columns)\nand then emits it, the two features compose on one write path:\n\n| | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |\n|---|---|---|\n| Purpose | tenant isolation column | proven-principal **identity** column |\n| Firewall arm? | **yes** β it is the tenant WHERE | **never** |\n| Verified how? | firewall re-verifies on read/patch/delete | token provenance (un-spoofable) |\n| Phrase | \"**stamp AND verify**\" | \"stamp AND **prove**\" |\n| Safe to broadcast? | to the matching scope-keyed room | **only** to an audience β the stamping scope kind |\n\nA `q.stamp` identity column (e.g. `guestId`) sourced via `root.<col>` is\n**audience-gated like `affectedIds`** (05Γ06 integration): the delivery must be\nscope-keyed to the **same scope kind** that stamped it, else the build fails β\nunless you acknowledge with **`disclosesStampedIdentity: true`**. A stamp is\nun-spoofable, not un-*sensitive*: provenance is not audience clearance.\n\n### Idempotency β at-least-once\n\nafterCommit is **at-least-once**, exactly as idempotent as the write it rides.\nA retry carrying the **same `Idempotency-Key`** neither re-writes nor re-emits\n(the middleware returns the cached response before the handler runs). A\n**keyless** retry re-runs the whole handler β re-writes **and** re-emits. Callers\nthat need single-delivery must send an `Idempotency-Key`.\n\n### No-tx: \"row written β event fired\"\n\nOn a no-tx provider (D1 / neon-http), a mid-changeset failure **throws** before\nthe success path, so **no frames emit** for the partially-applied prefix β\n`meta.transactional: false` is the only guarantee signal. A **fully-successful**\nno-tx changeset **does** emit, still with `transactional: false`. Never assume\n\"row written β event fired\"; `meta.transactional` is the contract.\n\n### `reindex` β re-embed the committed root\n\n```ts\nafterCommit: {\n reindex: true, // requires the root's `embeddings` block\n}\n```\n\n`reindex: true` re-enqueues the **committed root row** for embedding\nregeneration on the same at-least-once `EMBEDDINGS_QUEUE` lane the plain and\nbatch routes use β enqueued only **after** the changeset commits, so a\nrolled-back changeset produces no orphan embedding jobs. Fail-closed rules:\n\n- The root **must** declare an `embeddings` block β `reindex: true` without\n one is a compile error (there is nothing to re-embed).\n- `embeddings.onInsert` / `onUpdate: false` gate create/update changesets\n exactly like the plain routes; a field-watch `onUpdate: [...]` array is\n treated as **always** (changeset ops are aggregate-level, not a field diff).\n- Reindex covers the **root row only**. Owned children with `embeddings` still\n warn at compile time β keep child writes on the plain routes, or enqueue\n from an authored action.\n\n### `notify` β device push after commit\n\n```ts\nafterCommit: {\n notify: {\n bookingChanged: {\n delivery: \"thisEvent\", // defineRealtimeDelivery β the audience\n title: \"Booking updated\",\n body: \"Reservation {reservationId} changed\",\n tag: \"res-{reservationId}\", // collapse key (templated)\n payload: { eventId: \"root.eventId\", reservationId: \"rootId\" },\n },\n },\n}\n```\n\nRequires `push: { provider: 'web-push' }` β declaring `notify` without the\nprovider is a compile error. The audience is a **delivery profile**, resolved\nwith the same fail-closed lookup and the **same disclosure gates** as\n`broadcast` (masked columns, `q.stamp` proven identity, child-id enumeration\nβ the gates are shared code, not a parallel set). `{key}` template\nplaceholders must be mapped `payload` keys; an unresolvable placeholder is a\ncompile error, and a null placeholder value at runtime skips the push\n(fail-closed β nobody gets a blank notification).\n\nFan-out: a scope-keyed delivery targets subscriptions tagged\n`scope:<room key>`; an `organizationId` + `userIdFrom` delivery targets that\nuser's devices; profile roles AND-compose as a `role:` tag filter. Delivery\nrides the `PUSH_FANOUT_QUEUE` after commit β at-least-once, best-effort,\nnever rolling back the changeset. A delivery that resolves to no audience\npushes to nobody, mirroring the ws broadcast lane exactly.\n\n> **Deferred out of v1 (still):** lifting `afterCommit` onto plain\n> tables/actions. The compiler still **warns** when an `owns` root/child\n> declares `realtime` **without** `afterCommit`, or when an owned **child**\n> declares `embeddings` (root embeddings are covered by `reindex`), so a\n> silent asymmetry can't be enabled unknowingly.\n\n## Atomicity β honest, per provider\n\nThe whole changeset runs inside `db.transaction()` when the provider supports\nit; `meta.transactional` reports the actual guarantee (same contract as\n[batch operations](/api/batch-operations)):\n\n| Provider | transactional | Behavior |\n|---|---|---|\n| postgres / supabase / neon (websocket / hyperdrive) / libsql / better-sqlite3 / bun-sqlite | `true` | One transaction; any op failure rolls back the root op and every child op |\n| cloudflare-d1, neon over http (the Cloudflare default) | `false` | Deterministic parent-first **fail-fast**: the first failure stops the changeset; ops already applied stay committed (a consistent prefix β each was independently authorized) |\n\n## Calling it from authored code\n\nThe engine is exported per root as `apply<Singular>Changeset` β the seam\nauthored actions delegate through when they still need residue logic\n(preconditions, server-side transforms, notifications) around the aggregate\nwrite:\n\n{/* doc-compile: skip β the fence imports `../projects.changeset`, a module the compiler only generates for a contract-v2 root that declares `owns`; the gate's harness config pins v1, so the import cannot resolve. `description` / `input` / `access` are elided to `// ...` on purpose β the point is the delegation seam. */}\n```ts title=\"quickback/features/projects/actions/importBoard.ts\"\n// Action files are compiled into the feature directory, next to the\n// generated module β the relative import resolves at runtime.\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applyProjectChangeset } from \"../projects.changeset\";\n\nexport default defineAction({\n // ...description, input, access...\n execute: async ({ db, ctx, input }) => {\n // precondition / transform residue β¦\n const result = await applyProjectChangeset(db, ctx, input.projectId, input.changes);\n // notify / respond β¦\n return result;\n },\n});\n```\n\n**There is no trusted mode.** The auth assertion, cross-tenant guard, and the\nroot's own pre-record access gate are the helper's first statements β an\nauthored action whose action-level access is looser than the root's crud\naccess still pays the root's declared authorization when it delegates. The\nHTTP handler is a thin wrapper over the same helper (parse + Problem-Details\nrendering only).\n\n## Standards mapping\n\n| Changeset concept | Grounded in |\n|---|---|\n| Media-type dispatch on PATCH | RFC 5789 (the media type selects patch semantics) |\n| `lid` correlation + op list | JMAP `/set` creation ids, JSON:API `lid` |\n| Root-revision `If-Match` | JMAP state tokens, RFC 9110 preconditions |\n| Pointer-carrying errors | RFC 9457 Problem Details + RFC 6901 JSON Pointer |\n| Nested relation ops | SCIM PATCH (typed sub-resources) |\n\n## What stays phase 2\n\nFull-document `replace` diff sugar (and its `key:` reconciliation field), the\n`application/json-patch+json` representation, cross-branch `$lid` references,\nnested `Prefer: return=representation`, and find-or-create roots by business\nkey (`conflictTarget`). `?include=<ownsRelation>` aggregate reads have\n**landed** β see [read β Aggregate Reads](/define/read#aggregate-reads)."
|
|
150
|
+
"content": "A **changeset** writes a parent row and its owned relations β junction\nmemberships, normalized phones/emails, line items β in **one request**,\nreplacing the hand-rolled multi-table action. You declare the one fact the\ncompiler was missing β which relations are **compositions** (owned by this\nroot) vs **references** (independent entities) β and the compiler generates\nthe whole write path.\n\nChangesets are a **contract v2** capability (`contract: { version: \"v2\" }`).\nDeclaring `owns` on a v1-pinned project is a compile error.\n\n## Declaring the boundary β `owns`\n\n{/* doc-compile: skip β two reasons. (1) Project-config prerequisite: `owns` is a contract-v2 capability (stated two paragraphs above) and needs `contract: { version: \"v2\" }`; the gate's harness config pins v1. (2) The fence is the `owns` boundary only β columns/firewall/guards/masking/read are elided, and it names three sibling tables (`tasks`, `people`, `taskChecklistItems`) it deliberately does not repeat. */}\n```ts title=\"quickback/features/projects/projects.ts\"\nexport default feature(\"projects\", {\n // ...columns, firewall, guards, masking, read...\n create: { access: { roles: [\"admin\", \"owner\"] } },\n update: { access: { roles: [\"admin\", \"owner\"] } },\n\n owns: {\n tasks: {\n table: \"tasks\", // camelCase table name β a defineTable in this project\n fk: \"projectId\", // FK on the CHILD pointing at this root's PK\n refs: { // client-supplied pointers at INDEPENDENT entities\n assigneeId: \"people\",\n reviewerId: \"people\", // nullable refs may be omitted or null\n },\n inherit: [\"organizationId\"], // parent columns copied onto every inserted child\n owns: { // grandchildren β structural nesting, depth-capped\n checklist: { table: \"taskChecklistItems\", fk: \"taskId\", inherit: [\"organizationId\"] },\n },\n },\n },\n});\n```\n\n| Key | Meaning |\n|---|---|\n| `table` | The owned child β **must** be a `defineTable`/`feature()` in the project. String literal, never an identifier. Auth tables can never be owned. |\n| `fk` | The spine: the child column pointing at this root. **Compiler-stamped** on inserts; a client-supplied value is rejected. |\n| `refs` | Columns pointing at independent entities. Client-supplied, **existence-checked inside the caller's tenant** (the referenced table's firewall is ANDed) β on inserts **and** patches. The referenced row is never written through. |\n| `inherit` | Tenant/denorm columns copied verbatim from the (firewall-verified) parent row onto every inserted child. Compiler-stamped; client values rejected. |\n| `owns` | Nested owned relations. Max 3 levels of nesting (the aggregate spans at most 4 tables). |\n\nA child's [`q.stamp`](/define/schema#qstamp--proven-principal-identity-columns) identity columns are a **fourth, disjoint** source, sitting alongside `fk`/`inherit`/`refs`. On a changeset **insert** the engine stamps them from the **caller's proven scope claim** (`ctx.scope.<kind>.<claim>`) β *not* from the parent row β but only when the caller is a scope-only principal; an org-admitted caller keeps their client value (org-firewall-bounded). The contrast is exact: `inherit` copies **tenant** columns from the firewall-verified *parent*, `q.stamp` copies **identity** from the proven *token*. A required claim absent on a scope principal fails the op with **403** β emitted *before* the ref-existence checks, so a claim-less caller cannot probe which rows exist. A `refs` key may not alias a `q.stamp` column (a column is compiler-stamped **or** a client ref, never both). On a changeset **patch** op the stamp column is **immutable** β a client value for it is rejected (400) like any systemManaged column, matching the plain update path. Because the stamp lives inside the changeset handler, a **keyed** (`Idempotency-Key`) replay neither re-writes nor re-stamps; a keyless retry re-writes and re-stamps.\n\n**Owning a relation is not a write grant.** Every changeset op is admitted by\nthe **child table's own crud declaration**: `insert` requires `create:` on the\nchild, `patch` requires `update:`, `delete` requires `delete:` (soft mode only\nin v1) β each with its own `access`. There is no per-relation access override:\naccess is declared exactly once, on the child.\n\n### `routes: false` β changeset admission without a raw route\n\nWidening a child's access for changeset use must not silently open its raw\nCRUD surface. The `create`, `update`, and `delete` op configs accept\n`routes: false` (`upsert`/`put` does not): the access stays declared (it is\nthe changeset admission gate) while the raw HTTP route β and its\nauto-promoted batch variant β is never mounted, documented, or counted in\nthe operations manifest.\n\n```ts title=\"quickback/features/projects/tasks.ts\"\nupdate: { access: { roles: [\"member\", \"admin\", \"owner\"] }, routes: false },\n```\n\n## The wire contract\n\nOne blessed path β **RFC 5789 media-type dispatch** on the routes you already\nhave. No subpath.\n\n- `PATCH /api/v2/<resource>/:id` with\n `Content-Type: application/vnd.quickback.changeset+json` β apply a changeset\n to an existing root. Plain `application/json` keeps the flat-column PATCH.\n- `POST /api/v2/<resource>` with the same media type β create the root and its\n children in one changeset.\n\n```jsonc\n// PATCH /api/v2/projects/prj_1 (Content-Type: application/vnd.quickback.changeset+json)\n{\n \"patch\": { \"name\": \"Renamed\" }, // sparse ROOT patch (optional)\n \"tasks\": {\n \"insert\": [\n {\n \"lid\": \"t1\", // client correlation id\n \"title\": \"Ship it\",\n \"assigneeId\": \"per_9\", // ref β tenant-checked\n \"checklist\": { \"insert\": [{ \"label\": \"QA pass\" }] } // grandchild, FKs onto t1's minted id\n }\n ],\n \"patch\": [{ \"id\": \"tsk_2\", \"state\": \"done\" }],\n \"delete\": [\"tsk_3\"]\n }\n}\n```\n\n```jsonc\n// Response\n{\n \"success\": true,\n \"root\": { \"id\": \"prj_1\", \"name\": \"Renamed\", /* masked through the root's masking */ },\n \"created\": { \"t1\": \"tsk_9aβ¦\", \"/tasks/insert/0/checklist/insert/0\": \"tci_44β¦\" },\n \"meta\": { \"ops\": 4, \"transactional\": false }\n}\n```\n\n- Inserts/patches apply parent-first (document order); deletes apply\n children-first.\n- `lid` correlates a minted id in `created`; entries without a `lid` key on\n their JSON Pointer. A nested insert's FK comes from its parent op's minted\n id β an unresolvable parent lid is a pointer-carrying **400**, never a\n silent re-parent onto the root.\n- `Prefer: return=minimal` omits `root` from the response. v1 representation\n is **root-row-only** (re-read through the root's masking) β nested aggregate\n reads are the phase-2 `?include=` reader; use [`defineView`\n includes](/define/read) today.\n\n### Headers\n\n| Header | Behavior |\n|---|---|\n| `If-Match` | Optimistic concurrency against the **root revision** β the root's `updatedAt` (or the injected `modifiedAt` audit column). Accepted value forms: `W/\"<revision>\"`, `\"<revision>\"`, or the bare revision value, where `<revision>` is the raw value of the revision column as returned in the root row. **Do not echo `GET /:id`'s `ETag` header into `If-Match`** β that ETag is the contract layer's body-hash ETag, not this revision, and will always **412**. Compared inside the transaction; mismatch β **412**. Every accepted changeset touches the revision. A root with no revision column answers `If-Match` with **428 PRECONDITION_UNSUPPORTED** β never silently ignored; the POST variant always answers 428 (no pre-existing revision to match). |\n\n`If-Match` is honored with the **identical comparator on the plain\n`application/json` write lanes** too: single-record `PATCH`, `PUT`, and\n`DELETE` compare the supplied revision against the fetched row (mismatch β\n**412**), and `PATCH`/`PUT` additionally pin the revision into the write's\n`WHERE` (compare-and-swap), so a concurrent writer between the fetch and the\nwrite surfaces as **412** on every provider β including the transaction-less\nD1 / Neon-HTTP lanes. A `PUT` with `If-Match` against a missing row is a\n**412** (RFC 9110: no current representation), never a silent create. Tables\nwith no revision column, and every **batch** endpoint (`If-Match` is a\nsingle-resource precondition), answer **428 PRECONDITION_UNSUPPORTED**. A\nsupplied precondition is **never silently ignored** anywhere.\n| `Idempotency-Key` | The standard write-retry key. Claims are principal-scoped β a replayed key from a different principal is a 422, never a cached-body leak. |\n| `Prefer` | `return=representation` (default) or `return=minimal`. |\n\n### Errors\n\nRFC 9457 `application/problem+json`. The failing op is identified by a JSON\nPointer in the `pointer` extension (`/tasks/insert/0/assigneeId`). On\n**non-transactional providers** the error also carries an `ops` extension\nlisting the outcomes of ops applied before the failure β the honest committed\nprefix. On **transactional providers** the rollback erased every applied op,\nso the error carries **no `ops` extension** (advertising rolled-back ids would\npoint clients at rows that no longer exist). **Outcome entries carry only\n`{ pointer, status, id? }` β never child field values** (v1 deliberately\nwithholds nested child representation, so errors cannot become an\nunmasked-child side channel).\n\n## The security model β \"owning a relation is not a backdoor\"\n\nThe **root op** runs the root table's full single-record gate stack, in order:\nauth β cross-tenant guard β the root's own `update` (PATCH) / `create` (POST)\naccess β **always, including child-only bodies; there is no child-only bypass\nlane** β firewall fetch (reveal β 403 / hide β 404, byte-consistent with the\nplain handler) β `requireSelf` β root body schema + ownership guard + guards.\nThe POST variant runs the root's full create pipeline (org validation, FK\nexistence checks, defaults/computed, ownership stamping).\n\nEvery **child op** then pays:\n\n1. **Admission** β declared relation, declared op kind (unknown keys are 400s).\n2. **The child's own access** β the pre-record role gate runs **before any row\n fetch** (no 404-vs-403 ID probing under the aggregate); `record:`\n predicates are evaluated against the fetched row on patch/delete and\n against the submitted input on insert.\n3. **systemManaged rejection** β client data carrying `fk`, any `inherit`\n column, or an ownership column is **rejected** with the op's pointer, never\n stripped or stamped-over. (The child's *plain-CRUD* guards are unaffected β\n a junction may keep its FK createable for its raw route; the same field in\n a changeset op is rejected because the changeset supplies it structurally.)\n4. **The child's column body schema** β q-authored children pay the same Zod\n types/enums/lengths backstop their plain POST/PATCH enforces (strict,\n guards-aware, with the compiler-stamped columns omitted). Drizzle-authored\n children have no Zod on their plain routes either, so none applies here β\n parity, not an omission.\n5. **The child's guards** β `createable`/`updatable` validation.\n6. **The child's firewall** β every patch/delete WHERE is\n `spine FK = parent id AND child firewall AND id`, same-feature or\n cross-feature alike. Inserts derive tenant columns only from the\n firewall-verified parent row.\n7. **Tenant-scoped `refs` checks** β each non-null ref must exist inside the\n referenced table's firewall, on **inserts and patches alike** (re-pointing\n a ref pays the same check; only columns present in the op's data are\n checked).\n8. **Server-minted child ids** β a client-supplied child primary key on an\n insert is rejected (like the plain POST's strict body schema), unless the\n project is configured for client-provided ids (`generateId: false`).\n\nChild `delete` ops stamp the **fixed `deletedAt`** audit column β exactly what\nthe plain DELETE route stamps (the audit wrapper then auto-stamps\n`deletedBy`). An `isNull` firewall arm on any other column (e.g.\n`archivedAt`) is a read-scoping predicate, never the soft-delete stamp.\n\n### Handler triggers fire β the changeset is a first-party write\n\nEvery root and owned-child op writes through the **same audit-wrapped `db`\nchokepoint** the plain CRUD routes and actions use β not a raw Drizzle handle.\nSo a child's declared [`handler:` triggers](/define/triggers#handler-triggers-handler)\nfire on the changeset exactly as they do on the child's own route: `beforeInsert`\n/ `beforeUpdate` / `beforeDelete` run at the write (a throw becomes the same\n`TRIGGER_REJECTED` and β on a transactional provider β rolls the whole aggregate\nback), and `afterInsert` / `afterUpdate` run once per affected row. Audit\nstamping (`createdBy` / `modifiedBy`) rides the same chokepoint. The only gap is\n`afterDelete`, which the soft-delete stamp can't see β identical to the plain\nDELETE route's own limitation. (`sql:` triggers fire on every path regardless,\nas always.) This is the parity the trigger docs promise: a generated\ncontract-v2 changeset is a compiler write surface, not one of the\nqueue/cron/raw-SQL bypasses that skip handler hooks.\n\nCompile-time, fail-closed (everything throws, nothing normalizes silently):\n\n- **Per-arm tenant coverage**: every column arm of the child's *resolved*\n firewall β including **every branch of an `any:` OR** β must be satisfiable\n by `fk`/`inherit`. Covering one arm of an OR is not coverage. This runs over\n the post-expansion firewall, so lanes spliced from\n [`authz.rules`](/define/authz-roles#centrally-defined-access-rules)\n gates and `{ tenant }` anchors are checked too.\n- Children firewalled through a **subquery arm** (`via:`, `{ permission }`,\n arrows) cannot be owned in v1 β even when the arm arrives through a gate\n splice.\n- `refs` keys must be **disjoint** from `{fk} βͺ inherit βͺ ownership columns` β\n a column is either compiler-stamped or a client ref, never both (blocks\n ownership-column injection through a ref).\n- **Relationship / FGA access arms are compile errors** on the changeset lane\n β on the root's `update`/`create` access and on every admitted child op's\n access. Those arms are decided by inline route code the changeset engine\n does not emit in v1; rather than silently widen (or silently 403) the gate,\n the compiler refuses. Use roles/record predicates, or keep the write in an\n authored action. (Function-form access is refused for the same reason.)\n- **Envelope-encrypted roots cannot ride the changeset in v1** β the response\n path does not run the decrypt-then-mask prepare helper, so the returned root\n would carry sealed ciphertext. The compiler refuses rather than degrade\n silently. (Sealed-mode columns are unaffected β plain routes return those\n as-is too.)\n- **Relation names `insert`, `patch`, `delete`, and `lid` are rejected** β\n the wire parser reserves those payload keys, so such a relation would be\n silently unreachable on the wire.\n- One aggregate root per table, acyclic graph, bounded depth, declared child\n ops only, soft-delete children only, contract v2 only.\n\n## `afterCommit` β emit a realtime signal after the changeset commits\n\nA changeset that must notify live views declares **`afterCommit`** on the\naggregate root β a declarative broadcast, **not** a hand-rolled\n`try { realtime.* } catch {}` tail. It fires **one aggregate-level CloudEvent**\nstrictly **after** the transaction commits, riding the existing\n[named-invalidation / Broadcaster egress](/platform/realtime/named-invalidations)\n(so it inherits the CloudEvents envelope + AsyncAPI description for free).\n\n{/* doc-compile: skip β project-config prerequisites this fence cannot carry: `owns` needs `contract: { version: \"v2\" }`, and the `broadcast` event `attendRealtime.mobileBundleChanged.travelUpdated` plus its `thisEvent` delivery profile must be declared in a realtime registry under `services/realtime/`. Columns/firewall/read/crud are elided to `// ...` and the owned child table is not repeated. */}\n```ts title=\"quickback/features/travel/lodging-reservations.ts\"\nexport default defineTable(lodgingReservations, {\n // ...firewall / read / crud ...\n owns: { occupants: { table: \"lodgingReservationGuests\", fk: \"reservationId\",\n inherit: [\"eventId\", \"organizationId\"] } },\n afterCommit: {\n broadcast: {\n travelChanged: {\n event: \"attendRealtime.mobileBundleChanged.travelUpdated\", // registry.event.variant\n delivery: \"thisEvent\", // MUST be in the event's `deliveries` allowlist\n payload: {\n eventId: \"root.eventId\", // a committed root column\n reservationId: \"rootId\", // the root pk\n occupantIds: \"affectedIds\", // ids of child rows touched this changeset\n },\n },\n },\n },\n});\n```\n\n- **One event per aggregate**, not one per touched child. The payload carries\n an **affected-ids / changed-paths** roll-up derived from the applied ops\n (`affectedIds` = child ids, `changedPaths` = JSON pointers) β **ids and\n pointers only, never child field values**.\n- **`delivery` is required and fail-closed.** The audience lives on a named\n [delivery profile](/platform/realtime/named-invalidations); it must appear in the\n referenced event's `deliveries` allowlist. There is **no default selection**,\n so an event permitting a narrow AND a wide room can never silently fan a\n changeset frame to the wider one.\n- **Payload sources:** `root.<col>` (a committed root column), `rootId`,\n `affectedIds`, `changedPaths`. Every payload key the variant declares must be\n mapped; unknown sources / undeclared keys are compile errors.\n- **Best-effort:** a broadcast failure never rolls back the committed changeset\n (`console.warn`, dispatched on `waitUntil`).\n- **Root-row frame:** `afterCommit: { realtime: true }` additionally emits the\n root row (postgres_changes-style) on the table's own `realtime` room. The row\n rides unmasked **with the table's `MASKING_CONFIG`** so the Broadcaster masks\n per-subscriber-role at fanout β the same discipline plain CRUD realtime uses.\n\n### Fail-closed disclosure gates\n\nBecause a broadcast payload is **not** masked at fanout (only the root-row frame\nis), afterCommit fails the build rather than leak:\n\n- A **masked `root.<col>`** may ride a broadcast only to a role-only delivery\n whose roles β the column's unmask roles (same app-role namespace). A\n **scope-keyed** delivery or an **empty unmask set** (`show: { or: 'owner' }`)\n **always** throws.\n- **`affectedIds` / `rootId` / `changedPaths`** carry firewalled row IDs\n (existence/enumeration). They may ride a scope-keyed delivery (bounded to one\n scope-instance room); a role-only / org-wide delivery throws unless you\n acknowledge with `disclosesChildIds: true`.\n\n### `q.scope` verified vs `q.stamp` proven β the \"stamp then emit\" rule\n\nWhen a changeset [stamps a proven identity](/define/schema#qstamp--proven-principal-identity-columns)\nand then emits it, the two features compose on one write path:\n\n| | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |\n|---|---|---|\n| Purpose | tenant isolation column | proven-principal **identity** column |\n| Firewall arm? | **yes** β it is the tenant WHERE | **never** |\n| Verified how? | firewall re-verifies on read/patch/delete | token provenance (un-spoofable) |\n| Phrase | \"**stamp AND verify**\" | \"stamp AND **prove**\" |\n| Safe to broadcast? | to the matching scope-keyed room | **only** to an audience β the stamping scope kind |\n\nA `q.stamp` identity column (e.g. `guestId`) sourced via `root.<col>` is\n**audience-gated like `affectedIds`** (05Γ06 integration): the delivery must be\nscope-keyed to the **same scope kind** that stamped it, else the build fails β\nunless you acknowledge with **`disclosesStampedIdentity: true`**. A stamp is\nun-spoofable, not un-*sensitive*: provenance is not audience clearance.\n\n### Idempotency β at-least-once\n\nafterCommit is **at-least-once**, exactly as idempotent as the write it rides.\nA retry carrying the **same `Idempotency-Key`** neither re-writes nor re-emits\n(the middleware returns the cached response before the handler runs). A\n**keyless** retry re-runs the whole handler β re-writes **and** re-emits. Callers\nthat need single-delivery must send an `Idempotency-Key`.\n\n### No-tx: \"row written β event fired\"\n\nOn a no-tx provider (D1 / neon-http), a mid-changeset failure **throws** before\nthe success path, so **no frames emit** for the partially-applied prefix β\n`meta.transactional: false` is the only guarantee signal. A **fully-successful**\nno-tx changeset **does** emit, still with `transactional: false`. Never assume\n\"row written β event fired\"; `meta.transactional` is the contract.\n\n### `reindex` β re-embed the committed root\n\n```ts\nafterCommit: {\n reindex: true, // requires the root's `embeddings` block\n}\n```\n\n`reindex: true` re-enqueues the **committed root row** for embedding\nregeneration on the same at-least-once `EMBEDDINGS_QUEUE` lane the plain and\nbatch routes use β enqueued only **after** the changeset commits, so a\nrolled-back changeset produces no orphan embedding jobs. Fail-closed rules:\n\n- The root **must** declare an `embeddings` block β `reindex: true` without\n one is a compile error (there is nothing to re-embed).\n- `embeddings.onInsert` / `onUpdate: false` gate create/update changesets\n exactly like the plain routes; a field-watch `onUpdate: [...]` array is\n treated as **always** (changeset ops are aggregate-level, not a field diff).\n- Reindex covers the **root row only**. Owned children with `embeddings` still\n warn at compile time β keep child writes on the plain routes, or enqueue\n from an authored action.\n\n### `notify` β device push after commit\n\n```ts\nafterCommit: {\n notify: {\n bookingChanged: {\n delivery: \"thisEvent\", // defineRealtimeDelivery β the audience\n title: \"Booking updated\",\n body: \"Reservation {reservationId} changed\",\n tag: \"res-{reservationId}\", // collapse key (templated)\n payload: { eventId: \"root.eventId\", reservationId: \"rootId\" },\n },\n },\n}\n```\n\nRequires `push: { provider: 'web-push' }` β declaring `notify` without the\nprovider is a compile error. The audience is a **delivery profile**, resolved\nwith the same fail-closed lookup and the **same disclosure gates** as\n`broadcast` (masked columns, `q.stamp` proven identity, child-id enumeration\nβ the gates are shared code, not a parallel set). `{key}` template\nplaceholders must be mapped `payload` keys; an unresolvable placeholder is a\ncompile error, and a null placeholder value at runtime skips the push\n(fail-closed β nobody gets a blank notification).\n\nFan-out: a scope-keyed delivery targets subscriptions tagged\n`scope:<room key>`; an `organizationId` + `userIdFrom` delivery targets that\nuser's devices; profile roles AND-compose as a `role:` tag filter. Delivery\nrides the `PUSH_FANOUT_QUEUE` after commit β at-least-once, best-effort,\nnever rolling back the changeset. A delivery that resolves to no audience\npushes to nobody, mirroring the ws broadcast lane exactly.\n\n> **Deferred out of v1 (still):** lifting `afterCommit` onto plain\n> tables/actions. The compiler still **warns** when an `owns` root/child\n> declares `realtime` **without** `afterCommit`, or when an owned **child**\n> declares `embeddings` (root embeddings are covered by `reindex`), so a\n> silent asymmetry can't be enabled unknowingly.\n\n## Atomicity β honest, per provider\n\nThe whole changeset runs inside `db.transaction()` when the provider supports\nit; `meta.transactional` reports the actual guarantee (same contract as\n[batch operations](/api/batch-operations)):\n\n| Provider | transactional | Behavior |\n|---|---|---|\n| postgres / supabase / neon (websocket / hyperdrive) / libsql / better-sqlite3 / bun-sqlite | `true` | One transaction; any op failure rolls back the root op and every child op |\n| cloudflare-d1, neon over http (the Cloudflare default) | `false` | Deterministic parent-first **fail-fast**: the first failure stops the changeset; ops already applied stay committed (a consistent prefix β each was independently authorized) |\n\n## Calling it from authored code\n\nThe engine is exported per root as `apply<Singular>Changeset` β the seam\nauthored actions delegate through when they still need residue logic\n(preconditions, server-side transforms, notifications) around the aggregate\nwrite:\n\n{/* doc-compile: skip β the fence imports `../projects.changeset`, a module the compiler only generates for a contract-v2 root that declares `owns`; the gate's harness config pins v1, so the import cannot resolve. `description` / `input` / `access` are elided to `// ...` on purpose β the point is the delegation seam. */}\n```ts title=\"quickback/features/projects/actions/importBoard.ts\"\n// Action files are compiled into the feature directory, next to the\n// generated module β the relative import resolves at runtime.\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applyProjectChangeset } from \"../projects.changeset\";\n\nexport default defineAction({\n // ...description, input, access...\n execute: async ({ db, ctx, input }) => {\n // precondition / transform residue β¦\n const result = await applyProjectChangeset(db, ctx, input.projectId, input.changes);\n // notify / respond β¦\n return result;\n },\n});\n```\n\n**There is no trusted mode.** The auth assertion, cross-tenant guard, and the\nroot's own pre-record access gate are the helper's first statements β an\nauthored action whose action-level access is looser than the root's crud\naccess still pays the root's declared authorization when it delegates. The\nHTTP handler is a thin wrapper over the same helper (parse + Problem-Details\nrendering only).\n\n## Standards mapping\n\n| Changeset concept | Grounded in |\n|---|---|\n| Media-type dispatch on PATCH | RFC 5789 (the media type selects patch semantics) |\n| `lid` correlation + op list | JMAP `/set` creation ids, JSON:API `lid` |\n| Root-revision `If-Match` | JMAP state tokens, RFC 9110 preconditions |\n| Pointer-carrying errors | RFC 9457 Problem Details + RFC 6901 JSON Pointer |\n| Nested relation ops | SCIM PATCH (typed sub-resources) |\n\n## What stays phase 2\n\nFull-document `replace` diff sugar (and its `key:` reconciliation field), the\n`application/json-patch+json` representation, cross-branch `$lid` references,\nnested `Prefer: return=representation`, and find-or-create roots by business\nkey (`conflictTarget`). `?include=<ownsRelation>` aggregate reads have\n**landed** β see [read β Aggregate Reads](/define/read#aggregate-reads)."
|
|
147
151
|
},
|
|
148
152
|
"define/diagnostics": {
|
|
149
153
|
"title": "Diagnostics",
|
|
@@ -163,11 +167,11 @@ export const DOCS = {
|
|
|
163
167
|
},
|
|
164
168
|
"define/fga": {
|
|
165
169
|
"title": "FGA - Relationship-Based Access (Zanzibar)",
|
|
166
|
-
"content": "The **FGA pillar** brings [OpenFGA](https://openfga.dev) / Google Zanzibar\n**Relationship-Based Access Control (ReBAC)** to Quickback. You declare an\nauthorization model in the OpenFGA modeling DSL, store relationship tuples in a\ncompiler-owned table, and resolve graph-shaped permission checks at request\ntime β no external authorization service, all inside your Worker.\n\nIt is **opt-in** and sits alongside the role-based [Access](/define/access)\npillar and the lightweight [`authz.relationships`](/define/access#relationship-roles)\njoin-roles. Use whichever fits:\n\n| Need | Use |\n| --- | --- |\n| \"Admins can edit, members can read\" | [Access](/define/access) roles |\n| \"The caller has a row linking them to this record\" | [`authz.relationships`](/define/access) |\n| \"A recruiter is automatically a viewer; a folder's viewer can view its docs; share publicly\" | **FGA** |\n\n## When you need a permission *graph*\n\nRoles and one-hop relationship joins can't express:\n\n- **Derived** permissions β an `editor` is automatically a `viewer`.\n- **Hierarchical** permissions β a document inherits viewers from its folder.\n- **Group** permissions β every member of `team:eng` is a viewer.\n- **Per-record grants** β assign one person to one record without a global role.\n- **Public sharing** β make one object viewable by everyone, with a share link.\n\nThese are exactly what Zanzibar's *userset rewrites* and *tuple-to-userset*\nrelations solve, and what the FGA pillar gives you.\n\n## The model\n\nDeclare it with `authz.fga.model` in `quickback.config.ts`, using the OpenFGA\nmodeling DSL verbatim (the same text the OpenFGA CLI and VS Code extension\nuse):\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n authz: {\n fga: {\n model: `\n model\n schema 1.1\n\n type user\n\n type organization\n relations\n define member: [user]\n\n type job\n relations\n define org: [organization]\n define hiring_manager: [user]\n define recruiter: [user] or hiring_manager\n define viewer: [user, user:*] or recruiter or member from org\n define can_manage: recruiter\n\n type application\n relations\n define job: [job]\n define viewer: viewer from job\n define editor: can_manage from job\n `,\n },\n },\n});\n```\n\nThe compiler **parses and validates** the model at compile time β every type,\nrelation, and `from` reference must resolve, or the compile fails loud.\n\n### DSL reference\n\n| Syntax | Meaning |\n| --- | --- |\n| `define viewer: [user]` | Direct assignment β a stored tuple grants `viewer`. |\n| `define viewer: [user, user:*]` | `user:*` = **type-bound public access** (everyone). |\n| `define viewer: [team#member]` | A **userset** β every `member` of a `team` is a `viewer`. |\n| `define viewer: [user] or editor` | **Union** β `editor`s are also `viewer`s (derived). |\n| `define viewer: editor and member` | **Intersection** β must be both. |\n| `define viewer: editor but not blocked` | **Exclusion**. |\n| `define viewer: viewer from parent` | **Tuple-to-userset** β inherit `viewer` from the `parent` object. |\n\n## Tuples\n\nA **relationship tuple** is `(user, relation, object)` β e.g.\n`(user:anne, recruiter, job:123)`. Tuples live in a compiler-owned,\n**organization-scoped** `fga_tuples` table that the compiler emits and migrates\nfor you (a Check never reads another tenant's tuples).\n\nWrite them three ways:\n\n```typescript\n// 1. In an action / handler via ctx.fga\nawait ctx.fga.write([\n { user: 'user:' + input.userId, relation: 'recruiter', object: 'job:' + record.id },\n]);\n\n// 2. Over the REST API (admin / write-role gated)\n// POST /api/v1/fga/v1/write\n// { \"writes\": [{ \"user\": \"user:anne\", \"relation\": \"recruiter\", \"object\": \"job:123\" }] }\n\n// 3. A public share link (see Public sharing below)\n```\n\n## Checking access\n\n### `ctx.fga` in handlers and actions\n\nEvery authenticated request gets an org-scoped `ctx.fga` client:\n\n```typescript\nconst allowed = await ctx.fga.check('user:' + ctx.userId, 'can_manage', 'job:' + jobId);\nconst myJobs = await ctx.fga.listObjects('user:' + ctx.userId, 'viewer', 'job'); // ['job:1', ...]\nconst tree = await ctx.fga.expand('job:123', 'viewer'); // debug the userset tree\n```\n\n### The `access: { fga }` arm β secure by construction\n\nEnforce a Check declaratively on a resource operation. The compiler fetches the\nrecord and emits an inline `ctx.fga.check(...)` gate:\n\n```typescript\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n },\n // Org owners/admins can edit any job, OR anyone with the FGA `can_manage`\n // relation on THIS specific job β without an org-wide admin role.\n update: {\n access: {\n or: [\n { roles: ['owner', 'admin'] },\n { fga: { relation: 'can_manage', object: 'job:{id}' } },\n ],\n },\n },\n});\n```\n\n`object` is a template β `{field}` tokens interpolate the fetched record's\ncolumns (`job:{id}` β `job:${record.id}`). On per-record operations\n(`GET /:id`, `update`, `delete`, and record-based actions) the compiler emits\nthe inline check. It is **fail-closed**: if the check can't run, access is\ndenied.\n\n### Filtering a collection by an FGA relation\n\nOn `read.access` (and named views) the `fga` arm does more than gate the\nper-record `GET /:id` β it **filters the collection `GET /`** too. The compiler\nresolves the caller's authorized object ids via the engine's `ListObjects` and\ninjects an `inArray(id, β¦)` into the list query *before* it runs, so the row\npage, `total`, and `hasMore` all stay correct (no fetch-then-drop that would\nbreak pagination):\n\n```typescript\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n },\n read: {\n // Collection GET / returns only jobs the caller is a `viewer` of;\n // GET /:id enforces the same relation per record.\n access: { fga: { relation: 'viewer', object: 'job:{id}' } },\n },\n});\n```\n\nThree access shapes are supported on a collection-filtering arm:\n\n| Access shape | Collection behavior |\n| --- | --- |\n| `{ fga }` | Always filter to the FGA-authorized ids. |\n| `{ or: [{ roles }, { fga }] }` | If the role arm passes, return all firewall-scoped rows (no FGA filter); otherwise filter to the authorized ids. |\n| `{ and: [{ roles }, { fga }] }` | If the role arm fails, return an empty page; otherwise filter to the authorized ids. |\n\nDeeper nesting (an `fga` arm under multi-level `and`/`or`, or multiple\nconflicting `fga` arms) is a **compile error** that points you at\n`POST /fga/v1/list-objects` to filter manually.\n\n**The cap.** The authorized id set is bounded by `authz.fga.listObjects.maxIds`\n(default **1000**). If a caller's authorized set exceeds the cap, the collection\nrequest fails with a hard **422 `FGA_LIST_TOO_LARGE`** whose hint points to\n`POST /fga/v1/list-objects` for paginated enumeration β never a silent partial\npage. Raise the cap or paginate via the API for collections that legitimately\nauthorize more than `maxIds` rows per caller.\n\n## Public sharing\n\nThe FGA pillar is also Quickback's public-sharing mechanism β two\ncomplementary tools.\n\n### Type-bound public access (`user:*`)\n\nA model relation that lists `user:*` (e.g. `define viewer: [user, user:*] β¦`)\ncan be granted to *everyone* by writing one tuple:\n\n```typescript\nawait ctx.fga.write([{ user: 'user:*', relation: 'viewer', object: 'job:' + id }]);\n```\n\nNow every Check for `viewer` on that object passes.\n\n### Share links\n\nEnable signed, unauthenticated share links:\n\n```typescript\nauthz: {\n fga: {\n model: `...`,\n sharing: {\n enabled: true,\n // The dedicated public route (always mounted): GET /share/v1/:token\n route: '/share',\n // Optional vanity base URL (also add it to your runtime `routes`).\n baseUrl: 'https://share.acme.dev',\n // Tokens never expire by default; set a TTL in seconds to expire them.\n ttlSeconds: 0,\n // Public projection: what a `job:<id>` share link may reveal, no login.\n resources: {\n job: { table: 'jobs', fields: ['id', 'title', 'department', 'status'] },\n },\n },\n },\n}\n```\n\n- **Mint** a link: `POST /api/v1/fga/v1/share` `{ \"object\": \"job:123\", \"relation\": \"viewer\" }`\n (write-role gated) β `{ token, url }`. Minting **writes the `(user:*, relation,\n object)` tuple** (making the object publicly viewable per the model) and then\n signs the link. If the relation has no `user:*` arm in the model, minting\n fails with a 400 rather than handing back a dead link.\n- **Resolve** a link: `GET /share/v1/:token` β **no authentication**. The route\n verifies the HMAC, then **checks the stored grant** (no contextual shortcut):\n the object must still have the granted `user:*` relation right now. Only then\n does it return the configured public projection. Nothing else leaks β the\n token is scoped to exactly that object and relation.\n- **Revoke** a link: delete the `(user:*, relation, object)` tuple (via\n `POST /fga/v1/write` `deletes`, or your own action). The next `GET` Check\n fails and the link stops returning content β revocation is real, not just\n token expiry.\n\n### The share URL: route, base URL, or both\n\nYou get **both** by default:\n\n- A **dedicated route** on the API origin β `β¦/share/v1/:token` β always\n available when sharing is enabled.\n- An optional **vanity base URL** (`share.<your-domain>`). Set\n `sharing.baseUrl` and add the host to your runtime `routes`:\n\n ```typescript\n providers: {\n runtime: defineRuntime('cloudflare', {\n routes: [\n { pattern: 'api.acme.dev', custom_domain: true },\n { pattern: 'share.acme.dev', custom_domain: true }, // share base URL\n ],\n }),\n },\n ```\n\n Minted links then use `https://share.acme.dev/v1/:token`; otherwise they use\n the API origin + the dedicated route.\n\n## REST API\n\nWhen `authz.fga` is set, the compiler mounts an OpenFGA-compatible surface at\n`/api/v1/fga/v1`, all tenant-scoped to `ctx.activeOrgId`:\n\n| Endpoint | Body | Returns |\n| --- | --- | --- |\n| `POST /check` | `{ user, relation, object, contextual_tuples? }` | `{ allowed }` |\n| `POST /list-objects` | `{ user, relation, type }` | `{ objects }` |\n| `POST /expand` | `{ relation, object }` | `{ tree }` |\n| `POST /read` | `{ object?, relation?, user? }` | `{ tuples }` |\n| `POST /write` | `{ writes?, deletes? }` | `{ ok }` (write-role) |\n| `POST /share` | `{ object, relation, ttlSeconds? }` | `{ token, url }` (write-role) |\n\n`writeRoles` (default `['admin']`) controls who can write tuples and mint share\nlinks. Pseudo-roles and `+` hierarchy suffixes are honored.\n\n## How it resolves\n\nThe embedded engine resolves a Check by walking the model: direct tuples,\ntype-bound public access (`user:*`), userset subjects (`team:eng#member`),\ncomputed usersets (union / intersection / exclusion), and tuple-to-userset\n(`viewer from parent`), plus request-scoped **contextual tuples**. It has cycle\ndetection and a configurable resolution-depth cap (`authz.fga.maxDepth`,\ndefault 25).\n\nThe engine **enforces the model's direct type restrictions at check time**: a\nstored tuple whose subject shape isn't allowed for the relation is inert. So a\n`user:*` tuple on a relation declared `[user]` (no wildcard) can never grant\naccess, even if it was written out-of-band β the model is the ceiling.\n\n## Limitations (v0.35)\n\n- `access: { fga }` covers **per-record** operations (`GET /:id`, `update`,\n `delete`, record-based actions) and **collection filtering** on\n `read.access` / views (see\n [Filtering a collection](#filtering-a-collection-by-an-fga-relation)). It is\n **not valid on `create`** (no record yet β rejected at compile) or\n **standalone actions** (use `ctx.fga.check` in `execute`).\n- **Collection filtering is bounded** by `authz.fga.listObjects.maxIds`\n (default 1000). A caller authorized for more rows than the cap gets a hard\n **422 `FGA_LIST_TOO_LARGE`**, not a partial page β paginate via\n `POST /fga/v1/list-objects` for those cases. Only the bare/`or`/`and`-with-roles\n shapes are filtered; deeper nesting is a compile error.\n- **Conditional tuples** (CEL conditions / ABAC) β the schema reserves the\n columns, but condition evaluation is not yet wired.\n- `ListObjects` enumerates candidate objects from tuples and Checks each β a\n reverse-index optimization is a planned follow-up."
|
|
170
|
+
"content": "The **FGA pillar** brings [OpenFGA](https://openfga.dev) / Google Zanzibar\n**Relationship-Based Access Control (ReBAC)** to Quickback. You declare an\nauthorization model in the OpenFGA modeling DSL, store relationship tuples in a\ncompiler-owned table, and resolve graph-shaped permission checks at request\ntime β no external authorization service, all inside your Worker.\n\nIt is **opt-in** and sits alongside the role-based [Access](/define/access)\npillar and the lightweight [`authz.relationships`](/define/relationships)\njoin-roles. Use whichever fits:\n\n| Need | Use |\n| --- | --- |\n| \"Admins can edit, members can read\" | [Access](/define/access) roles |\n| \"The caller has a row linking them to this record\" | [`authz.relationships`](/define/access) |\n| \"A recruiter is automatically a viewer; a folder's viewer can view its docs; share publicly\" | **FGA** |\n\n## When you need a permission *graph*\n\nRoles and one-hop relationship joins can't express:\n\n- **Derived** permissions β an `editor` is automatically a `viewer`.\n- **Hierarchical** permissions β a document inherits viewers from its folder.\n- **Group** permissions β every member of `team:eng` is a viewer.\n- **Per-record grants** β assign one person to one record without a global role.\n- **Public sharing** β make one object viewable by everyone, with a share link.\n\nThese are exactly what Zanzibar's *userset rewrites* and *tuple-to-userset*\nrelations solve, and what the FGA pillar gives you.\n\n## The model\n\nDeclare it with `authz.fga.model` in `quickback.config.ts`, using the OpenFGA\nmodeling DSL verbatim (the same text the OpenFGA CLI and VS Code extension\nuse):\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n authz: {\n fga: {\n model: `\n model\n schema 1.1\n\n type user\n\n type organization\n relations\n define member: [user]\n\n type job\n relations\n define org: [organization]\n define hiring_manager: [user]\n define recruiter: [user] or hiring_manager\n define viewer: [user, user:*] or recruiter or member from org\n define can_manage: recruiter\n\n type application\n relations\n define job: [job]\n define viewer: viewer from job\n define editor: can_manage from job\n `,\n },\n },\n});\n```\n\nThe compiler **parses and validates** the model at compile time β every type,\nrelation, and `from` reference must resolve, or the compile fails loud.\n\n### DSL reference\n\n| Syntax | Meaning |\n| --- | --- |\n| `define viewer: [user]` | Direct assignment β a stored tuple grants `viewer`. |\n| `define viewer: [user, user:*]` | `user:*` = **type-bound public access** (everyone). |\n| `define viewer: [team#member]` | A **userset** β every `member` of a `team` is a `viewer`. |\n| `define viewer: [user] or editor` | **Union** β `editor`s are also `viewer`s (derived). |\n| `define viewer: editor and member` | **Intersection** β must be both. |\n| `define viewer: editor but not blocked` | **Exclusion**. |\n| `define viewer: viewer from parent` | **Tuple-to-userset** β inherit `viewer` from the `parent` object. |\n\n## Tuples\n\nA **relationship tuple** is `(user, relation, object)` β e.g.\n`(user:anne, recruiter, job:123)`. Tuples live in a compiler-owned,\n**organization-scoped** `fga_tuples` table that the compiler emits and migrates\nfor you (a Check never reads another tenant's tuples).\n\nWrite them three ways:\n\n```typescript\n// 1. In an action / handler via ctx.fga\nawait ctx.fga.write([\n { user: 'user:' + input.userId, relation: 'recruiter', object: 'job:' + record.id },\n]);\n\n// 2. Over the REST API (admin / write-role gated)\n// POST /api/v1/fga/v1/write\n// { \"writes\": [{ \"user\": \"user:anne\", \"relation\": \"recruiter\", \"object\": \"job:123\" }] }\n\n// 3. A public share link (see Public sharing below)\n```\n\n## Checking access\n\n### `ctx.fga` in handlers and actions\n\nEvery authenticated request gets an org-scoped `ctx.fga` client:\n\n```typescript\nconst allowed = await ctx.fga.check('user:' + ctx.userId, 'can_manage', 'job:' + jobId);\nconst myJobs = await ctx.fga.listObjects('user:' + ctx.userId, 'viewer', 'job'); // ['job:1', ...]\nconst tree = await ctx.fga.expand('job:123', 'viewer'); // debug the userset tree\n```\n\n### The `access: { fga }` arm β secure by construction\n\nEnforce a Check declaratively on a resource operation. The compiler fetches the\nrecord and emits an inline `ctx.fga.check(...)` gate:\n\n```typescript\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n },\n // Org owners/admins can edit any job, OR anyone with the FGA `can_manage`\n // relation on THIS specific job β without an org-wide admin role.\n update: {\n access: {\n or: [\n { roles: ['owner', 'admin'] },\n { fga: { relation: 'can_manage', object: 'job:{id}' } },\n ],\n },\n },\n});\n```\n\n`object` is a template β `{field}` tokens interpolate the fetched record's\ncolumns (`job:{id}` β `job:${record.id}`). On per-record operations\n(`GET /:id`, `update`, `delete`, and record-based actions) the compiler emits\nthe inline check. It is **fail-closed**: if the check can't run, access is\ndenied.\n\n### Filtering a collection by an FGA relation\n\nOn `read.access` (and named views) the `fga` arm does more than gate the\nper-record `GET /:id` β it **filters the collection `GET /`** too. The compiler\nresolves the caller's authorized object ids via the engine's `ListObjects` and\ninjects an `inArray(id, β¦)` into the list query *before* it runs, so the row\npage, `total`, and `hasMore` all stay correct (no fetch-then-drop that would\nbreak pagination):\n\n```typescript\nexport default feature('jobs', {\n columns: {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n },\n read: {\n // Collection GET / returns only jobs the caller is a `viewer` of;\n // GET /:id enforces the same relation per record.\n access: { fga: { relation: 'viewer', object: 'job:{id}' } },\n },\n});\n```\n\nThree access shapes are supported on a collection-filtering arm:\n\n| Access shape | Collection behavior |\n| --- | --- |\n| `{ fga }` | Always filter to the FGA-authorized ids. |\n| `{ or: [{ roles }, { fga }] }` | If the role arm passes, return all firewall-scoped rows (no FGA filter); otherwise filter to the authorized ids. |\n| `{ and: [{ roles }, { fga }] }` | If the role arm fails, return an empty page; otherwise filter to the authorized ids. |\n\nDeeper nesting (an `fga` arm under multi-level `and`/`or`, or multiple\nconflicting `fga` arms) is a **compile error** that points you at\n`POST /fga/v1/list-objects` to filter manually.\n\n**The cap.** The authorized id set is bounded by `authz.fga.listObjects.maxIds`\n(default **1000**). If a caller's authorized set exceeds the cap, the collection\nrequest fails with a hard **422 `FGA_LIST_TOO_LARGE`** whose hint points to\n`POST /fga/v1/list-objects` for paginated enumeration β never a silent partial\npage. Raise the cap or paginate via the API for collections that legitimately\nauthorize more than `maxIds` rows per caller.\n\n## Public sharing\n\nThe FGA pillar is also Quickback's public-sharing mechanism β two\ncomplementary tools.\n\n### Type-bound public access (`user:*`)\n\nA model relation that lists `user:*` (e.g. `define viewer: [user, user:*] β¦`)\ncan be granted to *everyone* by writing one tuple:\n\n```typescript\nawait ctx.fga.write([{ user: 'user:*', relation: 'viewer', object: 'job:' + id }]);\n```\n\nNow every Check for `viewer` on that object passes.\n\n### Share links\n\nEnable signed, unauthenticated share links:\n\n```typescript\nauthz: {\n fga: {\n model: `...`,\n sharing: {\n enabled: true,\n // The dedicated public route (always mounted): GET /share/v1/:token\n route: '/share',\n // Optional vanity base URL (also add it to your runtime `routes`).\n baseUrl: 'https://share.acme.dev',\n // Tokens never expire by default; set a TTL in seconds to expire them.\n ttlSeconds: 0,\n // Public projection: what a `job:<id>` share link may reveal, no login.\n resources: {\n job: { table: 'jobs', fields: ['id', 'title', 'department', 'status'] },\n },\n },\n },\n}\n```\n\n- **Mint** a link: `POST /api/v1/fga/v1/share` `{ \"object\": \"job:123\", \"relation\": \"viewer\" }`\n (write-role gated) β `{ token, url }`. Minting **writes the `(user:*, relation,\n object)` tuple** (making the object publicly viewable per the model) and then\n signs the link. If the relation has no `user:*` arm in the model, minting\n fails with a 400 rather than handing back a dead link.\n- **Resolve** a link: `GET /share/v1/:token` β **no authentication**. The route\n verifies the HMAC, then **checks the stored grant** (no contextual shortcut):\n the object must still have the granted `user:*` relation right now. Only then\n does it return the configured public projection. Nothing else leaks β the\n token is scoped to exactly that object and relation.\n- **Revoke** a link: delete the `(user:*, relation, object)` tuple (via\n `POST /fga/v1/write` `deletes`, or your own action). The next `GET` Check\n fails and the link stops returning content β revocation is real, not just\n token expiry.\n\n### The share URL: route, base URL, or both\n\nYou get **both** by default:\n\n- A **dedicated route** on the API origin β `β¦/share/v1/:token` β always\n available when sharing is enabled.\n- An optional **vanity base URL** (`share.<your-domain>`). Set\n `sharing.baseUrl` and add the host to your runtime `routes`:\n\n ```typescript\n providers: {\n runtime: defineRuntime('cloudflare', {\n routes: [\n { pattern: 'api.acme.dev', custom_domain: true },\n { pattern: 'share.acme.dev', custom_domain: true }, // share base URL\n ],\n }),\n },\n ```\n\n Minted links then use `https://share.acme.dev/v1/:token`; otherwise they use\n the API origin + the dedicated route.\n\n## REST API\n\nWhen `authz.fga` is set, the compiler mounts an OpenFGA-compatible surface at\n`/api/v1/fga/v1`, all tenant-scoped to `ctx.activeOrgId`:\n\n| Endpoint | Body | Returns |\n| --- | --- | --- |\n| `POST /check` | `{ user, relation, object, contextual_tuples? }` | `{ allowed }` |\n| `POST /list-objects` | `{ user, relation, type }` | `{ objects }` |\n| `POST /expand` | `{ relation, object }` | `{ tree }` |\n| `POST /read` | `{ object?, relation?, user? }` | `{ tuples }` |\n| `POST /write` | `{ writes?, deletes? }` | `{ ok }` (write-role) |\n| `POST /share` | `{ object, relation, ttlSeconds? }` | `{ token, url }` (write-role) |\n\n`writeRoles` (default `['admin']`) controls who can write tuples and mint share\nlinks. Pseudo-roles and `+` hierarchy suffixes are honored.\n\n## How it resolves\n\nThe embedded engine resolves a Check by walking the model: direct tuples,\ntype-bound public access (`user:*`), userset subjects (`team:eng#member`),\ncomputed usersets (union / intersection / exclusion), and tuple-to-userset\n(`viewer from parent`), plus request-scoped **contextual tuples**. It has cycle\ndetection and a configurable resolution-depth cap (`authz.fga.maxDepth`,\ndefault 25).\n\nThe engine **enforces the model's direct type restrictions at check time**: a\nstored tuple whose subject shape isn't allowed for the relation is inert. So a\n`user:*` tuple on a relation declared `[user]` (no wildcard) can never grant\naccess, even if it was written out-of-band β the model is the ceiling.\n\n## Limitations (v0.35)\n\n- `access: { fga }` covers **per-record** operations (`GET /:id`, `update`,\n `delete`, record-based actions) and **collection filtering** on\n `read.access` / views (see\n [Filtering a collection](#filtering-a-collection-by-an-fga-relation)). It is\n **not valid on `create`** (no record yet β rejected at compile) or\n **standalone actions** (use `ctx.fga.check` in `execute`).\n- **Collection filtering is bounded** by `authz.fga.listObjects.maxIds`\n (default 1000). A caller authorized for more rows than the cap gets a hard\n **422 `FGA_LIST_TOO_LARGE`**, not a partial page β paginate via\n `POST /fga/v1/list-objects` for those cases. Only the bare/`or`/`and`-with-roles\n shapes are filtered; deeper nesting is a compile error.\n- **Conditional tuples** (CEL conditions / ABAC) β the schema reserves the\n columns, but condition evaluation is not yet wired.\n- `ListObjects` enumerates candidate objects from tuples and Checks each β a\n reverse-index optimization is a planned follow-up."
|
|
167
171
|
},
|
|
168
172
|
"define/firewall": {
|
|
169
173
|
"title": "Firewall - Data Isolation",
|
|
170
|
-
"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\nimport { feature, q } from '@quickback/compiler';\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 ...q.audit(),\n ...q.softDelete(),\n },\n // `email` is detected as sensitive and every detected column needs an\n // explicit decision β `false` records \"reviewed, not sensitive here\".\n masking: { email: false },\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 | Bound to |\n|---|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` | `ctx.activeOrgId` |\n| Owner | `ownerId` | `ctx.userId` |\n| Team | `teamId` | `ctx.activeTeamId` |\n\nOrganization detection accepts **six spellings** β American (`organizationId` / `orgId` / `organization` / `org`) and British (`organisationId` / `organisation`). The first one found in the schema source is used as the predicate field. Detection matches either the JS key (`organizationId`) or the SQL name (`organization_id`).\n\n### `ownerId` vs `userId`\n\n`ownerId` is auto-detected as the owner column: the compiler firewalls reads with `WHERE ownerId = ctx.userId` and auto-stamps the column on insert.\n\n`userId` is **not** auto-detected on feature tables. It is a Better Auth convention on Better Auth's own tables (`session`, `account`, `member`, `passkey`), and on a feature table it usually means *a user this row references* (member, contact, invitee) rather than *the row's owner*.\n\nWhat the compiler does when it sees `userId` on a feature table:\n\n| Situation | Result |\n|---|---|\n| `userId` is the only candidate column (no `organizationId` / `ownerId` / `teamId`) | **Compile error** β the table has no isolation column |\n| `userId` alongside a detected isolation column | **Warning** β `userId` is neither auto-stamped on insert nor auto-scoped on read |\n\nTwo escapes, both explicit:\n\n```typescript\n// 1. Rename the column to ownerId β it becomes the auto-detected owner scope.\n\n// 2. Or declare it, and keep the name:\nfirewall: { owner: { column: 'userId' } }\n// equivalently, in predicate-array form:\nfirewall: [{ field: 'userId', equals: 'ctx.userId' }]\n```\n\nAn explicit predicate on a custom-named column is honoured **on that table** via its own generated `buildFirewallConditions` helper; it does not enter the project-global owner scope rules, so other tables that happen to share the column name are unaffected.\n\nIf `userId` is genuinely informational, rename it to something that says so (`linkedUserId`, `assigneeId`, `inviteeId`) and the warning goes away.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string; optional?: boolean; nullable?: true } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string; optional?: boolean } // column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { field?: string; permission: string } // named authz.permissions reference (v0.35+)\n | { all: FirewallPredicate[] } // AND group (v0.35+)\n | { any: FirewallPredicate[] } // OR group (v0.35+)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nThe top-level array is AND'd together. `firewallErrorMode` lives at the resource top level β it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Boolean groups: `all` / `any` (v0.35+)\n\nA flat array can only express AND. To grant access through **either** of two independent paths β \"an org member **OR** an event attendee\" β nest an `any` group. The top-level array stays sugar for `all`, so every existing firewall is byte-identical.\n\n```typescript\nfirewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventId', equals: 'ctx.scope.event' }, // attendee grant (token-verified)\n ],\n}\n```\n\nNull-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):\n\n- A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / \"match every row\" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\\`1 = 0\\`` (the empty-guard) β never a full-table read. In an `all` group an absent required scope **denies** the group.\n- Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice β `ctx.activeTeamId` is implicitly optional).\n- **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd β never relaxed.\n\n`nullable: true` is a separate database-schema opt-in, supported only on an\nowner predicate whose source is exactly `ctx.userId`. It allows the persisted\nowner column to be NULL; NULL rows still do not match the owner arm because SQL\nequality never matches NULL. It does not make the request claim optional.\n\n```typescript\n// (org OR event) AND owner AND not-deleted\nfirewall: {\n all: [\n { any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] },\n { field: 'ownerId', equals: 'ctx.userId' },\n ],\n}\n```\n\nThe `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shuttle drivers, vendors) reach event-scoped rows without org membership β see [Scopes & capability grants](/define/scopes).\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization β \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" β declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate. These relationships (and the named roles/permissions built on them) are defined once, centrally β see [Centrally defined access rules](/define/access#centrally-defined-access-rules).\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](/define/access#authz-relationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Named permissions (`{ permission }`)\n\nA `via:` arm references **one** relationship. When the same grant rule β\n\"organizer **or** confirmed attendee\" β recurs across several resources,\nname it **once** under `authz.permissions` and reference it from any\nfirewall with a `{ permission }` arm. See [Permissions](/define/permissions)\nfor the full DSL.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: { organizerOf: { /* β¦ */ }, attendeeOf: { /* β¦ */ } },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler lowers `{ permission }` to the same `all` / `any` relationship\nsubqueries the expression names β `anyOf` becomes an OR of subqueries,\n`allOf` an AND. `field` is the resource-side column those subqueries\nconstrain (the same column you'd put on a `via:` arm).\n\nA permission referenced from a firewall can also resolve an\n[**arrow**](/define/arrows) β an `{ arrowRef, permission }`\nleaf that traverses a foreign key to inherit authority from a parent object\n(\"org admins of the event's org can see its announcements\", \"anyone who\nadministers an ancestor folder can read this one\"). An arrow leaf lowers to\nan FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE\n(self-FK hierarchy), tenant-constrained at every row.\n\n**M1 limit β firewall arms must be SQL-pushable.** A firewall runs as a\nWHERE clause, so a permission referenced from one may only resolve to\nrelationship subqueries. A permission whose expression contains a\n**claim-site leaf** (`{ role }`, `{ scopeRole }`, `{ pseudoRole }`) or a\n`not` is rejected at compile time when referenced from a firewall β those\nshapes are valid in the DSL but reserved for future claim/runtime\nenforcement sites. Use a role gate on `read.access` / `crud.*.access` for\nmembership checks.\n\nThe compile-time analyzer additionally flags a referenced permission that can\nnever be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost\nof each permission β see [Diagnostics](/define/diagnostics).\n\n## Named tenant anchors (`{ tenant }`)\n\nThe tenant predicate `{ field: 'organizationId', equals: 'ctx.activeOrgId' }` tends to be repeated on every table. Declare it **once** as a named anchor and reference it by name:\n\n```typescript\n// quickback.config.ts\nauthz: {\n tenants: {\n org: { column: 'organizationId', equals: 'ctx.activeOrgId' },\n },\n}\n\n// any firewall β top level or inside all/any groups:\nfirewall: [\n { tenant: 'org' }, // β { field: 'organizationId', equals: 'ctx.activeOrgId' }\n { field: 'deletedAt', isNull: true },\n]\n\n// per-site COLUMN override (the claim side is never overridable):\nfirewall: [{ field: 'orgId', tenant: 'org' }]\n```\n\nThe anchor's `equals` must be a **verified ctx claim**: `ctx.activeOrgId` | `ctx.userId` | `ctx.scope.<kind>` | `ctx.scope.<kind>.<subKey>`. `ctx.activeTeamId` (drop-when-absent semantics stay a per-resource decision) and legacy aliases are rejected at declaration time β an anchor can never bind a request-derived value. A `{ tenant }` reference carrying its own `equals` is a compile error (one source of truth); an unknown anchor name is a compile error listing the declared anchors.\n\nExpansion happens at compile time, before rendering β the emitted SQL is byte-identical to writing the predicate inline. Auth-DB read views accept the same anchors as a string: [`tenant: 'org'`](/platform/realtime/live-views#auth-db-includes-source-auth) β with one extra constraint: an anchor referenced from an auth-view include must bind a single-segment session claim (`ctx.<claim>`); scope-principal claims (`ctx.scope.*`) are firewall-lane bindings and are rejected there.\n\n## Named gate references (`{ rule }`)\n\nA [gate](/define/access#named-gates-authzrules) that declares `firewall` lanes can be stamped onto a resource by name:\n\n```typescript\n// quickback.config.ts\nauthz: {\n rules: {\n eventRow: {\n who: { roles: ['owner', 'admin', 'member'] },\n firewall: [{ any: [\n { tenant: 'org' }, // org staff\n { field: 'eventId', equals: 'ctx.scope.event' }, // signed scope claim\n ] }],\n },\n },\n}\n\n// the resource:\nfirewall: [{ rule: 'eventRow' }]\n// composes with the resource's own lanes (top-level AND):\nfirewall: [{ rule: 'eventRow' }, { field: 'kind', equals: 'ctx.scope.event.kind' }]\n```\n\nSemantics β **AND-compose, top-level only, a reference can only narrow**:\n\n- The gate's lanes splice into the resource's **top-level AND array** in place. They never replace the resource's own lanes, and composition can only *narrow* the row set.\n- `{ rule }` is **not** valid inside an `{ all }` / `{ any }` group β a gate's firewall is one-or-more AND lanes, and splicing a multi-lane gate into an `any` group would OR-flatten it, admitting rows in **other tenants** that merely match one lane. This is a type error at authoring time and a compile error at coerce time.\n- A gate's firewall may not contain `{ exception: true }` (a named bundle can never smuggle a firewall opt-out) or another `{ rule }` (gates don't nest β expansion is single-step, so cycles are impossible by construction).\n- A gate with **no** `firewall` arm referenced from `firewall:` is a compile error β a who/record-only gate would silently contribute zero row lanes while the `record:` filter only ever applies at access sites.\n\nThe splice expands before validation and rendering, so the emitted `buildFirewallConditions` helper is byte-identical to writing the lanes inline β same groups, same absent-claim `1 = 0` guards, same `via:` subqueries.\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| `ctx.scope.<kind>` / `ctx.scope.<kind>.<subKey>` | A verified scope-principal claim (see [Scopes](/define/scopes)) |\n| `ctx.<claim>.<subKey>` | A [feature-area](/define/areas) context anchor β a row the area/relationship middleware loaded from a proven route param and exposed on `ctx` (e.g. `ctx.event.id`, `ctx.event.organizationId`). Present only on the area-claimed route; renders null-safe (deny-when-absent) inside `all`/`any` groups |\n\nThese values are populated by the auth middleware (or, for scope/area anchors, the area middleware) from the request. 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 / changeset-root insert / upsert** from that context source β a raw-Drizzle selected-event fence like `{ field: 'eventId', equals: 'ctx.event.id' }` stamps `eventId` from `ctx.event.id` the same way `q.scope('organization')` stamps `organizationId`.\n\n**Only conjunctive arms auto-populate.** A `ctx.*`-bound column is auto-populated only when its arm is **conjunctive** β reachable through the top-level array or a nested `all:` group, so it holds for every admitted row. A column bound *only* through an `any:` branch is disjunctive and lane-dependent (e.g. an attendee's own `eventPersonId`, which must come from a **proven** scope claim, not the org lane), so the compiler does **not** guess a create value for it. Give such a column its own population source β declare it with [`q.scope()` / `q.stamp()`](/define/schema#qstamp--proven-principal-identity-columns) (a proven-identity column force-stamps from the scope claim), let it inherit through a changeset `inherit`/`fk`, or write it in an authored action. A `NOT NULL` disjunctive-only column with none of these has no create path and will hit the database `NOT NULL` constraint on insert.\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| `ownerId` | `{ field: 'ownerId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (present whenever the resource soft-deletes) | `{ field: 'deletedAt', isNull: true }` β appended automatically whenever the table carries the column, regardless of which firewall shape you wrote |\n| `userId` | **Nothing.** Not an auto-detected owner column β see [`ownerId` vs `userId`](#ownerid-vs-userid) |\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\"). If the only candidate is `userId`, the error says so specifically.\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 columns.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy` are on every table (declared with `...q.audit()`), and `deletedAt` / `deletedBy` are on every table whose resource soft-deletes (declared with `...q.softDelete()`). Disable the whole mechanism globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column β which it does unless both `crud.delete.mode` and `crud.batchDelete.mode` are `'hard'` β the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out on an exception resource, switch the resource to hard deletes or set `compiler.features.auditFields: false` globally.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` β no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from appmanager.** `userRole === 'appmanager'` callers still go through the firewall normally β only `userRole === 'sysadmin'` triggers the bypass. Appmanager is the platform control-plane tier, expressed with plain `userRole` checks; sysadmin is the opt-in cross-tenant DB-admin tier. See [CMS Configuration](/configure#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\n// features/records/records.ts\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const records = q.table('records', {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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](/define/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\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const templateLibrary = q.table('templateLibrary', {\n id: q.id(),\n title: q.text().required(),\n body: q.text().required(),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const customTemplates = q.table('customTemplates', {\n id: q.id(),\n title: q.text().required(),\n body: q.text().required(),\n ownerId: q.text().required(),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n isPublic: q.bool().default(false).required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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 |"
|
|
174
|
+
"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\nimport { feature, q } from '@quickback/compiler';\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 ...q.audit(),\n ...q.softDelete(),\n },\n // `email` is detected as sensitive and every detected column needs an\n // explicit decision β `false` records \"reviewed, not sensitive here\".\n masking: { email: false },\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 | Bound to |\n|---|---|---|\n| Organization | `organizationId`, `organisationId`, `orgId`, `organization`, `organisation`, `org` | `ctx.activeOrgId` |\n| Owner | `ownerId` | `ctx.userId` |\n| Team | `teamId` | `ctx.activeTeamId` |\n\nOrganization detection accepts **six spellings** β American (`organizationId` / `orgId` / `organization` / `org`) and British (`organisationId` / `organisation`). The first one found in the schema source is used as the predicate field. Detection matches either the JS key (`organizationId`) or the SQL name (`organization_id`).\n\n### `ownerId` vs `userId`\n\n`ownerId` is auto-detected as the owner column: the compiler firewalls reads with `WHERE ownerId = ctx.userId` and auto-stamps the column on insert.\n\n`userId` is **not** auto-detected on feature tables. It is a Better Auth convention on Better Auth's own tables (`session`, `account`, `member`, `passkey`), and on a feature table it usually means *a user this row references* (member, contact, invitee) rather than *the row's owner*.\n\nWhat the compiler does when it sees `userId` on a feature table:\n\n| Situation | Result |\n|---|---|\n| `userId` is the only candidate column (no `organizationId` / `ownerId` / `teamId`) | **Compile error** β the table has no isolation column |\n| `userId` alongside a detected isolation column | **Warning** β `userId` is neither auto-stamped on insert nor auto-scoped on read |\n\nTwo escapes, both explicit:\n\n```typescript\n// 1. Rename the column to ownerId β it becomes the auto-detected owner scope.\n\n// 2. Or declare it, and keep the name:\nfirewall: { owner: { column: 'userId' } }\n// equivalently, in predicate-array form:\nfirewall: [{ field: 'userId', equals: 'ctx.userId' }]\n```\n\nAn explicit predicate on a custom-named column is honoured **on that table** via its own generated `buildFirewallConditions` helper; it does not enter the project-global owner scope rules, so other tables that happen to share the column name are unaffected.\n\nIf `userId` is genuinely informational, rename it to something that says so (`linkedUserId`, `assigneeId`, `inviteeId`) and the warning goes away.\n\n## Predicate Shape\n\n```typescript\ntype FirewallPredicate =\n | { field: string; equals: string; optional?: boolean; nullable?: true } // column = ctx.* (or literal)\n | { field: string; isNull: true } // column IS NULL\n | { field: string; in: string[] | string; optional?: boolean } // column IN (...)\n | { field: string; via: string } // column IN (relationship subquery)\n | { field?: string; permission: string } // named authz.permissions reference (v0.35+)\n | { all: FirewallPredicate[] } // AND group (v0.35+)\n | { any: FirewallPredicate[] } // OR group (v0.35+)\n | { exception: true }; // opt out of tenant scoping\n\ntype FirewallConfig = ReadonlyArray<FirewallPredicate>;\n\n// Resource top-level (sibling to `firewall:`)\nfirewallErrorMode?: 'reveal' | 'hide';\n```\n\nThe top-level array is AND'd together. `firewallErrorMode` lives at the resource top level β it's a presentation-layer choice (403 vs 404), not a query-shape one.\n\n## Boolean groups: `all` / `any` (v0.35+)\n\nA flat array can only express AND. To grant access through **either** of two independent paths β \"an org member **OR** an event attendee\" β nest an `any` group. The top-level array stays sugar for `all`, so every existing firewall is byte-identical.\n\n```typescript\nfirewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' }, // org-member grant\n { field: 'eventId', equals: 'ctx.scope.event' }, // attendee grant (token-verified)\n ],\n}\n```\n\nNull-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):\n\n- A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / \"match every row\" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\\`1 = 0\\`` (the empty-guard) β never a full-table read. In an `all` group an absent required scope **denies** the group.\n- Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice β `ctx.activeTeamId` is implicitly optional).\n- **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd β never relaxed.\n\n`nullable: true` is a separate database-schema opt-in, supported only on an\nowner predicate whose source is exactly `ctx.userId`. It allows the persisted\nowner column to be NULL; NULL rows still do not match the owner arm because SQL\nequality never matches NULL. It does not make the request claim optional.\n\n```typescript\n// (org OR event) AND owner AND not-deleted\nfirewall: {\n all: [\n { any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', equals: 'ctx.scope.event' },\n ] },\n { field: 'ownerId', equals: 'ctx.userId' },\n ],\n}\n```\n\nThe `ctx.scope.*` arms are how **relationship-derived scopes** (attendees, shuttle drivers, vendors) reach event-scoped rows without org membership β see [Scopes & capability grants](/define/scopes).\n\n## Relationship-based scoping (`via:`)\n\nFor relationship authorization β \"this user can see rows X if they have a confirmed `event_guests` row pointing at X\" β declare the relationship under `authz.relationships` in `quickback.config.ts`, then reference it from `firewall:` with a `via:` predicate. These relationships (and the named roles/permissions built on them) are defined once, centrally β see [Centrally defined access rules](/define/authz-roles#centrally-defined-access-rules).\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](/define/relationships#authzrelationships) for the full `authz.relationships` shape and role-binding patterns.\n\n## Named permissions (`{ permission }`)\n\nA `via:` arm references **one** relationship. When the same grant rule β\n\"organizer **or** confirmed attendee\" β recurs across several resources,\nname it **once** under `authz.permissions` and reference it from any\nfirewall with a `{ permission }` arm. See [Permissions](/define/permissions)\nfor the full DSL.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: { organizerOf: { /* β¦ */ }, attendeeOf: { /* β¦ */ } },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n },\n}\n\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler lowers `{ permission }` to the same `all` / `any` relationship\nsubqueries the expression names β `anyOf` becomes an OR of subqueries,\n`allOf` an AND. `field` is the resource-side column those subqueries\nconstrain (the same column you'd put on a `via:` arm).\n\nA permission referenced from a firewall can also resolve an\n[**arrow**](/define/arrows) β an `{ arrowRef, permission }`\nleaf that traverses a foreign key to inherit authority from a parent object\n(\"org admins of the event's org can see its announcements\", \"anyone who\nadministers an ancestor folder can read this one\"). An arrow leaf lowers to\nan FK-hop subquery (non-recursive) or a bounded `WITH RECURSIVE` CTE\n(self-FK hierarchy), tenant-constrained at every row.\n\n**M1 limit β firewall arms must be SQL-pushable.** A firewall runs as a\nWHERE clause, so a permission referenced from one may only resolve to\nrelationship subqueries. A permission whose expression contains a\n**claim-site leaf** (`{ role }`, `{ scopeRole }`, `{ pseudoRole }`) or a\n`not` is rejected at compile time when referenced from a firewall β those\nshapes are valid in the DSL but reserved for future claim/runtime\nenforcement sites. Use a role gate on `read.access` / `crud.*.access` for\nmembership checks.\n\nThe compile-time analyzer additionally flags a referenced permission that can\nnever be satisfied, an arm shadowed by a broader one, and the SQL / CTE cost\nof each permission β see [Diagnostics](/define/diagnostics).\n\n## Named tenant anchors (`{ tenant }`)\n\nThe tenant predicate `{ field: 'organizationId', equals: 'ctx.activeOrgId' }` tends to be repeated on every table. Declare it **once** as a named anchor and reference it by name:\n\n```typescript\n// quickback.config.ts\nauthz: {\n tenants: {\n org: { column: 'organizationId', equals: 'ctx.activeOrgId' },\n },\n}\n\n// any firewall β top level or inside all/any groups:\nfirewall: [\n { tenant: 'org' }, // β { field: 'organizationId', equals: 'ctx.activeOrgId' }\n { field: 'deletedAt', isNull: true },\n]\n\n// per-site COLUMN override (the claim side is never overridable):\nfirewall: [{ field: 'orgId', tenant: 'org' }]\n```\n\nThe anchor's `equals` must be a **verified ctx claim**: `ctx.activeOrgId` | `ctx.userId` | `ctx.scope.<kind>` | `ctx.scope.<kind>.<subKey>`. `ctx.activeTeamId` (drop-when-absent semantics stay a per-resource decision) and legacy aliases are rejected at declaration time β an anchor can never bind a request-derived value. A `{ tenant }` reference carrying its own `equals` is a compile error (one source of truth); an unknown anchor name is a compile error listing the declared anchors.\n\nExpansion happens at compile time, before rendering β the emitted SQL is byte-identical to writing the predicate inline. Auth-DB read views accept the same anchors as a string: [`tenant: 'org'`](/platform/realtime/live-views#auth-db-includes-source-auth) β with one extra constraint: an anchor referenced from an auth-view include must bind a single-segment session claim (`ctx.<claim>`); scope-principal claims (`ctx.scope.*`) are firewall-lane bindings and are rejected there.\n\n## Named gate references (`{ rule }`)\n\nA [gate](/define/authz-roles#named-gates-authzrules) that declares `firewall` lanes can be stamped onto a resource by name:\n\n```typescript\n// quickback.config.ts\nauthz: {\n rules: {\n eventRow: {\n who: { roles: ['owner', 'admin', 'member'] },\n firewall: [{ any: [\n { tenant: 'org' }, // org staff\n { field: 'eventId', equals: 'ctx.scope.event' }, // signed scope claim\n ] }],\n },\n },\n}\n\n// the resource:\nfirewall: [{ rule: 'eventRow' }]\n// composes with the resource's own lanes (top-level AND):\nfirewall: [{ rule: 'eventRow' }, { field: 'kind', equals: 'ctx.scope.event.kind' }]\n```\n\nSemantics β **AND-compose, top-level only, a reference can only narrow**:\n\n- The gate's lanes splice into the resource's **top-level AND array** in place. They never replace the resource's own lanes, and composition can only *narrow* the row set.\n- `{ rule }` is **not** valid inside an `{ all }` / `{ any }` group β a gate's firewall is one-or-more AND lanes, and splicing a multi-lane gate into an `any` group would OR-flatten it, admitting rows in **other tenants** that merely match one lane. This is a type error at authoring time and a compile error at coerce time.\n- A gate's firewall may not contain `{ exception: true }` (a named bundle can never smuggle a firewall opt-out) or another `{ rule }` (gates don't nest β expansion is single-step, so cycles are impossible by construction).\n- A gate with **no** `firewall` arm referenced from `firewall:` is a compile error β a who/record-only gate would silently contribute zero row lanes while the `record:` filter only ever applies at access sites.\n\nThe splice expands before validation and rendering, so the emitted `buildFirewallConditions` helper is byte-identical to writing the lanes inline β same groups, same absent-claim `1 = 0` guards, same `via:` subqueries.\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| `ctx.scope.<kind>` / `ctx.scope.<kind>.<subKey>` | A verified scope-principal claim (see [Scopes](/define/scopes)) |\n| `ctx.<claim>.<subKey>` | A [feature-area](/define/areas) context anchor β a row the area/relationship middleware loaded from a proven route param and exposed on `ctx` (e.g. `ctx.event.id`, `ctx.event.organizationId`). Present only on the area-claimed route; renders null-safe (deny-when-absent) inside `all`/`any` groups |\n\nThese values are populated by the auth middleware (or, for scope/area anchors, the area middleware) from the request. 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 / changeset-root insert / upsert** from that context source β a raw-Drizzle selected-event fence like `{ field: 'eventId', equals: 'ctx.event.id' }` stamps `eventId` from `ctx.event.id` the same way `q.scope('organization')` stamps `organizationId`.\n\n**Only conjunctive arms auto-populate.** A `ctx.*`-bound column is auto-populated only when its arm is **conjunctive** β reachable through the top-level array or a nested `all:` group, so it holds for every admitted row. A column bound *only* through an `any:` branch is disjunctive and lane-dependent (e.g. an attendee's own `eventPersonId`, which must come from a **proven** scope claim, not the org lane), so the compiler does **not** guess a create value for it. Give such a column its own population source β declare it with [`q.scope()` / `q.stamp()`](/define/schema#qstamp--proven-principal-identity-columns) (a proven-identity column force-stamps from the scope claim), let it inherit through a changeset `inherit`/`fk`, or write it in an authored action. A `NOT NULL` disjunctive-only column with none of these has no create path and will hit the database `NOT NULL` constraint on insert.\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| `ownerId` | `{ field: 'ownerId', equals: 'ctx.userId' }` |\n| `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |\n| `deletedAt` (present whenever the resource soft-deletes) | `{ field: 'deletedAt', isNull: true }` β appended automatically whenever the table carries the column, regardless of which firewall shape you wrote |\n| `userId` | **Nothing.** Not an auto-detected owner column β see [`ownerId` vs `userId`](#ownerid-vs-userid) |\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\"). If the only candidate is `userId`, the error says so specifically.\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 columns.** `createdAt`, `modifiedAt`, `createdBy`, `modifiedBy` are on every table (declared with `...q.audit()`), and `deletedAt` / `deletedBy` are on every table whose resource soft-deletes (declared with `...q.softDelete()`). Disable the whole mechanism globally with `compiler.features.auditFields: false`.\n- **Soft-delete filtering.** If the table has a `deletedAt` column β which it does unless both `crud.delete.mode` and `crud.batchDelete.mode` are `'hard'` β the firewall still emits `isNull(<table>.deletedAt)` so soft-deleted records stay hidden. To opt out on an exception resource, switch the resource to hard deletes or set `compiler.features.auditFields: false` globally.\n\nSo `firewall: [{ exception: true }]` on the default configuration returns `isNull(<table>.deletedAt)` from `buildFirewallConditions()` β no tenant filter, soft-delete filter still applied.\n\n## Sysadmin Escape Hatch\n\nWhen `cms: { sysadmin: true }` is set on the project (introduced in v0.15.0), every `buildFirewallConditions()` emits a runtime branch that drops tenant scopes for `ctx.userRole === 'sysadmin'` callers while keeping the soft-delete predicate:\n\n```typescript\n// Generated for an org-scoped table when cms.sysadmin: true\nexport function buildFirewallConditions(ctx: AppContext): SQL | undefined {\n if (ctx.userRole === 'sysadmin') {\n return isNull(invoices.deletedAt); // tenant predicate dropped, soft-delete kept\n }\n return and(\n eq(invoices.organizationId, ctx.activeOrgId!),\n isNull(invoices.deletedAt),\n );\n}\n```\n\nThe escape branch is **only** emitted when:\n\n- `cms.sysadmin: true` is set on the project config\n- The table has at least one tenant-scope predicate (org / owner / team / `via:` relationship). Tables with no tenant scopes already return what a sysadmin would see, so the runtime check would be dead code.\n- The firewall does not declare `{ exception: true }` (no tenant scopes to drop).\n\n**Sysadmin is distinct from appmanager.** `userRole === 'appmanager'` callers still go through the firewall normally β only `userRole === 'sysadmin'` triggers the bypass. Appmanager is the platform control-plane tier, expressed with plain `userRole` checks; sysadmin is the opt-in cross-tenant DB-admin tier. See [CMS Configuration](/configure#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\n// features/records/records.ts\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const records = q.table('records', {\n id: q.id(),\n title: q.text().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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](/define/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\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const templateLibrary = q.table('templateLibrary', {\n id: q.id(),\n title: q.text().required(),\n body: q.text().required(),\n ...q.audit(),\n ...q.softDelete(),\n});\n\nexport default defineTable(templateLibrary, {\n firewall: [{ exception: true }],\n // ...\n});\n\n// features/job-templates/custom-templates.ts - Org's custom job templates\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const customTemplates = q.table('customTemplates', {\n id: q.id(),\n title: q.text().required(),\n body: q.text().required(),\n ownerId: q.text().required(),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const jobs = q.table('jobs', {\n id: q.id(),\n title: q.text().required(),\n isPublic: q.bool().default(false).required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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 |"
|
|
171
175
|
},
|
|
172
176
|
"define/guards": {
|
|
173
177
|
"title": "Guards - Field Modification Rules",
|
|
@@ -175,15 +179,15 @@ export const DOCS = {
|
|
|
175
179
|
},
|
|
176
180
|
"define": {
|
|
177
181
|
"title": "Definitions Overview",
|
|
178
|
-
"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 `feature()`\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 (feature())\nβ βββ applications.ts # Secondary table + config\nβ βββ interview-scores.ts # Internal table (no routes)\nβ βββ actions/ # Custom actions β one file per action\nβ β βββ advanceStage.ts\nβ βββ lib/ # Feature-local helpers (optional)\nβ βββ pages/ # CMS page definitions (optional)\nβββ src/ # Generated code (output)\nβββ package.json\n```\n\n`actions/`, `lib/`, and `pages/` are the **reserved** sub-directories of a\nfeature β nothing else inside a feature folder is loaded, and a stray subdirectory that\ncontains `defineTable(...)` / `defineAction(...)` files fails the compile (files silently\ndisappearing after a mis-move is the failure mode this guards against).\n\nFeatures can also be grouped into **areas**: a folder carrying an `_area.ts`\n(`export default defineArea({...})`) declares a route prefix + admission gate and a shared\nauthz vocabulary, and every unreserved child directory becomes a child feature (nesting to\narbitrary depth):\n\n```\nquickback/features/\nβββ workspace/ # AREA (has _area.ts)\nβ βββ _area.ts # defineArea({...}) β prefix, via lanes, vocabulary\nβ βββ projects.ts # the area folder may itself be a feature\nβ βββ tasks/ # child feature\nβ βββ tasks.ts\nβ βββ actions/addTask.ts\nβββ billing/ # flat feature (unchanged)\n```\n\nArea projects must declare `requires: ['feature-areas']` in `quickback.config.ts`.\nSee [Feature areas](/define/areas) for the full model.\n\n**Table files** use `feature()` to combine schema and security config in one call:\n\n```typescript\n// features/candidates/candidates.ts\nimport { feature, q } from \"@quickback/compiler\";\n\nexport default feature(\"candidates\", {\n columns: {\n id: q.id(),\n organizationId: q.scope(\"organization\"),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n source: q.text().optional(),\n ...q.audit(),\n ...q.softDelete(),\n },\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```\n\nConsumers get the row type from the default export β `type Candidate = typeof import(\"./candidates\").default.$infer`.\n\n**Key points:**\n- Tables with `export default feature(...)` (or `defineTable(...)`) β resource routes generated\n- Tables without a default export β internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` β `/api/v1/applications`\n\n## The Five Security Layers\n\nEvery API request passes through five security layers, in order:\n\n```\nRequest β Rate Limit β 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 βββ Cap requests per user / op\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| `organizationId` (or `organisationId` / `orgId` / `organization` / `organisation` / `org`) | Data isolated by organization β `WHERE organizationId = ctx.activeOrgId` |\n| `ownerId` | Data isolated by user β `WHERE ownerId = ctx.userId`, and the column is auto-stamped on insert |\n| `teamId` | Data isolated by team β `WHERE teamId = ctx.activeTeamId` |\n| `userId` | **Not** auto-detected. On a feature table it usually means *a user this row references* (member, contact, invitee), not *the row's owner*. |\n\nDetection matches either spelling of a column β the JS key (`organizationId`) or its SQL name (`organization_id`).\n\nExactly one isolation column must match: zero is an error, two or more is an \"ambiguous firewall\" error that asks you to declare `firewall:` explicitly. `userId` is the one column that looks like isolation but isn't β see [Firewall β `ownerId` vs `userId`](/define/firewall#ownerid-vs-userid).\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](/define/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall β](/define/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 β](/define/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 β](/define/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 β](/define/masking)\n\n### 5. Rate Limiting (Request Caps)\n\nRate limiting caps **how often** an operation can be called, backed by Cloudflare's native Rate Limiting binding β no extra storage, no third-party libraries. Unlike the other four layers, it's applied to **every resource by default** (read `1000/60s`, writes `200/60s`) and runs first, before any data is touched.\n\n```typescript\nrateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n},\n// read / create / update keep shipped defaults\n```\n\nOverride per-op, per-resource, or project-wide; set `false` at any scope to opt out. Limits are keyed by `<resource>:<op>:<userId>` (falling back to client IP for anonymous callers), and over-cap requests get a `429` with `Retry-After`.\n\n[Learn more about Rate Limiting β](/define/rate-limit)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?\n - Yes β Continue\n - No β 429 Too Many Requests (with `Retry-After`)\n\n2. **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\n3. **Access** checks: Can interviewers perform GET?\n - Yes β Continue\n - No β 403 Forbidden\n\n4. **Guards** don't apply to GET (they're for writes)\n\n5. **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\n6. **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 an `organizationId` / `ownerId` / `teamId` column (`userId` is **not** a candidate). Declare `firewall:` explicitly when none matches, when two do, or to opt out with `[{ exception: true }]`. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |\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 five 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](/define/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId β contact`). | [CMS Schema Registry](/ui/admin/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](/ui/admin/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/ui/admin/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/ui/admin/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](/ui/admin/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack β Embeddings](/platform/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack β Realtime](/platform/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](/define/schema) β Define your tables\n2. [Firewall](/define/firewall) β Set up data isolation\n3. [Access](/define/access) β Configure read and write permissions\n4. [Guards](/define/guards) β Control field modifications\n5. [Masking](/define/masking) β Hide sensitive data\n6. [Rate Limit](/define/rate-limit) β Per-operation request caps\n7. [Views](/define/views) β Column-level security\n8. [Validation](/define/validation) β Field validation rules\n9. [Actions](/define/actions) β Add custom business logic"
|
|
182
|
+
"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 `feature()`\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## Tenancy is not yours to model\n\n**Workspace, team, tenant, account, org β they are all the Better Auth organization.** Quickback ships multi-tenancy; you never build it.\n\n- **Don't** create a `workspaces` / `teams` / `tenants` table.\n- **Don't** create a membership or `*_members` table.\n- **Do** put `organizationId: q.scope(\"organization\")` on every tenant-scoped table β the firewall is auto-derived from it.\n- Membership and roles arrive on every request as `ctx.activeOrgId` and `ctx.roles`. You never query for them.\n- Create a tenant with `POST /auth/v1/organization/create` and switch with `POST /auth/v1/organization/set-active` β not a custom action.\n\nIf your product calls it something else, that's a **label, not a schema decision** β the Account UI renames the organization surfaces for you (see [Account β Customization](/ui/account/customization)).\n\n## The authorization ladder\n\nFour rungs, in order. **Most apps never leave rung 1.** Climb only when the rung you're on genuinely can't express the rule β each one costs concepts, compile-time constraints, and per-request work.\n\n| Rung | Reach for it when | Skip it when |\n|---|---|---|\n| **1. Org roles + firewall** | `organizationId: q.scope('organization')` plus `roles: ['member+']` / `['admin+']`. No `authz` block at all. | β this is the floor. It covers the large majority of apps end to end. |\n| **2. Named rules** β [`authz.roles` / `authz.rules`](/define/authz-roles#centrally-defined-access-rules) | the same role expression repeats across many features and you want one source of truth | you have only a couple of repeats β inline them |\n| **3. Relationships + areas** β [`authz.relationships`](/define/relationships), [feature areas](/define/areas) | membership lives in **your own** domain table (an attendee, a collaborator, an external reviewer), or a subtree shares a URL prefix **and** a per-row admission gate | org membership already answers it β that's rung 1 |\n| **4. FGA** β [OpenFGA / Zanzibar](/define/fga) | you need a permission *graph*: derived, inherited, hierarchical, or public share links | a single hop answers it |\n\n**Rung 3 is never the answer to \"is this person in the org?\"** A relationship's `from:` must be one of *your* feature tables β the compiler rejects one pointing at Better Auth's `organization_memberships`, `organizations`, or `user`. Org membership is rung 1, and it is already decided before your handler runs.\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 (feature())\nβ βββ applications.ts # Secondary table + config\nβ βββ interview-scores.ts # Internal table (no routes)\nβ βββ actions/ # Custom actions β one file per action\nβ β βββ advanceStage.ts\nβ βββ lib/ # Feature-local helpers (optional)\nβ βββ pages/ # CMS page definitions (optional)\nβββ src/ # Generated code (output)\nβββ package.json\n```\n\n`actions/`, `lib/`, and `pages/` are the **reserved** sub-directories of a\nfeature β nothing else inside a feature folder is loaded, and a stray subdirectory that\ncontains `defineTable(...)` / `defineAction(...)` files fails the compile (files silently\ndisappearing after a mis-move is the failure mode this guards against).\n\nFeatures can also be grouped into **areas**: a folder carrying an `_area.ts`\n(`export default defineArea({...})`) declares a route prefix + admission gate and a shared\nauthz vocabulary, and every unreserved child directory becomes a child feature (nesting to\narbitrary depth):\n\n```\nquickback/features/\nβββ project/ # AREA (has _area.ts)\nβ βββ _area.ts # defineArea({...}) β prefix, via lanes, vocabulary\nβ βββ projects.ts # the area folder may itself be a feature\nβ βββ tasks/ # child feature\nβ βββ tasks.ts\nβ βββ actions/addTask.ts\nβββ billing/ # flat feature (unchanged)\n```\n\nAn area gates a **row inside a tenant** (this project, this event, this location) β it is not how you get multi-tenancy, which you already have. Area projects must declare `requires: ['feature-areas']` in `quickback.config.ts`. See [Feature areas](/define/areas) for the full model.\n\n**Table files** use `feature()` to combine schema and security config in one call:\n\n```typescript\n// features/candidates/candidates.ts\nimport { feature, q } from \"@quickback/compiler\";\n\nexport default feature(\"candidates\", {\n columns: {\n id: q.id(),\n organizationId: q.scope(\"organization\"),\n name: q.text().required(),\n email: q.text().required(),\n phone: q.text().optional(),\n source: q.text().optional(),\n ...q.audit(),\n ...q.softDelete(),\n },\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```\n\nConsumers get the row type from the default export β `type Candidate = typeof import(\"./candidates\").default.$infer`.\n\n**Key points:**\n- Tables with `export default feature(...)` (or `defineTable(...)`) β resource routes generated\n- Tables without a default export β internal/junction tables (no routes)\n- Route path derived from filename: `applications.ts` β `/api/v1/applications`\n\n## The Five Security Layers\n\nEvery API request passes through five security layers, in order:\n\n```\nRequest β Rate Limit β 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 βββ Cap requests per user / op\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| `organizationId` (or `organisationId` / `orgId` / `organization` / `organisation` / `org`) | Data isolated by organization β `WHERE organizationId = ctx.activeOrgId` |\n| `ownerId` | Data isolated by user β `WHERE ownerId = ctx.userId`, and the column is auto-stamped on insert |\n| `teamId` | Data isolated by team β `WHERE teamId = ctx.activeTeamId` |\n| `userId` | **Not** auto-detected. On a feature table it usually means *a user this row references* (member, contact, invitee), not *the row's owner*. |\n\nDetection matches either spelling of a column β the JS key (`organizationId`) or its SQL name (`organization_id`).\n\nExactly one isolation column must match: zero is an error, two or more is an \"ambiguous firewall\" error that asks you to declare `firewall:` explicitly. `userId` is the one column that looks like isolation but isn't β see [Firewall β `ownerId` vs `userId`](/define/firewall#ownerid-vs-userid).\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](/define/firewall#relationship-based-scoping-via).\n\n[Learn more about Firewall β](/define/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 β](/define/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 β](/define/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 β](/define/masking)\n\n### 5. Rate Limiting (Request Caps)\n\nRate limiting caps **how often** an operation can be called, backed by Cloudflare's native Rate Limiting binding β no extra storage, no third-party libraries. Unlike the other four layers, it's applied to **every resource by default** (read `1000/60s`, writes `200/60s`) and runs first, before any data is touched.\n\n```typescript\nrateLimit: {\n delete: { limit: 5, period: 60 }, // tighter than the 200/60s default\n},\n// read / create / update keep shipped defaults\n```\n\nOverride per-op, per-resource, or project-wide; set `false` at any scope to opt out. Limits are keyed by `<resource>:<op>:<userId>` (falling back to client IP for anonymous callers), and over-cap requests get a `429` with `Retry-After`.\n\n[Learn more about Rate Limiting β](/define/rate-limit)\n\n## How They Work Together\n\n**Scenario:** An interviewer requests `GET /candidates/cnd_123`\n\n1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?\n - Yes β Continue\n - No β 429 Too Many Requests (with `Retry-After`)\n\n2. **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\n3. **Access** checks: Can interviewers perform GET?\n - Yes β Continue\n - No β 403 Forbidden\n\n4. **Guards** don't apply to GET (they're for writes)\n\n5. **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\n6. **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 an `organizationId` / `ownerId` / `teamId` column (`userId` is **not** a candidate). Declare `firewall:` explicitly when none matches, when two do, or to opt out with `[{ exception: true }]`. |\n| Access | DENIED | Explicitly define `access` rules with roles |\n| Guards | LOCKED | Explicitly list `createable`, `updatable` fields |\n| Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |\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 five 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](/define/views) |\n| `references` | Explicit FK target table for columns that don't follow the \"Id\"-stripped convention (e.g. `vendorId β contact`). | [CMS Schema Registry](/ui/admin/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](/ui/admin/table-views) |\n| `defaultSort` | Default sort order for CMS list rendering (`{ field, order: \"asc\" \\| \"desc\" }`). | [CMS Table Views](/ui/admin/table-views) |\n| `inputHints` | Per-column CMS input type: `select`, `richtext`, `textarea`, `lookup`, `currency`, etc. Pure CMS hint, no runtime effect. | [CMS Record Layouts](/ui/admin/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](/ui/admin/record-layouts) |\n| `embeddings` | Auto-generate vector embeddings for specified fields on insert/update. | [Stack β Embeddings](/platform/vector/using-embeddings) |\n| `realtime` | Per-table broadcast config (`enabled`, `onInsert`, `onUpdate`, `onDelete`, `requiredRoles`, `fields`). | [Stack β Realtime](/platform/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](/define/schema) β Define your tables\n2. [Firewall](/define/firewall) β Set up data isolation\n3. [Access](/define/access) β Configure read and write permissions\n4. [Guards](/define/guards) β Control field modifications\n5. [Masking](/define/masking) β Hide sensitive data\n6. [Rate Limit](/define/rate-limit) β Per-operation request caps\n7. [Views](/define/views) β Column-level security\n8. [Validation](/define/validation) β Field validation rules\n9. [Actions](/define/actions) β Add custom business logic"
|
|
179
183
|
},
|
|
180
184
|
"define/masking": {
|
|
181
185
|
"title": "Masking - Field Redaction",
|
|
182
|
-
"content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Detection (the compiler asks, you decide)\n\nQuickback scans every table for columns whose names match its sensitive-column patterns β `email`, `ssn`, `apiKey`, `stripeSecret`, `refreshToken`, and the rest of the table below.\n\nIt does **not** decide what to do about them. It **refuses to compile** until you do:\n\n```\ncustomers: 2 columns match Quickback's sensitive-column patterns but carry no masking decision.\n\nQuickback will not guess whether a value is confidential β you decide, per column:\n - email { type: 'email', show: { or: 'owner', roles: ['admin'] } }\n - apiKey { type: 'redact', show: { or: 'owner', roles: ['admin'] } }\n\nAdd a `masking` block to \"customers\". Keep the suggested rule to mask the\ncolumn, or set `false` to record \"reviewed β not sensitive here\" (the value is then\nreturned in full and stays filterable / sortable / searchable):\n\n masking: {\n email: { type: 'email', show: { or: 'owner', roles: ['admin'] } }, // mask it\n // email: false, // β¦or this instead: reviewed, not sensitive here\n apiKey: { type: 'redact', show: { or: 'owner', roles: ['admin'] } }, // mask it\n // apiKey: false, // β¦or this instead: reviewed, not sensitive here\n },\n\nEvery detected column needs one or the other β an omitted key is not a decision.\n```\n\nPaste the block, delete the wrong line from each pair, and you're done:\n\n```typescript\nmasking: {\n // Yes β mask it. Redacted in responses, and only `admin` may filter/sort/search it.\n apiKey: { type: 'redact', show: { roles: ['admin'] } },\n\n // No β reviewed, not sensitive here. Returned in full, freely queryable.\n email: false,\n}\n```\n\n### Why a hard error and not a default\n\nWhether `customers.email` is PII to hide or the display label of a contact list is a product decision, and the compiler has no way to know which. Both possible defaults are wrong somewhere:\n\n- **Auto-mask silently** and you ship a broken list view, or you *think* a value is protected because a warning said so.\n- **Ignore it silently** and a `stripeSecret` column leaks in every response.\n\nSo the compiler asks. A false positive costs you one line (`cc: false`) β which is also a durable, reviewable record that somebody looked.\n\nIt also removes a bug class outright. When detection can never quietly supply a rule, the set of masked columns is the set you declared, so no two surfaces can disagree about it. That exact disagreement was a real defect: through v0.58.3 the response path applied declared-only masking while realtime and live views applied detected-plus-declared, so an auto-detected secret was redacted over WebSocket and returned in **plaintext** on `GET`.\n\n### What a decision controls\n\n| Surface | `{ type, show }` rule | `false` |\n| :--- | :--- | :--- |\n| `GET /:id`, list, named views, `POST`, `PATCH`, `PUT`, batch | Masked per role | Returned in full |\n| Realtime frames + live-view deltas | Masked per-subscriber-role | Sent in full |\n| `?filter=` / `?sort=` | Only roles in the [query gate](#query-gate-filter--sort--search) | Unrestricted |\n| `?search=` | Dropped from the default searchable set | Searchable |\n| FK display label / `embeddings` / action egress scan | Blocked β see [Egress protection](#egress-protection) | Allowed |\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\nThe rule shown in the error is a *suggestion*, not a default that applies on its own β nothing is masked until you write it down.\n\n#### Tables without an owner column\n\nThe suggested predicate is `show: { or: 'owner', roles: ['admin'] }` β admins always see the value, the row's owner sees their own. If you keep it on a table with no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and warns, 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\nDrop the `or: 'owner'` clause and pick a real predicate on an ownerless table.\n\n### Choosing the rule\n\nIf you want to show a sensitive field to everyone, or use a different rule, that's just what you write in the `resource.masking` block:\n\n{/* doc-compile: skip β one-key excerpt: the point is the `masking` block that overrides the auto-detected defaults. The same `candidates` table is declared whole in \"Basic Usage\" immediately below, so repeating the columns here would only bury the override. */}\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Masked, but visible to everyone (a rule with a wide-open audience)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Recruiter and above only\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n\n // Not masked at all, and not query-restricted either\n linkedinUrl: false,\n }\n});\n```\n\nYour rule replaces the suggestion **outright** β the suggested rule is never merged into yours. That also means the rule is where you set the [query gate](#query-gate-filter--sort--search): it defaults to `show.roles`, so a list UI that sorts by `email` for every signed-in member needs the roles spelled out.\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] }, // still redacted in the response bodyβ¦\n query: { roles: ['member', 'admin'] }, // β¦but members may sort/filter by it\n },\n}\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\nimport { feature, q } from '@quickback/compiler';\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 ...q.audit(),\n ...q.softDelete(),\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-aware field projection\n\nFor relationship-specific field visibility, use a named view gated by the\nrelationship role. The relationship resolver runs once at the access layer and\nthe view projects only the fields that caller may receive.\n\nQuickback deliberately does not run per-row database lookups from\n`masking.<field>.show`: doing so would turn list masking into an N+1 query\npipeline. A relationship-backed `show.roles` entry is therefore a clear\ncompile-time refusal, never a silently ignored condition or a broader grant.\n\n### Named gates in masking\n\n[Named gates](/define/access#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:\n\n- A **who-only** gate expands like a named role (its flat role list; the owner-gated flat-role constraint above applies).\n- A gate carrying a **`record:`** predicate is a **compile error** β masking cannot evaluate record conditions, so the record dimension would be silently dropped.\n- A gate carrying **firewall lanes** is a **compile error** β masking has no firewall array to satisfy, so the gate's row lanes would silently not apply. Reference a who-only rule (or inline the roles) in `show:`, and stamp the firewall gate on the resource's `firewall:` instead.\n\n**Supported patterns**, 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\nThe schema slot remains reserved for a future batched async-mask pipeline, so\nadding that execution mode will not require changing the surrounding masking\nshape.\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\nA column you answered with `false` is not gated at all β it stays freely filterable, sortable and searchable, which is the point of saying \"not sensitive here\".\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` is the unified replacement for the legacy per-capability masking flags\n(`filterable`, `searchable`, `sortable`). If an older definition still uses\none, the compiler stops with the exact migration to the single role gate.\n\n## Egress protection\n\nMasking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths β a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:\n\n- **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).\n- **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (``sql`β¦${record.col}` ``) are fine β only the storage/payload sinks are flagged.\n- **Realtime β webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.\n\n### Revealing a value on purpose: `unmask()`\n\nWhen an action legitimately needs the raw value (e.g. calling an external API with a token), route it through `unmask()` β the sanctioned, audited reveal. It returns the raw value and records a best-effort `masked_reveal` entry in the audit database when one is configured.\n\n```typescript\nimport { unmask } from '../../../lib/masking-reveal';\n\n// in an action's execute():\nconst token = await unmask(c, record.apiToken, 'apiToken');\nawait fetch(externalUrl, { headers: { Authorization: `Bearer ${token}` } });\n```\n\n### Opting a column out: `egress: 'allow'`\n\nIf a column is masked for display tidiness rather than secrecy, opt it out of both the compile-time block and the action scan:\n\n```typescript\nmasking: {\n shortCode: { type: 'redact', show: { roles: ['admin'] }, egress: 'allow' },\n}\n```\n\n`egress` defaults to `'block'` (fail-closed). The action scan is an\naccident-prevention layer: it catches direct `record.col` β sink flows without\npretending to be a whole-program information-flow proof. Aliased values,\nwhole-row spreads, and values re-fetched through `db.select()` remain ordinary\napplication code. Pair masking with the [encryption\npillar](/define/encryption) whenever the field needs a\ncryptographic boundary at rest or from the server itself.\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\nimport { feature, q } from '@quickback/compiler';\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 ...q.audit(),\n ...q.softDelete(),\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 // \"+\" role expansion requires auth.roleHierarchy in quickback.config.ts\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```"
|
|
186
|
+
"content": "Hide sensitive data from unauthorized users while showing it to those with permission.\n\n## Detection (the compiler asks, you decide)\n\nQuickback scans every table for columns whose names match its sensitive-column patterns β `email`, `ssn`, `apiKey`, `stripeSecret`, `refreshToken`, and the rest of the table below.\n\nIt does **not** decide what to do about them. It **refuses to compile** until you do:\n\n```\ncustomers: 2 columns match Quickback's sensitive-column patterns but carry no masking decision.\n\nQuickback will not guess whether a value is confidential β you decide, per column:\n - email { type: 'email', show: { or: 'owner', roles: ['admin'] } }\n - apiKey { type: 'redact', show: { or: 'owner', roles: ['admin'] } }\n\nAdd a `masking` block to \"customers\". Keep the suggested rule to mask the\ncolumn, or set `false` to record \"reviewed β not sensitive here\" (the value is then\nreturned in full and stays filterable / sortable / searchable):\n\n masking: {\n email: { type: 'email', show: { or: 'owner', roles: ['admin'] } }, // mask it\n // email: false, // β¦or this instead: reviewed, not sensitive here\n apiKey: { type: 'redact', show: { or: 'owner', roles: ['admin'] } }, // mask it\n // apiKey: false, // β¦or this instead: reviewed, not sensitive here\n },\n\nEvery detected column needs one or the other β an omitted key is not a decision.\n```\n\nPaste the block, delete the wrong line from each pair, and you're done:\n\n```typescript\nmasking: {\n // Yes β mask it. Redacted in responses, and only `admin` may filter/sort/search it.\n apiKey: { type: 'redact', show: { roles: ['admin'] } },\n\n // No β reviewed, not sensitive here. Returned in full, freely queryable.\n email: false,\n}\n```\n\n### Why a hard error and not a default\n\nWhether `customers.email` is PII to hide or the display label of a contact list is a product decision, and the compiler has no way to know which. Both possible defaults are wrong somewhere:\n\n- **Auto-mask silently** and you ship a broken list view, or you *think* a value is protected because a warning said so.\n- **Ignore it silently** and a `stripeSecret` column leaks in every response.\n\nSo the compiler asks. A false positive costs you one line (`cc: false`) β which is also a durable, reviewable record that somebody looked.\n\nIt also removes a bug class outright. When detection can never quietly supply a rule, the set of masked columns is the set you declared, so no two surfaces can disagree about it. That exact disagreement was a real defect: through v0.58.3 the response path applied declared-only masking while realtime and live views applied detected-plus-declared, so an auto-detected secret was redacted over WebSocket and returned in **plaintext** on `GET`.\n\n### What a decision controls\n\n| Surface | `{ type, show }` rule | `false` |\n| :--- | :--- | :--- |\n| `GET /:id`, list, named views, `POST`, `PATCH`, `PUT`, batch | Masked per role | Returned in full |\n| Realtime frames + live-view deltas | Masked per-subscriber-role | Sent in full |\n| `?filter=` / `?sort=` | Only roles in the [query gate](#query-gate-filter--sort--search) | Unrestricted |\n| `?search=` | Dropped from the default searchable set | Searchable |\n| FK display label / `embeddings` / action egress scan | Blocked β see [Egress protection](#egress-protection) | Allowed |\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\nThe rule shown in the error is a *suggestion*, not a default that applies on its own β nothing is masked until you write it down.\n\n#### Tables without an owner column\n\nThe suggested predicate is `show: { or: 'owner', roles: ['admin'] }` β admins always see the value, the row's owner sees their own. If you keep it on a table with no owner column at all (no `userId` / `ownerId` and no `q.scope('owner')`), the compiler drops the `owner` clause and warns, 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\nDrop the `or: 'owner'` clause and pick a real predicate on an ownerless table.\n\n### Choosing the rule\n\nIf you want to show a sensitive field to everyone, or use a different rule, that's just what you write in the `resource.masking` block:\n\n{/* doc-compile: skip β one-key excerpt: the point is the `masking` block that overrides the auto-detected defaults. The same `candidates` table is declared whole in \"Basic Usage\" immediately below, so repeating the columns here would only bury the override. */}\n```typescript\nexport default defineTable(candidates, {\n masking: {\n // Masked, but visible to everyone (a rule with a wide-open audience)\n email: { type: 'email', show: { roles: ['everyone'] } },\n\n // Recruiter and above only\n phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },\n\n // Not masked at all, and not query-restricted either\n linkedinUrl: false,\n }\n});\n```\n\nYour rule replaces the suggestion **outright** β the suggested rule is never merged into yours. That also means the rule is where you set the [query gate](#query-gate-filter--sort--search): it defaults to `show.roles`, so a list UI that sorts by `email` for every signed-in member needs the roles spelled out.\n\n```typescript\nmasking: {\n email: {\n type: 'email',\n show: { roles: ['admin'] }, // still redacted in the response bodyβ¦\n query: { roles: ['member', 'admin'] }, // β¦but members may sort/filter by it\n },\n}\n```\n\n## Basic Usage\n\n```typescript\n// features/candidates/candidates.ts\nimport { feature, q } from '@quickback/compiler';\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 ...q.audit(),\n ...q.softDelete(),\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-aware field projection\n\nFor relationship-specific field visibility, use a named view gated by the\nrelationship role. The relationship resolver runs once at the access layer and\nthe view projects only the fields that caller may receive.\n\nQuickback deliberately does not run per-row database lookups from\n`masking.<field>.show`: doing so would turn list masking into an N+1 query\npipeline. A relationship-backed `show.roles` entry is therefore a clear\ncompile-time refusal, never a silently ignored condition or a broader grant.\n\n### Named gates in masking\n\n[Named gates](/define/authz-roles#named-gates-authzrules) (`authz.rules`) follow the same discipline in `show:`:\n\n- A **who-only** gate expands like a named role (its flat role list; the owner-gated flat-role constraint above applies).\n- A gate carrying a **`record:`** predicate is a **compile error** β masking cannot evaluate record conditions, so the record dimension would be silently dropped.\n- A gate carrying **firewall lanes** is a **compile error** β masking has no firewall array to satisfy, so the gate's row lanes would silently not apply. Reference a who-only rule (or inline the roles) in `show:`, and stamp the firewall gate on the resource's `firewall:` instead.\n\n**Supported patterns**, 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\nThe schema slot remains reserved for a future batched async-mask pipeline, so\nadding that execution mode will not require changing the surrounding masking\nshape.\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\nA column you answered with `false` is not gated at all β it stays freely filterable, sortable and searchable, which is the point of saying \"not sensitive here\".\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` is the unified replacement for the legacy per-capability masking flags\n(`filterable`, `searchable`, `sortable`). If an older definition still uses\none, the compiler stops with the exact migration to the single role gate.\n\n## Egress protection\n\nMasking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths β a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:\n\n- **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).\n- **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (``sql`β¦${record.col}` ``) are fine β only the storage/payload sinks are flagged.\n- **Realtime β webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.\n\n### Revealing a value on purpose: `unmask()`\n\nWhen an action legitimately needs the raw value (e.g. calling an external API with a token), route it through `unmask()` β the sanctioned, audited reveal. It returns the raw value and records a best-effort `masked_reveal` entry in the audit database when one is configured.\n\n```typescript\nimport { unmask } from '../../../lib/masking-reveal';\n\n// in an action's execute():\nconst token = await unmask(c, record.apiToken, 'apiToken');\nawait fetch(externalUrl, { headers: { Authorization: `Bearer ${token}` } });\n```\n\n### Opting a column out: `egress: 'allow'`\n\nIf a column is masked for display tidiness rather than secrecy, opt it out of both the compile-time block and the action scan:\n\n```typescript\nmasking: {\n shortCode: { type: 'redact', show: { roles: ['admin'] }, egress: 'allow' },\n}\n```\n\n`egress` defaults to `'block'` (fail-closed). The action scan is an\naccident-prevention layer: it catches direct `record.col` β sink flows without\npretending to be a whole-program information-flow proof. Aliased values,\nwhole-row spreads, and values re-fetched through `db.select()` remain ordinary\napplication code. Pair masking with the [encryption\npillar](/define/encryption) whenever the field needs a\ncryptographic boundary at rest or from the server itself.\n\n## Complete Example\n\n```typescript\n// features/candidates/candidates.ts\nimport { feature, q } from '@quickback/compiler';\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 ...q.audit(),\n ...q.softDelete(),\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 // \"+\" role expansion requires auth.roleHierarchy in quickback.config.ts\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```"
|
|
183
187
|
},
|
|
184
188
|
"define/permissions": {
|
|
185
189
|
"title": "Permissions",
|
|
186
|
-
"content": "A `via:` arm references **one** relationship. A `roles: [...]` array ORs a\nflat list of role names. When the *same* grant rule recurs across several\nresources β \"organizer **or** confirmed attendee\", \"admin **and not**\nsuspended\" β name it once under `authz.permissions` and reference it\neverywhere by name. A permission is a **named boolean expression** over the\nauthorization primitives you've already declared.\n\n## Declaring permissions\n\nPermissions live in `quickback.config.ts` alongside `authz.relationships`:\n\n```typescript\n// quickback.config.ts\nimport { defineConfig } from '@quickback/compiler';\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n organizerOf: { from: 'event_staff', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n attendeeOf: { from: 'event_guests', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n 'event:manage': { allOf: ['organizerOf', { not: 'suspendedFromEvent' }] },\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n },\n },\n});\n```\n\n## The expression DSL\n\nA permission is a tree of three combinators over **leaves**:\n\n| Combinator | Meaning |\n|---|---|\n| `{ anyOf: [...] }` | union β satisfied if **any** arm holds |\n| `{ allOf: [...] }` | intersection β satisfied only if **all** arms hold |\n| `{ not: <expr> }` | exclusion β satisfied if the operand does **not** hold |\n\nA bare leaf (no combinator) is a one-arm permission β the replacement for a\nsingle `via:`.\n\n### Leaves\n\nA leaf names one authorization primitive. The common case is a bare string;\nobject forms are the unambiguous escape hatch.\n\n| Leaf | Resolves to |\n|---|---|\n| `'organizerOf'` (bare string, no prefix) | a declared **relationship** |\n| `{ relationRef: 'organizerOf' }` | a declared relationship (explicit) |\n| `{ permissionRef: 'event:view' }` | **another permission** (composition) |\n| `{ role: 'admin' }` | an org-membership role (`ctx.roles`) |\n| `{ scopeRole: { kind: 'event', role: 'organizer' } }` | a [scoped role](/define/scopes) |\n| `{ pseudoRole: 'AUTHENTICATED' }` | `PUBLIC` / `AUTHENTICATED` / `INTERNAL` / β¦ |\n| `{ arrowRef: 'eventOrg', permission: 'org:admin' }` | an [FK-traversal arrow](/define/arrows) β resolve the row's FK to its target object and require a permission there |\n\nString sugar for the prefixed forms is also accepted inside an expression:\n`'permission:event:view'`, `'scope:event:organizer'`, `'role:admin'`. A bare\nstring with no recognized prefix is always a relationship reference.\n\n## Referencing a permission\n\nA resource references a permission from its `firewall` with a\n`{ permission }` arm. `field` is the resource-side column the lowered\nsubqueries constrain β the same column a `via:` arm would carry:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler **lowers** the permission to the equivalent firewall arms:\n`anyOf` becomes an OR of relationship subqueries (`any`), `allOf` becomes an\nAND (`all`), and `{ permissionRef }` inlines the referenced permission's\narms. The result is byte-identical to writing those `via:` arms by hand β the\npermission is just the named, reusable spelling.\n\nSee [Firewall β named permissions](/define/firewall#named-permissions-permission)\nfor how the arm sits inside a firewall.\n\n## Firewall-pushable permission rules\n\nA firewall permission compiles all the way down to a SQL `WHERE` expression.\nThe production-ready subset includes relationship leaves, composed\n`{ permissionRef }` leaves, and FK-traversal arrows under `anyOf` / `allOf`.\nThose rules run in the database alongside the rest of the row firewall.\n\nTwo expression shapes belong at a different enforcement site, and the compiler\nroutes you there with a build error instead of weakening the policy:\n\n- **Claim checks.** `{ role }`, `{ scopeRole }`, and `{ pseudoRole }` are\n decided from verified request claims rather than row subqueries. Put them on\n `read.access` / `crud.*.access`, then keep the permission focused on row\n reachability.\n- **Negated SQL relationships.** `not` over a relationship site is refused\n because nullable `NOT IN (subquery)` semantics create the classic null trap.\n Express the positive relationship set or enforce the exclusion at a runtime\n access site.\n\nThe wider DSL remains available for permission definitions and future\nenforcement sites, while every firewall reference is checked for SQL\npushability today. FK-traversal arrows are firewall-pushable; see\n[Arrows](/define/arrows).\n\nThe compile-time analyzer flags permissions that can never be satisfied,\narms shadowed by a broader arm, a `not` over a SQL site (the null-trap), and\nthe subquery / CTE cost of each rule β see\n[Diagnostics](/define/diagnostics).\n\n## Reference\n\n```typescript\n// authz.permissions.<name>\ntype PermissionExpr =\n | PermissionLeaf\n | { anyOf: PermissionExpr[] }\n | { allOf: PermissionExpr[] }\n | { not: PermissionExpr };\n\ntype PermissionLeaf =\n | string // relationship name (bare) or prefixed sugar\n | { relationRef: string }\n | { permissionRef: string }\n | { role: string } // claim-site β not firewall-pushable (M1)\n | { scopeRole: { kind: string; role: string } } // claim-site β not firewall-pushable (M1)\n | { pseudoRole: string } // claim-site β not firewall-pushable (M1)\n | { arrowRef: string; permission: string }; // FK-traversal arrow β see Arrows\n```\n\n- Referenced from a firewall as `{ field, permission: '<name>' }`.\n- Relationship leaves carry every property of the underlying relationship β\n the `from` table's own firewall (tenant scope + soft-delete) is AND'd into\n each subquery, exactly as with a `via:` arm.\n- See [Scopes & capability grants](/define/scopes) for scoped\n roles and [Access β relationships](/define/
|
|
190
|
+
"content": "A `via:` arm references **one** relationship. A `roles: [...]` array ORs a\nflat list of role names. When the *same* grant rule recurs across several\nresources β \"organizer **or** confirmed attendee\", \"admin **and not**\nsuspended\" β name it once under `authz.permissions` and reference it\neverywhere by name. A permission is a **named boolean expression** over the\nauthorization primitives you've already declared.\n\n## Declaring permissions\n\nPermissions live in `quickback.config.ts` alongside `authz.relationships`:\n\n```typescript\n// quickback.config.ts\nimport { defineConfig } from '@quickback/compiler';\n\nexport default defineConfig({\n // ...providers...\n authz: {\n relationships: {\n organizerOf: { from: 'event_staff', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n attendeeOf: { from: 'event_guests', subject: { column: 'userId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n },\n permissions: {\n 'event:view': { anyOf: ['organizerOf', 'attendeeOf'] },\n 'event:manage': { allOf: ['organizerOf', { not: 'suspendedFromEvent' }] },\n 'org:admin': { anyOf: [{ role: 'admin' }, { role: 'owner' }] },\n },\n },\n});\n```\n\n## The expression DSL\n\nA permission is a tree of three combinators over **leaves**:\n\n| Combinator | Meaning |\n|---|---|\n| `{ anyOf: [...] }` | union β satisfied if **any** arm holds |\n| `{ allOf: [...] }` | intersection β satisfied only if **all** arms hold |\n| `{ not: <expr> }` | exclusion β satisfied if the operand does **not** hold |\n\nA bare leaf (no combinator) is a one-arm permission β the replacement for a\nsingle `via:`.\n\n### Leaves\n\nA leaf names one authorization primitive. The common case is a bare string;\nobject forms are the unambiguous escape hatch.\n\n| Leaf | Resolves to |\n|---|---|\n| `'organizerOf'` (bare string, no prefix) | a declared **relationship** |\n| `{ relationRef: 'organizerOf' }` | a declared relationship (explicit) |\n| `{ permissionRef: 'event:view' }` | **another permission** (composition) |\n| `{ role: 'admin' }` | an org-membership role (`ctx.roles`) |\n| `{ scopeRole: { kind: 'event', role: 'organizer' } }` | a [scoped role](/define/scopes) |\n| `{ pseudoRole: 'AUTHENTICATED' }` | `PUBLIC` / `AUTHENTICATED` / `INTERNAL` / β¦ |\n| `{ arrowRef: 'eventOrg', permission: 'org:admin' }` | an [FK-traversal arrow](/define/arrows) β resolve the row's FK to its target object and require a permission there |\n\nString sugar for the prefixed forms is also accepted inside an expression:\n`'permission:event:view'`, `'scope:event:organizer'`, `'role:admin'`. A bare\nstring with no recognized prefix is always a relationship reference.\n\n## Referencing a permission\n\nA resource references a permission from its `firewall` with a\n`{ permission }` arm. `field` is the resource-side column the lowered\nsubqueries constrain β the same column a `via:` arm would carry:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', permission: 'event:view' },\n]\n```\n\nThe compiler **lowers** the permission to the equivalent firewall arms:\n`anyOf` becomes an OR of relationship subqueries (`any`), `allOf` becomes an\nAND (`all`), and `{ permissionRef }` inlines the referenced permission's\narms. The result is byte-identical to writing those `via:` arms by hand β the\npermission is just the named, reusable spelling.\n\nSee [Firewall β named permissions](/define/firewall#named-permissions-permission)\nfor how the arm sits inside a firewall.\n\n## Firewall-pushable permission rules\n\nA firewall permission compiles all the way down to a SQL `WHERE` expression.\nThe production-ready subset includes relationship leaves, composed\n`{ permissionRef }` leaves, and FK-traversal arrows under `anyOf` / `allOf`.\nThose rules run in the database alongside the rest of the row firewall.\n\nTwo expression shapes belong at a different enforcement site, and the compiler\nroutes you there with a build error instead of weakening the policy:\n\n- **Claim checks.** `{ role }`, `{ scopeRole }`, and `{ pseudoRole }` are\n decided from verified request claims rather than row subqueries. Put them on\n `read.access` / `crud.*.access`, then keep the permission focused on row\n reachability.\n- **Negated SQL relationships.** `not` over a relationship site is refused\n because nullable `NOT IN (subquery)` semantics create the classic null trap.\n Express the positive relationship set or enforce the exclusion at a runtime\n access site.\n\nThe wider DSL remains available for permission definitions and future\nenforcement sites, while every firewall reference is checked for SQL\npushability today. FK-traversal arrows are firewall-pushable; see\n[Arrows](/define/arrows).\n\nThe compile-time analyzer flags permissions that can never be satisfied,\narms shadowed by a broader arm, a `not` over a SQL site (the null-trap), and\nthe subquery / CTE cost of each rule β see\n[Diagnostics](/define/diagnostics).\n\n## Reference\n\n```typescript\n// authz.permissions.<name>\ntype PermissionExpr =\n | PermissionLeaf\n | { anyOf: PermissionExpr[] }\n | { allOf: PermissionExpr[] }\n | { not: PermissionExpr };\n\ntype PermissionLeaf =\n | string // relationship name (bare) or prefixed sugar\n | { relationRef: string }\n | { permissionRef: string }\n | { role: string } // claim-site β not firewall-pushable (M1)\n | { scopeRole: { kind: string; role: string } } // claim-site β not firewall-pushable (M1)\n | { pseudoRole: string } // claim-site β not firewall-pushable (M1)\n | { arrowRef: string; permission: string }; // FK-traversal arrow β see Arrows\n```\n\n- Referenced from a firewall as `{ field, permission: '<name>' }`.\n- Relationship leaves carry every property of the underlying relationship β\n the `from` table's own firewall (tenant scope + soft-delete) is AND'd into\n each subquery, exactly as with a `via:` arm.\n- See [Scopes & capability grants](/define/scopes) for scoped\n roles and [Access β relationships](/define/relationships#authzrelationships)\n for the relationship shape."
|
|
187
191
|
},
|
|
188
192
|
"define/rate-limit": {
|
|
189
193
|
"title": "Rate Limit - Per-Operation Request Caps",
|
|
@@ -191,7 +195,11 @@ export const DOCS = {
|
|
|
191
195
|
},
|
|
192
196
|
"define/read": {
|
|
193
197
|
"title": "Read - Unified Read Pipeline",
|
|
194
|
-
"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\nimport { sqliteTable, text } from 'drizzle-orm/sqlite-core';\nimport { defineTable } from '@quickback/compiler';\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 // ββ quickback:audit (compiler-managed β edits are validated, not merged) ββ\n createdAt: text('created_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()),\n modifiedAt: text('modified_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()).$onUpdate(() => new Date().toISOString()),\n createdBy: text('created_by'),\n modifiedBy: text('modified_by'),\n deletedAt: text('deleted_at'),\n deletedBy: text('deleted_by'),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n // Detected as sensitive too; `false` records the reviewed-and-fine answer.\n email: false,\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\nEach `access` block takes a `roles: [...]` array. When the same role expression recurs across reads/views/CRUD, define it once in `authz.roles` and reference it by name β see [Centrally defined access rules](/define/access#centrally-defined-access-rules).\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'`](/define/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](/define/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\n// features/ledger/balance-snapshots.ts\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const balanceSnapshots = q.table('balanceSnapshots', {\n id: q.id(),\n accountId: q.text().required(),\n balanceCents: q.int().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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## Aggregate Reads\n\nReading a parent **with** its owned relations rides contract-v2 `?include=`,\nwhich accepts two kinds of tokens in the same `read.include` allowlist:\n\n- **FK columns** (`?include=vendorId`) β forward embeds: the target rows the\n source row points at.\n- **`owns` relation names** (`?include=reactions`) β the phase-2 aggregate\n reader: the changeset root's owned **child rows**, pivoting on the root PK\n and matching the child's declared `fk` column.\n\n{/* doc-compile: skip β project-config prerequisite: `owns` + `?include=` are contract-v2 capabilities (the prose above says so) and need `contract: { version: 'v2' }` in quickback.config.ts; the gate's harness config pins v1. It also names a `noteReactions` child table that the fence deliberately does not repeat. */}\n```typescript\nexport default defineTable(notes, {\n owns: { reactions: { table: 'noteReactions', fk: 'noteId' } },\n read: {\n access: { roles: ['member', 'admin'] },\n include: ['reactions'], // ?include=reactions embeds the children\n },\n});\n```\n\nBoth kinds land in the top-level `included` map keyed by the include token,\nthen row PK, and both inherit the **target's full security surface** β its\n`read.access` (pre-record-evaluable only, compile-enforced), its firewall\n(ANDed into the child fetch on the caller-claims handle), and its masking.\n`fields[<token>]` sparse projections apply identically. The aggregate-changeset\nwrite surface ([changesets](/define/changesets)) still returns\nthe **root row only** β read the aggregate back with `?include=<relation>`.\n\n## See Also\n\n- [Views](/define/views) β Full reference for named projections\n- [Changesets](/define/changesets) β Atomic writes over the `owns` graph\n- [Access](/define/access) β Roles, record conditions, and combinators\n- [Firewall](/define/firewall) β Tenant scoping and `firewallErrorMode`\n- [Views API](/api/views) β Calling views from clients"
|
|
198
|
+
"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\nimport { sqliteTable, text } from 'drizzle-orm/sqlite-core';\nimport { defineTable } from '@quickback/compiler';\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 // ββ quickback:audit (compiler-managed β edits are validated, not merged) ββ\n createdAt: text('created_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()),\n modifiedAt: text('modified_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()).$onUpdate(() => new Date().toISOString()),\n createdBy: text('created_by'),\n modifiedBy: text('modified_by'),\n deletedAt: text('deleted_at'),\n deletedBy: text('deleted_by'),\n});\n\nexport default defineTable(customers, {\n firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],\n masking: {\n ssn: { type: 'ssn', show: { roles: ['admin'] } },\n // Detected as sensitive too; `false` records the reviewed-and-fine answer.\n email: false,\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\nEach `access` block takes a `roles: [...]` array. When the same role expression recurs across reads/views/CRUD, define it once in `authz.roles` and reference it by name β see [Centrally defined access rules](/define/authz-roles#centrally-defined-access-rules).\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'`](/define/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](/define/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\n// features/ledger/balance-snapshots.ts\nimport { q, defineTable } from '@quickback/compiler';\n\nexport const balanceSnapshots = q.table('balanceSnapshots', {\n id: q.id(),\n accountId: q.text().required(),\n balanceCents: q.int().required(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n});\n\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## Aggregate Reads\n\nReading a parent **with** its owned relations rides contract-v2 `?include=`,\nwhich accepts two kinds of tokens in the same `read.include` allowlist:\n\n- **FK columns** (`?include=vendorId`) β forward embeds: the target rows the\n source row points at.\n- **`owns` relation names** (`?include=reactions`) β the phase-2 aggregate\n reader: the changeset root's owned **child rows**, pivoting on the root PK\n and matching the child's declared `fk` column.\n\n{/* doc-compile: skip β project-config prerequisite: `owns` + `?include=` are contract-v2 capabilities (the prose above says so) and need `contract: { version: 'v2' }` in quickback.config.ts; the gate's harness config pins v1. It also names a `noteReactions` child table that the fence deliberately does not repeat. */}\n```typescript\nexport default defineTable(notes, {\n owns: { reactions: { table: 'noteReactions', fk: 'noteId' } },\n read: {\n access: { roles: ['member', 'admin'] },\n include: ['reactions'], // ?include=reactions embeds the children\n },\n});\n```\n\nBoth kinds land in the top-level `included` map keyed by the include token,\nthen row PK, and both inherit the **target's full security surface** β its\n`read.access` (pre-record-evaluable only, compile-enforced), its firewall\n(ANDed into the child fetch on the caller-claims handle), and its masking.\n`fields[<token>]` sparse projections apply identically. The aggregate-changeset\nwrite surface ([changesets](/define/changesets)) still returns\nthe **root row only** β read the aggregate back with `?include=<relation>`.\n\n## See Also\n\n- [Views](/define/views) β Full reference for named projections\n- [Changesets](/define/changesets) β Atomic writes over the `owns` graph\n- [Access](/define/access) β Roles, record conditions, and combinators\n- [Firewall](/define/firewall) β Tenant scoping and `firewallErrorMode`\n- [Views API](/api/views) β Calling views from clients\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](/define/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## 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`mode` on the single-record path is inherited by `DELETE /batch` unless `batch` names its own β so `mode: \"hard\"` above makes the whole resource hard-delete. That changes the schema: a hard-delete table must **not** declare `deletedAt` / `deletedBy` (via `...q.softDelete()` or literal Drizzle lines), and the firewall drops its `isNull(deletedAt)` predicate. See [Soft-delete fields](/define/schema#soft-delete-fields)."
|
|
199
|
+
},
|
|
200
|
+
"define/relationships": {
|
|
201
|
+
"title": "Relationship-Based Authorization - authz.relationships",
|
|
202
|
+
"content": "**[Rung 3](/define#the-authorization-ladder).** Use a relationship when membership lives\nin **your own** domain table β an attendee, a collaborator, an external reviewer who\nisn't in your org.\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. These are the `{ via: '...' }` rule shape from [Centrally defined access rules](#centrally-defined-access-rules) above.\n\n### `authz.relationships`\n\nDeclare relationships once in `quickback.config.ts`:\n\n```typescript\n// quickback.config.ts\nimport { defineConfig } from '@quickback/compiler';\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#### Supported relationship-role surfaces\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| **Standalone** `actions.<name>.access` `roles: ['guest']` | β Supported | Inline gate; the surface exposes `resource.column` as a path param or input field |\n| **Record-based** `actions.<name>.access` `roles: ['guest']` | β Supported | Inline lookup uses the already-loaded, firewalled record |\n| Namespace `via` lanes | β Supported | Hoisted middleware resolves once and can hydrate `ctx.<exposeAs>` |\n| `masking.<field>.show` `roles: ['guest']` | Build-time refusal | Use a relationship-gated view for field projection; per-row async masking is not approximated |\n\nRelationship roles are therefore available across CRUD, reads, standalone\nactions, record-based actions, and namespace mounts. Masking is the one\ndifferent execution surface: list masking must stay synchronous and batched, so\nthe compiler rejects a relationship-bearing `masking.show` rule and points to a\nrelationship-gated view instead. It never drops the relationship arm or turns\nit into a broader role grant.\n\n### Standalone actions: surface keys and `loads` / `exposeAs` (v0.19+)\n\nWhen a standalone action's `access.roles` references a relationship-role, the compiler emits a runtime gate between input validation and `execute()`. The gate reads the relationship's `resource.column` value from the action surface β either a path parameter (`:eventId`) or an input field (`input.eventId`). If neither is present, the current compiler stops with a clear build error; an action can never ship with a relationship rule it has no key to evaluate.\n\nPair the relationship with `loads` + `exposeAs` to hydrate the loaded resource onto `ctx`:\n\n```typescript\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events', // β v0.19+: load matching event row\n exposeAs: 'event', // β onto ctx.event for the action body\n },\n },\n roles: {\n attendee: { via: 'attendeeOf' },\n },\n}\n```\n\nThe resolver (v0.20):\n\n1. **Cheap in-memory role check** first β `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.\n2. **Firewall-gated relationship match** if the role check failed β `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies β 403.\n3. **Tenant stamping from the matched row** β for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** β no JWT remint, no session-record write, no persistent grant.\n4. **Firewall-gated load of the loaded resource** β `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.\n5. Assigns the loaded row to `ctx.event` for the action body.\n\n**No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.\n\n### Conditional tenant preconditions (v0.20+)\n\nStandalone actions in features with org/team-scoped tables previously emitted unconditional preconditions:\n\n```ts\nif (!ctx.activeOrgId) return c.json(AccessErrors.noOrg(), 403);\nif (!ctx.activeTeamId) return c.json(AccessErrors.noTeam(), 403);\n```\n\nThese ran **before** the relationship resolver, which 403'd attendees whose sessions don't carry an active tenant claim (the canonical event-attendee shape).\n\nv0.20 makes these preconditions **conditional on relationship supply**. If the access tree contains a relationship arm whose `from` table carries the matching tenant column, the precondition is skipped β the resolver runs first and stamps the value. Pseudo-role short-circuits (PUBLIC / AUTHENTICATED / USER / SYSADMIN) and `firewall: { exception: true }` still bypass the preconditions as before. `ADMIN` is now rejected at compile time.\n\nTypical event-attendee setup (`guests` table carries `organizationId`): the org precondition is dropped on every action whose access references `attendee` or `eventStaff`. Org admins still get `ctx.activeOrgId` from their session as today; attendees get it from the relationship row, mid-request. Both paths converge on a valid tenant claim before `execute()` runs.\n\n### Requirement on the relationship's `from` table\n\nFor the v0.20 tenant-stamping to work, the relationship's `from` table must carry tenant columns:\n\n- For org stamping: an `organizationId` column (or whatever spelling the project's auth-provider defaults pick).\n- For team stamping: a `teamId` column.\n\nWhen the `from` table has **neither**, the compiler emits a `[quickback:authz]` warning at compile time:\n\n```\nRelationship \"X\" at authz.relationships.X has no organization or team columns\non its `from` table (\"guests\"). Action \"Y\" will compile, but downstream\nscoped-db queries inside execute() may 403 because ctx.activeOrgId /\nactiveTeamId cannot be stamped from the match row. Either add the tenant\ncolumn to \"guests\", or set firewall: { exception: true } on the action.\n```\n\nThe relationship match still works (existence check), but no tenant gets stamped β so the conventional precondition still fires and the action still 403s for callers without a session-resident tenant claim. Add the tenant column (or denormalize it onto the relationship table during writes) to enable the stamping path.\n\nThe body can then trust `ctx.event` and drop the hand-rolled `SELECT β¦ FROM guests WHERE β¦` boilerplate:\n\n```ts\n// features/chat/actions/getInbox.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"List the caller's chat inbox for one event they attend.\",\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role\n execute: async ({ db, ctx, input }) => {\n // No hand-rolled attendance check needed β the resolver already ran.\n // ctx.event is the loaded events row. Typed as `any` here because the\n // hand-rolled `roles: ['attendee']` action gates per-action, not per-\n // namespace β see \"Narrow ctx.<exposeAs> typing\" below for the typed\n // import flip available when the same hydration runs through a\n // namespace mount.\n const event = ctx.event as typeof events.$inferSelect;\n // β¦ domain logic only.\n },\n});\n```\n\n`loads` and `exposeAs` are co-required (set both or neither). `exposeAs` must be a valid JS identifier and must not collide with built-in `ctx` fields (`userId`, `activeOrgId`, `activeTeamId`, `db`, etc.).\n\n### Action firewall escape hatch (v0.19+)\n\n`defineAction({ firewall: { exception: true } })` opts the action out of the inherited session-key preconditions (`ctx.activeOrgId` / `ctx.activeTeamId` requirements) AND the relationship resolver. The handler receives `unsafeDb` for raw Drizzle access. Use for cross-tenant or admin routes whose surface intentionally doesn't name a session/relationship key:\n\n{/* doc-compile: skip β project-config prerequisite: `roles: [\"SYSADMIN\"]` requires `cms: { sysadmin: true }` in quickback.config.ts (documented above under SYSADMIN), and the gate compiles every fence against one fixed harness config that does not set it. */}\n```ts\n// features/admin/actions/crossTenantReport.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Report activity across every tenant for a date range (sysadmin only).\",\n path: '/admin/cross-tenant-report',\n input: z.object({ since: z.string(), until: z.string() }),\n firewall: { exception: true },\n unsafe: { reason: 'cross-tenant audit', adminOnly: true, targetScope: 'all' },\n access: { roles: ['SYSADMIN'] },\n execute: async ({ unsafeDb, ctx }) => { /* cross-org query */ },\n});\n```\n\n`firewall: { exception: true }` is the declarative twin of `unsafe: true` β they're conceptually distinct: `firewall.exception` opts out of the gate-emission pillars; `unsafe` signals audit/cross-tenant intent (and still applies for logging). Most cross-tenant actions set both.\n\n### Recommended pattern: gate at the firewall layer\n\nMost of the time, relationship-based row visibility is what you want, and putting it at the **firewall** layer is the cleanest expression. The firewall is row-filter; the access layer is route/role-filter; let each do its job:\n\n```typescript\n// features/sessions/sessions.ts\nfirewall: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { field: 'eventId', via: 'guestOf' }, // β row visibility\n],\nread: {\n access: { roles: ['admin', 'member'] }, // β who can hit the route\n views: {\n cms: { access: { roles: ['admin', 'member'] }, fields: [...] },\n guest: { access: { roles: ['member', 'admin'] }, fields: [...] },\n },\n},\n```\n\nA guest who's in your org as `member` can hit the endpoint and the firewall filters them down to events they're guests of. Cross-tenant access is impossible because the org filter is the outermost AND.\n\n### Cross-tenant \"my events\" dashboards are NOT this\n\nA common adjacent pattern β \"logged-in user wants `GET /my-events` returning events they're a guest of *across all tenants*\" β is **not** solved by relationship-roles. The tenant firewall is enforced at the outermost AND, so a guest of an event in another tenant remains correctly blocked.\n\nFor cross-tenant aggregation, use one of:\n\n- **User-scoped firewall**: `firewall: { owner: { column: 'userId' } }` β a flat per-user table.\n- **A standalone action that walks the relationship table itself** β see worked example below.\n\nDon't reach for relationship-roles first and then get confused when the tenant firewall blocks. The two patterns serve different problems.\n\n#### Worked example: `GET /my-events` standalone action\n\nThe cleanest expression of the cross-tenant attendee dashboard is a standalone action with a custom path that does its own join against the relationship table. The action is gated by `roles: ['AUTHENTICATED']` (any signed-in user can hit it; per-row scoping is the query itself), and the SQL filters by `ctx.userId` so each caller sees exactly the events they're a guest of:\n\n```ts\n// features/dashboard/actions/myEvents.ts\nimport { z } from 'zod';\nimport { eq, and, inArray } from 'drizzle-orm';\nimport { defineAction } from '../.quickback/define-action';\nimport { events } from '../../events/events';\nimport { guests } from '../../guests/guests';\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-backed rules in `masking.show` (use a relationship-gated view\n for field projection; action access is fully supported).\n\n## Outgrown this?\n\nWhen several actions share a path prefix *and* this gate, hoist it into a\n[feature area](/define/areas#namespace-mounts-hoisted-relationship-middleware) so the\nresolver runs once per request. When you need a permission *graph* β derived, inherited,\nhierarchical, or public share links β that's [rung 4 β FGA](/define/fga)."
|
|
195
203
|
},
|
|
196
204
|
"define/schema": {
|
|
197
205
|
"title": "Database Schema",
|
|
@@ -199,7 +207,7 @@ export const DOCS = {
|
|
|
199
207
|
},
|
|
200
208
|
"define/scopes": {
|
|
201
209
|
"title": "Scopes & Capability Grants",
|
|
202
|
-
"content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** β let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim β verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** β reads their event's announcements / sessions, not the org.\n- **Shuttle driver** β sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** β reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** β one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected β they keep their normal tenant access.\n\nMost scope principals are signed-in users who prove a relationship at [`/scope/v1/enter`](#2-enter-the-scope). But some have **no account at all** β an attendee who arrives by email + invite code, a kiosk/handout code, a partner token. For those, an action proves the principal its own way and [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) mints the same scope, no Better Auth user required.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing).\n\nScope kinds declare at root `authz` (visible everywhere) or inside a\n[feature area](/define/areas)'s `_area.ts` β then the kind, its bare\nrole aliases, the canonical `scope:<kind>:<role>` spellings, and `ctx.scope.<kind>` accessors\nare all visible to that area's subtree only (any outside reference is a compile error):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer β¦` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` β **no DB**. The claim is carried forward on every authed call (rolling refresh) for up to **15 minutes from the last actual relationship proof** β the mint stamps a proof timestamp (`sct`) that the refresh carries forward verbatim and checks against the carry-forward cap. Past the cap the refresh stops, the token expires within one TTL, and the client re-proves via `enter` (or any namespace route that mints) to restart the window.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts β the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: {\n id: q.id(),\n nameAtInvite: q.text().required(),\n email: q.text().required(),\n eventId: q.text().required(),\n shuttleId: q.text().optional(),\n pickupLocation: q.text().optional(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) β see [Firewall](/define/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening β a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only β it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm β written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) β is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` β a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert β no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n ...q.audit(),\n ...q.softDelete(),\n});\n```\n\nThe stamp is **insert-only** and null-safe β the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` β `ctx.activeOrgId`,\n`owner` β `ctx.userId`, `team` β `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n### Stamping a proven *identity* claim (`q.stamp`)\n\n`q.scope('event')` stamps the **tenant** id (`ctx.scope.event.id`). To stamp a\ndifferent **proven claim** off the same verified scope β the caller's own\n`subjectId` (the conferring row's PK) or a scalar sub-key β use\n[`q.stamp`](/define/schema#qstamp--proven-principal-identity-columns):\n\n```typescript\nauthorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }),\n```\n\nEvery proven scope carries `id`, `subjectId`, and any projected sub-keys; a\n`q.stamp` column reads one of those. Unlike `q.scope` it is **never** a firewall\narm (identity is not a tenant scope), and it force-stamps **only** for scope-only\nprincipals β an org member/admin/owner writes it via the org path. A scope-only\ncaller missing the claim gets a fail-closed **403**, never a `NULL` row.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/define/access#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest β so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role β an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched β so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role β it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` β see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver β and therefore the scope refresh and the\n[`mintScope`](#mintscope--mint-the-scope-token-from-the-namespace-resolver)\nmint β only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** β they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** β even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this β a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the Β§5.3 mint) into\nexistence:\n\n{/* doc-compile: skip β project-config prerequisite: the `manager+` gate needs `manager` in `auth.roleHierarchy`, and the gate compiles every fence against one fixed harness config whose roles are member/admin/owner. The file is otherwise whole. */}\n\n```typescript\n// features/events/actions/eventHome.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Return the event home payload for the caller's proven scope.\",\n path: '/event/:eventId/home', // β standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* β¦ */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` β mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header β so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes β mints the matched lane's role\n mintScope: true, // β fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> β carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe β the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role β `attendeeOf` β `scope.event.roles = ['attendee']`, `organizerOf` β `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role β it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/platform/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket β so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role β the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** β `auth.jwt.expiresIn` (default 180s), **clamped to a hard β€180s ceiling** at every signing site that emits a scope claim: both proven mints (`/scope/v1/enter`, the namespace resolver) *and* the middleware's rolling refresh. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable β an `auth.jwt.expiresIn` above the ceiling applies to plain tokens but never survives into a scope-bearing one.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) β never from request input β so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** β the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## `acceptScope` β accept an incoming scope claim as proof of entry\n\n`mintScope` is the resolver *minting* a scope claim after a `ctx.userId` lane\nmatches. **`acceptScope: '<kind>'` is the inverse: it lets the same resolver\n*accept* an already-minted `ctx.scope.<kind>` claim as its own proof** β so one\n`/event/:eventId/*` handler serves **both** the Better-Auth user (userId\nrelationship probe) **and** the sessionless scope principal (verified scope\nJWT, no account). It's the exact fast-path the realtime\n[ws-ticket](/platform/realtime/durable-objects) already has, ported to REST.\n\nWithout it, every scope-principal-facing namespaced action needs a **parallel\nPUBLIC twin** (a separate handler with a hand-rolled `requireScope` check and\nraw DB writes that bypass scoped-db) β double the surface, and \"someone forgot\nthe twin\" becomes a standing bug class. `acceptScope` retires the twin.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n inspectorOf: {\n from: 'site_inspectors',\n subject: { column: 'inspectorUserId', equals: 'ctx.userId' },\n resource: { column: 'locationId' },\n where: { status: 'active' },\n loads: 'locations',\n exposeAs: 'location',\n },\n },\n scopes: {\n location: {\n requestField: 'locationId',\n roles: {\n // supplied-reachable: a signed-in user AND a sessionless principal\n // converge on ONE scope:location:inspector.\n inspector: { via: 'inspectorOf', subKeys: ['inspectorId'], subject: 'both' },\n },\n },\n },\n namespaces: {\n locationScope: {\n prefix: '/location/:locationId',\n via: ['inspectorOf'],\n acceptScope: 'location', // β honor an incoming ctx.scope.location claim\n // mintScope: true, // β compose freely: a userId caller also re-mints\n },\n },\n}\n```\n\nA sessionless principal that already minted a token (via\n[`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) or `/scope/v1/enter`)\nthen hits the namespaced action directly, no second round-trip:\n\n```http\nGET /api/v1/location/loc_42/summary\nAuthorization: Bearer <scope-only-jwt carrying scope.location = { id: 'loc_42', roles: ['inspector'] }>\n\n200 OK\n```\n\nThe resolver reads `ctx.scope.location`, confirms its `id` equals the `:locationId`\nparam, sees the `inspector` role a supplied-reachable lane confers, and admits\nthe request β no `ctx.userId`, no DB relationship probe. `ctx.location` is\nhydrated through its own firewall exactly as it is for the userId caller.\n\n### Two locks (both required, fail-closed)\n\n`acceptScope` is **named-string only** β always the explicit kind, never a bare\n`true` (there's no inference from the `:param`). Default absent β the resolver\n**never** admits a scope principal (unchanged behavior). Beyond naming the kind,\nthe compiler enforces a second lock:\n\n1. **`acceptScope: '<kind>'`** opts *this namespace's* REST surface in, **and**\n2. at least one relationship lane of the namespace confers a `<kind>` role\n declared **`subject: 'supplied' | 'both'`** (supplied-reachable).\n\nA `subject: 'user'` role can be *minted* or *refreshed* by the namespace but can\n**never be accepted** from a token β a user-only role must be proven by a live\n`ctx.userId` probe. If `acceptScope` names a kind whose every conferring lane is\n`subject: 'user'`, the **compiler errors** rather than emit a dead fast-path.\nThe compiler also checks the kind is declared and its `requestField` equals the\nprefix's first `:param`.\n\n### Forging safety\n\nA scope principal can't use `acceptScope` to reach anything its token doesn't\nalready authorize:\n\n- **The claim is verified, not asserted** β `ctx.scope` is populated only from a\n JWT the auth middleware verified; the action can't write it.\n- **Named kind, not any-kind** β the fast-path reads `ctx.scope['<kind>']` for\n the declared kind (stricter than the ws-ticket's any-key loop); a colliding\n foreign-kind id can't open the gate.\n- **Instance pinned twice** β `entry.id === :param` in the gate, *and*\n `eq(loads.pk, :param)` in hydration. The principal enters exactly the instance\n its claim proved.\n- **Role β lane is exact and supplied-restricted** β each accept arm is one\n `(role, lane)` pair with `subject !== 'user'`; an `inspector` claim matches\n `inspectorOf`, never a sibling lane.\n- **No new enforcement surface** β firewall, masking, `access` arms, and\n scoped-db all read the same `ctx.scope` / `ctx.activeOrgId` they read for a\n userId caller. New proof source, zero new enforcement surface.\n\nThe tenant (`ctx.activeOrgId`) is sourced from the pinned-loaded resource\n(`ctx.<exposeAs>.organizationId`) β parity with the userId caller, not a new\ngrant. Fine-grained \"own rows only\" stays the resource author's job via a\nfirewall arm on `ctx.scope.<kind>.subjectId`, the **same** arm that already\nserves the userId principal.\n\n### Writes: audit fields for a userless principal\n\nA scope principal has no `ctx.userId`, so the scoped-db **audit wrapper** β which\nstamps `created_by` / `modified_by` β can't record a user. Rather than force a\nparallel raw-`db` write path (which would re-scatter the exact duplication\n`acceptScope` removes), the wrapper stamps the principal's synthetic, audit-only\nid β the token's `sub`, `scope:<kind>:<subjectId>` β into those columns:\n\n```ts\n// A verified scope principal's write, through the normal scoped db:\nawait db.insert(vendorCheckins).values({ eventId, note });\n// β created_by = modified_by = \"scope:event:guest_abc123\"\n```\n\nThe `scope:` prefix self-describes the actor (which kind, which subject), so no\nseparate \"actor type\" column is needed. This is the write-side companion to the\nread fast-path: **one handler body serves both a Better-Auth user and the\nsessionless principal, on reads and writes alike.**\n\nIt stays **fail-closed**: the relaxation fires *only* for `ctx.scopePrincipal\n=== true`. A write that reaches the wrapper with no `userId` and no scope\nprincipal (genuine auth-context loss) still throws β the audit layer never\nsilently logs an unauthenticated write. For a real system-side write outside any\nrequest, use the unwrapped `db` (`createDb`) directly, as before.\n\n## Sessionless scope mint β `ctx.mintScope`\n\n`POST /scope/v1/enter` and the namespace resolver both prove the relationship by\n**`ctx.userId`** β so they require a Better Auth account. But a legitimate\nprincipal often has none: an **event attendee who arrives by email + invite\ncode**, holding an opaque session token you validate yourself, who must never\nget a global account. The shape is general β magic links, kiosk/handout codes,\npartner-issued API keys, expiring share links that need row-level scope.\n\nFor these, prove the relationship **your own way** inside an action, then ask\nQuickback to mint a disciplined scope token from the row you proved.\n\n### 1. Opt the role into supplied-subject proof\n\nAdd `subject` to the scope role (default `'user'`):\n\n```typescript\nauthz: {\n scopes: {\n event: {\n requestField: 'eventId',\n roles: {\n // 'both' β the SAME scope:event:attendee for a logged-in user\n // (via /enter) AND a sessionless invite-holder (via ctx.mintScope).\n attendee: { via: 'attendeeOf', subKeys: ['guestId'], subject: 'both' },\n },\n },\n },\n}\n```\n\n- **`'user'`** (default) β `/scope/v1/enter` only, proven by `subject.column = ctx.userId`. Unchanged.\n- **`'supplied'`** β sessionless only. `ctx.mintScope` mints it; `/enter` won't (there's no user to probe).\n- **`'both'`** β either path. A user-attendee and a sessionless invite-attendee converge on **one** `scope:event:attendee` β one firewall arm, one masking rule, both principals.\n\nThis opt-in is the single fail-closed switch: without `'supplied'` or `'both'`, no relationship is mintable by a supplied id.\n\n### 2. Mint from the proven row\n\n`ctx.mintScope` is hydrated on `ctx` in **any action** when a `subject:\n'supplied' | 'both'` role is declared (including **PUBLIC** actions β the\ncanonical caller has no token yet). The action proves the principal however it\nlikes, then hands Quickback **only the conferring row's primary key**:\n\n```typescript\n// features/events/actions/enterEvent.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Redeem an invite code and mint the caller's event scope token.\",\n path: '/enter-event',\n method: 'POST',\n input: z.object({ code: z.string() }),\n access: { roles: ['PUBLIC'] }, // unauthenticated entry\n async execute({ ctx, input }) {\n const guestRowId = await validateInviteCode(ctx, input.code); // YOUR proof, YOUR table\n const { token } = await ctx.mintScope({ via: 'attendeeOf', subject: guestRowId });\n return { token }; // client sends it as `Authorization: Bearer β¦` thereafter\n },\n});\n```\n\nYou assert **nothing** about the scope. Quickback re-reads the `attendeeOf` row\nby primary key and takes the role, the resource id (`eventId`), the sub-keys,\nand the subject id **off that row** β so a buggy or hostile action can't forge\n`organizer`, can't pick a different event, and can't widen the slice. The only\nthing delegated to you is *which row* β exactly the opaque-credential check that\nhas to be custom code.\n\n| What you supply | What Quickback reads off the row |\n|---|---|\n| `via` (a declared `supplied`/`both` relationship) + `subject` (the `from`-row PK you proved) | the role, `id` (resource), sub-keys, and `subjectId` β none caller-asserted |\n\nThe `where:` filter runs on the mint probe exactly as at `/enter` β a cancelled\nor pending row confers nothing, so flipping a guest's `status` revokes them\nwithin one mint cycle (**β€180s**). Re-prove by calling `ctx.mintScope` again\n(your own refresh endpoint does exactly that). The by-PK probe does **not** apply\nthe relationship's tenant firewall (a sessionless principal has no\n`activeOrgId` yet β the proven row *is* what establishes scope), but matching by\nprimary key + the `where:` filter keeps it bounded and fail-closed.\n\n### 3. The scope-only token\n\n`ctx.mintScope` signs a **scope-only** JWT β it carries the `scope` claim and\nnothing else. There is **no user identity**: the auth middleware builds a context\nwith **`ctx.userId` undefined**, so every user-, org-, and owner-gated path\n**fails closed automatically** (an owner firewall compares against `undefined`\nβ matches nothing; org-role gates see empty `ctx.roles`). `AUTHENTICATED`\n**admits** a scope principal past the auth gate β it's the wrapper over session\n*and* scope callers (see [Access β Pseudo-roles](/define/access),\nwhere `SESSION` and `SCOPED` distinguish the two) β but a user/org/owner\n**firewall** then filters it to **zero rows** (no `ctx.userId`, no `ctx.activeOrgId`),\nso it reaches nothing it shouldn't. `USER` is likewise gate-permissive but\nfirewall-excluded: it mandates a `userId` scope the principal can't satisfy. To\nserve a scope principal actual rows, use `scope:<kind>:<role>` gates +\n`ctx.scope.<kind>` firewall arms (or `SCOPED` to admit any scope-token caller as\na tier).\n\nEverything downstream β REST firewall, masking, scoped-role access, the realtime\nws-ticket β then treats the sessionless attendee **identically** to a\nuser-proven one. There is no new enforcement surface; the principal is just\n`scope:event:attendee`.\n\n### `subjectId` β scoping to the person, not just the instance\n\nA user-proven scope scopes self-data (an attendee's travel, dietary, todos) by\n`ctx.userId`. A sessionless attendee has no `ctx.userId`, so the **proven\nsubject's identity rides in the claim** as a reserved **`subjectId`** β the\nconferring row's primary key:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\"], \"subjectId\": \"gst_42\" } }\n```\n\nScope self-data on it with one firewall arm:\n\n```typescript\n{ field: 'guestId', equals: 'ctx.scope.event.subjectId' }\n```\n\n`subjectId` is populated on **both** proof paths β `/scope/v1/enter` projects\nthe matched row's PK too β so the arm above is **one arm that serves both** a\nlogged-in attendee and a sessionless one. (It is distinct from\n`ctx.scope.event.id`, which is the *instance* β the event.)\n\n### Realtime\n\nA scope-only token authorizes the realtime\n[ws-ticket](/platform/realtime/durable-objects) directly off its proven\n`ctx.scope` claim β no `ctx.userId` re-probe. The sessionless attendee joins the\nsame per-event rooms (and per-attendee rooms keyed on `subjectId`) as a\nuser-attendee, carrying the same scope role on the ticket. So the REST gate and\nthe socket gate stay identical for accountless principals too.\n\n## Revocation & TTL\n\nThe scope claim is trusted between proofs β it is never re-checked against the database while it rides. Two bounds keep that window finite:\n\n- **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped β€180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.\n- **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while the claim's proof timestamp (`sct`, stamped exclusively by the proven mint sites) is younger than the cap. Past it the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship β which won't re-mint a revoked role.\n\nSo removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:\n\n- **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) β sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/configure/auth).\n- **`via` arms** β for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, {\n via: string;\n subKeys?: string[]; // 'col' β eq, 'col[]' β inArray\n subject?: 'user' | 'supplied' | 'both'; // who selects the conferring row (default 'user')\n }>;\n}\n\n// ctx.mintScope β present in actions when a `subject: 'supplied' | 'both'` role is declared\nctx.mintScope(opts: { via: string; subject: string; setAuthToken?: boolean }):\n Promise<{ token: string; scope: { id: string; roles: string[]; subjectId?: string } }>;\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `subject` defaults to `'user'`. `'supplied'`/`'both'` enable [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) (sessionless mint); `'supplied'` is **not** mintable via `/scope/v1/enter`.\n- `ctx.mintScope({ via, subject })` mints a **scope-only** token (no user identity, `ctx.userId` undefined) from the `from`-row whose PK is `subject` β reading the role, resource id, sub-keys, and `subjectId` off that row.\n- `subjectId` is the conferring row's primary key, populated on **both** proof paths β scope self-data on `ctx.scope.<kind>.subjectId`.\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
|
|
210
|
+
"content": "Org membership answers *\"which tenant is this caller in?\"* Scopes answer a different question: *\"this caller isn't an org member, but they're a **confirmed attendee of event E** β let them see exactly E's rows, as exactly the role they hold, and nothing else.\"*\n\nA **scope** is a tenant axis whose value is established by a **relationship you prove once** (at `POST /scope/v1/enter`) and then carry in a signed JWT claim β verified cryptographically on every later request with **no database round-trip**. It's the REST/JWT twin of the realtime ws-ticket.\n\n## When to use it\n\nReach for a scope when a principal must touch a bounded slice of an instance **without being an org member**:\n\n- **Event attendee** β reads their event's announcements / sessions, not the org.\n- **Shuttle driver** β sees only the passengers on *their* bus (a row slice), can DM them.\n- **F&B vendor** β reads dietary *counts*, zero attendee rows.\n- **Visiting nurse / carrier / contractor** β one patient's meds, one carrier's shipments.\n\nEach is *event-scoped* but a **distinct least-privilege role**. Org members are unaffected β they keep their normal tenant access.\n\nMost scope principals are signed-in users who prove a relationship at [`/scope/v1/enter`](#2-enter-the-scope). But some have **no account at all** β an attendee who arrives by email + invite code, a kiosk/handout code, a partner token. For those, an action proves the principal its own way and [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) mints the same scope, no Better Auth user required.\n\n## The model\n\n### 1. Declare relationships + scopes\n\nA scope **kind** (`event`) declares named **roles**, each conferred by a relationship whose `from` row carries the role (and optionally a **sub-key** for row slicing).\n\nScope kinds declare at root `authz` (visible everywhere) or inside a\n[feature area](/define/areas)'s `_area.ts` β then the kind, its bare\nrole aliases, the canonical `scope:<kind>:<role>` spellings, and `ctx.scope.<kind>` accessors\nare all visible to that area's subtree only (any outside reference is a compile error):\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },\n organizerOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'organizer' } },\n shuttleDriverOf: { from: 'staff', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'shuttleDriver' } },\n },\n scopes: {\n event: {\n requestField: 'eventId', // the body field the client sends to /enter\n roles: {\n attendee: { via: 'attendeeOf' },\n organizer: { via: 'organizerOf' },\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId'] }, // row-slice sub-key\n },\n },\n },\n}\n```\n\n### 2. Enter the scope\n\n```http\nPOST /scope/v1/enter (session OR existing JWT auth)\n{ \"eventId\": \"evt_123\" }\n```\n\nThe server probes **every declared role** for the proposed instance (one DB touch), and mints the proven roles + sub-keys into a signed JWT `scope` claim, returned via the `set-auth-token` header and the body:\n\n```jsonc\n// a shuttle driver who is also a confirmed guest\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\", \"shuttleDriver\"], \"shuttleId\": \"shA\" } }\n```\n\nThe client sends that JWT as `Authorization: Bearer β¦` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` β **no DB**. The claim is carried forward on every authed call (rolling refresh) for up to **15 minutes from the last actual relationship proof** β the mint stamps a proof timestamp (`sct`) that the refresh carries forward verbatim and checks against the carry-forward cap. Past the cap the refresh stops, the token expires within one TTL, and the client re-proves via `enter` (or any namespace route that mints) to restart the window.\n\n> **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.\n\n### 3. Gate the pillars\n\nScoped roles are referenced everywhere a pillar takes a role as the namespaced identifier **`scope:<kind>:<role>`**:\n\n```typescript\n// features/guests/guests.ts β the manifest, row-sliced + PII-masked\nexport default feature('guests', {\n columns: {\n id: q.id(),\n nameAtInvite: q.text().required(),\n email: q.text().required(),\n eventId: q.text().required(),\n shuttleId: q.text().optional(),\n pickupLocation: q.text().optional(),\n organizationId: q.scope('organization'),\n ...q.audit(),\n ...q.softDelete(),\n },\n // org staff see the whole event; a shuttle driver sees only their bus\n firewall: {\n any: [\n { field: 'organizationId', equals: 'ctx.activeOrgId' },\n { all: [\n { field: 'eventId', equals: 'ctx.scope.event' },\n { field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }, // sub-key row slice\n ] },\n ],\n },\n masking: {\n email: { type: 'email', show: { roles: ['admin', 'scope:event:organizer'] } }, // hidden from the driver\n },\n read: {\n views: {\n manifest: {\n fields: ['id', 'nameAtInvite', 'shuttleId', 'pickupLocation'],\n access: { roles: ['admin', 'scope:event:organizer', 'scope:event:shuttleDriver'] },\n },\n },\n },\n});\n```\n\n| Pillar | How it reads the scoped role |\n|--------|------------------------------|\n| **Firewall** (rows) | `all`/`any` arms keyed on `ctx.scope.<kind>` (+ sub-keys) β see [Firewall](/define/firewall) |\n| **Access** (verbs/views) | `access.roles: ['scope:event:shuttleDriver']` on CRUD, actions, and views |\n| **Masking** (fields) | `masking.<col>.show.roles` includes / excludes `scope:event:<role>` |\n\n## The org / scope split (security)\n\n**Scoped roles never merge into `ctx.roles`.** A `scope:*` identifier matches **only** the verified scope claim (`ctx.scope.<kind>.roles`); a bare org role (`admin`, `member`) matches **only** `ctx.roles`. The compiler enforces the split so an externally-provisioned `shuttleDriver` can **never** satisfy an `admin` gate by string coincidence, and a tampered scope claim can't impersonate an org role. This is the precondition for admitting limited outside users at all.\n\n## Sub-keys (row slicing)\n\nA role's `subKeys` name columns on the relationship's `from` row that are projected into the claim. A firewall arm then slices on them:\n\n```typescript\n{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }\n```\n\nBecause sub-key arms compose with `all`, an **absent** sub-key denies (`sql\\`1 = 0\\``) rather than widening β a driver can never see *all* shuttles by simply lacking the claim. The scope accessor is always emitted null-safe (`ctx.scope?.event?.shuttleId`), so an org caller who never entered the scope hits a clean deny, not a 500.\n\n### Set-valued sub-keys\n\nA driver may cover **more than one** bus. Append a `[]` marker to the\nsub-key name to project **every** matched `from` row's value into the claim\nas a `string[]`:\n\n```typescript\nroles: {\n shuttleDriver: { via: 'shuttleDriverOf', subKeys: ['shuttleId[]'] }, // set-valued\n}\n```\n\nThe `[]` is a marker only β it's stripped from the column name (the\nrelationship's `from` row still reads `shuttleId`). At `/scope/v1/enter` the\nproven rows union their values, so the claim carries an array:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"shuttleDriver\"], \"shuttleId\": [\"shA\", \"shC\"] } }\n```\n\nThe matching firewall arm β written exactly as for the scalar case\n(`{ field: 'shuttleId', equals: 'ctx.scope.event.shuttleId' }`) β is\n**rewritten by the compiler** to an `inArray` row-slice:\n\n```sql\nWHERE shuttle_id IN (ctx.scope?.event?.shuttleId ?? [])\n```\n\nThe `?? []` default makes an absent claim lower to `inArray(col, [])` β a\nclean DENY, never a malformed SQL fragment or a 500. A scalar sub-key (no\n`[]` marker) is untouched and keeps lowering to `eq`. You write the same\n`equals` arm either way; declaring `shuttleId[]` vs `shuttleId` in the scope\nrole is the only switch.\n\n## Auto-stamping the scope column on insert (`q.scope`)\n\n`q.scope('organization')` auto-stamps the tenant column on write, the same\nway `q.scope('owner')` stamps `ownerId`. A relationship-derived kind works\nidentically: `q.scope('event')` auto-stamps the column from the **verified\nscope claim** (`ctx.scope.event.id`) on insert β no need to pass `eventId`\nin the request body:\n\n```typescript\nexport const eventNotes = q.table('event_notes', {\n id: q.id(),\n eventId: q.scope('event'), // INSERT autofill from ctx.scope.event.id\n body: q.text().required(),\n organizationId: q.scope('organization'), // INSERT autofill from ctx.activeOrgId\n ...q.audit(),\n ...q.softDelete(),\n});\n```\n\nThe stamp is **insert-only** and null-safe β the generated CREATE handler\nwrites `eventId: ctx.scope?.event?.id`, so it never binds `undefined`. It\ndoes **not** add a read-time `WHERE` filter (that's the firewall's job; a\nread scoped to `eventId = ctx.scope.event.id` would be wrong here). Infra\nkinds map to their session fields (`organization` β `ctx.activeOrgId`,\n`owner` β `ctx.userId`, `team` β `ctx.activeTeamId`); any other kind maps to\n`ctx.scope.<kind>.id`.\n\n### Stamping a proven *identity* claim (`q.stamp`)\n\n`q.scope('event')` stamps the **tenant** id (`ctx.scope.event.id`). To stamp a\ndifferent **proven claim** off the same verified scope β the caller's own\n`subjectId` (the conferring row's PK) or a scalar sub-key β use\n[`q.stamp`](/define/schema#qstamp--proven-principal-identity-columns):\n\n```typescript\nauthorId: q.stamp({ fromScope: 'event', claim: 'subjectId' }),\n```\n\nEvery proven scope carries `id`, `subjectId`, and any projected sub-keys; a\n`q.stamp` column reads one of those. Unlike `q.scope` it is **never** a firewall\narm (identity is not a tenant scope), and it force-stamps **only** for scope-only\nprincipals β an org member/admin/owner writes it via the org path. A scope-only\ncaller missing the claim gets a fail-closed **403**, never a `NULL` row.\n\n## Namespace scope-claim refresh\n\nA scope is normally minted at `POST /scope/v1/enter`. When you also mount a\n[namespace](/define/areas#namespace-mounts-hoisted-relationship-middleware)\nthat gates `/event/:eventId/*` on the **same** relationship, the namespace\nresolver can refresh `ctx.scope.<kind>` in memory for the duration of that\nrequest β so an attendee hitting `/event/evt_123/announce` gets\n`ctx.scope.event = { id: 'evt_123', roles: ['attendee'] }` without a separate\n`enter` round-trip. The refresh runs **after** the gate (the gate proves the\nrelationship; the refresh stamps the proven role from the path param).\n\nThis is a strictly-guarded convenience, and it stamps **per matched lane**. The\nresolver records which `via:` lane opened the gate (first-match-wins) and stamps\n**only that lane's** scope role β an attendee who matched `attendeeOf` gets\n`roles: ['attendee']`; an organizer who matched `organizerOf` gets\n`roles: ['organizer']`. A caller can never receive a role they didn't prove this\nrequest.\n\n- **Relationship lanes** each confer their own scope role, stamped only when that exact lane matched β so a **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) refreshes the matched lane's role, not an ambiguous union.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) confers **no** scope role β it opens the gate via the caller's org role *without* proving any relationship, so there is nothing to stamp (stamping one would forge it). The gate still passes; the caller is simply authorized by their org role.\n\nThe refresh described so far is in-memory and single-request. To also hand the\ncaller a **persisted** scope token, opt the namespace into `mintScope` β see\nbelow.\n\n### Gotcha: a namespace only emits its resolver when it claims a standalone action\n\nThis is the single most common surprise (it has tripped up a customer): **a\nnamespace emits its resolver β and therefore the scope refresh and the\n[`mintScope`](#mintscope--mint-the-scope-token-from-the-namespace-resolver)\nmint β only when at least one STANDALONE action's `path:` falls under the\nnamespace prefix.**\n\nA standalone action declares its own `path:` (e.g.\n`path: '/event/:eventId/home'`), so the compiler can match it against the\nnamespace prefix and hoist it into the synthetic namespace routes file.\n**Record-based actions are different** β they mount under their resource's CRUD\nroutes (`/api/v1/guests/:id/checkin`), which live *outside* the\n`/event/:eventId` prefix. They never match the prefix, so they never get\nclaimed.\n\nA namespace that contains **only** record-based actions is therefore **inert**:\nnothing matches the prefix, no synthetic routes file is emitted, and so there\nis **no resolver, no scope refresh, and no mint** β even though the namespace\nis declared and validates cleanly. The middleware you expected to gate\n`/event/:eventId/*` simply isn't there.\n\nThe fix is to give the namespace at least one standalone action under the\nprefix. In `q-events`, `eventHome` exists precisely for this β a standalone\n`GET /event/:eventId/home` that pulls the resolver (and the Β§5.3 mint) into\nexistence:\n\n{/* doc-compile: skip β project-config prerequisite: the `manager+` gate needs `manager` in `auth.roleHierarchy`, and the gate compiles every fence against one fixed harness config whose roles are member/admin/owner. The file is otherwise whole. */}\n\n```typescript\n// features/events/actions/eventHome.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Return the event home payload for the caller's proven scope.\",\n path: '/event/:eventId/home', // β standalone path UNDER the namespace prefix\n method: 'GET',\n input: z.object({}),\n access: { roles: ['scope:event:attendee', 'scope:event:organizer', 'manager+'] },\n async execute({ db, ctx, c }) { /* β¦ */ },\n});\n```\n\nWith that action present, the `eventScope` resolver is emitted, runs the\n`attendeeOf` probe once per `/event/:eventId/*` request, stamps\n`ctx.scope.event`, and (because the namespace sets `mintScope: true`) mints the\nscope token. Without a standalone action under the prefix, none of that fires.\n\n## `mintScope` β mint the scope token from the namespace resolver\n\nA scope is normally minted by an explicit `POST /scope/v1/enter` round-trip.\nSetting **`mintScope: true`** on a namespace folds that mint into the\nnamespace resolver: on a successful relationship probe the resolver MINTS a\npersisted scope JWT and returns it via the `set-auth-token` header β so a\nnative client hitting `/event/:eventId/*` gets a scope token **without ever\ncalling `/scope/v1/enter`**.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'linkedUserId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'guests',\n exposeAs: 'guest',\n },\n },\n namespaces: {\n eventScope: {\n prefix: '/event/:eventId',\n via: ['attendeeOf'], // one or more lanes β mints the matched lane's role\n mintScope: true, // β fold the scope-token mint into the resolver\n },\n },\n}\n```\n\nA confirmed attendee then hits the standalone action under the prefix:\n\n```http\nGET /api/v1/event/evt_123/home\nAuthorization: Bearer <existing-jwt>\n\n200 OK\nset-auth-token: <new-scoped-jwt> β carries scope.event.roles = [\"attendee\"]\n```\n\nThe client stores the `set-auth-token` value and sends it as the bearer on\nevery subsequent `/event/:eventId/*` request. The JWT carries\n`scope.event = { id: 'evt_123', roles: ['attendee'] }`, so the scoped-role\naccess checks (`scope:event:attendee`) pass with no DB touch and no second\n`enter` call.\n\n`mintScope` is **opt-in per namespace** and defaults to `false`. With it off,\nthe resolver does the in-memory `ctx.scope.<kind>` refresh only (the section\nabove); subsequent requests must still call `/scope/v1/enter` for a persisted\ntoken.\n\n### Per-matched-lane minting (forging safety)\n\nThe mint stamps the scope role of **whichever lane matched**, gated on the\nfirst-match-wins probe β the *same* per-lane discipline as the in-memory stamp,\napplied here with higher stakes: a minted token **persists for its whole TTL**,\nso it can only ever carry the role the caller actually proved this request.\n\n- A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role β `attendeeOf` β `scope.event.roles = ['attendee']`, `organizerOf` β `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.\n- A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role β it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.\n\n> The realtime [ws-ticket](/platform/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket β so the socket gate and the REST gate stay identical.\n\nIn every suppressed case the gate still authorizes the request; only the mint\n(and the in-memory refresh) are skipped, and those callers obtain a scope\ntoken through `/scope/v1/enter` as usual. Flipping `mintScope: true` can never\nforge a scope role β the guard, not the flag, is the gate.\n\n### TTL and best-effort semantics\n\n- **TTL is the scope-token TTL** β `auth.jwt.expiresIn` (default 180s), **clamped to a hard β€180s ceiling** at every signing site that emits a scope claim: both proven mints (`/scope/v1/enter`, the namespace resolver) *and* the middleware's rolling refresh. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable β an `auth.jwt.expiresIn` above the ceiling applies to plain tokens but never survives into a scope-bearing one.\n- **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) β never from request input β so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).\n- **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** β the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.\n\n## `acceptScope` β accept an incoming scope claim as proof of entry\n\n`mintScope` is the resolver *minting* a scope claim after a `ctx.userId` lane\nmatches. **`acceptScope: '<kind>'` is the inverse: it lets the same resolver\n*accept* an already-minted `ctx.scope.<kind>` claim as its own proof** β so one\n`/event/:eventId/*` handler serves **both** the Better-Auth user (userId\nrelationship probe) **and** the sessionless scope principal (verified scope\nJWT, no account). It's the exact fast-path the realtime\n[ws-ticket](/platform/realtime/durable-objects) already has, ported to REST.\n\nWithout it, every scope-principal-facing namespaced action needs a **parallel\nPUBLIC twin** (a separate handler with a hand-rolled `requireScope` check and\nraw DB writes that bypass scoped-db) β double the surface, and \"someone forgot\nthe twin\" becomes a standing bug class. `acceptScope` retires the twin.\n\n```typescript\n// quickback.config.ts\nauthz: {\n relationships: {\n inspectorOf: {\n from: 'site_inspectors',\n subject: { column: 'inspectorUserId', equals: 'ctx.userId' },\n resource: { column: 'locationId' },\n where: { status: 'active' },\n loads: 'locations',\n exposeAs: 'location',\n },\n },\n scopes: {\n location: {\n requestField: 'locationId',\n roles: {\n // supplied-reachable: a signed-in user AND a sessionless principal\n // converge on ONE scope:location:inspector.\n inspector: { via: 'inspectorOf', subKeys: ['inspectorId'], subject: 'both' },\n },\n },\n },\n namespaces: {\n locationScope: {\n prefix: '/location/:locationId',\n via: ['inspectorOf'],\n acceptScope: 'location', // β honor an incoming ctx.scope.location claim\n // mintScope: true, // β compose freely: a userId caller also re-mints\n },\n },\n}\n```\n\nA sessionless principal that already minted a token (via\n[`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) or `/scope/v1/enter`)\nthen hits the namespaced action directly, no second round-trip:\n\n```http\nGET /api/v1/location/loc_42/summary\nAuthorization: Bearer <scope-only-jwt carrying scope.location = { id: 'loc_42', roles: ['inspector'] }>\n\n200 OK\n```\n\nThe resolver reads `ctx.scope.location`, confirms its `id` equals the `:locationId`\nparam, sees the `inspector` role a supplied-reachable lane confers, and admits\nthe request β no `ctx.userId`, no DB relationship probe. `ctx.location` is\nhydrated through its own firewall exactly as it is for the userId caller.\n\n### Two locks (both required, fail-closed)\n\n`acceptScope` is **named-string only** β always the explicit kind, never a bare\n`true` (there's no inference from the `:param`). Default absent β the resolver\n**never** admits a scope principal (unchanged behavior). Beyond naming the kind,\nthe compiler enforces a second lock:\n\n1. **`acceptScope: '<kind>'`** opts *this namespace's* REST surface in, **and**\n2. at least one relationship lane of the namespace confers a `<kind>` role\n declared **`subject: 'supplied' | 'both'`** (supplied-reachable).\n\nA `subject: 'user'` role can be *minted* or *refreshed* by the namespace but can\n**never be accepted** from a token β a user-only role must be proven by a live\n`ctx.userId` probe. If `acceptScope` names a kind whose every conferring lane is\n`subject: 'user'`, the **compiler errors** rather than emit a dead fast-path.\nThe compiler also checks the kind is declared and its `requestField` equals the\nprefix's first `:param`.\n\n### Forging safety\n\nA scope principal can't use `acceptScope` to reach anything its token doesn't\nalready authorize:\n\n- **The claim is verified, not asserted** β `ctx.scope` is populated only from a\n JWT the auth middleware verified; the action can't write it.\n- **Named kind, not any-kind** β the fast-path reads `ctx.scope['<kind>']` for\n the declared kind (stricter than the ws-ticket's any-key loop); a colliding\n foreign-kind id can't open the gate.\n- **Instance pinned twice** β `entry.id === :param` in the gate, *and*\n `eq(loads.pk, :param)` in hydration. The principal enters exactly the instance\n its claim proved.\n- **Role β lane is exact and supplied-restricted** β each accept arm is one\n `(role, lane)` pair with `subject !== 'user'`; an `inspector` claim matches\n `inspectorOf`, never a sibling lane.\n- **No new enforcement surface** β firewall, masking, `access` arms, and\n scoped-db all read the same `ctx.scope` / `ctx.activeOrgId` they read for a\n userId caller. New proof source, zero new enforcement surface.\n\nThe tenant (`ctx.activeOrgId`) is sourced from the pinned-loaded resource\n(`ctx.<exposeAs>.organizationId`) β parity with the userId caller, not a new\ngrant. Fine-grained \"own rows only\" stays the resource author's job via a\nfirewall arm on `ctx.scope.<kind>.subjectId`, the **same** arm that already\nserves the userId principal.\n\n### Writes: audit fields for a userless principal\n\nA scope principal has no `ctx.userId`, so the scoped-db **audit wrapper** β which\nstamps `created_by` / `modified_by` β can't record a user. Rather than force a\nparallel raw-`db` write path (which would re-scatter the exact duplication\n`acceptScope` removes), the wrapper stamps the principal's synthetic, audit-only\nid β the token's `sub`, `scope:<kind>:<subjectId>` β into those columns:\n\n```ts\n// A verified scope principal's write, through the normal scoped db:\nawait db.insert(vendorCheckins).values({ eventId, note });\n// β created_by = modified_by = \"scope:event:guest_abc123\"\n```\n\nThe `scope:` prefix self-describes the actor (which kind, which subject), so no\nseparate \"actor type\" column is needed. This is the write-side companion to the\nread fast-path: **one handler body serves both a Better-Auth user and the\nsessionless principal, on reads and writes alike.**\n\nIt stays **fail-closed**: the relaxation fires *only* for `ctx.scopePrincipal\n=== true`. A write that reaches the wrapper with no `userId` and no scope\nprincipal (genuine auth-context loss) still throws β the audit layer never\nsilently logs an unauthenticated write. For a real system-side write outside any\nrequest, use the unwrapped `db` (`createDb`) directly, as before.\n\n## Sessionless scope mint β `ctx.mintScope`\n\n`POST /scope/v1/enter` and the namespace resolver both prove the relationship by\n**`ctx.userId`** β so they require a Better Auth account. But a legitimate\nprincipal often has none: an **event attendee who arrives by email + invite\ncode**, holding an opaque session token you validate yourself, who must never\nget a global account. The shape is general β magic links, kiosk/handout codes,\npartner-issued API keys, expiring share links that need row-level scope.\n\nFor these, prove the relationship **your own way** inside an action, then ask\nQuickback to mint a disciplined scope token from the row you proved.\n\n### 1. Opt the role into supplied-subject proof\n\nAdd `subject` to the scope role (default `'user'`):\n\n```typescript\nauthz: {\n scopes: {\n event: {\n requestField: 'eventId',\n roles: {\n // 'both' β the SAME scope:event:attendee for a logged-in user\n // (via /enter) AND a sessionless invite-holder (via ctx.mintScope).\n attendee: { via: 'attendeeOf', subKeys: ['guestId'], subject: 'both' },\n },\n },\n },\n}\n```\n\n- **`'user'`** (default) β `/scope/v1/enter` only, proven by `subject.column = ctx.userId`. Unchanged.\n- **`'supplied'`** β sessionless only. `ctx.mintScope` mints it; `/enter` won't (there's no user to probe).\n- **`'both'`** β either path. A user-attendee and a sessionless invite-attendee converge on **one** `scope:event:attendee` β one firewall arm, one masking rule, both principals.\n\nThis opt-in is the single fail-closed switch: without `'supplied'` or `'both'`, no relationship is mintable by a supplied id.\n\n### 2. Mint from the proven row\n\n`ctx.mintScope` is hydrated on `ctx` in **any action** when a `subject:\n'supplied' | 'both'` role is declared (including **PUBLIC** actions β the\ncanonical caller has no token yet). The action proves the principal however it\nlikes, then hands Quickback **only the conferring row's primary key**:\n\n```typescript\n// features/events/actions/enterEvent.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Redeem an invite code and mint the caller's event scope token.\",\n path: '/enter-event',\n method: 'POST',\n input: z.object({ code: z.string() }),\n access: { roles: ['PUBLIC'] }, // unauthenticated entry\n async execute({ ctx, input }) {\n const guestRowId = await validateInviteCode(ctx, input.code); // YOUR proof, YOUR table\n const { token } = await ctx.mintScope({ via: 'attendeeOf', subject: guestRowId });\n return { token }; // client sends it as `Authorization: Bearer β¦` thereafter\n },\n});\n```\n\nYou assert **nothing** about the scope. Quickback re-reads the `attendeeOf` row\nby primary key and takes the role, the resource id (`eventId`), the sub-keys,\nand the subject id **off that row** β so a buggy or hostile action can't forge\n`organizer`, can't pick a different event, and can't widen the slice. The only\nthing delegated to you is *which row* β exactly the opaque-credential check that\nhas to be custom code.\n\n| What you supply | What Quickback reads off the row |\n|---|---|\n| `via` (a declared `supplied`/`both` relationship) + `subject` (the `from`-row PK you proved) | the role, `id` (resource), sub-keys, and `subjectId` β none caller-asserted |\n\nThe `where:` filter runs on the mint probe exactly as at `/enter` β a cancelled\nor pending row confers nothing, so flipping a guest's `status` revokes them\nwithin one mint cycle (**β€180s**). Re-prove by calling `ctx.mintScope` again\n(your own refresh endpoint does exactly that). The by-PK probe does **not** apply\nthe relationship's tenant firewall (a sessionless principal has no\n`activeOrgId` yet β the proven row *is* what establishes scope), but matching by\nprimary key + the `where:` filter keeps it bounded and fail-closed.\n\n### 3. The scope-only token\n\n`ctx.mintScope` signs a **scope-only** JWT β it carries the `scope` claim and\nnothing else. There is **no user identity**: the auth middleware builds a context\nwith **`ctx.userId` undefined**, so every user-, org-, and owner-gated path\n**fails closed automatically** (an owner firewall compares against `undefined`\nβ matches nothing; org-role gates see empty `ctx.roles`). `AUTHENTICATED`\n**admits** a scope principal past the auth gate β it's the wrapper over session\n*and* scope callers (see [Access β Pseudo-roles](/define/access),\nwhere `SESSION` and `SCOPED` distinguish the two) β but a user/org/owner\n**firewall** then filters it to **zero rows** (no `ctx.userId`, no `ctx.activeOrgId`),\nso it reaches nothing it shouldn't. `USER` is likewise gate-permissive but\nfirewall-excluded: it mandates a `userId` scope the principal can't satisfy. To\nserve a scope principal actual rows, use `scope:<kind>:<role>` gates +\n`ctx.scope.<kind>` firewall arms (or `SCOPED` to admit any scope-token caller as\na tier).\n\nEverything downstream β REST firewall, masking, scoped-role access, the realtime\nws-ticket β then treats the sessionless attendee **identically** to a\nuser-proven one. There is no new enforcement surface; the principal is just\n`scope:event:attendee`.\n\n### `subjectId` β scoping to the person, not just the instance\n\nA user-proven scope scopes self-data (an attendee's travel, dietary, todos) by\n`ctx.userId`. A sessionless attendee has no `ctx.userId`, so the **proven\nsubject's identity rides in the claim** as a reserved **`subjectId`** β the\nconferring row's primary key:\n\n```jsonc\n\"scope\": { \"event\": { \"id\": \"evt_123\", \"roles\": [\"attendee\"], \"subjectId\": \"gst_42\" } }\n```\n\nScope self-data on it with one firewall arm:\n\n```typescript\n{ field: 'guestId', equals: 'ctx.scope.event.subjectId' }\n```\n\n`subjectId` is populated on **both** proof paths β `/scope/v1/enter` projects\nthe matched row's PK too β so the arm above is **one arm that serves both** a\nlogged-in attendee and a sessionless one. (It is distinct from\n`ctx.scope.event.id`, which is the *instance* β the event.)\n\n### Realtime\n\nA scope-only token authorizes the realtime\n[ws-ticket](/platform/realtime/durable-objects) directly off its proven\n`ctx.scope` claim β no `ctx.userId` re-probe. The sessionless attendee joins the\nsame per-event rooms (and per-attendee rooms keyed on `subjectId`) as a\nuser-attendee, carrying the same scope role on the ticket. So the REST gate and\nthe socket gate stay identical for accountless principals too.\n\n## Revocation & TTL\n\nThe scope claim is trusted between proofs β it is never re-checked against the database while it rides. Two bounds keep that window finite:\n\n- **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped β€180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.\n- **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while the claim's proof timestamp (`sct`, stamped exclusively by the proven mint sites) is younger than the cap. Past it the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship β which won't re-mint a revoked role.\n\nSo removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:\n\n- **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) β sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/configure/auth).\n- **`via` arms** β for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.\n\n## Reference\n\n```typescript\n// AppContext (generated lib/types.ts)\nctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [subKey: string]: string | string[] | undefined }>;\n\n// authz.scopes.<kind>\n{\n requestField: string; // body field carrying the instance id\n roles: Record<string, {\n via: string;\n subKeys?: string[]; // 'col' β eq, 'col[]' β inArray\n subject?: 'user' | 'supplied' | 'both'; // who selects the conferring row (default 'user')\n }>;\n}\n\n// ctx.mintScope β present in actions when a `subject: 'supplied' | 'both'` role is declared\nctx.mintScope(opts: { via: string; subject: string; setAuthToken?: boolean }):\n Promise<{ token: string; scope: { id: string; roles: string[]; subjectId?: string } }>;\n```\n\n- `requestField` must equal every role-relationship's `resource.column`.\n- Each relationship's `from` table must exist and ship a generated firewall (it can't be `exception`).\n- A `subKeys` entry ending in `[]` is **set-valued** (lowers to `inArray`, minted as `string[]`); without the marker it's scalar (`eq`, minted as `string`).\n- `subject` defaults to `'user'`. `'supplied'`/`'both'` enable [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope) (sessionless mint); `'supplied'` is **not** mintable via `/scope/v1/enter`.\n- `ctx.mintScope({ via, subject })` mints a **scope-only** token (no user identity, `ctx.userId` undefined) from the `from`-row whose PK is `subject` β reading the role, resource id, sub-keys, and `subjectId` off that row.\n- `subjectId` is the conferring row's primary key, populated on **both** proof paths β scope self-data on `ctx.scope.<kind>.subjectId`.\n- `q.scope('<kind>')` auto-stamps the column from `ctx.scope.<kind>.id` on insert.\n- Generated route: `POST /scope/v1/enter` (mounted only when `authz.scopes` is declared)."
|
|
203
211
|
},
|
|
204
212
|
"define/sealed-protocol": {
|
|
205
213
|
"title": "Sealed protocol (qbseal:1)",
|
|
@@ -335,7 +343,7 @@ export const DOCS = {
|
|
|
335
343
|
},
|
|
336
344
|
"platform/realtime/using-realtime": {
|
|
337
345
|
"title": "Using Realtime",
|
|
338
|
-
"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// Note: /broadcast/v1 tracks contract.version β use /broadcast/v2 on contract-v2 projects.\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 subscribers who fall within the broadcast's audience. A broadcasting table's realtime config **must** declare `access: { roles: [...] }` β e.g. `access: { roles: [\"hiring-manager\", \"recruiter\"] }` delivers only to those roles. The audience is evaluated at fanout with the same uppercase pseudo-role semantics as REST (`PUBLIC` = everyone in the room, `AUTHENTICATED`, `USER`, `SYSADMIN`), plus concrete membership/scope roles. This is **fail-closed**: an empty or omitted audience delivers to no one (and is a compile error for a broadcasting resource). Applies to generated CRUD broadcasts and to [live view](/platform/realtime/live-views) `view_changes` deltas alike.\n\n### Named rules and gates in `requiredRoles`\n\nDeclared [`authz.roles`](/define/access#centrally-defined-access-rules) and [`authz.rules` gates](/define/access#named-gates-authzrules) can appear in `realtime.requiredRoles`. The compiler lowers them to flat static role names at build time, because the WebSocket ticket handshake has no DB in hand:\n\n- A named role lowers to its composing static roles; relationship (`via:`) arms contribute nothing at the handshake (the row-stream firewall enforces that dimension later) and emit a warning.\n- A **who-only gate** lowers as its `who`. A gate carrying `record:` or `firewall` arms is undecidable at the handshake β it contributes nothing, with a warning.\n- **Fail-closed rule:** a declared non-empty `requiredRoles` that lowers to an **empty** set is a **compile error**, never a silently-assigned `[]`. The error names which entries lowered to nothing and why. Fix it by referencing a who-only rule, adding a static BA/pseudo-role fallback arm, or dropping the undecidable entries and relying on the row-stream firewall.\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency. A `type: 'custom'` mask function can't run inside the Broadcaster β those columns broadcast as `[REDACTED]` (fail closed).\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast β all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client β note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## CloudEvents envelopes (contract v2)\n\nOn `contract: { version: \"v2\" }` the WebSocket endpoint moves to\n`/broadcast/v2` and every **data frame** is wrapped in a\n[CloudEvents 1.0](https://cloudevents.io) envelope at the Durable Object's\nsend boundary. Control frames (`pong`, `error`, `reauth_ok`) stay raw on both\nversions, and pinned-v1 projects keep the raw frames byte-identically.\n\n| v1 frame | CloudEvents `type` | `data` | extensions |\n|---|---|---|---|\n| `broadcast` (named invalidation) | the wire name verbatim | payload minus `version`/`reason` | `qbframe: \"broadcast\"`, `qbversion`, `qbreason` |\n| `postgres_changes` | `<project>.<table>.<insert\\|update\\|delete>` | `{ table, schema, eventType, new, old }` | `qbframe: \"postgres_changes\"` |\n| `view_changes` | `<project>.view.<viewName>.changed` | `{ view, rootId, delta }` | `qbframe: \"view_changes\"`, `qbseq` (the per-surface monotonic seq β your reconnect/gap-detection contract) |\n\nDiscriminate frames on the `qbframe` extension, **never** on payload keys β\nnamed-invalidation payloads are author-supplied maps, so a broadcast whose\npayload happens to carry `view`/`delta` or `table`/`eventType` keys must not\nbe mistaken for a system frame.\n\nA changeset's [`afterCommit`](/define/changesets#aftercommit--emit-a-realtime-signal-after-the-changeset-commits)\nbroadcast rides the **same `broadcast` frame** (the referenced typed event's\n`wireName` verbatim), so clients handle it exactly like any named invalidation β\none CloudEvent per aggregate write, carrying the mapped payload (e.g.\n`{ eventId, reservationId, occupantIds }`). Its optional root-row frame arrives\nas a normal `postgres_changes` frame on the table's room.\n\n```json\n{ \"specversion\": \"1.0\",\n \"id\": \"evt_9f2β¦\",\n \"source\": \"/broadcast/v2/websocket\",\n \"type\": \"event.mobile-bundle.changed\",\n \"time\": \"2026-07-20T12:00:00Z\",\n \"datacontenttype\": \"application/json\",\n \"qbframe\": \"broadcast\",\n \"qbversion\": 1, \"qbreason\": \"document.created\",\n \"data\": { \"eventId\": \"β¦\", \"documentId\": \"β¦\" } }\n```\n\nThe bundled CMS unwraps envelopes automatically. The full channel/message\ncatalog ships as `GET /asyncapi.json` (AsyncAPI 3.0), served under the same\nauth gating as `/openapi.json`. The catalog itself is not v2-only β any\nproject with realtime or webhooks serves it, on either contract version;\nwhat the pinned contract shapes is the message payload schemas it documents\n(raw frames on v1, the CloudEvents envelopes above on v2).\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](/platform/realtime/durable-objects) β Configuration, event formats, masking, and custom namespaces\n- [Masking](/define/masking) β Field masking configuration"
|
|
346
|
+
"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// Note: /broadcast/v1 tracks contract.version β use /broadcast/v2 on contract-v2 projects.\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 subscribers who fall within the broadcast's audience. A broadcasting table's realtime config **must** declare `access: { roles: [...] }` β e.g. `access: { roles: [\"hiring-manager\", \"recruiter\"] }` delivers only to those roles. The audience is evaluated at fanout with the same uppercase pseudo-role semantics as REST (`PUBLIC` = everyone in the room, `AUTHENTICATED`, `USER`, `SYSADMIN`), plus concrete membership/scope roles. This is **fail-closed**: an empty or omitted audience delivers to no one (and is a compile error for a broadcasting resource). Applies to generated CRUD broadcasts and to [live view](/platform/realtime/live-views) `view_changes` deltas alike.\n\n### Named rules and gates in `requiredRoles`\n\nDeclared [`authz.roles`](/define/authz-roles#centrally-defined-access-rules) and [`authz.rules` gates](/define/authz-roles#named-gates-authzrules) can appear in `realtime.requiredRoles`. The compiler lowers them to flat static role names at build time, because the WebSocket ticket handshake has no DB in hand:\n\n- A named role lowers to its composing static roles; relationship (`via:`) arms contribute nothing at the handshake (the row-stream firewall enforces that dimension later) and emit a warning.\n- A **who-only gate** lowers as its `who`. A gate carrying `record:` or `firewall` arms is undecidable at the handshake β it contributes nothing, with a warning.\n- **Fail-closed rule:** a declared non-empty `requiredRoles` that lowers to an **empty** set is a **compile error**, never a silently-assigned `[]`. The error names which entries lowered to nothing and why. Fix it by referencing a who-only rule, adding a static BA/pseudo-role fallback arm, or dropping the undecidable entries and relying on the row-stream firewall.\n\n### Per-Role Masking\n\nField values are masked according to the subscriber's role. For example, with this masking config:\n\n```typescript\nmasking: {\n ssn: { type: \"ssn\", show: { roles: [\"owner\"] } },\n}\n```\n\n- **Owner sees:** `{ ssn: \"123-45-6789\" }`\n- **Recruiter sees:** `{ ssn: \"*****6789\" }`\n\nMasking is pre-computed per-role (O(roles), not O(subscribers)) for efficiency. A `type: 'custom'` mask function can't run inside the Broadcaster β those columns broadcast as `[REDACTED]` (fail closed).\n\n### User-Specific Events\n\nEvents can target a specific user lane. Only that user receives the broadcast β all other connections on the same scope are skipped.\n\n### Scope Isolation\n\nEach WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.\n\n## Reconnection\n\nWebSocket connections can drop due to network issues. Implement reconnection logic in your client β note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:\n\n```typescript\nasync function connect() {\n // Get a fresh ticket each time\n const res = await fetch(\"/broadcast/v1/ws-ticket\", {\n method: \"POST\",\n headers: { Authorization: `Bearer ${sessionToken}` },\n body: JSON.stringify({ eventId: \"evt_123\" }),\n });\n const { wsTicket } = await res.json();\n\n const ws = new WebSocket(\n `wss://api.yourdomain.com/broadcast/v1/websocket?ws_ticket=${wsTicket}`\n );\n\n ws.onclose = () => {\n // Reconnect after delay\n setTimeout(connect, 2000);\n };\n\n ws.onmessage = (event) => {\n const msg = JSON.parse(event.data);\n handleMessage(msg);\n };\n\n return ws;\n}\n```\n\n## Environment\n\nNo additional environment variables are needed for realtime. The Broadcaster Durable Object runs inline in your main worker and reuses `BETTER_AUTH_SECRET` for WebSocket ticket signing.\n\nThe compiler generates the required `wrangler.toml` bindings automatically:\n\n```toml\n[[durable_objects.bindings]]\nname = \"BROADCASTER\"\nclass_name = \"Broadcaster\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"Broadcaster\"]\n```\n\n## CloudEvents envelopes (contract v2)\n\nOn `contract: { version: \"v2\" }` the WebSocket endpoint moves to\n`/broadcast/v2` and every **data frame** is wrapped in a\n[CloudEvents 1.0](https://cloudevents.io) envelope at the Durable Object's\nsend boundary. Control frames (`pong`, `error`, `reauth_ok`) stay raw on both\nversions, and pinned-v1 projects keep the raw frames byte-identically.\n\n| v1 frame | CloudEvents `type` | `data` | extensions |\n|---|---|---|---|\n| `broadcast` (named invalidation) | the wire name verbatim | payload minus `version`/`reason` | `qbframe: \"broadcast\"`, `qbversion`, `qbreason` |\n| `postgres_changes` | `<project>.<table>.<insert\\|update\\|delete>` | `{ table, schema, eventType, new, old }` | `qbframe: \"postgres_changes\"` |\n| `view_changes` | `<project>.view.<viewName>.changed` | `{ view, rootId, delta }` | `qbframe: \"view_changes\"`, `qbseq` (the per-surface monotonic seq β your reconnect/gap-detection contract) |\n\nDiscriminate frames on the `qbframe` extension, **never** on payload keys β\nnamed-invalidation payloads are author-supplied maps, so a broadcast whose\npayload happens to carry `view`/`delta` or `table`/`eventType` keys must not\nbe mistaken for a system frame.\n\nA changeset's [`afterCommit`](/define/changesets#aftercommit--emit-a-realtime-signal-after-the-changeset-commits)\nbroadcast rides the **same `broadcast` frame** (the referenced typed event's\n`wireName` verbatim), so clients handle it exactly like any named invalidation β\none CloudEvent per aggregate write, carrying the mapped payload (e.g.\n`{ eventId, reservationId, occupantIds }`). Its optional root-row frame arrives\nas a normal `postgres_changes` frame on the table's room.\n\n```json\n{ \"specversion\": \"1.0\",\n \"id\": \"evt_9f2β¦\",\n \"source\": \"/broadcast/v2/websocket\",\n \"type\": \"event.mobile-bundle.changed\",\n \"time\": \"2026-07-20T12:00:00Z\",\n \"datacontenttype\": \"application/json\",\n \"qbframe\": \"broadcast\",\n \"qbversion\": 1, \"qbreason\": \"document.created\",\n \"data\": { \"eventId\": \"β¦\", \"documentId\": \"β¦\" } }\n```\n\nThe bundled CMS unwraps envelopes automatically. The full channel/message\ncatalog ships as `GET /asyncapi.json` (AsyncAPI 3.0), served under the same\nauth gating as `/openapi.json`. The catalog itself is not v2-only β any\nproject with realtime or webhooks serves it, on either contract version;\nwhat the pinned contract shapes is the message payload schemas it documents\n(raw frames on v1, the CloudEvents envelopes above on v2).\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](/platform/realtime/durable-objects) β Configuration, event formats, masking, and custom namespaces\n- [Masking](/define/masking) β Field masking configuration"
|
|
339
347
|
},
|
|
340
348
|
"platform/schedules": {
|
|
341
349
|
"title": "Schedules (Cron)",
|
|
@@ -351,7 +359,7 @@ export const DOCS = {
|
|
|
351
359
|
},
|
|
352
360
|
"platform/storage/r2": {
|
|
353
361
|
"title": "File Storage (R2)",
|
|
354
|
-
"content": "Quickback provides built-in file storage using Cloudflare R2.\n\n## Two modes\n\n`defineFileStorage(\"cloudflare-r2\")` has two modes:\n\n- **Presign-only (default)** β emits just the `ctx.storage` signer (presigned\n PUT/GET URLs straight to R2). **No new D1, no `/storage/v1/*` endpoints, no\n files worker.** You compute keys and store file references in your own table.\n This is the recommended path for most apps and the lightest way to add\n uploads β see [Presigned uploads](#presigned-uploads-recommended).\n- **Managed (`managed: true`)** β adds the turnkey subsystem on top: a FILES_DB\n metadata database (buckets + objects), the `/storage/v1/*` upload/download/\n manage endpoints, and a public files worker for serving. Opt in only when you\n want buckets/objects handled for you instead of bringing your own media table.\n\n```ts\n// Presign-only (default) β ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem β adds FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true, bucketName: \"my-app-files\" })\n```\n\nNew projects can omit `bucketName` β it defaults to `<project>-media`, so the\nonly setup is `wrangler r2 bucket create <name>` once plus the R2 API-token\nsecrets. Existing projects set `bucketName` to a bucket they already have.\n\nThe sections below document the **managed** subsystem; for the default\npresign-only path jump to [Presigned uploads](#presigned-uploads-recommended).\n\n## Architecture\n\n```\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\nβ Your Application β\nβ β\nβ Upload/Manage Files Serve Files β\nβ βββββββββββββββββββββ ββββββββββββββ β\nβ api.yourdomain.com files.yourdomain.com β\nβ /storage/v1/* /* β\nβ β\nβ βββββββββββββββββββββββ βββββββββββββββββββββββ β\nβ β API Worker β β Files Worker β β\nβ β β β β β\nβ β POST /bucket β β GET /public/* β β\nβ β GET /bucket β β β No auth β β\nβ β POST /object/* β β β β\nβ β DELETE /object/* β β GET /* β β\nβ β β β β Session + RBAC β β\nβ ββββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ β\nβ β β β\nβ βββββββββββββ¬ββββββββββββββββββββ β\nβ β β\nβ βΌ β\nβ βββββββββββββββββββββββ β\nβ β R2 Bucket β β\nβ β quickback-files β β\nβ βββββββββββββββββββββββ β\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n```\n\n## Enabling File Storage\n\nAdd the `fileStorage` provider to your `quickback.config.ts`:\n\n```typescript\nexport default {\n name: 'my-app',\n providers: {\n runtime: { name: 'cloudflare' },\n database: { name: 'cloudflare-d1' },\n auth: { name: 'better-auth' },\n fileStorage: {\n name: 'cloudflare-r2',\n config: {\n binding: 'R2_BUCKET',\n bucketName: 'my-app-files',\n filesBinding: 'FILES_DB',\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],\n },\n },\n },\n};\n```\n\n## API Endpoints\n\n### Storage API (api.yourdomain.com/storage/v1)\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/bucket` | Create a bucket |\n| GET | `/bucket` | List buckets |\n| GET | `/bucket/:name` | Get bucket info |\n| DELETE | `/bucket/:name` | Delete bucket (must be empty) |\n| POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |\n| POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |\n| POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |\n| GET | `/object/:bucket/*path` | Download file |\n| HEAD | `/object/:bucket/*path` | Get file metadata |\n| DELETE | `/object/:bucket/*path` | Delete file (soft delete) |\n| GET | `/object` | List objects |\n| POST | `/url` | Get file URL for serving |\n\n### Files Worker (files.yourdomain.com)\n\n| Method | Path | Auth Required |\n|--------|------|---------------|\n| GET/HEAD | `/public/*` | No |\n| GET/HEAD | `/*` | Yes (session + RBAC) |\n\n## Buckets\n\nBuckets organize files and define access control policies.\n\n### Creating a Bucket\n\n```bash\nPOST /storage/v1/bucket\n{\n \"name\": \"avatars\",\n \"readScope\": \"organization\",\n \"writeScope\": \"organization\",\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\n### Scope Options\n\n| Scope | Read Behavior | Write Behavior |\n|-------|---------------|----------------|\n| `public` | Anyone can read | N/A |\n| `organization` | Org members only | Org members only |\n| `user` | Owner only | Owner only |\n\n### Role-Based Access\n\nYou can restrict operations to specific roles:\n\n```json\n{\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\", \"editor\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\nAn empty array `[]` means no role restriction (all authenticated users).\n\n## Uploading Files\n\n```bash\nPOST /storage/v1/object/avatars/profile.jpg\nContent-Type: image/jpeg\nContent-Length: 12345\n\n<binary data>\n```\n\nResponse:\n```json\n{\n \"id\": \"obj_123\",\n \"key\": \"org_abc/avatars/profile.jpg\",\n \"bucket\": \"avatars\",\n \"name\": \"profile.jpg\",\n \"size\": 12345,\n \"mimeType\": \"image/jpeg\",\n \"readScope\": \"organization\"\n}\n```\n\n## Presigned uploads (recommended)\n\nStreaming bytes through the Worker (`POST /object`) is fine for small files, but\nit puts every byte on the Worker's request path β subject to the body-size cap,\nand billed as Worker CPU/duration. For media (video, audio, large PDFs), use a\n**presigned URL**: the Worker runs all the access checks and hands back a\nshort-lived URL the client uploads to **directly**. The bytes never touch your\nWorker.\n\n```bash\n# 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)\ncurl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"video/mp4\", \"size\": 73400320 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc\",\n# \"key\": \"org_abc/videos/clip.mp4\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"video/mp4\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload the bytes straight to R2 (replay the returned headers verbatim)\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: video/mp4\" --data-binary @clip.mp4\n\n# 3. Confirm β reconciles the recorded size + etag against what actually landed\ncurl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Required secrets\n\nPresigning uses R2's S3-compatible API, which needs an **R2 API token** β the\nWorkers bucket binding alone cannot presign. Create a token in the Cloudflare\ndashboard (R2 β Manage API Tokens) and set:\n\n```bash\nwrangler secret put R2_ACCOUNT_ID # your Cloudflare account id\nwrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id\nwrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret\n# Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint\n```\n\n### Signing from your own action\n\nThe same signer is exposed as `ctx.storage` inside any\n[`defineAction`](/define/actions) β so you can author an upload endpoint that\nruns your own access rules (org, team, relationship/scoped roles) and stores the\nkey in **your own table**, instead of the generic `buckets`/`objects` metadata:\n\n```typescript title=\"quickback/features/events/actions/signMediaUpload.ts\"\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { images } from \"../images\";\n\nexport default defineAction({\n description: 'Issue a presigned R2 upload URL for a media file on an event.',\n path: '/event/:eventId/media/sign-upload',\n method: 'POST',\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: ['admin', 'member', 'scope:event:attendee'] },\n async execute({ input, ctx, db, storage }) {\n // Tenant-scoped key β secure by construction\n const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, {\n contentType: input.contentType,\n expiresIn: 600,\n });\n await db.insert(images).values({ key, eventId: input.eventId /* β¦ */ });\n return { uploadUrl: upload.url, key, headers: upload.headers };\n },\n});\n```\n\n`storage` exposes:\n\n| Method | Returns | Use |\n|--------|---------|-----|\n| `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |\n| `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |\n\nThis is the supported replacement for streaming a raw binary body through an\naction β the JSON body parser and its ~1 MiB cap stay on for every other route.\n\n## Serving Files\n\n### Public Files\n\nFiles in buckets with `readScope: \"public\"` are stored with a `public/` prefix:\n\n```\nhttps://files.yourdomain.com/public/org_abc/avatars/logo.png\n```\n\nNo authentication required.\n\n### Private Files\n\nPrivate files require a valid Better Auth session cookie:\n\n```\nhttps://files.yourdomain.com/org_abc/documents/report.pdf\n```\n\nThe files worker:\n1. Validates the session token\n2. Re-checks the caller's **current** membership in the object's organization\n3. Verifies role permissions (if `readRoles` configured)\n4. Serves the file or returns 403\n\n## Generated Files\n\nWhen file storage is configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |\n| `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |\n| `src/files/schema.ts` | Files database schema (buckets, objects) |\n| `cloudflare-workers/files/index.ts` | Files worker for serving |\n| `cloudflare-workers/files/wrangler.toml` | Files worker config |\n\nThe compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your\n`package.json` (used by the presigner) and the R2 presign secrets to your\ngenerated `CloudflareBindings` type.\n\n## Deployment\n\nAfter compiling:\n\n1. **Create the R2 bucket:**\n ```bash\n wrangler r2 bucket create my-app-files\n ```\n\n2. **Create the files database:**\n ```bash\n wrangler d1 create my-app-files\n ```\n\n3. **Run migrations:**\n ```bash\n wrangler d1 migrations apply my-app-files --local\n wrangler d1 migrations apply my-app-files --remote\n ```\n\n4. **Deploy the API:**\n ```bash\n wrangler deploy\n ```\n\n5. **Deploy the files worker:**\n ```bash\n cd cloudflare-workers/files\n wrangler deploy\n ```\n\n6. **Set the R2 presign secrets** (only if you use presigned uploads β see\n [Presigned uploads](#presigned-uploads-recommended)):\n ```bash\n wrangler secret put R2_ACCOUNT_ID\n wrangler secret put R2_ACCESS_KEY_ID\n wrangler secret put R2_SECRET_ACCESS_KEY\n ```\n\n## Configuration Reference\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |\n| `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |\n| `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |\n| `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |\n| `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |\n| `maxFileSize` | `number \\| string` | 10MB | Max upload size β bytes or `\"100mb\"` (managed mode) |\n| `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |\n| `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |\n\n## Security Model\n\n- **Upload security**: Enforced by API worker (auth middleware, org check, role check)\n- **Serve security**: Enforced by files worker (session validation, metadata RBAC)\n- **Soft deletes**: Files are marked deleted in metadata but retained in R2\n- **Tenant isolation**: All files are prefixed with organization ID"
|
|
362
|
+
"content": "Quickback provides built-in file storage using Cloudflare R2.\n\n## Two modes\n\n`defineFileStorage(\"cloudflare-r2\")` has two modes:\n\n- **Presign-only (default)** β emits just the `ctx.storage` signer (presigned\n PUT/GET URLs straight to R2). **No new D1, no `/storage/v1/*` endpoints, no\n files worker.** You compute keys and store file references in your own table.\n This is the recommended path for most apps and the lightest way to add\n uploads β see [Presigned uploads](#presigned-uploads-recommended).\n- **Managed (`managed: true`)** β adds the turnkey subsystem on top: a FILES_DB\n metadata database (buckets + objects), the `/storage/v1/*` upload/download/\n manage endpoints, and a public files worker for serving. Opt in only when you\n want buckets/objects handled for you instead of bringing your own media table.\n\n```ts\n// Presign-only (default) β ctx.storage against a bucket, nothing else\ndefineFileStorage(\"cloudflare-r2\", { bucketName: \"my-app-media\" })\n\n// Managed subsystem β adds FILES_DB + /storage/v1/* + files worker\ndefineFileStorage(\"cloudflare-r2\", { managed: true, bucketName: \"my-app-files\" })\n```\n\nNew projects can omit `bucketName` β it defaults to `<project>-media`, so the\nonly setup is `wrangler r2 bucket create <name>` once plus the R2 API-token\nsecrets. Existing projects set `bucketName` to a bucket they already have.\n\nThe sections below document the **managed** subsystem; for the default\npresign-only path jump to [Presigned uploads](#presigned-uploads-recommended).\n\n## Architecture\n\n```\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\nβ Your Application β\nβ β\nβ Upload/Manage Files Serve Files β\nβ βββββββββββββββββββββ ββββββββββββββ β\nβ api.yourdomain.com files.yourdomain.com β\nβ /storage/v1/* /* β\nβ β\nβ βββββββββββββββββββββββ βββββββββββββββββββββββ β\nβ β API Worker β β Files Worker β β\nβ β β β β β\nβ β POST /bucket β β GET /public/* β β\nβ β GET /bucket β β β No auth β β\nβ β POST /object/* β β β β\nβ β DELETE /object/* β β GET /* β β\nβ β β β β Session + RBAC β β\nβ ββββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ β\nβ β β β\nβ βββββββββββββ¬ββββββββββββββββββββ β\nβ β β\nβ βΌ β\nβ βββββββββββββββββββββββ β\nβ β R2 Bucket β β\nβ β quickback-files β β\nβ βββββββββββββββββββββββ β\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n```\n\n## Enabling File Storage\n\nAdd the `fileStorage` provider to your `quickback.config.ts`:\n\n```typescript\nexport default {\n name: 'my-app',\n providers: {\n runtime: { name: 'cloudflare' },\n database: { name: 'cloudflare-d1' },\n auth: { name: 'better-auth' },\n fileStorage: {\n name: 'cloudflare-r2',\n config: {\n binding: 'R2_BUCKET',\n bucketName: 'my-app-files',\n filesBinding: 'FILES_DB',\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],\n },\n },\n },\n};\n```\n\n## API Endpoints\n\n### Storage API (api.yourdomain.com/storage/v1)\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/bucket` | Create a bucket |\n| GET | `/bucket` | List buckets |\n| GET | `/bucket/:name` | Get bucket info |\n| DELETE | `/bucket/:name` | Delete bucket (must be empty) |\n| POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |\n| POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |\n| POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |\n| GET | `/object/:bucket/*path` | Download file |\n| HEAD | `/object/:bucket/*path` | Get file metadata |\n| DELETE | `/object/:bucket/*path` | Delete file (soft delete) |\n| GET | `/object` | List objects |\n| POST | `/url` | Get file URL for serving |\n\n### Files Worker (files.yourdomain.com)\n\n| Method | Path | Auth Required |\n|--------|------|---------------|\n| GET/HEAD | `/public/*` | No |\n| GET/HEAD | `/*` | Yes (session + RBAC) |\n\n## Buckets\n\nBuckets organize files and define access control policies.\n\n### Creating a Bucket\n\n```bash\nPOST /storage/v1/bucket\n{\n \"name\": \"avatars\",\n \"readScope\": \"organization\",\n \"writeScope\": \"organization\",\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\n### Scope Options\n\n| Scope | Read Behavior | Write Behavior |\n|-------|---------------|----------------|\n| `public` | Anyone can read | N/A |\n| `organization` | Org members only | Org members only |\n| `user` | Owner only | Owner only |\n\n### Role-Based Access\n\nYou can restrict operations to specific roles:\n\n```json\n{\n \"readRoles\": [\"admin\", \"member\"],\n \"writeRoles\": [\"admin\", \"editor\"],\n \"deleteRoles\": [\"admin\"]\n}\n```\n\nAn empty array `[]` means no role restriction (all authenticated users).\n\n## Uploading Files\n\n```bash\nPOST /storage/v1/object/avatars/profile.jpg\nContent-Type: image/jpeg\nContent-Length: 12345\n\n<binary data>\n```\n\nResponse:\n```json\n{\n \"id\": \"obj_123\",\n \"key\": \"org_abc/avatars/profile.jpg\",\n \"bucket\": \"avatars\",\n \"name\": \"profile.jpg\",\n \"size\": 12345,\n \"mimeType\": \"image/jpeg\",\n \"readScope\": \"organization\"\n}\n```\n\n## Presigned uploads (recommended)\n\nStreaming bytes through the Worker (`POST /object`) is fine for small files, but\nit puts every byte on the Worker's request path β subject to the body-size cap,\nand billed as Worker CPU/duration. For media (video, audio, large PDFs), use a\n**presigned URL**: the Worker runs all the access checks and hands back a\nshort-lived URL the client uploads to **directly**. The bytes never touch your\nWorker.\n\n```bash\n# 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)\ncurl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\" \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"contentType\": \"video/mp4\", \"size\": 73400320 }'\n\n# Response:\n# {\n# \"id\": \"obj_abc\",\n# \"key\": \"org_abc/videos/clip.mp4\",\n# \"uploadUrl\": \"https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...\",\n# \"method\": \"PUT\",\n# \"headers\": { \"Content-Type\": \"video/mp4\" },\n# \"expiresAt\": \"2026-06-02T12:10:00.000Z\"\n# }\n\n# 2. Upload the bytes straight to R2 (replay the returned headers verbatim)\ncurl -X PUT \"<uploadUrl>\" -H \"Content-Type: video/mp4\" --data-binary @clip.mp4\n\n# 3. Confirm β reconciles the recorded size + etag against what actually landed\ncurl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Required secrets\n\nPresigning uses R2's S3-compatible API, which needs an **R2 API token** β the\nWorkers bucket binding alone cannot presign. Create a token in the Cloudflare\ndashboard (R2 β Manage API Tokens) and set:\n\n```bash\nwrangler secret put R2_ACCOUNT_ID # your Cloudflare account id\nwrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id\nwrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret\n# Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint\n```\n\n### Signing from your own action\n\nThe same signer is exposed as `ctx.storage` inside any\n[`defineAction`](/define/actions) β so you can author an upload endpoint that\nruns your own access rules (org, team, relationship/scoped roles) and stores the\nkey in **your own table**, instead of the generic `buckets`/`objects` metadata:\n\n```typescript title=\"quickback/features/events/actions/signMediaUpload.ts\"\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { images } from \"../images\";\n\nexport default defineAction({\n description: 'Issue a presigned R2 upload URL for a media file on an event.',\n path: '/event/:eventId/media/sign-upload',\n method: 'POST',\n input: z.object({ filename: z.string(), contentType: z.string() }),\n access: { roles: ['admin', 'member', 'scope:event:attendee'] },\n async execute({ input, ctx, db, storage }) {\n // Tenant-scoped key β secure by construction\n const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;\n const upload = await storage.signPutUrl(key, {\n contentType: input.contentType,\n expiresIn: 600,\n });\n await db.insert(images).values({ key, eventId: input.eventId /* β¦ */ });\n return { uploadUrl: upload.url, key, headers: upload.headers };\n },\n});\n```\n\n`storage` exposes:\n\n| Method | Returns | Use |\n|--------|---------|-----|\n| `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |\n| `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |\n\nThis is the supported replacement for streaming a raw binary body through an\naction β the JSON body parser and its ~1 MiB cap stay on for every other route.\n\n## Serving Files\n\n### Public Files\n\nFiles in buckets with `readScope: \"public\"` are stored with a `public/` prefix:\n\n```\nhttps://files.yourdomain.com/public/org_abc/avatars/logo.png\n```\n\nNo authentication required.\n\n### Private Files\n\nPrivate files require a valid Better Auth session cookie:\n\n```\nhttps://files.yourdomain.com/org_abc/documents/report.pdf\n```\n\nThe files worker:\n1. Validates the session token\n2. Re-checks the caller's **current** membership in the object's organization\n3. Verifies role permissions (if `readRoles` configured)\n4. Serves the file or returns 403\n\n## Generated Files\n\nWhen file storage is configured, the compiler generates:\n\n| File | Purpose |\n|------|---------|\n| `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |\n| `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |\n| `src/files/schema.ts` | Files database schema (buckets, objects) |\n| `cloudflare-workers/files/index.ts` | Files worker for serving |\n| `cloudflare-workers/files/wrangler.toml` | Files worker config |\n\nThe compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your\n`package.json` (used by the presigner) and the R2 presign secrets to your\ngenerated `CloudflareBindings` type.\n\n## Deployment\n\nAfter compiling:\n\n1. **Create the R2 bucket:**\n ```bash\n wrangler r2 bucket create my-app-files\n ```\n\n2. **Create the files database:**\n ```bash\n wrangler d1 create my-app-files\n ```\n\n3. **Run migrations:**\n ```bash\n wrangler d1 migrations apply my-app-files --local\n wrangler d1 migrations apply my-app-files --remote\n ```\n\n4. **Deploy the API:**\n ```bash\n wrangler deploy\n ```\n\n5. **Deploy the files worker:**\n ```bash\n cd cloudflare-workers/files\n wrangler deploy\n ```\n\n6. **Set the R2 presign secrets** (only if you use presigned uploads β see\n [Presigned uploads](#presigned-uploads-recommended)):\n ```bash\n wrangler secret put R2_ACCOUNT_ID\n wrangler secret put R2_ACCESS_KEY_ID\n wrangler secret put R2_SECRET_ACCESS_KEY\n ```\n\n## Configuration Reference\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |\n| `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |\n| `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |\n| `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |\n| `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |\n| `maxFileSize` | `number \\| string` | 10MB | Max upload size β bytes or `\"100mb\"` (managed mode) |\n| `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |\n| `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |\n\n### How the size limit is enforced\n\n`maxFileSize` (and a bucket's `fileSizeLimit`) is enforced against bytes that\nactually arrive, not against what the client claims:\n\n- **Through-Worker uploads** (`POST /object/...`) are read through a byte\n counter that aborts the moment the limit is crossed, so nothing over-limit\n reaches R2. `Content-Length` is still checked first β it cheaply turns away\n honest oversized clients β but it is optional and client-supplied, so it is\n never the enforcement point.\n- **Presigned uploads** go straight from the client to R2, and the signature\n binds the content type, not the length. The `size` you declare at presign\n time is therefore advisory. `POST /confirm/...` HEADs the object, compares\n the real size against the bucket limit, and **deletes an over-limit object**\n rather than recording it β otherwise the declared-size check could be\n sidestepped by simply never calling confirm.\n\nBoth paths answer `413` with the actual and permitted byte counts.\n\n## Security Model\n\n- **Upload security**: Enforced by API worker (auth middleware, org check, role check)\n- **Serve security**: Enforced by files worker (session validation, metadata RBAC)\n- **Soft deletes**: Files are marked deleted in metadata but retained in R2\n- **Tenant isolation**: All files are prefixed with organization ID"
|
|
355
363
|
},
|
|
356
364
|
"platform/storage/using-kv": {
|
|
357
365
|
"title": "Using KV",
|
|
@@ -375,7 +383,7 @@ export const DOCS = {
|
|
|
375
383
|
},
|
|
376
384
|
"platform/webhooks/inbound": {
|
|
377
385
|
"title": "Inbound Webhooks",
|
|
378
|
-
"content": "Inbound webhooks allow external services (Stripe, Paddle, GitHub, etc.) to notify your API of events. Quickback generates endpoints that verify signatures, deduplicate events, and dispatch to your handler functions via a Cloudflare Queue.\n\n## Endpoint\n\n```\nPOST /webhooks/v1/inbound/:provider\n```\n\nThe `:provider` parameter identifies which service sent the webhook (e.g., `stripe`, `paddle`, `github`). Each provider has its own signature verification logic.\n\n## How It Works\n\n```\nExternal Service β POST /webhooks/v1/inbound/stripe\n β\n ββ 1. Verify signature (HMAC-SHA256)\n ββ 2. Parse event (provider-specific)\n ββ 3. Deduplicate via externalId\n ββ 4. Store in webhook_events table\n ββ 5. Enqueue for async processing\n ββ 6. Return 200 OK immediately\n\n Queue Consumer\n β\n ββ 1. Update status β 'processing'\n ββ 2. Call registered handlers\n ββ 3. Update status β 'processed' or 'failed'\n```\n\nThe API returns `200 OK` immediately after enqueuing. Your handler logic runs asynchronously via the queue consumer, so external services don't time out waiting for your processing to complete.\n\n## Registering Handlers\n\nUse `onWebhookEvent()` in your action code to register handlers for specific events:\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const { type, data, event, provider, env } = ctx;\n // ctx.event is the full Stripe envelope; ctx.data is event.data.object\n await createSubscription(data, env);\n});\n\n// Wildcard β handle all events from a provider\nonWebhookEvent(\"stripe:*\", async (ctx) => {\n console.log(`Received ${ctx.type} from ${ctx.provider}`);\n});\n```\n\n**Handler context:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `type` | `string` | Event type (e.g., `checkout.session.completed`) |\n| `data` | `unknown` | The convenience slice of the payload. For Stripe this is `event.data.object`. |\n| `event` | `unknown` | The **full event envelope**, exactly as the provider sent it β nothing dropped. For Stripe this carries `account` (Connect connected-account id), `id`, `livemode`, `api_version`, `request`, etc. |\n| `provider` | `string` | Provider name (e.g., `stripe`) |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\nFor `stripe:` patterns the context is typed automatically: `ctx.event` is a\n`StripeWebhookEvent` and `ctx.data` is its `data.object`, so `ctx.event.account`,\n`ctx.event.id`, and `ctx.event.livemode` are all typed with no cast.\n\n```typescript\nonWebhookEvent(\"stripe:invoice.paid\", async (ctx) => {\n ctx.event.account; // string | undefined β the acct_β¦ (Connect)\n ctx.event.id; // string β evt_β¦\n ctx.event.livemode; // boolean\n ctx.data; // event.data.object (Record<string, unknown>)\n});\n```\n\n`data.object` is an open record. Cast it when you need inner-field typing:\n\n```typescript\nconst session = ctx.data as import(\"stripe\").Stripe.Checkout.Session;\n```\n\n**Execution order:**\n1. Specific handlers run first (exact match on event type)\n2. Wildcard handlers run after\n3. All matching handlers run in parallel\n4. If any handler throws, the message is retried\n\n## Signature Verification\n\nEach provider verifies signatures differently. The secret is read from an environment variable.\n\n### Stripe\n\n**Environment variable:** `STRIPE_WEBHOOK_SECRET`\n\nStripe uses HMAC-SHA256 with a timestamp-based signature:\n\n```\nStripe-Signature: t=1614556800,v1=abc123...\n```\n\nThe signed payload is `<timestamp>.<raw_body>`. Verification checks:\n- HMAC matches\n- Timestamp is within 5 minutes (prevents replay attacks)\n\n#### Stripe Connect\n\nThe single-secret model is exactly what a Connect platform needs. With Standard\nconnected accounts and direct charges, each of your customers connects their own\nStripe account, and **one** webhook endpoint on your platform receives events\nfrom **all** connected accounts β every delivery signed with your **one**\nplatform signing secret.\n\n1. In the Stripe Dashboard, add a webhook endpoint pointing at\n `https://<your-api>/webhooks/v1/inbound/stripe` and enable **\"Listen to\n events on Connected accounts.\"**\n2. Set that endpoint's signing secret as `STRIPE_WEBHOOK_SECRET` (one secret\n covers every connected account β no per-account configuration).\n\nTo know **which connected account** an event belongs to, read the top-level\n`event.account` (an `acct_β¦` id) off the envelope via `ctx.event.account`. It is\n**not** inside `event.data.object`.\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const connectedAccount = ctx.event.account; // acct_β¦ β which organizer\n if (!connectedAccount) return; // platform-account event, ignore\n\n // Route to the org that owns this connected account, and validate the match.\n const org = await findOrgByStripeAccount(connectedAccount, ctx.env);\n if (!org) throw new Error(`Unknown connected account ${connectedAccount}`);\n\n await fulfillOrder(ctx.data, org, ctx.env);\n});\n```\n\n`ctx.data` remains `event.data.object` (the Checkout Session) for convenience;\n`ctx.event` gives you the rest of the envelope β `account`, `id`, `livemode`,\n`api_version`, `request` β so nothing about the delivery is lost.\n\n### Custom Providers\n\nProviders implement this interface:\n\n```typescript\ninterface InboundProvider {\n name: string;\n verifySignature(payload: string, signature: string, secret: string): Promise<boolean>;\n parseEvent(payload: string): {\n type: string;\n data: unknown; // convenience slice (e.g. Stripe's data.object)\n externalId?: string; // provider event id, for idempotency\n envelope?: unknown; // full event envelope, when available\n };\n}\n```\n\n## Idempotency\n\nEvents are deduplicated on the tuple `(provider, externalId)` (e.g., Stripe's `event.id`). The `webhook_events` table carries a **unique index** on this pair, and inbound delivery uses `INSERT β¦ ON CONFLICT DO NOTHING` so concurrent deliveries collapse deterministically:\n\n- The first delivery to win the race inserts the row, enqueues processing, and returns `{ received: true, eventId }`.\n- Any concurrent delivery with the same `(provider, externalId)` short-circuits and returns `{ received: true, duplicate: true }` β the queue is **never** sent the duplicate, so handlers run exactly once.\n\nEvents without an `externalId` (NULL) are not deduplicated. SQLite treats NULLs as distinct in unique indexes, so providers that don't supply a stable event ID continue to insert one row per delivery.\n\n### Migrating an existing deployment\n\nThe unique index was added in v0.10.x. Existing deployments may have duplicate rows from before the constraint existed; drizzle-kit's migration will fail until they are cleaned up. Run this once before applying the migration:\n\n```sql\nDELETE FROM webhook_events\nWHERE rowid NOT IN (\n SELECT MIN(rowid) FROM webhook_events\n WHERE external_id IS NOT NULL\n GROUP BY provider, external_id\n);\n```\n\nThis keeps the earliest row for each `(provider, external_id)` pair and discards the duplicates.\n\n## Database Schema\n\nInbound events are stored in the `webhook_events` table:\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `id` | text | Primary key (`whe_<uuid>`) |\n| `provider` | text | Provider name |\n| `eventType` | text | Event type from provider |\n| `externalId` | text | Provider's event ID (for deduplication) |\n| `payload` | text | Raw JSON payload |\n| `status` | text | `received`, `processing`, `processed`, `failed` |\n| `attempts` | integer | Processing attempt count |\n| `processedAt` | timestamp | When successfully processed |\n| `error` | text | Error message if failed |\n| `createdAt` | timestamp | When received |\n\n## Admin Routes\n\nTwo admin-only routes are generated for monitoring inbound webhooks:\n\n### List Events\n\n```\nGET /webhooks/v1/inbound/events\n```\n\nReturns recent inbound events with their status. Requires admin role.\n\n### Retry Failed Event\n\n```\nPOST /webhooks/v1/inbound/events/:id/retry\n```\n\nRe-queues a failed event for processing. Requires admin role.\n\n## Error Handling\n\n- **Invalid signature** β Returns `401 Unauthorized`, event not stored\n- **Handler failure** β Event marked as `failed`, message retried (up to 3 times via queue)\n- **All retries exhausted** β Event remains in `failed` status; use the admin retry endpoint to re-process manually\n\n## Configuration\n\nWebhooks are enabled by setting `webhooksBinding` in your database config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nSet the provider secret as a Wrangler secret:\n\n```bash\nwrangler secret put STRIPE_WEBHOOK_SECRET\n```\n\n## See Also\n\n- [Outbound Webhooks](/platform/webhooks/outbound) β Send webhooks when data changes\n- [Queues](/platform/queues) β Background processing infrastructure\n\n## Verified webhook actions (`webhook:` on defineAction)\n\nFor gateways that should hit a **custom action** rather than the queued\n`/webhooks/v1/inbound/:provider` pipeline, declare verification on the action\nitself. Verification runs **before** JSON parse, input validation, and access\nevaluation, over the raw request bytes β and it is additive to the access\ngate (a PUBLIC webhook action keeps its public-audit block).\n\n```ts title=\"quickback/features/comms/actions/sesDeliveryWebhook.ts\"\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Receive SES delivery notifications and record the message outcome.\",\n path: \"/comms/hooks/delivery\",\n method: \"POST\",\n access: { roles: [\"PUBLIC\"] },\n webhook: {\n verify: \"standard-webhooks\", // webhook-id / webhook-timestamp / webhook-signature\n secretEnv: \"SES_WEBHOOK_SECRET\", // env binding, validated at compile time\n tolerance: 300, // seconds (default 300)\n },\n input: z.object({ messageId: z.string(), event: z.string() }),\n execute: async ({ input }) => { /* ... */ },\n});\n```\n\nFor gateways speaking `sha256=`-hex HMAC instead of Standard Webhooks:\n\n```ts\nwebhook: {\n verify: {\n scheme: \"hmac-sha256\",\n header: \"X-Signature\",\n prefix: \"sha256=\",\n timestampHeader: \"X-Webhook-Timestamp\",\n signedContent: \"timestamp.body\", // MAC covers `${timestamp}.${rawBody}`\n tolerance: 300,\n },\n secretEnv: \"WEBHOOK_SIGNING_SECRET\",\n}\n```\n\n**Replay semantics β read this before choosing `signedContent`:** a tolerance\nwindow only closes replay when the timestamp is *inside* the signed content.\nWith `signedContent: \"body\"` the MAC covers raw bytes only, so a captured\nrequest can be replayed forever with a fresh timestamp header β which is why\nthe compiler **rejects** `tolerance`/`timestampHeader` on body-only schemes\ninstead of pretending they help. Pair body-only receivers with\n[`Idempotency-Key`](/platform/api-contract) or gateway-event-id dedupe.\n\nFor AWS SNS (SES/SMS event topics) β asymmetric X.509 verification, no shared\nsecret:\n\n```ts\nwebhook: {\n verify: {\n scheme: \"aws-sns\",\n topicArnsEnv: \"AWS_SES_SNS_TOPIC_ARNS\", // comma-separated allowlist (REQUIRED)\n // autoConfirmSubscription: true (default) β verified SubscriptionConfirmation\n // handshakes are completed and short-circuited; your action never runs for them.\n },\n}\n```\n\n`topicArnsEnv` is **compile-required**: without a TopicArn allowlist the\nsignature check proves only \"AWS signed it\" β any AWS account could create\nits own topic, subscribe your endpoint (auto-confirmed by the handshake),\nand deliver arbitrary messages that pass verification. The compiler refuses\nthe declaration rather than defaulting to accept-any-topic.\n\nThe signing certificate URL and SubscribeURL are validated against the\n`sns.<region>.amazonaws.com` allowlist before any fetch; a topic allowlist\nthat resolves empty at runtime fails closed (500). The signed `Timestamp`\nis bounded to a 1-hour tolerance window β it sits *inside* the signed\ncanonical string, so this is a real replay bound (a captured envelope stops\nreplaying), while staying generous enough for SNS's own delivery retries,\nwhich re-send the original signed envelope.\n\n**Fail-closed runtime posture for every scheme:** an unset secret env is a\n500 rejection β never a verify-skip; any signature failure is a 401 Problem\nbefore the body is ever parsed."
|
|
386
|
+
"content": "Inbound webhooks allow external services (Stripe, Paddle, GitHub, etc.) to notify your API of events. Quickback generates endpoints that verify signatures, deduplicate events, and dispatch to your handler functions via a Cloudflare Queue.\n\n## Endpoint\n\n```\nPOST /webhooks/v1/inbound/:provider\n```\n\nThe `:provider` parameter identifies which service sent the webhook (e.g., `stripe`, `paddle`, `github`). Each provider has its own signature verification logic.\n\n## How It Works\n\n```\nExternal Service β POST /webhooks/v1/inbound/stripe\n β\n ββ 1. Read body, capped at 1 MiB (413 if exceeded)\n ββ 2. Verify signature (HMAC-SHA256)\n ββ 3. Parse event (provider-specific)\n ββ 4. Deduplicate via externalId\n ββ 5. Store in webhook_events table\n ββ 6. Enqueue for async processing\n ββ 7. Return 200 OK immediately\n\n Queue Consumer\n β\n ββ 1. Update status β 'processing'\n ββ 2. Call registered handlers\n ββ 3. Update status β 'processed' or 'failed'\n```\n\nThe API returns `200 OK` immediately after enqueuing. Your handler logic runs asynchronously via the queue consumer, so external services don't time out waiting for your processing to complete.\n\n## Registering Handlers\n\nUse `onWebhookEvent()` in your action code to register handlers for specific events:\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const { type, data, event, provider, env } = ctx;\n // ctx.event is the full Stripe envelope; ctx.data is event.data.object\n await createSubscription(data, env);\n});\n\n// Wildcard β handle all events from a provider\nonWebhookEvent(\"stripe:*\", async (ctx) => {\n console.log(`Received ${ctx.type} from ${ctx.provider}`);\n});\n```\n\n**Handler context:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `type` | `string` | Event type (e.g., `checkout.session.completed`) |\n| `data` | `unknown` | The convenience slice of the payload. For Stripe this is `event.data.object`. |\n| `event` | `unknown` | The **full event envelope**, exactly as the provider sent it β nothing dropped. For Stripe this carries `account` (Connect connected-account id), `id`, `livemode`, `api_version`, `request`, etc. |\n| `provider` | `string` | Provider name (e.g., `stripe`) |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\nFor `stripe:` patterns the context is typed automatically: `ctx.event` is a\n`StripeWebhookEvent` and `ctx.data` is its `data.object`, so `ctx.event.account`,\n`ctx.event.id`, and `ctx.event.livemode` are all typed with no cast.\n\n```typescript\nonWebhookEvent(\"stripe:invoice.paid\", async (ctx) => {\n ctx.event.account; // string | undefined β the acct_β¦ (Connect)\n ctx.event.id; // string β evt_β¦\n ctx.event.livemode; // boolean\n ctx.data; // event.data.object (Record<string, unknown>)\n});\n```\n\n`data.object` is an open record. Cast it when you need inner-field typing:\n\n```typescript\nconst session = ctx.data as import(\"stripe\").Stripe.Checkout.Session;\n```\n\n**Execution order:**\n1. Specific handlers run first (exact match on event type)\n2. Wildcard handlers run after\n3. All matching handlers run in parallel\n4. If any handler throws, the message is retried\n\n## Signature Verification\n\nEach provider verifies signatures differently. The secret is read from an environment variable.\n\n### Stripe\n\n**Environment variable:** `STRIPE_WEBHOOK_SECRET`\n\nStripe uses HMAC-SHA256 with a timestamp-based signature:\n\n```\nStripe-Signature: t=1614556800,v1=abc123...\n```\n\nThe signed payload is `<timestamp>.<raw_body>`. Verification checks:\n- HMAC matches\n- Timestamp is within 5 minutes (prevents replay attacks)\n\n#### Stripe Connect\n\nThe single-secret model is exactly what a Connect platform needs. With Standard\nconnected accounts and direct charges, each of your customers connects their own\nStripe account, and **one** webhook endpoint on your platform receives events\nfrom **all** connected accounts β every delivery signed with your **one**\nplatform signing secret.\n\n1. In the Stripe Dashboard, add a webhook endpoint pointing at\n `https://<your-api>/webhooks/v1/inbound/stripe` and enable **\"Listen to\n events on Connected accounts.\"**\n2. Set that endpoint's signing secret as `STRIPE_WEBHOOK_SECRET` (one secret\n covers every connected account β no per-account configuration).\n\nTo know **which connected account** an event belongs to, read the top-level\n`event.account` (an `acct_β¦` id) off the envelope via `ctx.event.account`. It is\n**not** inside `event.data.object`.\n\n```typescript\nonWebhookEvent(\"stripe:checkout.session.completed\", async (ctx) => {\n const connectedAccount = ctx.event.account; // acct_β¦ β which organizer\n if (!connectedAccount) return; // platform-account event, ignore\n\n // Route to the org that owns this connected account, and validate the match.\n const org = await findOrgByStripeAccount(connectedAccount, ctx.env);\n if (!org) throw new Error(`Unknown connected account ${connectedAccount}`);\n\n await fulfillOrder(ctx.data, org, ctx.env);\n});\n```\n\n`ctx.data` remains `event.data.object` (the Checkout Session) for convenience;\n`ctx.event` gives you the rest of the envelope β `account`, `id`, `livemode`,\n`api_version`, `request` β so nothing about the delivery is lost.\n\n### Custom Providers\n\nProviders implement this interface:\n\n```typescript\ninterface InboundProvider {\n name: string;\n verifySignature(payload: string, signature: string, secret: string): Promise<boolean>;\n parseEvent(payload: string): {\n type: string;\n data: unknown; // convenience slice (e.g. Stripe's data.object)\n externalId?: string; // provider event id, for idempotency\n envelope?: unknown; // full event envelope, when available\n };\n}\n```\n\n## Idempotency\n\nEvents are deduplicated on the tuple `(provider, externalId)` (e.g., Stripe's `event.id`). The `webhook_events` table carries a **unique index** on this pair, and inbound delivery uses `INSERT β¦ ON CONFLICT DO NOTHING` so concurrent deliveries collapse deterministically:\n\n- The first delivery to win the race inserts the row, enqueues processing, and returns `{ received: true, eventId }`.\n- Any concurrent delivery with the same `(provider, externalId)` short-circuits and returns `{ received: true, duplicate: true }` β the queue is **never** sent the duplicate, so handlers run exactly once.\n\nEvents without an `externalId` (NULL) are not deduplicated. SQLite treats NULLs as distinct in unique indexes, so providers that don't supply a stable event ID continue to insert one row per delivery.\n\n### Migrating an existing deployment\n\nThe unique index was added in v0.10.x. Existing deployments may have duplicate rows from before the constraint existed; drizzle-kit's migration will fail until they are cleaned up. Run this once before applying the migration:\n\n```sql\nDELETE FROM webhook_events\nWHERE rowid NOT IN (\n SELECT MIN(rowid) FROM webhook_events\n WHERE external_id IS NOT NULL\n GROUP BY provider, external_id\n);\n```\n\nThis keeps the earliest row for each `(provider, external_id)` pair and discards the duplicates.\n\n## Database Schema\n\nInbound events are stored in the `webhook_events` table:\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `id` | text | Primary key (`whe_<uuid>`) |\n| `provider` | text | Provider name |\n| `eventType` | text | Event type from provider |\n| `externalId` | text | Provider's event ID (for deduplication) |\n| `payload` | text | Raw JSON payload |\n| `status` | text | `received`, `processing`, `processed`, `failed` |\n| `attempts` | integer | Processing attempt count |\n| `processedAt` | timestamp | When successfully processed |\n| `error` | text | Error message if failed |\n| `createdAt` | timestamp | When received |\n\n## Admin Routes\n\nTwo admin-only routes are generated for monitoring inbound webhooks:\n\n### List Events\n\n```\nGET /webhooks/v1/inbound/events\n```\n\nReturns recent inbound events with their status. Requires admin role.\n\n### Retry Failed Event\n\n```\nPOST /webhooks/v1/inbound/events/:id/retry\n```\n\nRe-queues a failed event for processing. Requires admin role.\n\n## Error Handling\n\n- **Invalid signature** β Returns `401 Unauthorized`, event not stored\n- **Handler failure** β Event marked as `failed`, message retried (up to 3 times via queue)\n- **All retries exhausted** β Event remains in `failed` status; use the admin retry endpoint to re-process manually\n\n## Configuration\n\nWebhooks are enabled by setting `webhooksBinding` in your database config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nSet the provider secret as a Wrangler secret:\n\n```bash\nwrangler secret put STRIPE_WEBHOOK_SECRET\n```\n\n## See Also\n\n- [Outbound Webhooks](/platform/webhooks/outbound) β Send webhooks when data changes\n- [Queues](/platform/queues) β Background processing infrastructure\n\n## Verified webhook actions (`webhook:` on defineAction)\n\nFor gateways that should hit a **custom action** rather than the queued\n`/webhooks/v1/inbound/:provider` pipeline, declare verification on the action\nitself. Verification runs **before** JSON parse, input validation, and access\nevaluation, over the raw request bytes β and it is additive to the access\ngate (a PUBLIC webhook action keeps its public-audit block).\n\n```ts title=\"quickback/features/comms/actions/sesDeliveryWebhook.ts\"\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Receive SES delivery notifications and record the message outcome.\",\n path: \"/comms/hooks/delivery\",\n method: \"POST\",\n access: { roles: [\"PUBLIC\"] },\n webhook: {\n verify: \"standard-webhooks\", // webhook-id / webhook-timestamp / webhook-signature\n secretEnv: \"SES_WEBHOOK_SECRET\", // env binding, validated at compile time\n tolerance: 300, // seconds (default 300)\n },\n input: z.object({ messageId: z.string(), event: z.string() }),\n execute: async ({ input }) => { /* ... */ },\n});\n```\n\nFor gateways speaking `sha256=`-hex HMAC instead of Standard Webhooks:\n\n```ts\nwebhook: {\n verify: {\n scheme: \"hmac-sha256\",\n header: \"X-Signature\",\n prefix: \"sha256=\",\n timestampHeader: \"X-Webhook-Timestamp\",\n signedContent: \"timestamp.body\", // MAC covers `${timestamp}.${rawBody}`\n tolerance: 300,\n },\n secretEnv: \"WEBHOOK_SIGNING_SECRET\",\n}\n```\n\n**Replay semantics β read this before choosing `signedContent`:** a tolerance\nwindow only closes replay when the timestamp is *inside* the signed content.\nWith `signedContent: \"body\"` the MAC covers raw bytes only, so a captured\nrequest can be replayed forever with a fresh timestamp header β which is why\nthe compiler **rejects** `tolerance`/`timestampHeader` on body-only schemes\ninstead of pretending they help. Pair body-only receivers with\n[`Idempotency-Key`](/platform/api-contract) or gateway-event-id dedupe.\n\nFor AWS SNS (SES/SMS event topics) β asymmetric X.509 verification, no shared\nsecret:\n\n```ts\nwebhook: {\n verify: {\n scheme: \"aws-sns\",\n topicArnsEnv: \"AWS_SES_SNS_TOPIC_ARNS\", // comma-separated allowlist (REQUIRED)\n // autoConfirmSubscription: true (default) β verified SubscriptionConfirmation\n // handshakes are completed and short-circuited; your action never runs for them.\n },\n}\n```\n\n`topicArnsEnv` is **compile-required**: without a TopicArn allowlist the\nsignature check proves only \"AWS signed it\" β any AWS account could create\nits own topic, subscribe your endpoint (auto-confirmed by the handshake),\nand deliver arbitrary messages that pass verification. The compiler refuses\nthe declaration rather than defaulting to accept-any-topic.\n\nThe signing certificate URL and SubscribeURL are validated against the\n`sns.<region>.amazonaws.com` allowlist before any fetch; a topic allowlist\nthat resolves empty at runtime fails closed (500). The signed `Timestamp`\nis bounded to a 1-hour tolerance window β it sits *inside* the signed\ncanonical string, so this is a real replay bound (a captured envelope stops\nreplaying), while staying generous enough for SNS's own delivery retries,\nwhich re-send the original signed envelope.\n\n**Fail-closed runtime posture for every scheme:** an unset secret env is a\n500 rejection β never a verify-skip; any signature failure is a 401 Problem\nbefore the body is ever parsed."
|
|
379
387
|
},
|
|
380
388
|
"platform/webhooks": {
|
|
381
389
|
"title": "Webhooks",
|
|
@@ -385,9 +393,17 @@ export const DOCS = {
|
|
|
385
393
|
"title": "Outbound Webhooks",
|
|
386
394
|
"content": "Outbound webhooks notify external services when events happen in your API. Users register webhook endpoints, subscribe to event types, and receive signed HTTP POST requests when events are emitted.\n\n## Overview\n\nOutbound webhooks are a multi-step system:\n\n1. **Users register endpoints** via the REST API\n2. **Your code emits events** using `emitWebhookEvent()`\n3. **Quickback queues deliveries** for each matching endpoint\n4. **The queue consumer delivers** with retry and exponential backoff\n5. **Payloads are signed** with HMAC-SHA256 (Stripe-compatible format)\n\n## Emitting Events\n\nCall `emitWebhookEvent()` in your actions or custom routes:\n\n```typescript\nimport { emitWebhookEvent } from '../lib/webhooks/emit';\n\n// After creating a user\nconst newUser = await db.insert(users).values(data).returning();\n\nawait emitWebhookEvent(\n \"user.created\",\n newUser[0],\n { organizationId: ctx.activeOrgId },\n env\n);\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `eventType` | `string` | Event name (e.g., `user.created`) |\n| `payload` | `unknown` | Event data (auto-wrapped with metadata) |\n| `options` | `object` | `{ organizationId?, userId? }` β scope for endpoint matching |\n| `env` | `CloudflareBindings` | Cloudflare environment bindings |\n\n**Note:** The compiler does NOT auto-emit events after CRUD operations. You must call `emitWebhookEvent()` explicitly where you want webhooks triggered.\n\n## Event Types\n\nQuickback provides recommended event naming conventions:\n\n| Category | Events |\n|----------|--------|\n| User | `user.created`, `user.updated`, `user.deleted` |\n| Subscription | `subscription.created`, `subscription.updated`, `subscription.cancelled`, `subscription.renewed` |\n| Organization | `organization.created`, `organization.updated`, `organization.deleted`, `organization.member_added`, `organization.member_removed` |\n| File | `file.uploaded`, `file.deleted` |\n\nYou can emit any custom event type β these are conventions, not restrictions.\n\n## Payload Format\n\nThe emitted payload is wrapped automatically:\n\n```json\n{\n \"type\": \"user.created\",\n \"data\": {\n \"id\": \"usr_abc123\",\n \"name\": \"Jane Doe\",\n \"email\": \"jane@example.com\"\n },\n \"createdAt\": \"2025-01-15T10:00:00.000Z\"\n}\n```\n\n## Payload Signing\n\nEvery delivery is signed with HMAC-SHA256 using the endpoint's secret. The signature format is Stripe-compatible:\n\n```\nX-Webhook-Signature: t=1705312800,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd\n```\n\n**Signed payload:** `<timestamp>.<json_body>`\n\n**Additional headers:**\n\n| Header | Description |\n|--------|-------------|\n| `X-Webhook-Signature` | `t=<timestamp>,v1=<hmac>` |\n| `X-Webhook-Event` | Event type (e.g., `user.created`) |\n| `X-Webhook-Delivery` | Delivery ID for tracking |\n| `Content-Type` | `application/json` |\n\n### Verifying Signatures (Consumer Side)\n\n```typescript\nimport { createHmac, timingSafeEqual } from 'crypto';\n\nfunction verifyWebhook(payload: string, signature: string, secret: string): boolean {\n const [tPart, v1Part] = signature.split(',');\n const timestamp = tPart.replace('t=', '');\n const expectedSig = v1Part.replace('v1=', '');\n\n // Check timestamp (5 minute tolerance)\n const age = Date.now() / 1000 - parseInt(timestamp);\n if (age > 300) return false;\n\n const signed = `${timestamp}.${payload}`;\n const computed = createHmac('sha256', secret).update(signed).digest('hex');\n return timingSafeEqual(Buffer.from(computed), Buffer.from(expectedSig));\n}\n```\n\n## Endpoint Management API\n\n### Register an Endpoint\n\n```\nPOST /webhooks/v1/endpoints\n```\n\n```json\n{\n \"name\": \"My Integration\",\n \"url\": \"https://example.com/webhook\",\n \"events\": [\"user.created\", \"subscription.*\"]\n}\n```\n\n**Response (201):**\n\n```json\n{\n \"id\": \"wep_abc123\",\n \"name\": \"My Integration\",\n \"url\": \"https://example.com/webhook\",\n \"secret\": \"whsec_a1b2c3d4...\",\n \"events\": [\"user.created\", \"subscription.*\"],\n \"enabled\": true,\n \"createdAt\": \"2025-01-15T10:00:00.000Z\"\n}\n```\n\nThe `secret` is only returned on creation. Store it securely.\n\n### Event Pattern Matching\n\nEndpoints subscribe to events using patterns:\n\n| Pattern | Matches |\n|---------|---------|\n| `user.created` | Exact match only |\n| `user.*` | All user events |\n| `*` | All events |\n\n### Other Endpoints\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `GET` | `/webhooks/v1/endpoints` | List your endpoints |\n| `GET` | `/webhooks/v1/endpoints/:id` | Get endpoint details (secret masked) |\n| `PATCH` | `/webhooks/v1/endpoints/:id` | Update endpoint (name, url, events, enabled) |\n| `DELETE` | `/webhooks/v1/endpoints/:id` | Delete endpoint |\n| `GET` | `/webhooks/v1/endpoints/:id/deliveries` | List delivery attempts |\n| `POST` | `/webhooks/v1/endpoints/:id/test` | Send a test event |\n| `POST` | `/webhooks/v1/endpoints/:id/rotate-secret` | Generate a new signing secret |\n| `GET` | `/webhooks/v1/events` | List available event types |\n\n### Access Control\n\nEndpoints are scoped by `userId` or `organizationId`. Users can only manage their own endpoints. When emitting events, only endpoints matching the event's scope receive deliveries.\n\n### URL Validation (anti-SSRF)\n\nRegistered URLs are validated at registration and again before each delivery attempt. The default policy rejects:\n\n- Any scheme other than `https:` (matches Stripe, GitHub, and Slack webhook conventions)\n- Loopback hosts (`localhost`, `127.0.0.1`, `::1`)\n- Cloud metadata endpoints (`169.254.169.254`, `metadata.google.internal`)\n- RFC 1918 private ranges (`10/8`, `172.16/12`, `192.168/16`), `169.254/16`, and `0.0.0.0/8`\n- Hosts ending in `.internal` or `.local`\n\nPlaintext `http:` is rejected by default. To allow `http:` (e.g. for a self-hosted dev environment without TLS), set `webhookAllowInsecure: true` on the database provider config:\n\n```ts\n// quickback.config.ts\nproviders: {\n database: {\n name: 'cloudflare-d1',\n config: {\n webhooksBinding: 'WEBHOOKS_DB',\n webhookAllowInsecure: true, // dev/self-host only\n },\n },\n}\n```\n\nThe other validation rules (private/loopback/metadata blocking) still apply when this flag is on.\n\n### Redirect Handling\n\nOutbound delivery uses `redirect: \"manual\"` β the runtime refuses to follow 3xx responses. A redirect is treated as a **terminal** delivery failure (no retry), and the redirect target is recorded in the `responseBody`. This protects signed payloads from being bounced to a different host than the one the user registered.\n\nIf your endpoint legitimately needs to relocate, update the `url` on the endpoint record instead of relying on a 301/302.\n\n## Delivery and Retry\n\nDeliveries are processed asynchronously via a Cloudflare Queue.\n\n**Success:** HTTP 2xx response marks the delivery as `delivered`.\n\n**Failure:** HTTP 4xx/5xx or network errors trigger retries with exponential backoff:\n\n| Attempt | Delay |\n|---------|-------|\n| 1st retry | ~2 seconds |\n| 2nd retry | ~4 seconds |\n| 3rd retry (final) | ~8 seconds |\n\nMaximum backoff is capped at 1 hour. After 3 failed attempts, the delivery is marked as `failed`.\n\n**Disabled endpoints:** If an endpoint is disabled or deleted between emission and delivery, the delivery is marked as failed immediately.\n\n### Delivery Record\n\nEach delivery attempt is tracked in the `webhook_deliveries` table:\n\n| Field | Description |\n|-------|-------------|\n| `status` | `pending`, `delivered`, or `failed` |\n| `attempts` | Number of delivery attempts |\n| `responseStatus` | HTTP status from last attempt |\n| `responseBody` | Response body (truncated to 1000 chars) |\n| `lastAttemptAt` | Timestamp of last attempt |\n| `nextRetryAt` | When the next retry will occur |\n\n## Infrastructure\n\n### Queue Configuration\n\nOutbound webhooks use a dedicated Cloudflare Queue:\n\n```toml\n# Auto-generated in wrangler.toml\n[[queues.producers]]\nqueue = \"my-app-webhooks-queue\"\nbinding = \"WEBHOOKS_QUEUE\"\n\n[[queues.consumers]]\nqueue = \"my-app-webhooks-queue\"\nmax_batch_size = 10\nmax_batch_timeout = 30\nmax_retries = 3\ndead_letter_queue = \"my-app-webhooks-dlq\"\n```\n\n### Dead Letter Queue\n\nFailed webhook deliveries (after all retries) are sent to a dead letter queue for investigation:\n\n```toml\n[[queues.consumers]]\nqueue = \"my-app-webhooks-dlq\"\nmax_batch_size = 1\n```\n\n## Enabling Webhooks\n\nSet `webhooksBinding` in your database provider config:\n\n```typescript\ndatabase: defineDatabase(\"cloudflare-d1\", {\n binding: \"DB\",\n webhooksBinding: \"WEBHOOKS_DB\",\n})\n```\n\nThis generates the webhook database schema, routes, queue consumer, and all supporting code.\n\n### On Neon (Postgres)\n\nWebhooks are supported on the `neon` provider too. `webhooksBinding` acts as a\npure enable flag β there is no separate webhooks database. The webhook tables\nlive in a dedicated `webhooks` Postgres schema of your single Neon database,\ncreated by the standard drizzle migration set, and are locked down by an RLS\npolicy so only the Worker's internal service-role handle can touch them:\n\n```typescript\ndatabase: defineDatabase(\"neon\", {\n connectionMode: \"http\", // required for webhooks\n webhooksBinding: \"WEBHOOKS_DB\", // enable flag; no D1 binding is emitted\n // queue names stay configurable on any provider:\n webhooksQueueName: \"my-app-webhooks-queue\",\n webhooksDlqName: \"my-app-webhooks-dlq\",\n})\n```\n\nThe D1-only keys `webhooksDatabaseId` / `webhooksDatabaseName` are rejected at\ncompile time on Neon, and webhooks require `connectionMode: 'http'` (the\nCloudflare default). Queue wiring (`WEBHOOKS_QUEUE`, the consumer, and the\ndead letter queue) is identical across providers.\n\n## See Also\n\n- [Inbound Webhooks](/platform/webhooks/inbound) β Receive webhooks from external services\n- [Queues](/platform/queues) β Background processing infrastructure\n\n## Standard Webhooks signing\n\nOutbound deliveries are signed in the [Standard Webhooks](https://www.standardwebhooks.com)\nformat:\n\n| Header | Value |\n|---|---|\n| `webhook-id` | the delivery id (unique per delivery) |\n| `webhook-timestamp` | unix seconds |\n| `webhook-signature` | `v1,<base64 HMAC-SHA256 over id.timestamp.body>` |\n\nOn **contract v1** these are sent **in addition to** the legacy\n`X-Webhook-Signature` / `X-Webhook-Event` / `X-Webhook-Delivery` set, so\nexisting receivers keep working during the migration window. On\n**contract v2** only the Standard Webhooks headers are sent β the legacy set\n(and its Stripe-format signature) is dropped.\n\nReceiver verification (any Standard Webhooks library works):\n\n```ts\nimport { Webhook } from \"standardwebhooks\";\n\nconst wh = new Webhook(endpointSecret); // whsec_β¦\nconst payload = wh.verify(rawBody, {\n \"webhook-id\": req.headers[\"webhook-id\"],\n \"webhook-timestamp\": req.headers[\"webhook-timestamp\"],\n \"webhook-signature\": req.headers[\"webhook-signature\"],\n});\n```\n\nThe timestamp is inside the MAC, so the library's tolerance window is a real\nreplay bound."
|
|
387
395
|
},
|
|
396
|
+
"start/deploy-browser": {
|
|
397
|
+
"title": "Deploy from your browser",
|
|
398
|
+
"content": "Build a backend in [Quickback Start](https://start.quickback.dev), get a green compile, and ship it to **your own Cloudflare account** with one click β databases created, migrations applied, secrets minted, Worker live on a `workers.dev` URL. No local tooling required.\n\nThis page covers the browser flow. For local projects, or anything the browser flow doesn't support yet, use [`quickback deploy`](/start/deploy) β the CLI covers every resource type and is always available.\n\n## Browser vs CLI\n\n| | Deploy from Start | `quickback deploy` |\n|---|---|---|\n| Where you work | start.quickback.dev chat | Your terminal, local project |\n| Cloudflare auth | OAuth consent (no tokens handled by you) | `wrangler login` / `CLOUDFLARE_API_TOKEN` |\n| Resource coverage | The supported matrix below, fail-closed | Everything the compiler emits |\n| Custom domains | Not yet β `workers.dev` only | Yes, via your `wrangler.toml` routes |\n| Best for | Chat-built apps, first deploys, demos | Local development, full-featured apps, CI |\n\n## How a deploy runs\n\nWhen you click **Deploy this app**, the pipeline runs four phases and reports each one:\n\n1. **Compile** β your project compiles on the hosted compiler and emits a *deployment manifest*: the exact set of resources, migrations, and secrets the deploy will touch. Anything the browser flow can't deploy fails **here**, with a named reason β never as a half-deployed app.\n2. **Provision** β each D1 database, KV namespace, and R2 bucket is created in your account, or **adopted** if a resource with the same name already exists. Retries and redeploys never create duplicates. Nothing is ever deleted automatically.\n3. **Package** β the project recompiles with the real resource ids folded in and is bundled into Worker modules (plus your CMS/Account SPA assets, when enabled). Every byte is hash-verified against the manifest before anything is uploaded.\n4. **Finalize** β migrations apply, the Worker uploads with its bindings, secrets are set, and the `workers.dev` route is enabled. Start probes the URL and only shows **Live** once it actually answers.\n\nA typical deploy takes one to two minutes, most of it compilation.\n\n## What deploys\n\nSupported today, end to end:\n\n| Resource | Notes |\n|---|---|\n| D1 databases | All of a project's databases β auth, features, and (when your features pull them in) audit, webhooks, and file-metadata |\n| KV namespace | The `KV` binding for rate limiting and session overflow |\n| R2 bucket | Managed file storage (`managed: true`) |\n| Realtime | The inline Broadcaster Durable Object, including its class registration |\n| Email binding | The Cloudflare Email Service binding is attached (see the delivery caveat below) |\n| CMS / Account UI | The bundled SPAs upload as static assets on the same Worker, with your app's real URL baked in |\n\nBlocked, fail-closed at the compile phase β the deploy stops with the reason, and `quickback deploy` remains the path for these:\n\n| Blocked | Why |\n|---|---|\n| Webhooks, embeddings | Need queue and Workers AI bindings the broker can't create yet |\n| Vectorize | Not yet supported |\n| Neon / Postgres | Browser deploys are D1-only; Neon projects deploy via the CLI |\n| Separate-worker realtime | Needs a second Worker + service binding |\n| Custom `apps:` mounts | Typically need custom domains |\n| Custom `bindings:` (Durable Objects, queues, services, extra R2 buckets) | Not represented by the deploy contract yet |\n| Secrets you supply (third-party API keys, etc.) | The browser flow has no way to collect them yet β a project that *requires* one is refused rather than deployed broken |\n| Hyperdrive, public R2 buckets, containers, workflows | Out of MVP scope |\n\n## Connecting your Cloudflare account\n\nThe first deploy starts with **Continue with Cloudflare** β a standard OAuth consent against Cloudflare's own dashboard, shown by the **Quickback** OAuth client. You pick the account, see exactly which permissions are requested, and can revoke at any time from Cloudflare under **My Profile β Access Management β Connected Applications** (or disconnect from Start).\n\nWhat's requested, and why:\n\n| Scope | Used for |\n|---|---|\n| `openid`, `user-details.read` | Identifying the connection (your email is stored masked, e.g. `p***@example.com`) |\n| `memberships.read` | The account picker β so you never copy a 32-character account id |\n| `account-settings.read` | Looking up your `workers.dev` subdomain to build your app's URL |\n| `workers-scripts.write` | Uploading the Worker, enabling its route, setting its secrets |\n| `d1.write` | Creating databases and applying migrations |\n| `workers-kv-storage.write` | Creating the KV namespace |\n| `workers-r2.write` | Creating file-storage buckets |\n\nNothing broader is requested β no zone, DNS, billing, or account-management access.\n\n## Where your token lives\n\nThe OAuth token never reaches your browser, the chat model, or the compiler. It is held by the deploy service and:\n\n- encrypted at rest with AES-256-GCM under a versioned key-encryption key;\n- bound to its connection record (the ciphertext is unusable if copied elsewhere);\n- decrypted only inside the API calls of an active deploy, then discarded.\n\nTokens expire; when one does, Start shows a reconnect prompt and a fresh consent re-issues it onto the same connection. Revoking in Cloudflare kills the token immediately β the stored ciphertext becomes useless.\n\n## Secrets on the deployed app\n\n- `BETTER_AUTH_SECRET` is minted by the deploy service β 256 bits of fresh entropy per app β and set on the Worker directly. It's never shown to the browser or stored in your project.\n- **Existing Worker secrets are always preserved.** Cloudflare's upload API replaces a Worker's bindings wholesale; the deploy explicitly carries every existing secret across, so a redeploy can never silently delete a secret you set by hand.\n\n## Redeploys are safe by construction\n\nClick Deploy as often as you like:\n\n- **Provisioning adopts** β existing resources are matched by name and reused, never duplicated, never deleted.\n- **Migrations apply exactly once** β a ledger in each database records every applied migration with a content hash. Already-applied migrations are skipped (even when a recompile renames the file), and a migration whose *content changed after it ran* refuses the deploy outright instead of corrupting the schema.\n- **Assets are content-addressed** β a redeploy with unchanged CMS/Account assets uploads zero bytes.\n- **Realtime classes register once** β Durable Object registrations follow Cloudflare's append-only chronology; a redeploy sends nothing new.\n\n## After it's live\n\nYour app answers at `https://<app-name>.<your-subdomain>.workers.dev`:\n\n- **API-only apps** serve a small landing page at `/` (browsers) and a JSON service descriptor (everything else), linking `/api/v1`, `/openapi.json`, and `/health` β never a bare 404 on first visit.\n- **Apps with the Account UI or CMS** redirect `/` to the login page or CMS.\n- `/health` reports status and whether email is configured.\n\nThe deployed app is a normal Worker in *your* account: logs, metrics, and settings live in your Cloudflare dashboard, and you can take over management with the CLI at any time β download the project from Start and `quickback deploy` picks up the same resources by name.\n\n## Not yet available\n\n- **Owner login in deployed apps** (\"Continue with Cloudflare\" as the app's admin sign-in) β the UI half ships with the Account SPA, but the server half and its per-app OAuth client are still in progress.\n- **Custom domains** for browser-deployed apps β `workers.dev` only for now.\n- The blocked resources listed above.\n\nThese all work β or will work first β through [`quickback deploy`](/start/deploy)."
|
|
399
|
+
},
|
|
400
|
+
"start/deploy-owner-access": {
|
|
401
|
+
"title": "Owner access after a browser deploy",
|
|
402
|
+
"content": "When you deploy from Quickback Start's **Deploy to Cloudflare** card, the very\nfirst deploy seeds your app's first administrator (an `appmanager` user) and\nshows a **one-time claim link** next to the live URL:\n\n```\nhttps://<your-app>.<subdomain>.workers.dev/__quickback/claim#token=β¦\n```\n\nOpening it lets you set your email and a password, and you're the app's admin.\nThat's the whole setup.\n\n## What the claim link is\n\n- **One-time and short-lived.** The link works once and expires about six\n hours after the deploy. It's shown exactly once, in the deploy card β\n Quickback keeps no copy of it.\n- **Owner-only.** The link can only claim the admin account the deploy\n seeded. It can never create a new account or elevate an existing one.\n- **Fragment-carried.** The token rides the URL fragment (`#token=β¦`), which\n browsers never send to servers β it stays out of request logs entirely.\n- **Closed once it's used.** The claim page checks the link before it renders\n anything: a spent, expired, or unrecognised token gets a \"this app has\n already been claimed\" message instead of a form. Visiting\n `/__quickback/claim` without a valid token never shows a working signup.\n\nThe record of a used link lives in your app's own database, so single-use is\nenforced exactly β there's no window in which a spent link claims again.\n\n## What happens when you claim\n\n1. You open the link and choose your **email** and a **password** (the seeded\n placeholder email is synthetic β deployed apps can't send mail, so your\n chosen address is marked verified directly).\n2. From that moment you sign in through **your app's own auth** β the same\n email + password login every other user of your app gets. If your app has\n the Account UI enabled, you land on `/account`; API-only apps sign in via\n `POST /auth/v1/sign-in/email`.\n\n**Quickback is not your app's identity provider.** The claim link is a\nbootstrap window, not a login method: once claimed (or expired), your app has\nno runtime dependency on Quickback or the deploy broker for authentication.\n\n## Lost access? Re-issue from Start\n\nDeployed apps on `workers.dev` can't send password-reset email, so your\nCloudflare account is the recovery root: in the deploy card, **Re-issue admin\nclaim link** mints a fresh link β authorized by the same Cloudflare connection\nthat deployed the app. Re-claiming resets the admin password.\n\nEvery issue **rotates the signing key**, so any older link immediately stops\nworking, claimed or not. A fresh link re-opens the claim page on its own β\nnothing has to be reset first, because \"claimable\" just means a signed,\nunexpired, unused token exists.\n\n## For CLI deploys\n\nThe claim route only activates when the `QUICKBACK_CLAIM_KEY` Worker secret is\nset β the browser-deploy broker mints it automatically. Apps deployed with\n`quickback deploy` don't get a claim link (the route answers 404); create your\nadmin through your own flow, or deploy once through Start to bootstrap."
|
|
403
|
+
},
|
|
388
404
|
"start/deploy": {
|
|
389
405
|
"title": "Deploying",
|
|
390
|
-
"content": "
|
|
406
|
+
"content": "Building in [Quickback Start](https://start.quickback.dev) instead of locally? You can also [deploy straight from the browser](/start/deploy-browser) β no CLI needed.\n\nA freshly compiled project's `wrangler.toml` contains **placeholder resource ids** β the compiler can't know your D1 database ids or KV namespace id until those resources exist in your Cloudflare account. Historically that meant a manual dance: `wrangler d1 create`, copy the id, paste it into `quickback.config.ts`, repeat for every database, recompile, deploy.\n\n`quickback deploy` does the whole dance for you:\n\n```bash\ncd my-app && quickback deploy\n```\n\n## What it does\n\n1. **Preflight** β verifies `wrangler` is runnable (via `npx`) and authenticated with Cloudflare (`wrangler whoami`). Log in with `npx wrangler login` or set `CLOUDFLARE_API_TOKEN`.\n2. **Compiles first if needed** β if the project has never compiled (no `wrangler.toml`), it runs the same flow as `quickback compile` before planning anything.\n3. **Plans from wrangler.toml** β reads the generated `wrangler.toml` and finds every resource whose id is still a placeholder:\n - **D1 databases** β auth, features, files, and webhooks databases (whichever your project's features pull in; split-database projects get one entry each)\n - **KV namespace** β the `KV` binding used for rate limiting and session overflow\n - **R2 buckets** β file-storage buckets (R2 is referenced by name, so buckets are simply ensured to exist)\n4. **Creates what's missing** β `wrangler d1 create <name>`, `wrangler kv namespace create <BINDING>`, `wrangler r2 bucket create <name>`. Resources are named from your project name exactly the way the compiler names them (`my-app-auth`, `my-app-features`, `my-app-files`, `my-app-KV`, β¦). If a resource with the expected name already exists in your account, its id is reused instead of creating a duplicate.\n5. **Writes ids back into quickback.config.ts** β a surgical, formatting-preserving edit of your `providers.database.config` (and `providers.storage.config` for the KV id when you declare a `cloudflare-kv` storage provider). Comments, indentation, and every other key are left untouched. Works with both authoring styles:\n\n ```ts\n // defineDatabase(...) wrapper\n database: defineDatabase(\"cloudflare-d1\", {\n splitDatabases: true,\n authDatabaseId: \"β¦\", // β inserted/updated here\n featuresDatabaseId: \"β¦\",\n }),\n\n // plain object form\n database: {\n name: \"cloudflare-d1\",\n config: {\n authDatabaseId: \"β¦\", // β or here\n },\n },\n ```\n\n6. **Recompiles** β so `wrangler.toml` regenerates with the real ids.\n7. **Applies D1 migrations remotely** β `wrangler d1 migrations apply <db> --remote` for each database that has pending migration files (each database's `migrations_dir` comes straight from `wrangler.toml`).\n8. **Deploys** β `wrangler deploy`, streaming wrangler's output.\n\n## Idempotent by design\n\nRun it again any time. When every id is real, there's nothing to create β the command goes straight to compile β migrations β deploy. It's a perfectly good everyday \"ship it\" command, not just a first-deploy tool.\n\n## Flags\n\n| Flag | Effect |\n|------|--------|\n| `--dry-run` | Print the provisioning plan (what would be created vs. what's already set) and exit. Creates nothing. |\n| `--skip-deploy` | Provision resources + sync ids + recompile, but skip migrations and the deploy itself. |\n| `--force` | Overwrite a config id that differs from what Cloudflare reports. Without it, a mismatch prints both values and aborts β never silently overwritten. |\n| `--verbose` | Detailed remote compile failure output (same as `quickback compile --verbose`). |\n\n```bash\n# See the plan without touching your account\nquickback deploy --dry-run\n\n# Provision + write ids only; deploy later\nquickback deploy --skip-deploy\n```\n\n## Conflicting ids\n\nIf `quickback.config.ts` already carries a real id for a resource and Cloudflare reports a different one for the same-named resource, `quickback deploy` prints both and stops:\n\n```\nβ Config ids differ from what Cloudflare reports:\n providers.database.config.authDatabaseId\n in quickback.config.ts: 13b688c8-β¦\n from Cloudflare: f6b8f9a0-β¦\n```\n\nRe-run with `--force` to take Cloudflare's value, or fix the config by hand.\n\n## Notes\n\n- **Security-audit database** β projects using unsafe cross-tenant actions require an audit D1 database, and the compiler fails closed at compile time until `auditDatabaseId` is set. Follow the compile error's instructions (create the database, set the id), then re-run `quickback deploy`.\n- **Neon projects** β `quickback deploy` does not apply Postgres migrations. Run `npm run db:migrate` (needs `DATABASE_MIGRATION_URL`) before traffic hits the worker, or use the generated project's `npm run deploy` script which chains both.\n- **Hyperdrive** β a Hyperdrive binding can't be auto-created (it needs your database connection string). Create it with `wrangler hyperdrive create <name> --connection-string=β¦ --caching-disabled` and set `providers.database.config.hyperdrive.id`.\n- **Two logins** β the compile step uses your Quickback account (`quickback login`); resource creation and deploy use your wrangler credentials."
|
|
391
407
|
},
|
|
392
408
|
"start/first-api": {
|
|
393
409
|
"title": "Complete Example",
|
|
@@ -435,7 +451,7 @@ export const DOCS = {
|
|
|
435
451
|
},
|
|
436
452
|
"tooling/cli": {
|
|
437
453
|
"title": "CLI Reference",
|
|
438
|
-
"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 (`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\n- `todos` β Working todos example with masking + actions + a named view\n- `blog` β Single-tenant blog, PUBLIC reads, admin writes\n- `empty` β Cloudflare scaffold, no example features\n- `saas` β Full B2B SaaS: orgs, R2 file storage, webhooks, split databases, realtime\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](/start/templates) page for a deeper guide on choosing between them.\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nUse `quickback compile --verbose` when a remote compile fails and you need the\nunderlying command, exit code, stderr/stdout tail, and compiler-suggested fixes.\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#### Configuration-aware completion steps\n\nAfter a successful compile, the CLI derives its next steps from the configured\ndatabase connection mode. Neon HTTP projects receive the direct\n`DATABASE_URL`, `.dev.vars`, migration, and deploy workflow. Hyperdrive\nprojects instead receive migration-only `DATABASE_MIGRATION_URL` guidance and\nlocal development instructions for the configured Hyperdrive\n`localConnectionString`; the CLI never recommends `DATABASE_URL` as a Worker\nsecret for that mode.\n\nWhen `providers.database.environments` defines isolated targets, the footer\nlists the configured Neon branches, each target's required Worker secrets, and\nexplicit `wrangler ... --env <target>` deploy commands. It does not suggest a\nbare deploy or the unnamed `.env.neon` / `.dev.vars` workflow for named\nHyperdrive environments.\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### Typecheck the Authored Tree\n\n```bash\nquickback check # one-shot; CI-friendly exit codes\nquickback check --watch # re-check on change (tsc --watch)\n```\n\nRuns `tsc` over `quickback/tsconfig.json` β the config the compiler emits on\nevery compile, which typechecks the tree you actually edit (actions, lib,\ntable files) against the generated `.quickback/` typed helpers. No compile,\nno server: this is your editor's view of the source, on demand.\n\nExit codes: `0` clean Β· `1` type errors Β· `2` setup missing. A fresh clone\n(or a project that has never compiled) exits `2` with a pointer at\n`quickback compile`, which generates the tsconfig and helpers the check\nresolves against. Re-run `quickback compile` after schema changes so the\nhelpers track your tables.\n\n### Authored-Source Codemods\n\n```bash\nquickback migrate visible-columns [--dry-run] # declare managed audit columns\nquickback migrate helper-imports [--dry-run] # single typed helper import\n```\n\n`helper-imports` rewrites action files from the legacy pair β\n\n```ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\"; // resolves to the authored file\n```\n\nβ to the single typed import the helpers are designed for:\n\n```ts\nimport { defineAction, applications } from \"../.quickback/define-action\";\n```\n\nOnly provably-safe merges are made: the table import must resolve to the\nhelper's own bound table under a name the helper exports. Sibling-table and\ncross-feature imports are left untouched, and unusual shapes (aliases,\nmulti-line imports, `import type`) are reported for manual attention instead\nof guessed at.\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 ./.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 },\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:3000 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3000\nquickback compile\n```\n\nSee [Local Compiler](/tooling/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```"
|
|
454
|
+
"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 (`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\n- `todos` β Working todos example with masking + actions + a named view\n- `blog` β Single-tenant blog, PUBLIC reads, admin writes\n- `empty` β Cloudflare scaffold, no example features\n- `saas` β Full B2B SaaS: orgs, R2 file storage, webhooks, split databases, realtime\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](/start/templates) page for a deeper guide on choosing between them.\n\n### Compile Definitions\n\n```bash\nquickback compile\n```\n\nUse `quickback compile --verbose` when a remote compile fails and you need the\nunderlying command, exit code, stderr/stdout tail, and compiler-suggested fixes.\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#### Configuration-aware completion steps\n\nAfter a successful compile, the CLI derives its next steps from the configured\ndatabase connection mode. Neon HTTP projects receive the direct\n`DATABASE_URL`, `.dev.vars`, migration, and deploy workflow. Hyperdrive\nprojects instead receive migration-only `DATABASE_MIGRATION_URL` guidance and\nlocal development instructions for the configured Hyperdrive\n`localConnectionString`; the CLI never recommends `DATABASE_URL` as a Worker\nsecret for that mode.\n\nWhen `providers.database.environments` defines isolated targets, the footer\nlists the configured Neon branches, each target's required Worker secrets, and\nexplicit `wrangler ... --env <target>` deploy commands. It does not suggest a\nbare deploy or the unnamed `.env.neon` / `.dev.vars` workflow for named\nHyperdrive environments.\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### Typecheck the Authored Tree\n\n```bash\nquickback check # one-shot; CI-friendly exit codes\nquickback check --watch # re-check on change (tsc --watch)\n```\n\nRuns `tsc` over `quickback/tsconfig.json` β the config the compiler emits on\nevery compile, which typechecks the tree you actually edit (actions, lib,\ntable files) against the generated `.quickback/` typed helpers. No compile,\nno server: this is your editor's view of the source, on demand.\n\nExit codes: `0` clean Β· `1` type errors Β· `2` setup missing. A fresh clone\n(or a project that has never compiled) exits `2` with a pointer at\n`quickback compile`, which generates the tsconfig and helpers the check\nresolves against. Re-run `quickback compile` after schema changes so the\nhelpers track your tables.\n\n### Synchronize Managed Columns\n\n```bash\nquickback schema check # report missing managed-column declarations; read-only\nquickback schema sync # write the safe additive declarations into authored files\nquickback schema sync --dry-run # show the sync diff without writing\n```\n\nChecks every authored table under `quickback/features/` for the managed\ncolumns the compiler expects (audit timestamps, soft-delete markers) and β\non `sync` β writes the missing declarations into your source. `check` never\nwrites; anything that needs a human decision is reported as a diagnostic and\nblocks the write.\n\nThe SQL dialect for written declarations comes from your configured database\nprovider β the same providerβdialect table the compiler uses. Postgres\nproviders (`supabase`, `neon`, `vercel-postgres`, `postgres`, `postgresql`)\nget Postgres declarations; SQLite providers (`cloudflare-d1`,\n`better-sqlite3`, `bun-sqlite`, `libsql`, `turso`) get SQLite. MySQL\nproviders are refused with an error rather than written in the wrong\ndialect; no provider (or an unrecognized one) defaults to SQLite.\n\n### Authored-Source Codemods\n\n```bash\nquickback migrate visible-columns [--dry-run] # declare managed audit columns\nquickback migrate helper-imports [--dry-run] # single typed helper import\n```\n\n`helper-imports` rewrites action files from the legacy pair β\n\n```ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\"; // resolves to the authored file\n```\n\nβ to the single typed import the helpers are designed for:\n\n```ts\nimport { defineAction, applications } from \"../.quickback/define-action\";\n```\n\nOnly provably-safe merges are made: the table import must resolve to the\nhelper's own bound table under a name the helper exports. Sibling-table and\ncross-feature imports are left untouched, and unusual shapes (aliases,\nmulti-line imports, `import type`) are reported for manual attention instead\nof guessed at.\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 ./.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 },\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:3000 quickback compile\n\n# Or export for the session\nexport QUICKBACK_API_URL=http://localhost:3000\nquickback compile\n```\n\nSee [Local Compiler](/tooling/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```"
|
|
439
455
|
},
|
|
440
456
|
"tooling/cloud-compiler/authentication": {
|
|
441
457
|
"title": "Authentication",
|
|
@@ -459,7 +475,7 @@ export const DOCS = {
|
|
|
459
475
|
},
|
|
460
476
|
"tooling/output": {
|
|
461
477
|
"title": "Output Structure",
|
|
462
|
-
"content": "The compiler generates a complete project structure based on your definitions and provider configuration. Cloudflare Workers is the only supported runtime; what varies is which optional surfaces your config enables.\n\n**Warning:** Never edit files in `src/` directly. They are overwritten on every compile. Make changes in your `quickback/` definitions instead.\n\n## Output\n\n```\nsrc/\nβββ index.ts # Hono app entry point (Workers export)\nβββ env.d.ts # Cloudflare bindings TypeScript types\nβββ db/\nβ βββ index.ts # Database connection factory\nβ βββ auth-schema.ts # Auth table schemas (dual mode)\nβ βββ features-schema.ts # Feature table schemas (dual mode)\nβββ auth/\nβ βββ schema.ts # Better Auth table schemas (generated by the Better Auth CLI)\nβββ features/\nβ βββ {feature}/\nβ βββ schema.ts # Drizzle table definition(s)\nβ βββ {feature}.ts # Table alias β re-exports the table from schema.ts\nβ βββ {feature}.resource.ts # Firewall / access / masking helpers for this resource\nβ βββ {feature}.routes.ts # CRUD + record-bound action endpoints\nβ βββ {feature}-actions.routes.ts # Standalone action endpoints (when an action sets `path:`)\nβ βββ actions.ts # Aggregator β imports every action's default export\nβ βββ actions/\nβ β βββ {action}.ts # One file per authored action\nβ βββ .quickback/\nβ βββ define-action.ts # Typed per-feature `defineAction` helper\nβββ routes/\nβ βββ {feature}.ts # Mount re-export consumed by src/index.ts\nβββ lib/\nβ βββ auth.ts # Better Auth instance & config\nβ βββ access.ts # Access control helpers\nβ βββ types.ts # Runtime type definitions\nβ βββ masks.ts # Field masking utilities\nβ βββ services.ts # Service layer\nβ βββ audit-wrapper.ts # Stamps the managed audit columns on write\nβ βββ security-audit.ts # Unsafe cross-tenant audit logger (when needed)\nβββ middleware/\n βββ auth.ts # Auth context middleware\n βββ db.ts # Database instance middleware\n βββ services.ts # Service injection middleware\n\nquickback/drizzle/\nβββ auth/ # Auth migrations (dual mode)\nβ βββ meta/\nβ β βββ _journal.json\nβ β βββ 0000_snapshot.json\nβ βββ 0000_initial.sql\nβββ features/ # Feature migrations (dual mode)\nβ βββ meta/\nβ β βββ _journal.json\nβ β βββ 0000_snapshot.json\nβ βββ 0000_initial.sql\nβββ audit/ # Unsafe cross-tenant action audit migrations (when needed)\n βββ meta/\n βββ 0000_initial.sql\n\n# Root config files\nβββ package.json\nβββ tsconfig.json\nβββ wrangler.toml # Cloudflare Workers config\nβββ drizzle.config.ts # Features DB drizzle config\nβββ drizzle.auth.config.ts # Auth DB drizzle config (dual mode)\nβββ drizzle.audit.config.ts # Audit DB drizzle config (when unsafe actions exist)\n```\n\nNot every per-feature file is always emitted:\n\n- `actions.ts`, `actions/`, and `.quickback/define-action.ts` appear only when the feature has at least one authored action under `quickback/features/{feature}/actions/`.\n- `{feature}-actions.routes.ts` appears only when at least one of those actions declares `path:` (the marker that makes an action standalone).\n- `schema.ts`, `{feature}.ts`, and `{feature}.resource.ts` are skipped for tableless features.\n- A multi-table feature gets one alias file per table (`{feature}.ts`, `{other_table}.ts`) alongside the single `schema.ts`.\n\n## Generated Package Dependency Security\n\nFor projects using Better Auth, the generated `package.json` keeps the stable\n`auth@1.6.x` development dependency that provides the `better-auth` executable\nused by `auth:schema`. It also emits this npm override:\n\n```json\n{\n \"overrides\": {\n \"lodash\": \"4.18.1\"\n }\n}\n```\n\nThe override lifts the CLI's dev-only Prisma schema-parser chain off Lodash\nversions affected by the 2026 code-injection and prototype-pollution\nadvisories. It does not change the Better Auth runtime package or generated\nauthentication behavior. Quickback preserves unrelated overrides already in\nyour package manifest, but the compiler-owned Lodash security pin wins if an\nexisting override conflicts.\n\nAfter recompiling, run your package manager's install command so its lockfile\nrecords the patched transitive version. Use `npm audit --omit=dev` when\nevaluating the production dependency tree; development-tool advisories are a\nseparate review surface.\n\nFor Better Auth projects, `quickback compile` owns auth-schema generation.\nThe generated `build` script runs TypeScript only and never rewrites\n`src/auth/schema.ts`, so build and deployment preflight checks preserve a clean\ngenerated worktree. `auth:schema` remains an explicit diagnostic command; run\n`quickback compile` afterward to restore canonical generated bytes.\n\nOn recompilation, Quickback replaces commands for script names it generates,\nincluding `build`, with the current compiler output. Scripts with other names\nare treated as project customizations and preserved. This lets existing\nprojects acquire build and deployment fixes without losing unrelated tooling.\n\n## Optional Output Files\n\nThese files are generated only when the corresponding features are configured:\n\n### Embeddings\n\nWhen any feature has `embeddings` configured:\n\n```\nsrc/\nβββ lib/\nβ βββ embeddings.ts # Embedding helpers\nβββ routes/\nβ βββ embeddings.ts # POST /api/{v1|v2}/embeddings endpoint\nβββ queue-consumer.ts # Queue handler for async embedding jobs\n```\n\n### File Storage (R2)\n\nWhen `fileStorage` is configured:\n\n```\nsrc/\nβββ routes/\n βββ storage.ts # File upload/download endpoints\nquickback/drizzle/\nβββ files/ # File metadata migrations\n βββ meta/\n βββ 0000_*.sql\n```\n\n### Webhooks\n\nWhen webhooks are enabled:\n\n```\nsrc/\nβββ lib/\n βββ webhooks/\n βββ index.ts # Webhook module entry\n βββ sign.ts # Webhook payload signing\n βββ handlers.ts # Handler registry\n βββ emit.ts # Queue emission helpers\n βββ routes.ts # Inbound/outbound endpoints\n βββ providers/\n βββ index.ts\n βββ stripe.ts # Stripe webhook handler\nquickback/drizzle/\nβββ webhooks/ # Webhook schema migrations\n βββ meta/\n βββ 0000_*.sql\n```\n\n### Security Audit Database (Unsafe Actions)\n\nWhen any action enables unsafe cross-tenant mode (`unsafe.crossTenant: true`):\n\n```\nsrc/\nβββ db/\nβ βββ audit-schema.ts # audit_events table\nβββ lib/\n βββ security-audit.ts # mandatory audit writer\n\nquickback/drizzle/\nβββ audit/\n βββ meta/\n βββ 0000_*.sql\n\n# Root\nβββ drizzle.audit.config.ts\n```\n\nCloudflare output also includes an `AUDIT_DB` D1 binding in `wrangler.toml` and migration scripts:\n\n- `db:migrate:audit:local`\n- `db:migrate:audit:remote`\n\n### Security Contract Report and Signature\n\nGenerated on every compile (unless disabled via `compiler.securityContracts.report.enabled: false`):\n\n```\nreports/\nβββ security-contracts.report.json # Contract evaluation summary + violations\nβββ security-contracts.report.sig.json # Signature / digest envelope for the report\n```\n\nThe signature file uses HMAC-SHA256 when a signing key is configured, otherwise it falls back to SHA-256 digest mode. \nSet `compiler.securityContracts.report.signature.required: true` to fail compilation when a signing key is missing.\n\n### Realtime\n\nWhen any feature has `realtime` configured:\n\n```\nsrc/\nβββ lib/\nβ βββ realtime.ts # Broadcast helpers\nβ βββ Broadcaster.ts # Durable Object class (inline in main worker)\nβ βββ ws-ticket.ts # WebSocket ticket auth utility\nβββ routes/\n βββ ws-ticket.ts # POST /realtime/v1/ws-ticket endpoint\n```\n\nThe Broadcaster DO class is exported from your main worker entry point and runs inline β no separate `cloudflare-workers/broadcast/` deployment needed.\n\n### Device Authorization\n\nWhen the `deviceAuthorization` plugin is enabled:\n\n```\nsrc/\nβββ routes/\n βββ cli-auth.ts # Device auth flow endpoints\n```\n\n## Database Schemas\n\n### Dual Database Mode (D1 default)\n\nThe compiler separates schemas into two files:\n\n**`src/db/auth-schema.ts`** β Re-exports Better Auth table schemas:\n- `users`, `sessions`, `accounts`\n- `organizations`, `members`, `invitations` (if organizations enabled)\n- Plugin-specific tables (`apiKeys`, etc.)\n\n**`src/db/features-schema.ts`** β Re-exports your feature schemas:\n- Every table declared with `feature()` or `defineTable()`\n- The managed audit / soft-delete columns you declared on each table β `...q.audit()` / `...q.softDelete()` on the q path, the canonical Drizzle lines on the raw-Drizzle path\n\n### Single Database Mode (`splitDatabases: false`)\n\n**`src/db/schema.ts`** β Combined re-export of all schemas (auth + features).\n\n## Generated Routes\n\nFor each feature, the compiler generates a routes file at `src/features/{name}/routes.ts` containing:\n\n| Route | Generated When |\n|-------|----------------|\n| `GET /` | `crud.list` configured |\n| `GET /:id` | `crud.get` configured |\n| `POST /` | `crud.create` configured |\n| `PATCH /:id` | `crud.update` configured |\n| `DELETE /:id` | `crud.delete` configured |\n| `PUT /:id` | `crud.put` configured |\n| `POST /batch` | `crud.create` exists (auto-enabled) |\n| `PATCH /batch` | `crud.update` exists (auto-enabled) |\n| `DELETE /batch` | `crud.delete` exists (auto-enabled) |\n| `PUT /batch` | `crud.put` exists (auto-enabled) |\n| `GET /views/{name}` | `views` configured |\n| `POST /:id/{action}` | Record-based actions defined |\n| `POST /{action}` | Standalone actions defined |\n\nRoutes are mounted under `/api/v1/{feature}` for the default contract or\n`/api/v2/{feature}` when `contract: { version: \"v2\" }` is selected.\n\n## Migrations\n\nThe compiler runs the project-local `drizzle-kit generate` binary during compilation to produce SQL migration files. On subsequent compiles, it uses `existingFiles` (your current migration state) to generate only incremental changes.\n\nIf a compiler response returns migration generation as a post-compile command,\nthe command matches `build.packageManager`: `npm exec`, `pnpm exec`, `yarn exec`,\nor `bun run`. These forms resolve the binary from the generated project's\ndependencies. The npm form runs offline and declines npm's missing package\ninstall prompt, so Quickback never downloads an unpinned Drizzle CLI as a\nfallback. If the local binary is missing, install the generated project's\ndependencies and compile again.\n\nThe CLI loads migration meta JSON from one location only β `<project>/quickback/drizzle/`:\n\n- `quickback/drizzle/auth/meta/`\n- `quickback/drizzle/features/meta/`\n- `quickback/drizzle/files/meta/`\n- `quickback/drizzle/webhooks/meta/`\n- `quickback/drizzle/audit/meta/`\n- `quickback/drizzle/meta/` (single-database mode)\n\nQuickback owns this state β nothing under a project-root `drizzle/` folder is ever read or written.\n\nMigration and report artifacts are written to the `quickback/` state directory:\n\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\nFor non-interactive environments (cloud compile, CI), table/column renames must be declared with `compiler.migrations.renames` in `quickback.config.ts`. This avoids interactive rename prompts during migration generation.\n\nMigration files follow the Drizzle Kit naming convention:\n```\n0000_initial.sql\n0001_add_status_column.sql\n0002_create_orders_table.sql\n```\n\n## CMS and Account UI Assets\n\nWhen `cms` and/or `account` are enabled, the compiler builds the SPAs from source at compile time and includes the assets in the output.\n\nEach SPA is placed in its own subdirectory under `src/apps/`:\n\n```\nsrc/apps/ # Root assets directory\nβββ cms/ # CMS SPA (served at /cms/ on unified domain)\nβ βββ index.html\nβ βββ assets/\nβ βββ app.abc123.js # Content-hashed filenames from Vite\nβ βββ app.xyz456.css\nβββ account/ # Account SPA (served at /account/ on unified domain)\n βββ index.html\n βββ assets/\n βββ app.def789.js\n βββ app.ghi012.css\n```\n\nOn custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.\n\n### Static Assets (`quickback/public/`)\n\nAnything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files β they are bytes that ride past it into the Cloudflare ASSETS binding.\n\n```\nquickback/public/ # Source β checked into your repo\nβββ favicon.ico\nβββ robots.txt\nβββ og/\nβ βββ og-image.png\nβββ pdfs/\n βββ whitepaper.pdf\n```\n\nAfter compile:\n\n```\nsrc/apps/ # Destination β written by the CLI\nβββ favicon.ico # Served at https://your-domain/favicon.ico\nβββ robots.txt # Served at /robots.txt\nβββ og/og-image.png # Served at /og/og-image.png\nβββ pdfs/whitepaper.pdf\nβββ cms/ # Compiler-emitted SPA (don't shadow)\nβββ account/ # Compiler-emitted SPA (don't shadow)\n```\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile β `src/` is wiped and rewritten each run.\n- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.\n- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.\n- Binaries (images, fonts, PDFs) are copied byte-for-byte β there is no string round-trip.\n\n### Source Apps (`quickback/apps/`)\n\nFor hand-authored TypeScript apps and prebuilt SPA bundles that live alongside the compiler-emitted SPA shells, drop them under `quickback/apps/<name>/`. The CLI copies the tree into `src/apps/<name>/` on every compile, byte-for-byte, after the compiler has finished writing. Bind a directory to a hostname via [`config.apps`](/configure/domains#app-domains) β the compiler emits the matching Worker middleware automatically.\n\n```\nquickback/apps/ # Source β checked into your repo\nβββ m/ # A hand-authored mobile companion app\nβ βββ index.tsx\nβ βββ components/Button.tsx\nβ βββ lib/utils.ts\nβββ admin/ # A hand-authored admin tool\n βββ index.tsx\n```\n\nAfter compile:\n\n```\nsrc/apps/\nβββ m/index.tsx # Hand-authored β preserved across compiles\nβββ m/components/Button.tsx\nβββ m/lib/utils.ts\nβββ admin/index.tsx\nβββ cms/ # Compiler-emitted SPA (don't shadow)\nβββ account/ # Compiler-emitted SPA (don't shadow)\n```\n\nWhen to choose `apps/` vs `public/`:\n\n| | `quickback/public/` | `quickback/apps/` |\n|---|---|---|\n| **Use for** | Static binaries (logos, fonts, OG images, PDFs, robots.txt) | Hand-authored TS/TSX/JS app source |\n| **Skips** | Hidden entries only (`.DS_Store`, `.git/`) | Hidden entries + `node_modules/`, `dist/`, `build/`, `.next/`, `.turbo/`, `.cache/` |\n| **Folder layout** | Files at any depth β flat or nested | Apps under named subfolders (`m/`, `admin/`, β¦) |\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/apps/<name>/` disappear from `src/apps/<name>/` on the next compile β `src/` is wiped and rewritten each run.\n- A file in `quickback/apps/` that would overwrite a compiler-emitted path (e.g. `quickback/apps/cms/index.tsx` while `cms: true`) fails the compile with a clear error.\n- Migrating from hand-edited `src/apps/<name>/`: move the entire folder under `quickback/apps/<name>/` once, then trust the compile cycle. The hermetic `src/` contract holds again.\n\n### Generated Wrangler Assets Config\n\nThe compiler always generates `run_worker_first = true` when SPAs are enabled β the Worker handles all SPA routing (per hostname and per path prefix):\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nSee [Multi-Domain Architecture](/configure/domains) for details on hostname routing.\n\n## See Also\n\n- [Providers](/configure/providers) β Configure runtime, database, and auth providers\n- [Environment variables](/configure/variables) β Required variables by runtime\n- [Multi-Domain Architecture](/configure/domains) β Custom domains and hostname routing"
|
|
478
|
+
"content": "The compiler generates a complete project structure based on your definitions and provider configuration. Cloudflare Workers is the only supported runtime; what varies is which optional surfaces your config enables.\n\n**Warning:** Never edit files in `src/` directly. They are overwritten on every compile. Make changes in your `quickback/` definitions instead.\n\n## Output\n\n```\nsrc/\nβββ index.ts # Hono app entry point (Workers export)\nβββ env.d.ts # Cloudflare bindings TypeScript types\nβββ db/\nβ βββ index.ts # Database connection factory\nβ βββ auth-schema.ts # Auth table schemas (dual mode)\nβ βββ features-schema.ts # Feature table schemas (dual mode)\nβββ auth/\nβ βββ schema.ts # Better Auth table schemas (generated by the Better Auth CLI)\nβββ features/\nβ βββ {feature}/\nβ βββ schema.ts # Drizzle table definition(s)\nβ βββ {feature}.ts # Table alias β re-exports the table from schema.ts\nβ βββ {feature}.resource.ts # Firewall / access / masking helpers for this resource\nβ βββ {feature}.routes.ts # CRUD + record-bound action endpoints\nβ βββ {feature}-actions.routes.ts # Standalone action endpoints (when an action sets `path:`)\nβ βββ actions.ts # Aggregator β imports every action's default export\nβ βββ actions/\nβ β βββ {action}.ts # One file per authored action\nβ βββ .quickback/\nβ βββ define-action.ts # Typed per-feature `defineAction` helper\nβββ routes/\nβ βββ {feature}.ts # Mount re-export consumed by src/index.ts\nβββ lib/\nβ βββ auth.ts # Better Auth instance & config\nβ βββ access.ts # Access control helpers\nβ βββ types.ts # Runtime type definitions\nβ βββ masks.ts # Field masking utilities\nβ βββ services.ts # Service layer\nβ βββ audit-wrapper.ts # Stamps the managed audit columns on write\nβ βββ security-audit.ts # Unsafe cross-tenant audit logger (when needed)\nβββ middleware/\n βββ auth.ts # Auth context middleware\n βββ db.ts # Database instance middleware\n βββ services.ts # Service injection middleware\n\nquickback/drizzle/\nβββ auth/ # Auth migrations (dual mode)\nβ βββ meta/\nβ β βββ _journal.json\nβ β βββ 0000_snapshot.json\nβ βββ 0000_initial.sql\nβββ features/ # Feature migrations (dual mode)\nβ βββ meta/\nβ β βββ _journal.json\nβ β βββ 0000_snapshot.json\nβ βββ 0000_initial.sql\nβββ audit/ # Unsafe cross-tenant action audit migrations (when needed)\n βββ meta/\n βββ 0000_initial.sql\n\n# Root config files\nβββ package.json\nβββ tsconfig.json\nβββ wrangler.toml # Cloudflare Workers config\nβββ drizzle.config.ts # Features DB drizzle config\nβββ drizzle.auth.config.ts # Auth DB drizzle config (dual mode)\nβββ drizzle.audit.config.ts # Audit DB drizzle config (when unsafe actions exist)\n```\n\nNot every per-feature file is always emitted:\n\n- `actions.ts`, `actions/`, and `.quickback/define-action.ts` appear only when the feature has at least one authored action under `quickback/features/{feature}/actions/`.\n- `{feature}-actions.routes.ts` appears only when at least one of those actions declares `path:` (the marker that makes an action standalone).\n- `schema.ts`, `{feature}.ts`, and `{feature}.resource.ts` are skipped for tableless features.\n- A multi-table feature gets one alias file per table (`{feature}.ts`, `{other_table}.ts`) alongside the single `schema.ts`.\n\n## Spec Blobs Load As Text\n\nThe generated `wrangler.toml` contains a rule you did not configure:\n\n```toml\n[[rules]]\ntype = \"Text\"\nglobs = [\"**/openapi.json\", \"**/asyncapi.json\", \"**/schema-registry.json\"]\n```\n\nThis is deliberate, and it exists to protect cold-start time.\n\nA Worker has a limited CPU budget for its **startup window** β the module\nevaluation that runs before the first request is served. A plain JSON import is\ninlined by the bundler as a JavaScript object literal, so the runtime parses it\nas source and builds the entire object graph during that window. For a large\nAPI the spec is the single biggest thing in the bundle, and the cost is paid on\nevery cold start to serve discovery routes that most callers never request.\n\nLoading the blobs as text means startup only allocates a string. The generated\n`src/index.ts` parses each one lazily, on first request, and memoizes it:\n\n```ts\nimport openapiSpecText from '../openapi.json';\n\nlet __openapiSpec: unknown;\nconst openapiSpec = () => (__openapiSpec ??= JSON.parse(openapiSpecText as unknown as string));\n\napp.get('/openapi.json', (c) => c.json(openapiSpec()));\n```\n\nBehavior is unchanged β the same routes return the same payloads. Only *when*\nthe parse happens moves.\n\nThe saving scales with spec size. On a ~7 MB spec this cut measured startup CPU\nby roughly 40%; below ~0.5 MB it is within measurement noise. Projects that\nemit no spec are unaffected, because bundler rules only apply to files that are\nactually imported.\n\n**Warning:** Do not hand-edit this rule out. Without it the `β¦Text` imports\nresolve to parsed objects and `JSON.parse` receives an object instead of a\nstring.\n\n## Generated Package Dependency Security\n\nFor projects using Better Auth, the generated `package.json` keeps the stable\n`auth@1.6.x` development dependency that provides the `better-auth` executable\nused by `auth:schema`. It also emits this npm override:\n\n```json\n{\n \"overrides\": {\n \"lodash\": \"4.18.1\"\n }\n}\n```\n\nThe override lifts the CLI's dev-only Prisma schema-parser chain off Lodash\nversions affected by the 2026 code-injection and prototype-pollution\nadvisories. It does not change the Better Auth runtime package or generated\nauthentication behavior. Quickback preserves unrelated overrides already in\nyour package manifest, but the compiler-owned Lodash security pin wins if an\nexisting override conflicts.\n\nAfter recompiling, run your package manager's install command so its lockfile\nrecords the patched transitive version. Use `npm audit --omit=dev` when\nevaluating the production dependency tree; development-tool advisories are a\nseparate review surface.\n\nFor Better Auth projects, `quickback compile` owns auth-schema generation.\nThe generated `build` script runs TypeScript only and never rewrites\n`src/auth/schema.ts`, so build and deployment preflight checks preserve a clean\ngenerated worktree. `auth:schema` remains an explicit diagnostic command; run\n`quickback compile` afterward to restore canonical generated bytes.\n\nOn recompilation, Quickback replaces commands for script names it generates,\nincluding `build`, with the current compiler output. Scripts with other names\nare treated as project customizations and preserved. This lets existing\nprojects acquire build and deployment fixes without losing unrelated tooling.\n\n## Optional Output Files\n\nThese files are generated only when the corresponding features are configured:\n\n### Embeddings\n\nWhen any feature has `embeddings` configured:\n\n```\nsrc/\nβββ lib/\nβ βββ embeddings.ts # Embedding helpers\nβββ routes/\nβ βββ embeddings.ts # POST /api/{v1|v2}/embeddings endpoint\nβββ queue-consumer.ts # Queue handler for async embedding jobs\n```\n\n### File Storage (R2)\n\nWhen `fileStorage` is configured:\n\n```\nsrc/\nβββ routes/\n βββ storage.ts # File upload/download endpoints\nquickback/drizzle/\nβββ files/ # File metadata migrations\n βββ meta/\n βββ 0000_*.sql\n```\n\n### Webhooks\n\nWhen webhooks are enabled:\n\n```\nsrc/\nβββ lib/\n βββ webhooks/\n βββ index.ts # Webhook module entry\n βββ sign.ts # Webhook payload signing\n βββ handlers.ts # Handler registry\n βββ emit.ts # Queue emission helpers\n βββ routes.ts # Inbound/outbound endpoints\n βββ providers/\n βββ index.ts\n βββ stripe.ts # Stripe webhook handler\nquickback/drizzle/\nβββ webhooks/ # Webhook schema migrations\n βββ meta/\n βββ 0000_*.sql\n```\n\n### Security Audit Database (Unsafe Actions)\n\nWhen any action enables unsafe cross-tenant mode (`unsafe.crossTenant: true`):\n\n```\nsrc/\nβββ db/\nβ βββ audit-schema.ts # audit_events table\nβββ lib/\n βββ security-audit.ts # mandatory audit writer\n\nquickback/drizzle/\nβββ audit/\n βββ meta/\n βββ 0000_*.sql\n\n# Root\nβββ drizzle.audit.config.ts\n```\n\nCloudflare output also includes an `AUDIT_DB` D1 binding in `wrangler.toml` and migration scripts:\n\n- `db:migrate:audit:local`\n- `db:migrate:audit:remote`\n\n### Security Contract Report and Signature\n\nGenerated on every compile (unless disabled via `compiler.securityContracts.report.enabled: false`):\n\n```\nreports/\nβββ security-contracts.report.json # Contract evaluation summary + violations\nβββ security-contracts.report.sig.json # Signature / digest envelope for the report\n```\n\nThe signature file uses HMAC-SHA256 when a signing key is configured, otherwise it falls back to SHA-256 digest mode. \nSet `compiler.securityContracts.report.signature.required: true` to fail compilation when a signing key is missing.\n\n### Realtime\n\nWhen any feature has `realtime` configured:\n\n```\nsrc/\nβββ lib/\nβ βββ realtime.ts # Broadcast helpers\nβ βββ Broadcaster.ts # Durable Object class (inline in main worker)\nβ βββ ws-ticket.ts # WebSocket ticket auth utility\nβββ routes/\n βββ ws-ticket.ts # POST /realtime/v1/ws-ticket endpoint\n```\n\nThe Broadcaster DO class is exported from your main worker entry point and runs inline β no separate `cloudflare-workers/broadcast/` deployment needed.\n\n### Device Authorization\n\nWhen the `deviceAuthorization` plugin is enabled:\n\n```\nsrc/\nβββ routes/\n βββ cli-auth.ts # Device auth flow endpoints\n```\n\n## Database Schemas\n\n### Dual Database Mode (D1 default)\n\nThe compiler separates schemas into two files:\n\n**`src/db/auth-schema.ts`** β Re-exports Better Auth table schemas:\n- `users`, `sessions`, `accounts`\n- `organizations`, `members`, `invitations` (if organizations enabled)\n- Plugin-specific tables (`apiKeys`, etc.)\n\n**`src/db/features-schema.ts`** β Re-exports your feature schemas:\n- Every table declared with `feature()` or `defineTable()`\n- The managed audit / soft-delete columns you declared on each table β `...q.audit()` / `...q.softDelete()` on the q path, the canonical Drizzle lines on the raw-Drizzle path\n\n### Single Database Mode (`splitDatabases: false`)\n\n**`src/db/schema.ts`** β Combined re-export of all schemas (auth + features).\n\n## Generated Routes\n\nFor each feature, the compiler generates a routes file at `src/features/{name}/routes.ts` containing:\n\n| Route | Generated When |\n|-------|----------------|\n| `GET /` | `crud.list` configured |\n| `GET /:id` | `crud.get` configured |\n| `POST /` | `crud.create` configured |\n| `PATCH /:id` | `crud.update` configured |\n| `DELETE /:id` | `crud.delete` configured |\n| `PUT /:id` | `crud.put` configured |\n| `POST /batch` | `crud.create` exists (auto-enabled) |\n| `PATCH /batch` | `crud.update` exists (auto-enabled) |\n| `DELETE /batch` | `crud.delete` exists (auto-enabled) |\n| `PUT /batch` | `crud.put` exists (auto-enabled) |\n| `GET /views/{name}` | `views` configured |\n| `POST /:id/{action}` | Record-based actions defined |\n| `POST /{action}` | Standalone actions defined |\n\nRoutes are mounted under `/api/v1/{feature}` for the default contract or\n`/api/v2/{feature}` when `contract: { version: \"v2\" }` is selected.\n\n## Migrations\n\nThe compiler runs the project-local `drizzle-kit generate` binary during compilation to produce SQL migration files. On subsequent compiles, it uses `existingFiles` (your current migration state) to generate only incremental changes.\n\nIf a compiler response returns migration generation as a post-compile command,\nthe command matches `build.packageManager`: `npm exec`, `pnpm exec`, `yarn exec`,\nor `bun run`. These forms resolve the binary from the generated project's\ndependencies. The npm form runs offline and declines npm's missing package\ninstall prompt, so Quickback never downloads an unpinned Drizzle CLI as a\nfallback. If the local binary is missing, install the generated project's\ndependencies and compile again.\n\nThe CLI loads migration meta JSON from one location only β `<project>/quickback/drizzle/`:\n\n- `quickback/drizzle/auth/meta/`\n- `quickback/drizzle/features/meta/`\n- `quickback/drizzle/files/meta/`\n- `quickback/drizzle/webhooks/meta/`\n- `quickback/drizzle/audit/meta/`\n- `quickback/drizzle/meta/` (single-database mode)\n\nQuickback owns this state β nothing under a project-root `drizzle/` folder is ever read or written.\n\nMigration and report artifacts are written to the `quickback/` state directory:\n\n- `quickback/drizzle/...` for Drizzle migration SQL/meta artifacts\n- `quickback/reports/...` for security contract report artifacts\n\n### Migration history is never wiped\n\nUnlike `src/`, the `quickback/drizzle/` tree is **not** hermetic β it is history,\nand history is only ever appended to or superseded.\n\nTo keep compile payloads small, the CLI uploads every migration `.sql` and\n`_journal.json` but only the **newest** `NNNN_snapshot.json` per meta directory.\nThe compiler's response is therefore a partial view by construction, and a file\nmissing from it carries no instruction. Compile removes a file only when the\ncompiler was actually shown it and left it out; anything never uploaded β every\nhistorical snapshot β is preserved untouched.\n\nWhen something is removed, the previous tree is archived to\n`quickback/.archives/drizzle-<timestamp>/` (the three most recent are kept) and\nthe compile prints what it removed and what it preserved.\n\nFor non-interactive environments (cloud compile, CI), table/column renames must be declared with `compiler.migrations.renames` in `quickback.config.ts`. This avoids interactive rename prompts during migration generation.\n\nMigration files follow the Drizzle Kit naming convention:\n```\n0000_initial.sql\n0001_add_status_column.sql\n0002_create_orders_table.sql\n```\n\n## CMS and Account UI Assets\n\nWhen `cms` and/or `account` are enabled, the compiler builds the SPAs from source at compile time and includes the assets in the output.\n\nEach SPA is placed in its own subdirectory under `src/apps/`:\n\n```\nsrc/apps/ # Root assets directory\nβββ cms/ # CMS SPA (served at /cms/ on unified domain)\nβ βββ index.html\nβ βββ assets/\nβ βββ app.abc123.js # Content-hashed filenames from Vite\nβ βββ app.xyz456.css\nβββ account/ # Account SPA (served at /account/ on unified domain)\n βββ index.html\n βββ assets/\n βββ app.def789.js\n βββ app.ghi012.css\n```\n\nOn custom domains, each SPA is served at root (`/`) via hostname-based routing. On the unified domain, CMS is at `/cms/` and Account is at `/account/`.\n\n### Static Assets (`quickback/public/`)\n\nAnything you drop under `quickback/public/` is copied verbatim into `src/apps/` on every compile. The compiler does not parse, template, or otherwise touch these files β they are bytes that ride past it into the Cloudflare ASSETS binding.\n\n```\nquickback/public/ # Source β checked into your repo\nβββ favicon.ico\nβββ robots.txt\nβββ og/\nβ βββ og-image.png\nβββ pdfs/\n βββ whitepaper.pdf\n```\n\nAfter compile:\n\n```\nsrc/apps/ # Destination β written by the CLI\nβββ favicon.ico # Served at https://your-domain/favicon.ico\nβββ robots.txt # Served at /robots.txt\nβββ og/og-image.png # Served at /og/og-image.png\nβββ pdfs/whitepaper.pdf\nβββ cms/ # Compiler-emitted SPA (don't shadow)\nβββ account/ # Compiler-emitted SPA (don't shadow)\n```\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/public/` disappear from `src/apps/` on the next compile β `src/` is wiped and rewritten each run.\n- Hidden entries (`.DS_Store`, `.git/`, dotfiles) are skipped.\n- A file in `quickback/public/` that would overwrite a compiler-emitted path (e.g. `quickback/public/cms/index.html`) fails the compile with a clear error rather than silently shadowing the SPA shell.\n- Binaries (images, fonts, PDFs) are copied byte-for-byte β there is no string round-trip.\n\n### Source Apps (`quickback/apps/`)\n\nFor hand-authored TypeScript apps and prebuilt SPA bundles that live alongside the compiler-emitted SPA shells, drop them under `quickback/apps/<name>/`. The CLI copies the tree into `src/apps/<name>/` on every compile, byte-for-byte, after the compiler has finished writing. Bind a directory to a hostname via [`config.apps`](/configure/domains#app-domains) β the compiler emits the matching Worker middleware automatically.\n\n```\nquickback/apps/ # Source β checked into your repo\nβββ m/ # A hand-authored mobile companion app\nβ βββ index.tsx\nβ βββ components/Button.tsx\nβ βββ lib/utils.ts\nβββ admin/ # A hand-authored admin tool\n βββ index.tsx\n```\n\nAfter compile:\n\n```\nsrc/apps/\nβββ m/index.tsx # Hand-authored β preserved across compiles\nβββ m/components/Button.tsx\nβββ m/lib/utils.ts\nβββ admin/index.tsx\nβββ cms/ # Compiler-emitted SPA (don't shadow)\nβββ account/ # Compiler-emitted SPA (don't shadow)\n```\n\nWhen to choose `apps/` vs `public/`:\n\n| | `quickback/public/` | `quickback/apps/` |\n|---|---|---|\n| **Use for** | Static binaries (logos, fonts, OG images, PDFs, robots.txt) | Hand-authored TS/TSX/JS app source |\n| **Skips** | Hidden entries only (`.DS_Store`, `.git/`) | Hidden entries + `node_modules/`, `dist/`, `build/`, `.next/`, `.turbo/`, `.cache/` |\n| **Folder layout** | Files at any depth β flat or nested | Apps under named subfolders (`m/`, `admin/`, β¦) |\n\nNotes:\n\n- The folder is optional. If it doesn't exist, this step is a no-op.\n- Files removed from `quickback/apps/<name>/` disappear from `src/apps/<name>/` on the next compile β `src/` is wiped and rewritten each run.\n- A file in `quickback/apps/` that would overwrite a compiler-emitted path (e.g. `quickback/apps/cms/index.tsx` while `cms: true`) fails the compile with a clear error.\n- Migrating from hand-edited `src/apps/<name>/`: move the entire folder under `quickback/apps/<name>/` once, then trust the compile cycle. The hermetic `src/` contract holds again.\n\n### Generated Wrangler Assets Config\n\nThe compiler always generates `run_worker_first = true` when SPAs are enabled β the Worker handles all SPA routing (per hostname and per path prefix):\n\n```toml\n[assets]\nbinding = \"ASSETS\"\ndirectory = \"src/apps\"\nnot_found_handling = \"none\"\nrun_worker_first = true\n```\n\nSee [Multi-Domain Architecture](/configure/domains) for details on hostname routing.\n\n## See Also\n\n- [Providers](/configure/providers) β Configure runtime, database, and auth providers\n- [Environment variables](/configure/variables) β Required variables by runtime\n- [Multi-Domain Architecture](/configure/domains) β Custom domains and hostname routing"
|
|
463
479
|
},
|
|
464
480
|
"tooling/troubleshooting": {
|
|
465
481
|
"title": "Troubleshooting",
|
|
@@ -605,6 +621,7 @@ export const TOPIC_LIST = [
|
|
|
605
621
|
"define/actions/scoped-db",
|
|
606
622
|
"define/areas",
|
|
607
623
|
"define/arrows",
|
|
624
|
+
"define/authz-roles",
|
|
608
625
|
"define/bundles",
|
|
609
626
|
"define/changesets",
|
|
610
627
|
"define/diagnostics",
|
|
@@ -619,6 +636,7 @@ export const TOPIC_LIST = [
|
|
|
619
636
|
"define/permissions",
|
|
620
637
|
"define/rate-limit",
|
|
621
638
|
"define/read",
|
|
639
|
+
"define/relationships",
|
|
622
640
|
"define/schema",
|
|
623
641
|
"define/scopes",
|
|
624
642
|
"define/sealed-protocol",
|
|
@@ -667,6 +685,8 @@ export const TOPIC_LIST = [
|
|
|
667
685
|
"platform/webhooks/inbound",
|
|
668
686
|
"platform/webhooks",
|
|
669
687
|
"platform/webhooks/outbound",
|
|
688
|
+
"start/deploy-browser",
|
|
689
|
+
"start/deploy-owner-access",
|
|
670
690
|
"start/deploy",
|
|
671
691
|
"start/first-api",
|
|
672
692
|
"start/hand-crafted",
|