@quickback-dev/cli 0.40.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/commands/claude.d.ts.map +1 -1
  2. package/dist/commands/claude.js +8 -0
  3. package/dist/commands/claude.js.map +1 -1
  4. package/dist/commands/compile.d.ts.map +1 -1
  5. package/dist/commands/compile.js +13 -2
  6. package/dist/commands/compile.js.map +1 -1
  7. package/dist/commands/compile.test.js +26 -21
  8. package/dist/commands/compile.test.js.map +1 -1
  9. package/dist/commands/create.js +6 -9
  10. package/dist/commands/create.js.map +1 -1
  11. package/dist/commands/login.d.ts.map +1 -1
  12. package/dist/commands/login.js +0 -9
  13. package/dist/commands/login.js.map +1 -1
  14. package/dist/commands/start.d.ts.map +1 -1
  15. package/dist/commands/start.js +6 -7
  16. package/dist/commands/start.js.map +1 -1
  17. package/dist/commands/whoami.d.ts.map +1 -1
  18. package/dist/commands/whoami.js +0 -4
  19. package/dist/commands/whoami.js.map +1 -1
  20. package/dist/docs/content.d.ts.map +1 -1
  21. package/dist/docs/content.js +23 -33
  22. package/dist/docs/content.js.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/lib/api-client.d.ts +0 -12
  25. package/dist/lib/api-client.d.ts.map +1 -1
  26. package/dist/lib/api-client.js +0 -10
  27. package/dist/lib/api-client.js.map +1 -1
  28. package/dist/lib/api-client.test.js +13 -8
  29. package/dist/lib/api-client.test.js.map +1 -1
  30. package/dist/lib/auth.d.ts +0 -1
  31. package/dist/lib/auth.d.ts.map +1 -1
  32. package/dist/lib/auth.js.map +1 -1
  33. package/dist/lib/compiler-stubs.d.ts +12 -0
  34. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  35. package/dist/lib/compiler-stubs.js +18 -0
  36. package/dist/lib/compiler-stubs.js.map +1 -1
  37. package/dist/lib/file-loader.d.ts +14 -0
  38. package/dist/lib/file-loader.d.ts.map +1 -1
  39. package/dist/lib/file-loader.js +63 -9
  40. package/dist/lib/file-loader.js.map +1 -1
  41. package/dist/skill/SKILL.md +76 -6
  42. package/dist/skill/docs/changelog.md +253 -0
  43. package/dist/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  44. package/dist/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  45. package/dist/skill/docs/compiler/config/agents.md +49 -1
  46. package/dist/skill/docs/compiler/config/auth.md +20 -5
  47. package/dist/skill/docs/compiler/config/security.md +46 -0
  48. package/dist/skill/docs/compiler/definitions/access.md +1 -1
  49. package/dist/skill/docs/compiler/definitions/actions.md +46 -4
  50. package/dist/skill/docs/compiler/definitions/scopes.md +11 -3
  51. package/dist/skill/docs/compiler/getting-started/full-example.md +5 -3
  52. package/dist/skill/docs/compiler/getting-started/index.md +7 -7
  53. package/dist/skill/docs/compiler/getting-started/patterns.md +39 -5
  54. package/dist/skill/docs/compiler/getting-started/template-blog.md +65 -44
  55. package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  56. package/dist/skill/docs/compiler/getting-started/template-empty.md +7 -1
  57. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  59. package/dist/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  60. package/dist/skill/docs/stack/account-ui/hooks.md +24 -1
  61. package/dist/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  62. package/dist/skill/docs/stack/auth/plugins/index.md +71 -28
  63. package/dist/skill/docs/stack/storage/r2.md +8 -6
  64. package/dist/skill/docs/stack/storage/using-r2.md +58 -33
  65. package/dist/templates/registry.d.ts +0 -12
  66. package/dist/templates/registry.d.ts.map +1 -1
  67. package/dist/templates/registry.js +0 -42
  68. package/dist/templates/registry.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/skill/SKILL.md +76 -6
  71. package/src/skill/docs/changelog.md +253 -0
  72. package/src/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  73. package/src/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  74. package/src/skill/docs/compiler/config/agents.md +49 -1
  75. package/src/skill/docs/compiler/config/auth.md +20 -5
  76. package/src/skill/docs/compiler/config/security.md +46 -0
  77. package/src/skill/docs/compiler/definitions/access.md +1 -1
  78. package/src/skill/docs/compiler/definitions/actions.md +46 -4
  79. package/src/skill/docs/compiler/definitions/scopes.md +11 -3
  80. package/src/skill/docs/compiler/getting-started/full-example.md +5 -3
  81. package/src/skill/docs/compiler/getting-started/index.md +7 -7
  82. package/src/skill/docs/compiler/getting-started/patterns.md +39 -5
  83. package/src/skill/docs/compiler/getting-started/template-blog.md +65 -44
  84. package/src/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  85. package/src/skill/docs/compiler/getting-started/template-empty.md +7 -1
  86. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  88. package/src/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  89. package/src/skill/docs/stack/account-ui/hooks.md +24 -1
  90. package/src/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  91. package/src/skill/docs/stack/auth/plugins/index.md +71 -28
  92. package/src/skill/docs/stack/storage/r2.md +8 -6
  93. package/src/skill/docs/stack/storage/using-r2.md +58 -33
  94. package/dist/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  95. package/dist/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
  96. package/src/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  97. package/src/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
