@quickback-dev/cli 0.31.1 → 0.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +9 -1
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/migrations.d.ts +17 -0
  5. package/dist/commands/migrations.d.ts.map +1 -0
  6. package/dist/commands/migrations.js +328 -0
  7. package/dist/commands/migrations.js.map +1 -0
  8. package/dist/docs/content.d.ts.map +1 -1
  9. package/dist/docs/content.js +15 -10
  10. package/dist/docs/content.js.map +1 -1
  11. package/dist/index.js +7 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/lib/file-loader.d.ts +15 -0
  14. package/dist/lib/file-loader.d.ts.map +1 -1
  15. package/dist/lib/file-loader.js +27 -0
  16. package/dist/lib/file-loader.js.map +1 -1
  17. package/dist/lib/file-loader.test.js +22 -1
  18. package/dist/lib/file-loader.test.js.map +1 -1
  19. package/dist/skill/docs/changelog.md +758 -0
  20. package/dist/skill/docs/compiler/config/domains.md +26 -0
  21. package/dist/skill/docs/compiler/config/index.md +74 -3
  22. package/dist/skill/docs/compiler/config/single-tenant.md +1 -1
  23. package/dist/skill/docs/compiler/definitions/access.md +161 -9
  24. package/dist/skill/docs/compiler/definitions/actions.md +45 -1
  25. package/dist/skill/docs/stack/account-ui/features/admin.md +2 -2
  26. package/dist/skill/docs/stack/account-ui/hooks.md +4 -0
  27. package/dist/skill/docs/stack/auth/plugins/aws-ses.md +60 -0
  28. package/dist/skill/docs/stack/auth/plugins/aws-sns.md +169 -0
  29. package/dist/skill/docs/stack/auth/plugins/index.md +32 -0
  30. package/package.json +1 -1
  31. package/src/skill/docs/changelog.md +758 -0
  32. package/src/skill/docs/compiler/config/domains.md +26 -0
  33. package/src/skill/docs/compiler/config/index.md +74 -3
  34. package/src/skill/docs/compiler/config/single-tenant.md +1 -1
  35. package/src/skill/docs/compiler/definitions/access.md +161 -9
  36. package/src/skill/docs/compiler/definitions/actions.md +45 -1
  37. package/src/skill/docs/stack/account-ui/features/admin.md +2 -2
  38. package/src/skill/docs/stack/account-ui/hooks.md +4 -0
  39. package/src/skill/docs/stack/auth/plugins/aws-ses.md +60 -0
  40. package/src/skill/docs/stack/auth/plugins/aws-sns.md +169 -0
  41. package/src/skill/docs/stack/auth/plugins/index.md +32 -0
@@ -175,6 +175,32 @@ If you enable `cms` and `account` without custom domains, everything is served o
175
175
 
176
176
  This is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.
177
177
 
178
+ ## Preview Deploys
179
+
180
+ The same compiled bundle can be deployed to additional hostnames — preview environments, staging, per-PR URLs — without recompiling. Set the `EXTRA_APP_HOSTS` env var on the deploy target (a comma-separated list of hostnames) and the worker treats each one like an entry in `apps[*].domain`:
181
+
182
+ - Apps hostname middleware serves the SPA at root.
183
+ - CORS / Better Auth `trustedOrigins` trusts requests whose `Origin` hostname matches.
184
+
185
+ Empty or unset means no extension and zero behavior change for production.
186
+
187
+ ```toml title="wrangler.preview.toml"
188
+ [vars]
189
+ EXTRA_APP_HOSTS = "app-preview.example.com,pr-42.example.com"
190
+ ```
191
+
192
+ ```bash
193
+ # Or set as a secret per deploy target
194
+ wrangler secret put EXTRA_APP_HOSTS --env preview
195
+ ```
196
+
197
+ Mirrors the existing `BETTER_AUTH_URL` auto-trust behavior, where the deployed worker auto-trusts its own configured base origin without needing an explicit `trustedOrigins` entry. With `EXTRA_APP_HOSTS`, one env var extends both the apps allowlist and the CORS allowlist.
198
+
199
+ > **Multi-app deploys**
200
+ >
201
+ > When more than one app is hostname-mounted, extras attach to the first registered apps middleware (Hono runs middleware in registration order and terminates on first match). If you need extras to route to a specific app in a multi-app deploy, set `apps[*].domain` directly and recompile rather than using this env var.
202
+
203
+
178
204
  ## See Also
