@quickback-dev/cli 0.47.9 → 0.47.11

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.
@@ -79,17 +79,18 @@ export type Candidate = typeof candidates.$inferSelect;
79
79
  > A table **without** `defineTable()` is a supporting table — used internally by actions or handlers, but never exposed as its own API endpoint. See [Internal Tables](/compiler/definitions/schema#internal-tables-no-routes) for details.
80
80
 
81
81
 
82
- ## The Four Security Layers
82
+ ## The Five Security Layers
83
83
 
84
- Every API request passes through four security layers, in order:
84
+ Every API request passes through five security layers, in order:
85
85
 
86
86
  ```
87
- Request → Firewall → Access → Guards → Masking → Response
88
- │ │ │ │
89
- │ │ │ └── Hide sensitive fields
90
- │ │ └── Block field modifications
91
- │ └── Check roles & conditions
92
- └── Isolate data by owner/org/team
87
+ Request → Rate Limit → Firewall → Access → Guards → Masking → Response
88
+ │ │ │ │ │
89
+ │ │ │ │ └── Hide sensitive fields
90
+ │ │ │ └── Block field modifications
91
+ │ │ └── Check roles & conditions
92
+ │ └── Isolate data by owner/org/team
93
+ └── Cap requests per user / op
93
94
  ```
94
95
 
95
96
  > **Security Applies Everywhere**
@@ -154,25 +155,44 @@ masking: {
154
155
 
155
156
  [Learn more about Masking →](/compiler/definitions/masking)
156
157
 
158
+ ### 5. Rate Limiting (Request Caps)
159
+
160
+ Rate 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.
161
+
162
+ ```typescript
163
+ rateLimit: {
164
+ delete: { limit: 5, period: 60 }, // tighter than the 200/60s default
165
+ },
166
+ // read / create / update keep shipped defaults
167
+ ```
168
+
169
+ Override 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`.
170
+
171
+ [Learn more about Rate Limiting →](/compiler/definitions/rate-limit)
172
+
157
173
  ## How They Work Together
158
174
 
159
175
  **Scenario:** An interviewer requests `GET /candidates/cnd_123`
160
176
 
161
- 1. **Firewall** checks: Is candidate `cnd_123` in the user's organization?
177
+ 1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?
178
+ - Yes → Continue
179
+ - No → 429 Too Many Requests (with `Retry-After`)
180
+
181
+ 2. **Firewall** checks: Is candidate `cnd_123` in the user's organization?
162
182
  - Yes → Continue
163
183
  - No → 404 Not Found (as if it doesn't exist)
164
184
 
165
- 2. **Access** checks: Can interviewers perform GET?
185
+ 3. **Access** checks: Can interviewers perform GET?
166
186
  - Yes → Continue
167
187
  - No → 403 Forbidden
168
188
 
169
- 3. **Guards** don't apply to GET (they're for writes)
189
+ 4. **Guards** don't apply to GET (they're for writes)
170
190
 
171
- 4. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`
191
+ 5. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`
172
192
  - Email: `jane@company.com` → `j***@c******.com`
173
193
  - Phone: `555-123-4567` → `******4567`
174
194
 
175
- 5. **Response** sent with masked data
195
+ 6. **Response** sent with masked data
176
196
 
177
197
  ## Locked Down by Default
178
198
 
@@ -183,13 +203,14 @@ Quickback is **secure by default**. Nothing is accessible until you explicitly a
183
203
  | Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |
184
204
  | Access | DENIED | Explicitly define `access` rules with roles |
185
205
  | Guards | LOCKED | Explicitly list `createable`, `updatable` fields |
206
+ | Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |
186
207
  | Actions | BLOCKED | Explicitly define `access` for each action |
187
208
 
188
209
  **You must deliberately open each door.** This prevents accidental data exposure.
189
210
 
190
211
  ## Other Resource Options
191
212
 
192
- Beyond the four security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.
213
+ Beyond the five security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.
193
214
 
194
215
  | Option | What it does | Full reference |
195
216
  |---|---|---|
@@ -212,6 +233,7 @@ All options are optional — omit them and Quickback uses sensible defaults (aut
212
233
  3. [Access](/compiler/definitions/access) — Configure read and write permissions
213
234
  4. [Guards](/compiler/definitions/guards) — Control field modifications
214
235
  5. [Masking](/compiler/definitions/masking) — Hide sensitive data
215
- 6. [Views](/compiler/definitions/views) — Column-level security
216
- 7. [Validation](/compiler/definitions/validation) — Field validation rules
217
- 8. [Actions](/compiler/definitions/actions) — Add custom business logic
236
+ 6. [Rate Limit](/compiler/definitions/rate-limit) — Per-operation request caps
237
+ 7. [Views](/compiler/definitions/views) — Column-level security
238
+ 8. [Validation](/compiler/definitions/validation) — Field validation rules
239
+ 9. [Actions](/compiler/definitions/actions) — Add custom business logic
@@ -154,6 +154,11 @@ The compiler emits a per-trigger lowering report and warns at compile time
154
154
  when a `before*` handler is used as a guard — if a rule must hold for every
155
155
  write path, use the `sql:` lane with `RAISE(ABORT)`.
156
156
 
157
+ > Cron jobs themselves are first-class — declare them with
158
+ > [`defineSchedule`](/stack/schedules) and the compiler emits the Worker
159
+ > `scheduled()` handler + `wrangler.toml` triggers. This note is only about
160
+ > the table-trigger `handler:` lane not firing inside them.
161
+
157
162
  ## Choosing a lane
158
163
 
159
164
  | Need | Use |
@@ -1,6 +1,6 @@
1
1
  # Auth Hooks
2
2
 
3
- Quickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.
3
+ Quickback discovers project-level auth hooks at `quickback/hooks/`. The `before-`/`after-` lifecycle hooks wire into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks); the `resolve-*` hooks are trusted server resolvers called from generated middleware (OAuth) or the email send, not databaseHooks. Use them for post-signup bootstrap, signup gating, tenant resolution, and per-recipient email context.
4
4
 
5
5
  The classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `403 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.
6
6
 
@@ -13,6 +13,8 @@ quickback/
13
13
  before-user-create.ts
14
14
  after-session-create.ts
15
15
  after-admin-user-create.ts
16
+ resolve-oauth-context.ts
17
+ resolve-email-context.ts
16
18
  ```
17
19
 
18
20
  Each file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.
@@ -26,6 +28,7 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
26
28
  | `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |
27
29
  | `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
28
30
  | `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |
31
+ | `resolve-email-context.ts` | emailOTP `sendVerificationOTP` | `{ email, type, name }` | Extra fields merged into the email template context |
29
32
 
30
33
  `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.
31
34
 
@@ -53,6 +56,49 @@ The returned object is merged into the standard `AppContext`. The compiler
53
56
  always preserves the validated `authenticated`, `userId`, and `user` fields,
54
57
  so this hook cannot replace the OAuth identity.
55
58
 
59
+ ## Email context resolver
60
+
61
+ Better Auth routes OTP emails by **type** (`sign-in`, `email-verification`,
62
+ `forget-password`), not by audience, and a template only receives fixed
63
+ `appName` / `appUrl` / `supportEmail`. When you need **per-recipient** context —
64
+ a branded palette for organizers vs. attendees, a plan tier, a locale —
65
+ add `quickback/hooks/resolve-email-context.ts`. The emailOTP send calls it for
66
+ each recipient and **spreads the returned object into your email templates**.
67
+
68
+ ```ts title="quickback/hooks/resolve-email-context.ts"
69
+ export default async ({ email, type, name, db, schema, eq, and }) => {
70
+ // Is this recipient a member of any organization?
71
+ const [u] = await db.select({ id: schema.user.id })
72
+ .from(schema.user).where(eq(schema.user.email, email)).limit(1);
73
+ const isOrgMember = u
74
+ && (await db.select({ id: schema.member.id })
75
+ .from(schema.member).where(eq(schema.member.userId, u.id)).limit(1)).length > 0;
76
+
77
+ return { audience: isOrgMember ? "organizer" : "attendee" };
78
+ };
79
+ ```
80
+
81
+ Your [email template](/stack/auth/plugins/aws-ses#per-type-template-overrides) then reads the extra field:
82
+
83
+ ```ts title="quickback/email-templates/sign-in.ts"
84
+ export default ({ otp, appName, audience }) => ({
85
+ subject: `Your ${appName} code`,
86
+ html: renderOtp({ otp, theme: audience === "organizer" ? "eggplant" : "blue" }),
87
+ text: `Your code is ${otp}`,
88
+ });
89
+ ```
90
+
91
+ Notes:
92
+
93
+ - **Fail-open.** If the hook throws, the context falls back to `{}` and the OTP
94
+ still sends — a hook bug can never lock users out of sign-in.
95
+ - **Spread into user templates only.** The packaged default templates have a
96
+ fixed signature; convert a type to a [custom template](/stack/auth/plugins/aws-ses#per-type-template-overrides) to consume the extra context.
97
+ - `db`, `schema`, `eq`, and `and` are passed in (the same Drizzle handle Better
98
+ Auth uses) so you can look the recipient up without an import.
99
+ - This is **not** a Better Auth `databaseHook` — it's consumed only by the
100
+ emailOTP send, so it adds no signup/session latency.
101
+
56
102
  ## ctx shape
57
103
 
58
104
  Every hook receives `(entity, ctx)`:
@@ -10,6 +10,7 @@
10
10
  | [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |
11
11
  | [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |
12
12
  | [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |
13
+ | [Schedules](/stack/schedules) | Cron Triggers | `defineSchedule` cron jobs, server-internal |
13
14
  | [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |
14
15
  | [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |
15
16
  | [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |
@@ -35,6 +36,11 @@
35
36
  │ │ Queues │ │ Better Auth │ │
36
37
  │ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │
37
38
  │ └─────────────┘ └─────────────────────────────────┘ │
39
+ │ │
40
+ │ ┌─────────────┐ │
41
+ │ │ Schedules │ │
42
+ │ │ (Cron) │ │
43
+ │ └─────────────┘ │
38
44
  └─────────────────────────────────────────────────────────────┘
39
45
  ```
40
46
 
@@ -163,6 +163,16 @@ bindings: {
163
163
  access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
164
164
  },
165
165
 
166
+ // Identity-gated room — the roomId IS the caller's own id, with no backing
167
+ // table. A per-user gateway / presence / inbox keyed on `ctx.userId`:
168
+ // auto-emits a gate at /realtime/user-gateway/* that 403s unless the room
169
+ // segment equals the authenticated user's id. Use `ctx.activeOrgId` for a
170
+ // per-org room. No DB query — it's a string compare against ctx.
171
+ {
172
+ name: 'UserGateway', className: 'UserGateway', from: 'lib/UserGateway',
173
+ access: { roomIdEquals: 'ctx.userId' },
174
+ },
175
+
166
176
  // Genuinely public room (no auth, no row lookup) — opt out explicitly.
167
177
  { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',
168
178
  access: 'public' },
@@ -176,6 +186,7 @@ What the compiler emits:
176
186
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
177
187
  - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
178
188
  - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
189
+ - **`access: { roomIdEquals: 'ctx.userId' }`** — an **identity gate** for rooms with no backing table, where the roomId *is* the caller's own id. Emits `app.use('/realtime/<kebab>/*', …)` that 401s anonymous, 400s a missing segment, and 403s unless the decoded room segment equals `ctx.userId`. No schema import, no firewall, no DB query — a string compare against the server-resolved `ctx`. Use `'ctx.activeOrgId'` for a per-org room. This is the right gate for per-user gateways, presence, or inbox DOs keyed on `ns.idFromName(ctx.userId)`. Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted (validated at compile time); anything else is a build error. Distinct from `resource` because there's no row to firewall — it closes the cross-user hole that "no `access` declared" leaves open (any authenticated user could otherwise open another user's room via the catchall).
179
190
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
180
191
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)
181
192
 
@@ -189,6 +200,7 @@ If a room currently enforces access by hand inside `onConnect` / `onBeforeConnec
189
200
  2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.
190
201
  3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.
191
202
  4. **access depends on membership, not just tenant** (e.g. "is this user an attendee of the event that owns this page") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.
203
+ 5. **roomId is the caller's own identity** (a per-user gateway/presence/inbox where the room *is* `ctx.userId`, with no backing table) → `access: { roomIdEquals: 'ctx.userId' }` (or `'ctx.activeOrgId'`). Do **not** enforce this inside the DO from request data — a Durable Object has no session and only sees client-settable headers, so trusting an `x-user-id` header lets any authenticated user open another user's room. The gate belongs at the Worker edge, which is exactly what this arm emits.
192
204
 
193
205
  The declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.
194
206
 
@@ -0,0 +1,78 @@
1
+ # Schedules (Cron)
2
+
3
+ `defineSchedule` is the trigger-side mirror of [`defineQueue`](/stack/queues). Drop a file in `services/schedules/` and the compiler emits a Worker `scheduled()` (cron) handler plus the matching `[triggers] crons` in `wrangler.toml` — no separate cron Worker, no hand-patching the generated entry.
4
+
5
+ ## Define a schedule
6
+
7
+ ```typescript
8
+ // services/schedules/sweepDigests.ts
9
+ import { defineSchedule } from "quickback";
10
+
11
+ export default defineSchedule({
12
+ name: "sweepDigests", // identifier + audit actor (system:cron-<name>)
13
+ cron: "* * * * *", // Cloudflare cron syntax
14
+ description: "Send pending unread-email digests",
15
+ execute: async ({ db, env, services }) => {
16
+ await runDigestSweep(db, env, services);
17
+ },
18
+ });
19
+ ```
20
+
21
+ One file per schedule under `services/schedules/*.ts`. Files prefixed with `_` are ignored. `name` must be a valid camelCase identifier (it's used as a generated symbol and the audit actor).
22
+
23
+ ## What the compiler emits
24
+
25
+ 1. **`scheduled(event, env, ctx)`** in the Worker's default export, dispatching to every schedule whose cron matches `event.cron`. Multiple schedules can share a cron; a failure in one is isolated from the others.
26
+ 2. **`[triggers] crons = [...]`** in `wrangler.toml` — one deduped, sorted list across all schedules.
27
+ 3. **`src/lib/schedules.ts`** — the generated runner. Regenerated on every `quickback compile`, so there's nothing to hand-maintain.
28
+
29
+ ## Execute context
30
+
31
+ | Field | Type | Notes |
32
+ |-------|------|-------|
33
+ | `db` | Drizzle instance | The same DB the queue handlers get |
34
+ | `env` | `CloudflareBindings` | All worker bindings |
35
+ | `services` | `Services` | The services layer (`createServices(env)`) |
36
+ | `cron` | `string` | The cron pattern that fired |
37
+ | `scheduledTime` | `number` | `event.scheduledTime` (ms epoch) |
38
+ | `withInternalContext` | helper | Opt into the `INTERNAL` trust zone for `roles: ['INTERNAL']`-gated rows |
39
+
40
+ ## Audit & trust
41
+
42
+ Cron runs are **server-internal**: there's no authenticated user, no request, no org scope. A fired tick gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:
43
+
44
+ ```typescript
45
+ execute: async ({ db, withInternalContext }) => {
46
+ // `db` here is unscoped — no firewall WHERE, no audit actor.
47
+
48
+ // Opt into the INTERNAL trust zone for cross-tenant work:
49
+ await withInternalContext(async ({ ctx, db, services }) => {
50
+ // ctx.internal = true, ctx.userId = "system:cron-<name>"
51
+ // audited writes are attributable to e.g. system:cron-sweepDigests
52
+ });
53
+ },
54
+ ```
55
+
56
+ `withInternalContext` builds a context with `internal: true` and `userId: "system:cron-<name>"`, so audited writes made through it are attributable to the schedule (e.g. `system:cron-sweepDigests`) and can reach `roles: ['INTERNAL']`-gated rows. Reach for it whenever the schedule legitimately operates across tenants.
57
+
58
+ ## Failure isolation
59
+
60
+ The generated `scheduled()` dispatcher runs every schedule whose cron matches `event.cron` concurrently (`Promise.all`), and each handler's errors are caught individually — one failing schedule logs `[Cron] Schedule error` and the others still run to completion. A cron with no registered handler logs `[Cron] No schedule registered` and returns.
61
+
62
+ ## Cron syntax
63
+
64
+ Standard Cloudflare cron (`minute hour day-of-month month day-of-week`):
65
+
66
+ | Pattern | Runs |
67
+ |---------|------|
68
+ | `* * * * *` | every minute |
69
+ | `0 * * * *` | top of every hour |
70
+ | `0 0 * * *` | daily at 00:00 UTC |
71
+ | `*/5 * * * *` | every 5 minutes |
72
+
73
+ See Cloudflare's [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) docs for the full grammar and limits.
74
+
75
+ ## See also
76
+
77
+ - [Queues](/stack/queues) — the async-message counterpart (`defineQueue`)
78
+ - [Triggers](/compiler/definitions/triggers) — row-level lifecycle hooks (distinct from cron)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.47.9",
3
+ "version": "0.47.11",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -30,7 +30,7 @@
30
30
  ],
31
31
  "type": "module",
32
32
  "bin": {
33
- "quickback": "./dist/index.js"
33
+ "quickback": "dist/index.js"
34
34
  },
35
35
  "main": "./dist/index.js",
36
36
  "files": [
@@ -2,6 +2,75 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ### Custom secrets via `bindings.secrets`
6
+
7
+ Declare a custom secret your feature/action code reads off `env` — name and
8
+ contract only, never the value:
9
+
10
+ ```ts
11
+ bindings: {
12
+ secrets: [
13
+ { name: "WEBHOOK_SIGNING_SECRET", description: "HMAC for webhook callbacks", required: true },
14
+ ],
15
+ }
16
+ ```
17
+
18
+ It's emitted into the generated `env.d.ts` `Env` interface so `env.<NAME>`
19
+ type-checks, and `required` secrets join the boot-time env guard — the worker
20
+ fails closed with `503 MISSING_ENV` if one is unset. The value is set
21
+ out-of-band (`wrangler secret put`); the schema rejects any inline value so a
22
+ real secret can never be committed. See
23
+ [Bindings → secrets](/compiler/config/bindings#secrets).
24
+
25
+ ### Auth: `resolve-email-context.ts` hook for per-recipient OTP context
26
+
27
+ Drop `quickback/hooks/resolve-email-context.ts` and the emailOTP send calls it
28
+ per recipient, spreading the returned object into your email templates — branded
29
+ palettes (organizer vs. attendee), plan tier, locale, etc. — without patching
30
+ generated output. Fail-open, with the Drizzle handle passed in. See
31
+ [Auth Hooks → Email context resolver](/stack/account-ui/hooks#email-context-resolver).
32
+
33
+ ### Codegen fixes
34
+
35
+ - **Schedules:** handler import paths are now rebased on relocation, so a cron
36
+ handler importing `../../features/...` resolves correctly from the generated
37
+ `src/lib/schedules.ts` instead of failing the worker build.
38
+ - **OAuth/MCP middleware:** the auth-schema tables are imported under aliased
39
+ names so a function-scoped `const session` can no longer shadow the `session`
40
+ table import — closes a temporal-dead-zone crash that silently 401'd every
41
+ OAuth/MCP bearer.
42
+ - **MCP route:** the large tool-data literal is split into a `mcp-tools.ts` data
43
+ module (suppressed) so it can't overrun `tsc`'s type-instantiation budget; the
44
+ `mcp.ts` route logic stays fully type-checked.
45
+
46
+ ### Realtime: identity-gated Durable Object rooms (`roomIdEquals`)
47
+
48
+ Per-user Durable Object entrypoints (gateway / presence / inbox) can now declare
49
+ an identity gate on the binding — `access: { roomIdEquals: 'ctx.userId' }` (or
50
+ `'ctx.activeOrgId'`). The compiler emits a Worker-edge gate at
51
+ `/realtime/<kebab>/*` that 401s anonymous callers, 400s a missing segment, and
52
+ 403s unless the decoded room segment equals the server-resolved `ctx` id — a
53
+ string compare with no backing table or DB query. See
54
+ [PartyServer rooms → Per-room authorization](/stack/realtime/partyserver-rooms).
55
+
56
+ - Closes the cross-user hole that "no `access` declared" leaves open: a per-user
57
+ room without a gate falls through to the authenticated-only catchall, so any
58
+ authenticated user could open another user's room by guessing the id.
59
+ - The gate lives at the edge, not in the DO — a Durable Object has no session
60
+ and only sees client-settable headers, so it must never re-authorize from
61
+ request data (trusting an `x-user-id` header was the original spoof hole).
62
+ - Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted; anything else is a
63
+ compile-time error (fail-closed Zod + generator validation).
64
+
65
+ ### OAuth provider: spurious authorization-server warning silenced by default
66
+
67
+ The generated `oauthProvider({...})` now emits
68
+ `silenceWarnings: { oauthAuthServerConfig: true }` by default. The compiler
69
+ always serves the `/.well-known/oauth-authorization-server` discovery route when
70
+ the provider is enabled, so `@better-auth/oauth-provider`'s
71
+ "please ensure … exists" boot warning was always spurious. Override or extend it
72
+ via `plugins.oauthProvider.silenceWarnings`.
73
+
5
74
  ### `defineSchedule` — cron jobs from a single source
6
75
 
7
76
  Declare a cron schedule in `services/schedules/*.ts` and the compiler emits the
@@ -1,6 +1,6 @@
1
1
  # Custom Bindings
2
2
 
3
- Quickback's compiler owns the D1/KV/R2/ASSETS/queue blocks it needs for its own features. Anything else your worker binds to — Cloudflare Email, an extra R2 bucket, a custom queue, a service binding, your own Durable Object, Workers AI, or non-secret `[vars]` — goes under the top-level `bindings` key:
3
+ Quickback's compiler owns the D1/KV/R2/ASSETS/queue blocks it needs for its own features. Anything else your worker binds to — Cloudflare Email, an extra R2 bucket, a custom queue, a service binding, your own Durable Object, Workers AI, non-secret `[vars]`, or a custom `secret` your code reads off `env` — goes under the top-level `bindings` key:
4
4
 
5
5
  ```ts
6
6
  import { defineConfig, defineRuntime, defineDatabase, defineAuth } from "@quickback-dev/cli";
@@ -22,6 +22,9 @@ export default defineConfig({
22
22
  vars: {
23
23
  MAIL_SENDING_DOMAIN: "studio.example.com",
24
24
  },
25
+ secrets: [
26
+ { name: "MAIL_INBOUND_SECRET", description: "Verifies inbound mail webhooks", required: true },
27
+ ],
25
28
  },
26
29
  });
27
30
  ```
@@ -170,12 +173,48 @@ vars: {
170
173
  }
171
174
  ```
172
175
 
173
- Secrets do **not** go here. Use Wrangler's secret store instead:
176
+ Secrets do **not** go here. Declare them under [`secrets`](#secrets) (name only) and set the value with Wrangler's secret store:
174
177
 
175
178
  ```bash
176
179
  wrangler secret put MAIL_INBOUND_SECRET
177
180
  ```
178
181
 
182
+ ### `secrets`
183
+
184
+ Declares a custom secret your feature or action code reads off `env`. You record the **name and contract only** — the value is never stored in config, `wrangler.toml`, or git.
185
+
186
+ ```ts
187
+ secrets: [
188
+ {
189
+ name: "WEBHOOK_SIGNING_SECRET",
190
+ description: "HMAC secret for outbound webhook callbacks",
191
+ required: true,
192
+ },
193
+ { name: "PARTNER_API_KEY" }, // optional
194
+ ]
195
+ ```
196
+
197
+ Each declared secret:
198
+
199
+ - is emitted into the generated `env.d.ts` `Env` interface as an optional `WEBHOOK_SIGNING_SECRET?: string`, so `env.WEBHOOK_SIGNING_SECRET` type-checks in your code;
200
+ - when `required: true`, joins the **boot-time env guard** — the worker fails closed with a `503 MISSING_ENV` if the secret is unset, rather than 500ing on the first request that reads it (same posture as `BETTER_AUTH_SECRET`);
201
+ - surfaces its `description` and a `wrangler secret put <NAME>` hint in the generated type's JSDoc.
202
+
203
+ | Field | Type | |
204
+ | --- | --- | --- |
205
+ | `name` | `string` | Env var name. Letters, digits, underscores only — `SCREAMING_SNAKE_CASE` by convention. |
206
+ | `description` | `string?` | Human note shown in the JSDoc + secret-setup hint. |
207
+ | `required` | `boolean?` | Fail closed at boot if unset. Default `false`. |
208
+
209
+ Set the value out-of-band — it lands in Cloudflare's encrypted secret store:
210
+
211
+ ```bash
212
+ wrangler secret put WEBHOOK_SIGNING_SECRET
213
+ ```
214
+
215
+ > `secrets` records a **contract**, not a value. The schema rejects any inline value key, so a real secret can never be pasted into committed config. Use [`vars`](#vars) for non-secret values that are safe to commit.
216
+
217
+
179
218
  ### `ai`
180
219
 
181
220
  Emits a top-level `[ai]` block. Use this if you need Workers AI bound under a name different from Quickback's internal `AI`.
@@ -84,21 +84,30 @@ quickback compile --no-sync-config
84
84
 
85
85
  ## Optional Fields
86
86
 
87
+ Every 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.
88
+
87
89
  | Field | Type | Description |
88
90
  |-------|------|-------------|
89
- | `features` | `object` | Feature flags such as `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |
90
- | `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |
91
- | `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |
92
- | `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |
93
- | `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |
94
- | `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |
95
- | `cms` | `boolean \| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |
96
- | `account` | `boolean \| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |
91
+ | `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) — see [Domains](/compiler/config/domains) |
92
+ | `api` | `object` | Dedicated hostname for the feature API surface (`/api/v1/*`); additive alias — see [Domains](/compiler/config/domains) |
93
+ | `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) |
94
+ | `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `permissions`, `arrows`) — see [Permissions](/compiler/definitions/permissions) |
97
95
  | `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |
98
- | `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |
99
- | `dev` | `object` | Local development settings (`port`) |
100
- | `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |
101
- | `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |
96
+ | `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |
97
+ | `cms` | `boolean \| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) — see [CMS](/stack/cms) |
98
+ | `account` | `boolean \| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) — see [Account UI](/stack/account-ui) |
99
+ | `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix — see [Domains](/compiler/config/domains) |
100
+ | `agents` | `boolean \| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) — see [Agents](/compiler/config/agents) |
101
+ | `security` | `object \| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) — see [Security Headers](/compiler/config/security) |
102
+ | `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \| 'swagger'`, `types`) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |
103
+ | `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |
104
+ | `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |
105
+ | `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) — see [Email Configuration](#email-configuration) |
106
+ | `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) — see [Bindings](/compiler/config/bindings) |
107
+ | `compiler` | `object` | Compiler internals — `features.auditFields: false`, `migrations.renames` (headless CI), `securityContracts`, `injectId`, `routes` |
108
+ | `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) — see [Custom Dependencies](#custom-dependencies) |
109
+ | `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) — see [Variables](/compiler/config/variables) |
110
+ | `preset` | `string` | Inherit defaults from a named preset |
102
111
 
103
112
  ## Custom Dependencies
104
113
 
@@ -79,17 +79,18 @@ export type Candidate = typeof candidates.$inferSelect;
79
79
  > A table **without** `defineTable()` is a supporting table — used internally by actions or handlers, but never exposed as its own API endpoint. See [Internal Tables](/compiler/definitions/schema#internal-tables-no-routes) for details.
80
80
 
81
81
 
82
- ## The Four Security Layers
82
+ ## The Five Security Layers
83
83
 
84
- Every API request passes through four security layers, in order:
84
+ Every API request passes through five security layers, in order:
85
85
 
86
86
  ```
87
- Request → Firewall → Access → Guards → Masking → Response
88
- │ │ │ │
89
- │ │ │ └── Hide sensitive fields
90
- │ │ └── Block field modifications
91
- │ └── Check roles & conditions
92
- └── Isolate data by owner/org/team
87
+ Request → Rate Limit → Firewall → Access → Guards → Masking → Response
88
+ │ │ │ │ │
89
+ │ │ │ │ └── Hide sensitive fields
90
+ │ │ │ └── Block field modifications
91
+ │ │ └── Check roles & conditions
92
+ │ └── Isolate data by owner/org/team
93
+ └── Cap requests per user / op
93
94
  ```
94
95
 
95
96
  > **Security Applies Everywhere**
@@ -154,25 +155,44 @@ masking: {
154
155
 
155
156
  [Learn more about Masking →](/compiler/definitions/masking)
156
157
 
158
+ ### 5. Rate Limiting (Request Caps)
159
+
160
+ Rate 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.
161
+
162
+ ```typescript
163
+ rateLimit: {
164
+ delete: { limit: 5, period: 60 }, // tighter than the 200/60s default
165
+ },
166
+ // read / create / update keep shipped defaults
167
+ ```
168
+
169
+ Override 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`.
170
+
171
+ [Learn more about Rate Limiting →](/compiler/definitions/rate-limit)
172
+
157
173
  ## How They Work Together
158
174
 
159
175
  **Scenario:** An interviewer requests `GET /candidates/cnd_123`
160
176
 
161
- 1. **Firewall** checks: Is candidate `cnd_123` in the user's organization?
177
+ 1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?
178
+ - Yes → Continue
179
+ - No → 429 Too Many Requests (with `Retry-After`)
180
+
181
+ 2. **Firewall** checks: Is candidate `cnd_123` in the user's organization?
162
182
  - Yes → Continue
163
183
  - No → 404 Not Found (as if it doesn't exist)
164
184
 
165
- 2. **Access** checks: Can interviewers perform GET?
185
+ 3. **Access** checks: Can interviewers perform GET?
166
186
  - Yes → Continue
167
187
  - No → 403 Forbidden
168
188
 
169
- 3. **Guards** don't apply to GET (they're for writes)
189
+ 4. **Guards** don't apply to GET (they're for writes)
170
190
 
171
- 4. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`
191
+ 5. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`
172
192
  - Email: `jane@company.com` → `j***@c******.com`
173
193
  - Phone: `555-123-4567` → `******4567`
174
194
 
175
- 5. **Response** sent with masked data
195
+ 6. **Response** sent with masked data
176
196
 
177
197
  ## Locked Down by Default
178
198
 
@@ -183,13 +203,14 @@ Quickback is **secure by default**. Nothing is accessible until you explicitly a
183
203
  | Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |
184
204
  | Access | DENIED | Explicitly define `access` rules with roles |
185
205
  | Guards | LOCKED | Explicitly list `createable`, `updatable` fields |
206
+ | Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |
186
207
  | Actions | BLOCKED | Explicitly define `access` for each action |
187
208
 
188
209
  **You must deliberately open each door.** This prevents accidental data exposure.
189
210
 
190
211
  ## Other Resource Options
191
212
 
192
- Beyond the four security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.
213
+ Beyond the five security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.
193
214
 
194
215
  | Option | What it does | Full reference |
195
216
  |---|---|---|
@@ -212,6 +233,7 @@ All options are optional — omit them and Quickback uses sensible defaults (aut
212
233
  3. [Access](/compiler/definitions/access) — Configure read and write permissions
213
234
  4. [Guards](/compiler/definitions/guards) — Control field modifications
214
235
  5. [Masking](/compiler/definitions/masking) — Hide sensitive data
215
- 6. [Views](/compiler/definitions/views) — Column-level security
216
- 7. [Validation](/compiler/definitions/validation) — Field validation rules
217
- 8. [Actions](/compiler/definitions/actions) — Add custom business logic
236
+ 6. [Rate Limit](/compiler/definitions/rate-limit) — Per-operation request caps
237
+ 7. [Views](/compiler/definitions/views) — Column-level security
238
+ 8. [Validation](/compiler/definitions/validation) — Field validation rules
239
+ 9. [Actions](/compiler/definitions/actions) — Add custom business logic