@@ -225,6 +225,52 @@ security: {
225
225
 
226
226
  The compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).
227
227
 
228
+ ## Custom response headers
229
+
230
+ `security.headers` sets arbitrary response headers on every response, alongside the managed security headers. Keys are header names; values are static strings or templates that interpolate per-deploy Worker env vars via the `{{env.VAR_NAME}}` token.
231
+
232
+ ```ts title="quickback.config.ts"
233
+ security: {
234
+ headers: {
235
+ // Stamp the deployed build identity. Read from Worker vars at runtime,
236
+ // so the value tracks whatever you inject at deploy time.
237
+ 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',
238
+
239
+ // Static value — always emitted.
240
+ 'X-Powered-By': 'Quickback',
241
+ },
242
+ }
243
+ ```
244
+
245
+ The canonical use case is exposing a build/version identity on every response so clients (`curl -I`, mobile apps, dashboards) can read the running build without a body request — and so you can detect drift between what's deployed and what git/CF report.
246
+
247
+ ### Omit-if-unset
248
+
249
+ A header whose value references env vars is emitted **only when every referenced var is set** (non-`undefined`, non-empty string) at runtime. A version header on a Worker that forgot to inject the var simply doesn't appear — never `X-Server-Version: undefined`. Static headers (no `{{env…}}`) are always emitted.
250
+
251
+ The value is read from `c.env` per request, so you don't declare these vars at compile time — inject them as Worker vars (`[vars]` in `wrangler.toml`, or `--var` at deploy) and the header picks them up.
252
+
253
+ ### Generated middleware
254
+
255
+ For the config above, the compiler appends this to the security-headers middleware — no post-compile patching:
256
+
257
+ ```ts
258
+ // Custom response headers (security.headers).
259
+ {
260
+ const v0 = (c.env as unknown as Record<string, string | undefined>)["SERVER_VERSION"];
261
+ const v1 = (c.env as unknown as Record<string, string | undefined>)["SERVER_BUILD"];
262
+ if (v0 != null && v0 !== '' && v1 != null && v1 !== '') {
263
+ c.header("X-Server-Version", `${v0}+${v1}`);
264
+ }
265
+ }
266
+ c.header("X-Powered-By", "Quickback");
267
+ ```
268
+
269
+ ### Rules
270
+
271
+ - **Header names** must be valid HTTP field tokens. Names already managed by a dedicated `security` field — `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Cross-Origin-Opener-Policy`/`-Embedder-Policy`/`-Resource-Policy`, `Referrer-Policy`, `Permissions-Policy` — are rejected; use that field instead so the two emitters don't race.
272
+ - **Only `{{env.VAR_NAME}}`** interpolation is supported (`VAR_NAME` is a valid env-var identifier). A malformed token (`{{env.FOO}`, `{{ENV.FOO}}`) is a compile-time error rather than leaking literal braces into the wire header.
273
+
228
274
  ## Compile-time lint rules
229
275
 
230
276
  The compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.
@@ -159,7 +159,7 @@ For org-scoped tables, `PUBLIC` routes still filter by organization. Since the u
159
159
  GET /api/v1/listings?organizationId=org_abc123
160
160
  ```
161
161
 
162
- The firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.
162
+ The firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.
163
163
 
164
164
  ```typescript
165
165
  // Public listing page — anyone can browse, but scoped to an org
@@ -517,7 +517,7 @@ Use `$ctx` to reference the current user's context:
517
517
  access: {
518
518
  record: {
519
519
  ownerId: { equals: "$ctx.userId" },
520
- orgId: { equals: "$ctx.orgId" }
520
+ organizationId: { equals: "$ctx.activeOrgId" }
521
521
  }
522
522
  }