179
205
 
180
206
  - [Configuration](/compiler/config) — CMS and Account config options
@@ -212,6 +212,77 @@ export default defineConfig({
212
212
 
213
213
  If `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: "warn"`).
214
214
 
215
+ ## Hostname architecture (v0.33+)
216
+
217
+ A 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.
218
+
219
+ ### The unified backend contract
220
+
221
+ When 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:
222
+
223
+ - `/api/v1/*` — feature routes
224
+ - `/auth/v1/*` — Better Auth
225
+ - `/storage/*` — R2 file storage
226
+ - `/health`, `/openapi.json` — monitoring/discovery
227
+ - `/account/*`, `/cms/*` — bundled SPAs (when enabled)
228
+ - `/broadcast/v1/*` (realtime), `/mcp` (MCP), etc.
229
+
230
+ The 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.
231
+
232
+ This 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.
233
+
234
+ ### Dedicated hostnames (optional, additive)
235
+
236
+ For branding or operational separation, you can opt specific surfaces onto their own hostnames:
237
+
238
+ ```ts
239
+ {
240
+ // Bundled SPAs on their own hosts (already-shipped pattern):
241
+ cms: { domain: 'cms.example.com' },
242
+ account: { domain: 'account.example.com' },
243
+
244
+ // v0.33+ — backend surfaces on their own hosts:
245
+ auth: { domain: 'auth.example.com' },
246
+ api: { domain: 'api.example.com' },
247
+
248
+ // User SPAs (existing pattern):
249
+ apps: {
250
+ www: { domain: 'app.example.com' },
251
+ },
252
+ }
253
+ ```
254
+
255
+ On a dedicated hostname, **the hostname IS the namespace** — the path drops the prefix that matches the hostname:
256
+
257
+ | URL on dedicated host | Internally rewritten to | Notes |
258
+ |---|---|---|
259
+ | `https://api.example.com/v1/users` | `/api/v1/users` | Worker-entry rewriter prepends `/api` |
260
+ | `https://auth.example.com/v1/sign-in/email` | `/auth/v1/sign-in/email` | Same shape with `/auth` |
261
+ | `https://api.example.com/api/v1/users` | (unchanged) | Long form also accepted |
262
+ | `https://api.example.com/auth/v1/sign-in` | **404** | Auth doesn't live on the API hostname |
263
+ | `https://api.example.com/health` | (unchanged) | Explicit exception — monitoring agents expect `/health` everywhere |
264
+
265
+ Dual-reach is preserved on the unified host:
266
+
267
+ | URL on unified host | Handler | Notes |
268
+ |---|---|---|
269
+ | `https://quickback.example.com/api/v1/users` | feature route | Works whether `api.domain` is set or not |
270
+ | `https://quickback.example.com/auth/v1/sign-in/email` | Better Auth | Works whether `auth.domain` is set or not |
271
+ | `https://quickback.example.com/v1/users` | **404** | Shortcut only applies on dedicated hostnames |
272
+
273
+ Each dedicated hostname also:
274
+
275
+ - Gets a `{ pattern, custom_domain: true }` route in `wrangler.toml` automatically
276
+ - Joins `trustedOrigins` for CORS
277
+ - 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)
278
+ - Joins CSP `connect-src` so SPAs can fetch from it
279
+
280
+ ### Why two URL shapes (Shape 1 vs Shape 2)
281
+
282
+ If 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.
283
+
284
+ `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.
285
+
215
286
  ## CMS Configuration
216
287
 
217
288
  Embed the [Quickback CMS](/stack/cms) in your compiled Worker. The CMS reads your schema registry and renders a complete admin interface — zero UI code per table.
@@ -234,7 +305,7 @@ cms: { domain: "cms.example.com", sysadmin: true },
234
305
  |--------|------|---------|-------------|
235
306
  | `domain` | `string` | — | Custom domain for CMS. Adds a `custom_domain` route to `wrangler.toml`. |
236
307
  | `access` | `"user" \| "admin"` | `"user"` | Controls who can access the CMS. When `"admin"`, only users with `user.role === "admin"` can enter — enforced at the Worker level (SPA shell, `/api/v1/schema`, and `custom_view` CRUD all return 403 to non-admins) and in the SPA. Also hides the CMS link in Account UI. See [CMS Connecting](/stack/cms/connecting) for the full enforcement model. |
237
- | `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === "sysadmin"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's "All organizations" sentinel. The CMS HTML gate admits `userRole === "sysadmin"` alongside `"admin"` — sysadmin is a strict superset. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |
308
+ | `sysadmin` | `boolean` | `false` | Cross-tenant DB-admin tier. When `true`, opts into the `SYSADMIN` pseudo-role (`user.role === "sysadmin"`), the firewall escape hatch (sysadmins bypass tenant scopes, soft-delete still enforced), the cross-tenant `/auth/v1/admin/list-organizations` endpoint (sibling of Better Auth's `/auth/v1/admin/list-users`, gated to sysadmin only), and the SPA's "All organizations" sentinel. The CMS HTML gate admits `userRole === "sysadmin"` alongside `"admin"`. Off by default. See [`SYSADMIN` pseudo-role](/compiler/definitions/access#sysadmin--cross-tenant-db-admin-tier). |
238
309
 
239
310
  ### Sysadmin tier (`cms.sysadmin: true`)
240
311
 
@@ -242,9 +313,9 @@ Quickback's default model assumes every CMS user belongs to at least one organiz
242
313
 
243
314
  `cms: { sysadmin: true }` introduces a separate role tier:
244
315
 
245
- - **Role**: `user.role === "sysadmin"` (set on the Better Auth user table). Distinct from `"admin"` — admins keep org-scoped CMS access via the membership switcher; sysadmins get cross-tenant.
316
+ - **Role**: `user.role === "sysadmin"` (set on the Better Auth user table). Distinct from `"admin"` — admins keep org-scoped CMS access via the membership switcher; sysadmins get cross-tenant. The two roles are independent at the pseudo-role evaluator level: `ADMIN` admits `'admin'` only, `SYSADMIN` admits `'sysadmin'` only. Routes that need both write `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly.
246
317
  - **Firewall**: every `buildFirewallConditions()` emits an `if (ctx.userRole === "sysadmin") return undefined` (or just the soft-delete predicate when present) at the top, so sysadmins see every tenant's rows. See [Firewall escape hatch](/compiler/definitions/firewall#sysadmin-escape-hatch).
247
- - **Org listing**: a new `GET /admin/v1/sysadmin/organizations` endpoint selects directly from the auth-schema `organization` table — every row, every tenant. The existing `/admin/v1/organizations` (membership-bound, used by org admins) is unchanged.
318
+ - **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`.
248
319
  - **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.
249
320
  - **CMS HTML gate**: admits `userRole === "sysadmin"` alongside `"admin"`. Org admins are not locked out — both roles can enter the CMS in `cms.access: "admin"` mode.
250
321
 
@@ -31,7 +31,7 @@ export default defineConfig({
31
31
  | `organizationId` columns | Required on resources | Not used |
32
32
  | Role source | Org membership table | `user.role` field |
33
33
  | Firewall scopes | `owner`, `organization`, `team`, `exception` | `owner`, `exception` only |
34
- | Admin org endpoints | `/admin/v1/organizations` generated | Skipped |
34
+ | Admin org endpoints | Use Better Auth's `/auth/v1/organization/list` (caller's orgs) and `/auth/v1/admin/list-organizations` when `cms.sysadmin: true` (cross-tenant) | N/A (no org plugin) |
35
35
  | `ctx.activeOrgId` | From session/JWT | Always `undefined` |
36
36
  | `ctx.roles` | From org member role | From `user.role` |
37
37
 
@@ -220,9 +220,9 @@ Use `roles: ["SYSADMIN"]` for endpoints that should only be reachable by platfor
220
220
  read: { access: { roles: ["SYSADMIN"] } }
221
221
  ```
222
222
 
223
- `SYSADMIN` is a strict superset of `ADMIN` — at runtime, the universal-bypass shortcuts in `evaluateAccess` admit `userRole === 'sysadmin'` anywhere they admit `userRole === 'admin'`. The distinction matters for one thing only: **the firewall escape hatch**. When `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.
223
+ `ADMIN` and `SYSADMIN` are **independent** at the evaluator level — `ADMIN` admits `userRole === 'admin'` only, `SYSADMIN` admits `userRole === 'sysadmin'` only. Routes that need both write `access: { roles: ['ADMIN', 'SYSADMIN'] }` explicitly. The one place sysadmin gets implicit extra powers is **the firewall escape hatch**: when `cms.sysadmin: true`, every `buildFirewallConditions` emits an `if (ctx.userRole === 'sysadmin') return undefined;` (or just the soft-delete predicate when present) at the top — so sysadmins see every tenant's rows, not just their own org's. That escape hatch does NOT fire for `userRole === 'admin'`; admins still go through the firewall like everyone else.
224
224
 
225
- This separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/admin/v1/sysadmin/organizations` endpoint, and the SPA's "All organizations" sentinel.
225
+ This separation exists so Better Auth admin-plugin powers (user management, impersonation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'admin'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/compiler/config#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's "All organizations" sentinel.
226
226
 
227
227
  #### Mixing pseudo-roles with real roles
228
228
 
@@ -407,8 +407,11 @@ export default defineAction({
407
407
  access: { roles: ['admin', 'member', 'attendee'] }, // attendee is a relationship-role
408
408
  execute: async ({ db, ctx, input }) => {
409
409
  // No hand-rolled attendance check needed — the resolver already ran.
410
- // ctx.event is the loaded events row (typed as any in v0.19; cast as
411
- // needed — narrow per-action types are a follow-up).
410
+ // ctx.event is the loaded events row. Typed as `any` here because the
411
+ // hand-rolled `roles: ['attendee']` action gates per-action, not per-
412
+ // namespace — see "Narrow ctx.<exposeAs> typing" below for the typed
413
+ // import flip available when the same hydration runs through a
414
+ // namespace mount.
412
415
  const event = ctx.event as typeof events.$inferSelect;
413
416
  // … domain logic only.
414
417
  },
@@ -546,7 +549,21 @@ The validator and resolver reject:
546
549
 
547
550
  When 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).
548
551
 
549
- Namespace 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 and typed automatically inside the handlers.
552
+ Namespace 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.
553
+
554
+ ### When to use roles vs. relationships
555
+
556
+ A user is authorized for a row when **any** of the following is true:
557
+
558
+ - they have a **per-row relationship** to it (e.g. an attendee row, a named organizer row), or
559
+ - they have a **role on the row's tenant** (org admin/owner of the row's `organizationId`), or
560
+ - they have **team membership** matching the row's `teamId`.
561
+
562
+ Use **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.
563
+
564
+ The 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.
565
+
566
+ > **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.
550
567
 
551
568
  Two declaration sites depending on whether the participating actions live in one feature or many:
552
569
 
@@ -575,6 +592,8 @@ export default defineAction({
575
592
 
576
593
  The 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.
577
594
 
595
+ Multi-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.
596
+
578
597
  ### Cross-feature: `authz.namespaces` (v0.24+)
579
598
 
580
599
  Use when the namespace spans multiple features. The declaration sits next to your other authz config in `quickback.config.ts`.
@@ -595,14 +614,18 @@ authz: {
595
614
  eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },
596
615
  },
597
616
  }
617
+ ```
618
+
619
+ With the namespace declared, any standalone action whose `path:` matches the prefix joins the gate — regardless of which feature owns it:
598
620
 
599
- // features/feeds/actions/feed-moments.ts (in a different feature)
621
+ ```typescript
622
+ // features/feeds/actions/feed-moments.ts (in one feature)
600
623
  export default defineAction({
601
624
  path: '/event/:eventId/feed-moments',
602
625
  method: 'POST',
603
626
  });
604
627
 
605
- // features/rsvp/actions/respond.ts (and another)
628
+ // features/rsvp/actions/respond.ts (in a different feature)
606
629
  export default defineAction({
607
630
  path: '/event/:eventId/respond',
608
631
  method: 'POST',
@@ -611,6 +634,71 @@ export default defineAction({
611
634
 
612
635
  The 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.
613
636
 
637
+ ### Multi-lane via (v0.25+) — first match wins
638
+
639
+ When 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.
640
+
641
+ ```typescript
642
+ authz: {
643
+ relationships: {
644
+ attendeeOf: {
645
+ from: 'guests',
646
+ subject: { column: 'linkedUserId', equals: 'ctx.userId' },
647
+ resource: { column: 'eventId' },
648
+ where: { status: 'confirmed' },
649
+ loads: 'events',
650
+ exposeAs: 'event',
651
+ },
652
+ // Named per-event organizers (potentially EXTERNAL — these users may
653
+ // not be a member of the event's org. That's the point: lets you grant
654
+ // event-level access to freelancers / partner staff without adding
655
+ // them to the org's member list.)
656
+ organizerOf: {
657
+ from: 'eventOrganizers',
658
+ subject: { column: 'linkedUserId', equals: 'ctx.userId' },
659
+ resource: { column: 'eventId' },
660
+ loads: 'events',
661
+ exposeAs: 'event',
662
+ },
663
+ },
664
+ namespaces: {
665
+ eventScope: {
666
+ prefix: '/event/:eventId',
667
+ via: ['attendeeOf', 'organizerOf'],
668
+ },
669
+ },
670
+ }
671
+ ```
672
+
673
+ All 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.
674
+
675
+ ### Bulk-grant lanes (v0.26+)
676
+
677
+ Relationship 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.
678
+
679
+ ```typescript
680
+ namespaces: {
681
+ eventScope: {
682
+ prefix: '/event/:eventId',
683
+ via: [
684
+ 'attendeeOf',
685
+ 'organizerOf',
686
+ { roles: ['admin', 'owner'] }, // org-role bulk grant
687
+ { team: true }, // active-team-membership bulk grant
688
+ ],
689
+ },
690
+ }
691
+ ```
692
+
693
+ Each bulk-grant lane:
694
+
695
+ - **`{ 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.
696
+ - **`{ 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.
697
+
698
+ Both 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:`).
699
+
700
+ When 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.
701
+
614
702
  ### Discovery is path-prefix-only
615
703
 
616
704
  Actions 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.
@@ -619,7 +707,10 @@ Actions opt in by matching `path:` against a declared namespace prefix. There's
619
707
 
620
708
  Both forms share the same shape checks:
621
709
 
622
- - **`via:` must point at a declared `authz.relationships[*]` entry**, and that relationship must declare `loads + exposeAs`. Without `loads` there's nothing for the middleware to hydrate, and the namespace gate becomes indistinguishable from a per-action access rule.
710
+ - **`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 }`).
711
+ - **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.
712
+ - **All relationship lanes in one namespace must agree on `loads:` + `exposeAs:`.** Otherwise `ctx.<exposeAs>` would change shape depending on which lane matched.
713
+ - **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.
623
714
  - **`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.
624
715
  - **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.
625
716
 
@@ -632,10 +723,71 @@ Project-level only:
632
723
 
633
724
  Inside a namespace action's `execute()`:
634
725
 
635
- - `ctx.<exposeAs>` is populated by the middleware with the loaded resource row, typed as `typeof <loadsTable>.$inferSelect`.
726
+ - `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)).
636
727
  - 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.