523
523
  ```
@@ -790,7 +790,7 @@ import type { Auth } from "better-auth";
790
790
  interface ActionExecutorParams {
791
791
  db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)
792
792
  unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)
793
- ctx: AppContext; // User context (userId, roles, orgId)
793
+ ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)
794
794
  record?: TRecord; // The record (record-based only, undefined for standalone)
795
795
  input: TInput; // Validated input from Zod schema
796
796
  services: TServices; // Configured integrations (billing, notifications, etc.)
@@ -884,6 +884,45 @@ always reflects the real actor and the real moment.
884
884
  the parameter is typed as optional. `whereTransition` extends `whereRecord`
885
885
  with the transition's "from" precondition for transition actions.
886
886
 
887
+ #### Reaching Better Auth tables (`authDb`)
888
+
889
+ The scoped `db` only sees your feature tables. To read Better Auth tables —
890
+ users, organizations, members — use the auth database connection from the
891
+ Hono context plus the generated `lib/org-access.ts` helper:
892
+
893
+ ```typescript
894
+ // features/projects/actions/assign.ts — validate a userId is an org member
895
+ import { z } from "zod";
896
+ import { eq } from "drizzle-orm";
897
+ import { ActionError } from "@quickback/compiler";
898
+ import { defineAction } from "../.quickback/define-action";
899
+ import { getOrgMemberRole } from "../../../lib/org-access";
900
+ import { projects } from "../projects";
901
+
902
+ export default defineAction({
903
+ description: "Assign a project to an org member",
904
+ input: z.object({ assigneeId: z.string() }),
905
+ access: { roles: ["member", "admin"] },
906
+ async execute({ db, record, input, ctx, c, whereRecord }) {
907
+ // getOrgMemberRole(authDb, userId, organizationId) → role string | null
908
+ const role = await getOrgMemberRole(c.get("authDb"), input.assigneeId, ctx.activeOrgId!);
909
+ if (!role) {
910
+ throw new ActionError("Assignee is not a member of this organization", "NOT_A_MEMBER", 400);
911
+ }
912
+ const [updated] = await db
913
+ .update(projects)
914
+ .set({ assigneeId: input.assigneeId })
915
+ .where(whereRecord!(projects))
916
+ .returning();
917
+ return updated;
918
+ },
919
+ });
920
+ ```
921
+
922
+ `c.get("authDb")` is the Drizzle connection to the auth database (in dual-DB
923
+ mode it's a separate D1 from your features). For richer queries, import the
924
+ auth schema tables from `../../../auth/schema` and query `authDb` directly.
925
+
887
926
  ## HTTP API Reference
888
927
 
889
928
  ### Request Format
@@ -953,7 +992,7 @@ async execute({ ctx, record, input, c }) {
953
992
  **Option 2: Throw an ActionError**
954
993
 
955
994
  ```typescript
956
- import { ActionError } from "@quickback/types";
995
+ import { ActionError } from "@quickback/compiler";
957
996
 
958
997
  async execute({ ctx, record, input }) {
959
998
  if (record.stage === 'hired') {
@@ -965,7 +1004,10 @@ async execute({ ctx, record, input }) {
965
1004
  }
966
1005
  ```
967
1006
 
968
- The `ActionError` constructor signature is `(message, code, statusCode, details?)`.
1007
+ The `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.
1008
+
1009
+ > Do **not** throw Hono's `HTTPException` from an action — the route handler doesn't unwrap it, so it surfaces as an unhandled **500 ACTION_EXECUTION_FAILED**. Use `ActionError` (or return `c.json(...)` directly) for clean 4xx responses.
1010
+
969
1011
 
970
1012
  ## Protected Fields
971
1013
 
@@ -56,7 +56,7 @@ The server probes **every declared role** for the proposed instance (one DB touc
56
56
  "scope": { "event": { "id": "evt_123", "roles": ["attendee", "shuttleDriver"], "shuttleId": "shA" } }
57
57
  ```
58
58
 
59
- The client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) until you `enter` a different instance.
59
+ The 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.
60
60
 
61
61
  > **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.
62
62
 
@@ -311,13 +311,21 @@ forge a scope role — the guard, not the flag, is the gate.
311
311
 
312
312
  ### TTL and best-effort semantics
313
313
 
314
- - **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at the mint site. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable.
314
+ - **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.
315
315
  - **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).
316
316
  - **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`.
317
317
 
318
318
  ## Revocation & TTL
319
319
 
320
- The scope claim is trusted for the JWT TTL (default 180s, `auth.jwt.expiresIn`) — identical to how `orgId` / `role` claims already behave. Removing a guest/staff row takes effect within one TTL (the next `enter` won't re-mint the role). Immediate revocation (`auth.jwt.revocationCheck: 'kv'`) is on the roadmap.
320
+ The scope claim is trusted between proofs — it is never re-checked against the database while it rides. Two bounds keep that window finite:
321
+
322
+ - **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.
323
+ - **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.
324
+
325
+ So 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:
326
+
327
+ - **`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](/compiler/config/auth).
328
+ - **`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.
321
329
 
322
330
  ## Reference
323
331
 
@@ -60,10 +60,12 @@ export default feature('candidates', {
60
60
  // WRITE OPERATIONS
61
61
  create: { access: { roles: ['hiring-manager', 'recruiter'] } },
62
62
  update: { access: { roles: ['hiring-manager', 'recruiter'] } },
63
- delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },
63
+ delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },
64
64
  });
65
65
  ```
66
66
 
67
+ > `mode: 'hard'` is also available, but hard deletes erase the row — so they require the security-audit pipeline. On D1 that means setting `auditDatabaseId` on the database provider config (the compiler errors with setup instructions if it's missing).
68
+
67
69
  > Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.
68
70
 
69
71
  ---
@@ -75,7 +77,7 @@ Run `quickback compile` and Quickback generates production-ready code.
75
77
  ### Security Helpers
76
78
 
77
79
  ```typescript title="src/features/candidates/candidates.resource.ts"
78
- import { eq, and } from 'drizzle-orm';
80
+ import { eq, and, isNull } from 'drizzle-orm';
79
81
  import { candidates } from './schema';
80
82
  import type { AppContext } from '../../lib/types';
81
83
  import { masks } from '../../lib/masks';
@@ -213,7 +215,7 @@ export function maskCandidates<T extends Record<string, any>>(
213
215
  export const CRUD_ACCESS = {
214
216
  create: { access: { roles: ['hiring-manager', 'recruiter'] } },
215
217
  update: { access: { roles: ['hiring-manager', 'recruiter'] } },
216
- delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },
218
+ delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },
217
219
  };
218
220
 
219
221
  // Views configuration (read pipeline)
@@ -25,11 +25,11 @@ Both paths scaffold the same project:
25
25
  - Working example feature with full security configuration (when you pick `todos`/`blog`/`saas`)
26
26
 
27
27
  **Available templates:**
28
- - `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold (free)
29
- - `todos` — Working CRUD example with masking + actions (free)
30
- - `blog` — Single-tenant blog, PUBLIC reads, admin writes (free)
31
- - `empty` — Cloudflare scaffold, no example features (free)
32
- - `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks (pro)
28
+ - `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold
29
+ - `todos` — Working CRUD example with masking + actions
30
+ - `blog` — Single-tenant blog, PUBLIC reads, admin writes
31
+ - `empty` — Cloudflare scaffold, no example features
32
+ - `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks
33
33
 
34
34
  ## File Structure
35
35
 
@@ -153,12 +153,12 @@ After `quickback compile` and `npm run dev`, your API is running locally. Open a
153
153
 
154
154
  ```bash
155
155
  # 1. Create a user account
156
- curl -X POST http://localhost:8787/api/auth/sign-up/email \
156
+ curl -X POST http://localhost:8787/auth/v1/sign-up/email \
157
157
  -H "Content-Type: application/json" \
158
158
  -d '{"email": "admin@example.com", "password": "securepassword123", "name": "Admin"}'
159
159
 
160
160
  # 2. Sign in and get a session token
161
- curl -X POST http://localhost:8787/api/auth/sign-in/email \
161
+ curl -X POST http://localhost:8787/auth/v1/sign-in/email \
162
162
  -H "Content-Type: application/json" \
163
163
  -d '{"email": "admin@example.com", "password": "securepassword123"}'
164
164
  # → Response includes a session token in Set-Cookie header
@@ -2,7 +2,7 @@
2
2
 
3
3
  Quick recipes for common scenarios. Each pattern shows the complete `defineTable` configuration.
4
4
 
5
- ## Public Read, Authenticated Write
5
+ ## Team-Wide Read, Manager-Only Write
6
6
 
7
7
  A job board where all team members can browse open positions but only hiring managers can create or edit jobs:
8
8
 
@@ -95,16 +95,18 @@ export const interviewScores = sqliteTable("interview_scores", {
95
95
 
96
96
  ```typescript
97
97
  // quickback/features/applications/actions.ts — uses the internal table
98
+ import { z } from "zod";
98
99
  import { defineActions } from "@quickback/compiler";
99
100
  import { applications } from "./applications";
100
101
  import { interviewScores } from "./interview-scores";
101
102
 
102
103
  export default defineActions(applications, {
104
+ // No `path:` → record-based action, mounted at POST /applications/:id/submitScore
103
105
  submitScore: {
104
- type: "record",
105
106
  input: z.object({ score: z.number().min(1).max(5), feedback: z.string() }),
106
107
  access: { roles: ["owner", "hiring-manager", "interviewer"] },
107
108
  execute: async ({ db, record, input, ctx }) => {
109
+ // The scoped db auto-injects organizationId (and audit fields) on insert.
108
110
  await db.insert(interviewScores).values({
109
111
  applicationId: record.id,
110
112
  interviewerId: ctx.userId,
@@ -117,6 +119,39 @@ export default defineActions(applications, {
117
119
  });
118
120
  ```
119
121
 
122
+ ## Referencing Users / Org Members (Assignees)
123
+
124
+ Assignee-style features need to validate that a submitted `userId` is actually a member of the caller's organization. The scoped `db` only sees feature tables — reach the Better Auth tables via `c.get("authDb")` and the generated `getOrgMemberRole` helper:
125
+
126
+ ```typescript
127
+ // quickback/features/projects/actions/assign.ts
128
+ import { z } from "zod";
129
+ import { ActionError } from "@quickback/compiler";
130
+ import { defineAction } from "../.quickback/define-action";
131
+ import { getOrgMemberRole } from "../../../lib/org-access";
132
+ import { projects } from "../projects";
133
+
134
+ export default defineAction({
135
+ description: "Assign a project to an org member",
136
+ input: z.object({ assigneeId: z.string() }),
137
+ access: { roles: ["member+"] },
138
+ async execute({ db, record, input, ctx, c, whereRecord }) {
139
+ const role = await getOrgMemberRole(c.get("authDb"), input.assigneeId, ctx.activeOrgId!);
140
+ if (!role) {
141
+ throw new ActionError("Assignee is not a member of this organization", "NOT_A_MEMBER", 400);
142
+ }
143
+ const [updated] = await db
144
+ .update(projects)
145
+ .set({ assigneeId: input.assigneeId })
146
+ .where(whereRecord!(projects))
147
+ .returning();
148
+ return updated;
149
+ },
150
+ });
151
+ ```
152
+
153
+ Store the assignee as a plain text column (e.g. `assigneeId: q.text().optional()`) — don't name it `userId`, which the firewall validator treats as an ownership column on feature tables.
154
+
120
155
  ## Admin-Only Status Field
121
156
 
122
157
  A field that only hiring managers can modify, but everyone can see:
@@ -126,8 +161,8 @@ export default defineTable(applications, {
126
161
  firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
127
162
  guards: {
128
163
  createable: ["candidateId", "jobId", "notes"],
129
- updatable: ["notes"], // Recruiters can only update notes
130
- protected: ["stage"], // Stage can only be changed via actions
164
+ updatable: ["notes"], // Recruiters can only update notes
165
+ protected: { stage: ["advanceStage"] }, // Stage only changes via the named action
131
166
  },
132
167
  read: {
133
168
  access: { roles: ["owner", "hiring-manager", "recruiter", "interviewer"] },
@@ -144,7 +179,6 @@ Then create an action that hiring managers use to change stage:
144
179
  // quickback/features/applications/actions.ts
145
180
  export default defineActions(applications, {
146
181
  advanceStage: {
147
- type: "record",
148
182
  input: z.object({ stage: z.enum(["applied", "screening", "interview", "offer", "hired", "rejected"]) }),
149
183
  access: { roles: ["hiring-manager"] },
150
184
  execute: async ({ db, record, input }) => {
@@ -20,7 +20,9 @@ my-site/
20
20
  │ └── features/
21
21
  │ └── posts/
22
22
  │ ├── posts.ts # Schema + security (defineTable)
23
- │ └── actions.ts # Publish/unpublish actions
23
+ │ └── actions/
24
+ │ ├── publish.ts # Publish action
25
+ │ └── unpublish.ts # Unpublish action
24
26
  ├── src/ # Compiled output (generated)
25
27
  ├── package.json
26
28
  ├── tsconfig.json
@@ -68,22 +70,31 @@ export const posts = sqliteTable("posts", {
68
70
  excerpt: text("excerpt"),
69
71
  status: text("status").notNull().default("draft"),
70
72
  publishedAt: text("published_at"),
71
- ownerId: text("owner_id").notNull(),
73
+
74
+ // Author tracking only — this is metadata, not access control.
75
+ // Named "authorId" (not "userId") so the firewall validator does NOT
76
+ // enter user-scoped RLS mode. Reads are gated by PUBLIC; writes by the
77
+ // admin access check below.
78
+ authorId: text("author_id").notNull(),
72
79
  });
73
80
 
74
81
  export default defineTable(posts, {
75
- firewall: [
76
- { field: 'ownerId', equals: 'ctx.userId' },
77
- { field: 'deletedAt', isNull: true },
78
- ],
82
+ // PUBLIC reads — no isolation predicate at the firewall layer.
83
+ // Anonymous viewers have no ctx.userId, so a userId/orgId WHERE clause
84
+ // would gate every row out. softDelete keeps deleted posts hidden.
85
+ firewall: {
86
+ softDelete: {},
87
+ },
79
88
  guards: {
80
89
  createable: ["title", "slug", "content", "excerpt", "status", "publishedAt"],
81
90
  updatable: ["title", "slug", "content", "excerpt", "status", "publishedAt"],
82
- immutable: ["id", "ownerId"],
91
+ immutable: ["id", "authorId"],
83
92
  },
84
93
  read: {
85
94
  access: { roles: ["PUBLIC"] },
86
95
  },
96
+ // "admin" = org-membership admin role, resolved from membership in
97
+ // the pinned organization (features.pinnedOrganizationId).
87
98
  create: { access: { roles: ["admin"] } },
88
99
  update: { access: { roles: ["admin"] } },
89
100
  delete: { access: { roles: ["admin"] }, mode: "soft" },
@@ -91,42 +102,44 @@ export default defineTable(posts, {
91
102
  ```
92
103
 
93
104
  - **`PUBLIC`** role on `read.access` means no authentication required for `GET /` and `GET /:id`
94
- - **`admin`** role on `create`, `update`, and `delete` requires an authenticated user with `member.role === "admin"` in the pinned organization
95
- - **`owner`** firewall scope tracks who created each post via `ownerId`
105
+ - **`admin`** is the org-membership admin role — an authenticated user whose membership in the pinned organization has `role: "admin"` (or above). For platform-wide roles stored on `user.role`, use `userRole: [...]` instead — see [Pinned Organization Mode](/compiler/config/single-tenant)
106
+ - **`authorId`** is plain metadata recording who wrote the post — it is deliberately *not* a firewall scope, because an owner predicate would hide every post from anonymous readers
96
107
  - **`softDelete`** marks posts as deleted rather than removing them from the database
97
108
 
98
- ### Post Actions (actions.ts)
109
+ ### Post Actions (actions/publish.ts, actions/unpublish.ts)
99
110
 
100
- The template includes publish/unpublish actions with guard conditions:
111
+ The template scaffolds one file per action under `features/posts/actions/`. Each is a `defineAction` with a record-level access condition and an `execute` handler:
101
112
 
102
113
  ```typescript
103
- import { posts } from './posts';
104
- import { defineActions } from '@quickback/compiler';
105
- import { z } from 'zod';
106
-
107
- export default defineActions(posts, {
108
- publish: {
109
- description: "Publish a draft post",
110
- input: z.object({}),
111
- guard: {
112
- roles: ["admin"],
113
- record: { status: { equals: "draft" } },
114
- },
115
- sideEffects: "sync",
114
+ // quickback/features/posts/actions/publish.ts
115
+ import { z } from "zod";
116
+ import { eq } from "drizzle-orm";
117
+ import { defineAction } from "../.quickback/define-action";
118
+ import { posts } from "../posts";
119
+
120
+ export default defineAction({
121
+ description: "Publish a draft post",
122
+ input: z.object({}),
123
+ access: {
124
+ roles: ["admin"],
125
+ record: { status: { equals: "draft" } },
116
126
  },
117
- unpublish: {
118
- description: "Revert a published post to draft",
119
- input: z.object({}),
120
- guard: {
121
- roles: ["admin"],
122
- record: { status: { equals: "published" } },
123
- },
124
- sideEffects: "sync",
127
+ sideEffects: "sync",
128
+ async execute({ db, record }) {
129
+ const [updated] = await db
130
+ .update(posts)
131
+ .set({
132
+ status: "published",
133
+ publishedAt: new Date().toISOString(),
134
+ })
135
+ .where(eq(posts.id, record.id))
136
+ .returning();
137
+ return updated;
125
138
  },
126
139
  });
127
140
  ```
128
141
 
129
- These actions are admin-only and include record-level guards — you can only publish drafts and unpublish published posts.
142
+ `unpublish.ts` is the mirror image — it requires `status: "published"` and reverts the post to draft. These actions are admin-only and include record-level access conditions: you can only publish drafts and unpublish published posts.
130
143
 
131
144
  ## Setup Steps
132
145
 
@@ -148,21 +161,27 @@ quickback login
148
161
  quickback compile
149
162
  ```
150
163
 
151
- ### 4. Create D1 Database
164
+ ### 4. Create D1 Databases
152
165
 
153
- The blog template uses a single D1 database (no split databases):
166
+ Like every D1 project, the blog template uses dual database mode by default — separate databases for auth and application data:
154
167
 
155
168
  ```bash
156
- npx wrangler d1 create my-site
169
+ npx wrangler d1 create my-site-auth
170
+ npx wrangler d1 create my-site-features
157
171
  ```
158
172
 
159
- Copy the database ID from the output and update your `wrangler.toml`:
173
+ Copy the database IDs from the output and update your `wrangler.toml`:
160
174
 
161
175
  ```toml
176
+ [[d1_databases]]
177
+ binding = "AUTH_DB"
178
+ database_name = "my-site-auth"
179
+ database_id = "paste-auth-id-here"
180
+
162
181
  [[d1_databases]]
163
182
  binding = "DB"
164
- database_name = "my-site"
165
- database_id = "paste-id-here"
183
+ database_name = "my-site-features"
184
+ database_id = "paste-features-id-here"
166
185
  ```
167
186
 
168
187
  ### 5. Run Migrations (Local)
@@ -200,8 +219,8 @@ curl -X POST http://localhost:8787/api/v1/posts \
200
219
  -H "Content-Type: application/json" \
201
220
  -d '{"title": "Hello World", "slug": "hello-world", "content": "..."}'
202
221
 
203
- # Publish a post (admin only)
204
- curl -X POST http://localhost:8787/api/v1/posts/post-id/actions/publish \
222
+ # Publish a post (admin only) — record actions mount at /:id/{actionName}
223
+ curl -X POST http://localhost:8787/api/v1/posts/post-id/publish \
205
224
  -H "Authorization: Bearer $TOKEN"
206
225
  ```
207
226
 
@@ -238,17 +257,19 @@ export const pages = sqliteTable("pages", {
238
257
  title: text("title").notNull(),
239
258
  slug: text("slug").notNull().unique(),
240
259
  content: text("content"),
241
- ownerId: text("owner_id").notNull(),
260
+ authorId: text("author_id").notNull(),
242
261
  });
243
262
 
244
263
  export default defineTable(pages, {
245
- firewall: [{ field: 'ownerId', equals: 'ctx.userId' }],
264
+ // PUBLIC reads need an open firewall — an owner predicate would hide
265
+ // every row from anonymous visitors. softDelete still hides deletions.
266
+ firewall: { softDelete: {} },
246
267
  read: {
247
268
  access: { roles: ["PUBLIC"] },
248
269
  },
249
270
  create: { access: { roles: ["admin"] } },
250
271
  update: { access: { roles: ["admin"] } },
251
- delete: { access: { roles: ["admin"] } },
272
+ delete: { access: { roles: ["admin"] }, mode: "soft" },
252
273
  });
253
274
  ```
254
275
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  The Cloudflare template creates a production-ready backend running on Cloudflare Workers with D1 (SQLite at the edge), KV storage, and Better Auth.
4
4
 
5
- `cloudflare` is a **bare scaffold** — multi-tenant orgs + auth + DB are wired in, but there are no example features. Add your own feature files under `quickback/features/`. If you want a working example to read first, use the [todos template](/compiler/getting-started/templates#multi-tenant-scaffolds-free) — same providers, but with a complete `todos` feature ready to extend.
5
+ `cloudflare` is a **bare scaffold** — multi-tenant orgs + auth + DB are wired in, but there are no example features. Add your own feature files under `quickback/features/`. If you want a working example to read first, use the [todos template](/compiler/getting-started/templates#multi-tenant-scaffolds) — same providers, but with a complete `todos` feature ready to extend.
6
6
 
7
7
  ## Create the Project
8
8
 
@@ -43,9 +43,6 @@ my-app/
43
43
  export default {
44
44
  name: "my-app",
45
45
  template: "hono",
46
- features: {
47
- organizations: true,
48
- },
49
46
  auth: {
50
47
  // Use "role+" in access rules to mean "this role and above".
51
48
  // e.g. roles: ["member+"] expands to ["member", "admin", "owner"].
@@ -62,9 +59,11 @@ export default {
62
59
  };
63
60
  ```
64
61
 
62
+ Multi-tenant organizations are on by default — no flag needed. To build a single-tenant app instead, set `organizations: false` on the database provider config.
63
+
65
64
  ### Adding your first feature
66
65
 
67
- Create a file at `quickback/features/<name>/<name>.ts` and export a `defineTable(...)` default. The shape used by the `todos` template makes a good starting point — see [todos.ts in the template registry](/compiler/getting-started/templates#multi-tenant-scaffolds-free) for a full multi-tenant example with masking, actions, and a named view.
66
+ Create a file at `quickback/features/<name>/<name>.ts` and export a `defineTable(...)` default. The shape used by the `todos` template makes a good starting point — see [todos.ts in the template registry](/compiler/getting-started/templates#multi-tenant-scaffolds) for a full multi-tenant example with masking, actions, and a named view.
68
67
 
69
68
  ```typescript
70
69
  // quickback/features/posts/posts.ts
@@ -33,6 +33,12 @@ my-app/
33
33
  export default {
34
34
  name: "my-app",
35
35
  template: "hono",
36
+ auth: {
37
+ // Role hierarchy: lowest → highest privilege.
38
+ // Use "role+" in access rules to mean "this role and above".
39
+ // e.g. roles: ["member+"] expands to ["member", "admin", "owner"].
40
+ roleHierarchy: ["member", "admin", "owner"],
41
+ },
36
42
  providers: {
37
43
  runtime: { name: "cloudflare", config: {} },
38
44
  database: {
@@ -96,7 +102,7 @@ quickback compile
96
102
 
97
103
  ## Setup Steps
98
104
 
99
- Follow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). The only difference is you'll need to add at least one feature before compiling.
105
+ Follow the same setup steps as the [Cloudflare template](/compiler/getting-started/template-cloudflare#setup-steps). Compiling with zero features works (you get an auth-only API); add feature files as you go and recompile.
100
106
 
101
107
  ## Next Steps
102
108
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Quickback provides pre-configured templates to get you started quickly. Each template combines a runtime, database, and auth provider into a working project.
4
4
 
5
- The fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. Every template below can be reached either via `start`'s picker (free tier) or scriptably via `quickback create <template> <name>`.
5
+ The fastest way to start is `quickback start` — an interactive picker that asks for a template + project name and scaffolds in the current directory if it's empty, otherwise creates a subfolder. The picker offers `cloudflare`, `todos`, `blog`, and `empty`; every template (including `saas`) is available scriptably via `quickback create <template> <name>`.
6
6
 
7
7
  ```bash
8
8
  # Interactive (recommended for first-time use)
@@ -12,7 +12,7 @@ npx @quickback-dev/cli start
12
12
 
13
13
  ## Available Templates
14
14
 
15
- ### Multi-tenant scaffolds (free)
15
+ ### Multi-tenant scaffolds
16
16
 
17
17
  Cloudflare Workers + D1 + Better Auth with the organization plugin and a `member` / `admin` / `owner` role hierarchy wired in.
18
18
 
@@ -23,7 +23,7 @@ Cloudflare Workers + D1 + Better Auth with the organization plugin and a `member
23
23
 
24
24
  The **todos** template is the recommended first read — it exercises every security pillar (firewall, access, guards, masking) plus actions and views in ~80 lines you can scan in five minutes.
25
25
 
26
- ### Fixed-org starter (free)
26
+ ### Fixed-org starter
27
27
 
28
28
  | Template | Includes | Command |
29
29
  |----------|----------|---------|
@@ -31,7 +31,7 @@ The **todos** template is the recommended first read — it exercises every secu
31
31
 
32
32
  The **blog** template uses [pinned organization mode](/compiler/config/single-tenant) and scaffolds `features.pinnedOrganizationId: "org_replace_me"`.
33
33
 
34
- ### Empty scaffold (free)
34
+ ### Empty scaffold
35
35
 
36
36
  | Template | Includes | Command |
37
37
  |----------|----------|---------|
@@ -39,7 +39,7 @@ The **blog** template uses [pinned organization mode](/compiler/config/single-te
39
39
 
40
40
  The empty template creates the project structure with `quickback.config.ts` only. Add your first feature by creating a file under `quickback/features/<name>/<name>.ts` exporting `defineTable(...)` — there is no separate `init` step.
41
41
 
42
- ### B2B SaaS (Pro)
42
+ ### B2B SaaS
43
43
 
44
44
  | Template | Includes | Command |
45
45
  |----------|----------|---------|
@@ -80,7 +80,7 @@ Best for personal sites, blogs, or any app that only needs one organization at r
80
80
 
81
81
  Best when you know exactly what you want to build. Gets you the project structure and config without any opinionated features.
82
82
 
83
- ### SaaS (Pro)
83
+ ### SaaS
84
84
 
85
85
  Best for production B2B work. Adds R2 file uploads, outbound webhooks (with retry/dedupe), split auth/features/webhooks databases, realtime broadcast, and named views.
86
86