637
728
  - 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.
638
729
 
730
+ ### Narrow `ctx.<exposeAs>` typing (v0.27+)
731
+
732
+ The 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.
733
+
734
+ v0.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.
735
+
736
+ ```ts title="features/feeds/actions/feed-moments.ts"
737
+ // One-line flip per namespace-scoped action:
738
+ import { defineAction } from '../.quickback/define-action.event-scope';
739
+ // └──────┬──────┘
740
+ // kebab(namespaceName)
741
+
742
+ export default defineAction({
743
+ path: '/event/:eventId/feed-moments',
744
+ method: 'POST',
745
+ input: z.object({ body: z.string() }),
746
+ access: { roles: ['attendee'] },
747
+ async execute({ ctx, input }) {
748
+ ctx.event.id // ✓ string
749
+ ctx.event.startsAt // ✓ Date — autocomplete works
750
+ ctx.event.organizerId // ✓ narrows on the field's declared type
751
+
752
+ ctx.event.idd // ✗ TS2339 — typo caught at compile time
753
+ },
754
+ });
755
+ ```
756
+
757
+ The 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.
758
+
759
+ #### Opt-in, not breaking
760
+
761
+ Actions 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.
762
+
763
+ #### Compile-time advisory
764
+
765
+ When `quickback compile` sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:
766
+
767
+ ```text
768
+ [quickback:typing] action "feedMoments" in feature "feeds" lives under
769
+ namespace "eventScope" — switch its import to
770
+ `../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.
771
+ (Runtime behavior is unchanged; the narrowed helper only refines TS types.)
772
+ ```
773
+
774
+ Non-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).
775
+
776
+ #### Multi-namespace features
777
+
778
+ A 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.
779
+
780
+ ```text
781
+ src/features/interviews/.quickback/
782
+ ├── define-action.ts # generic — standard fallback
783
+ ├── define-action.interview-scope.ts # ctx.interview typed
784
+ └── define-action.event-scope.ts # ctx.event typed
785
+ ```
786
+
787
+ #### Why per-namespace and not per-action
788
+
789
+ A `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.
790
+
639
791
  ## Read & Write Configuration
640
792
 
641
793
  Reads (`GET /` and `GET /:id`) live under `read:`; mutations live under top-level `create:`, `update:`, `delete:`, and `upsert:`. See [Read](/compiler/definitions/read) for the full read pipeline reference.
@@ -127,7 +127,7 @@ export default defineAction({
127
127
  | `access` | Yes | Access control (roles, record conditions, or function) |
128
128
  | `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
129
129
  | `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |
130
- | `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST) |
130
+ | `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |
131
131
  | `responseType` | No | Response format: json, stream, file (default: json) |
132
132
  | `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |
133
133
  | `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |
@@ -404,6 +404,50 @@ export default defineAction({
404
404
  });
405
405
  ```
406
406
 
407
+ ### GET vs POST for input
408
+
409
+ GET actions read `input` from URL query parameters; every other method (POST,
410
+ PUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in
411
+ both cases — the compiler picks the right parser based on `method`.
412
+
413
+ ```typescript
414
+ // GET — input populated from ?q=…&limit=…
415
+ defineAction({
416
+ method: "GET",
417
+ path: "/search",
418
+ input: z.object({
419
+ q: z.string(),
420
+ limit: z.coerce.number().int().positive().max(100).default(20),
421
+ }),
422
+ access: { roles: ["AUTHENTICATED"] },
423
+ async execute({ input }) {
424
+ // input is { q: string, limit: number } — fully typed.
425
+ },
426
+ });
427
+ ```
428
+
429
+ Repeated query keys (`?tag=a&tag=b`) come through as arrays automatically;
430
+ single values stay as strings. Use Zod's `.coerce.number()` /
431
+ `.coerce.boolean()` when you want typed primitives from the parsed strings.
432
+
433
+ **Use POST when input is structured.** GET requests cannot carry a JSON body
434
+ in any of the surfaces Quickback APIs are commonly called from:
435
+
436
+ - Browsers throw on `fetch(url, { method: 'GET', body })`.
437
+ - CDNs and caches key on URL+method; a GET with a body either gets the body
438
+ stripped at the edge or cache-collides with semantically different requests.
439
+ - OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)
440
+ refuse to emit GET-with-body, so the generated SDKs break.
441
+ - The MCP agent surface treats GET as parameter-only — agents calling a GET
442
+ action will only see what the URL exposes.
443
+
444
+ If your action takes nested objects, arrays of objects, or large inputs that
445
+ don't serialize cleanly to a query string, set `method: "POST"`. POST doesn't
446
+ imply "this writes data" — it's the right method whenever the request body is
447
+ load-bearing. Use the response shape (`responseType: "json"`, or just the data
448
+ your handler returns) to convey read semantics; HTTP method choice is about
449
+ input transport, not action intent.
450
+
407
451
  ## Access Configuration
408
452
 
409
453
  Access controls who can execute an action and under what conditions.
@@ -32,10 +32,10 @@ When `auth.admin` is `false` (the default), admin routes are excluded from the S
32
32
 
33
33
  The admin panel is restricted to users with `role: "admin"` on their Better Auth user record. Non-admin users are redirected away from `/admin`.
34
34
 
35
- To grant admin access to a user, use the Better Auth admin API:
35
+ To grant admin access to a user, use the Better Auth admin plugin:
36
36
 
37
37
  ```bash
38
- curl -X POST https://api.example.com/admin/v1/set-role \
38
+ curl -X POST https://api.example.com/auth/v1/admin/set-role \
39
39
  -H "Authorization: Bearer $TOKEN" \
40
40
  -H "Content-Type: application/json" \
41
41
  -d '{ "userId": "user_123", "role": "admin" }'
@@ -12,6 +12,7 @@ quickback/
12
12
  after-user-create.ts
13
13
  before-user-create.ts
14
14
  after-session-create.ts
15
+ after-admin-user-create.ts
15
16
  ```
16
17
 
17
18
  Each file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.
@@ -23,6 +24,9 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
23
24
  | `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \| { data?: Partial<User> }` |
24
25
  | `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |
25
26
  | `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |
27
+ | `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
28
+
29
+ `after-admin-user-create.ts` is a **virtual event** — it wires into the same Better Auth `user.create.after` slot as the generic `after-user-create.ts`, but the compiler wraps the call in a runtime filter on the BA context path so it only fires when the row was created via the admin plugin's `POST /admin/create-user` endpoint. Use it for first-time-user provisioning (welcome email, default org assignment) without inspecting `_baCtx?.context?.path` by hand. The generic `after-user-create.ts` still runs for every signup, including admin-created ones.
26
30
 
27
31
  Filenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).
28
32
 
@@ -44,6 +44,66 @@ Each email type has both HTML and plain text templates. Templates include:
44
44
  - Fallback plain text versions for all email clients
45
45
  - XSS prevention via HTML escaping and URL sanitization
46
46
 
47
+ ### Per-Type Template Overrides
48
+
49
+ Override the default subject + HTML + text for any OTP type without forking the package. Drop a `.ts` file into `quickback/email-templates/` and reference it from `plugins.emailOtp.templates`:
50
+
51
+ ```typescript
52
+ // quickback/quickback.config.ts
53
+ defineAuth("better-auth", {
54
+ plugins: {
55
+ emailOtp: {
56
+ templates: {
57
+ 'forget-password': './email-templates/forget-password',
58
+ 'welcome': './email-templates/welcome',
59
+ },
60
+ },
61
+ },
62
+ });
63
+ ```
64
+
65
+ Each template module default-exports a function that returns `{ subject, html, text }`:
66
+
67
+ ```typescript
68
+ // quickback/email-templates/welcome.ts
69
+ interface Input {
70
+ email: string;
71
+ otp: string;
72
+ type: 'sign-in' | 'email-verification' | 'forget-password' | 'welcome';
73
+ name?: string;
74
+ appName: string;
75
+ appUrl: string;
76
+ supportEmail?: string;
77
+ }
78
+
79
+ export default function welcomeTemplate({ otp, name, appName, appUrl }: Input) {
80
+ const greeting = name ? `Hi ${name},` : 'Hi,';
81
+ return {
82
+ subject: `Welcome to ${appName} — set your password`,
83
+ html: `
84
+ <h1>Welcome to ${appName}</h1>
85
+ <p>${greeting} your account is ready. Use this code to set your password and sign in:</p>
86
+ <p style="font-size:32px;letter-spacing:8px"><b>${otp}</b></p>
87
+ <p>Visit <a href="${appUrl}/set-password">${appUrl}/set-password</a> to finish setup.</p>
88
+ `,
89
+ text: `${greeting}\n\nYour ${appName} code: ${otp}\n\nFinish setup at ${appUrl}/set-password`,
90
+ };
91
+ }
92
+ ```
93
+
94
+ Recognized keys:
95
+
96
+ | Key | When it fires |
97
+ |-----|---------------|
98
+ | `'sign-in'` | OTP sign-in flow |
99
+ | `'email-verification'` | Signup email verification |
100
+ | `'forget-password'` | Password reset request — and admin-bootstrap if `welcome` isn't set |
101
+ | `'welcome'` | **Synthetic** — routed when `forget-password` fires for a user with no credential row yet (the admin-plugin → bootstrap flow). Without it, those sends fall through to `forget-password`. |
102
+
103
+ Missing keys fall through to the built-in defaults from `@quickback-dev/better-auth-aws-ses`. The compiler stages each referenced file into `src/email-templates/<name>.ts` and wires the default import in `src/lib/auth.ts` — the template function is called inline from `sendVerificationOTP`, so it has access to whatever modules the file imports.
104
+
105
+ > **Provider scope.** Overrides are only honored when `email.provider: 'aws-ses'`. The Cloudflare Email path uses the helper's own template pipeline and ignores `plugins.emailOtp.templates`.
106
+
47
107
  ## Configuration
48
108
 
49
109
  ### Server Plugin