@quickback-dev/cli 0.47.8 → 0.47.10

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 (71) hide show
  1. package/README.md +3 -1
  2. package/dist/codex/AGENTS.md +290 -0
  3. package/dist/commands/codex.d.ts +16 -0
  4. package/dist/commands/codex.d.ts.map +1 -0
  5. package/dist/commands/codex.js +159 -0
  6. package/dist/commands/codex.js.map +1 -0
  7. package/dist/commands/compile.d.ts +5 -0
  8. package/dist/commands/compile.d.ts.map +1 -1
  9. package/dist/commands/compile.js +14 -4
  10. package/dist/commands/compile.js.map +1 -1
  11. package/dist/commands/create.d.ts.map +1 -1
  12. package/dist/commands/create.js +1 -1
  13. package/dist/commands/create.js.map +1 -1
  14. package/dist/commands/dev.d.ts +16 -0
  15. package/dist/commands/dev.d.ts.map +1 -0
  16. package/dist/commands/dev.js +117 -0
  17. package/dist/commands/dev.js.map +1 -0
  18. package/dist/commands/init.d.ts +6 -0
  19. package/dist/commands/init.d.ts.map +1 -0
  20. package/dist/commands/init.js +405 -0
  21. package/dist/commands/init.js.map +1 -0
  22. package/dist/docs/content.d.ts.map +1 -1
  23. package/dist/docs/content.js +25 -10
  24. package/dist/docs/content.js.map +1 -1
  25. package/dist/index.js +10 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/api-client.d.ts +13 -1
  28. package/dist/lib/api-client.d.ts.map +1 -1
  29. package/dist/lib/api-client.js +47 -20
  30. package/dist/lib/api-client.js.map +1 -1
  31. package/dist/lib/api-client.test.js +78 -0
  32. package/dist/lib/api-client.test.js.map +1 -1
  33. package/dist/lib/file-loader.d.ts +13 -2
  34. package/dist/lib/file-loader.d.ts.map +1 -1
  35. package/dist/lib/file-loader.js +51 -15
  36. package/dist/lib/file-loader.js.map +1 -1
  37. package/dist/lib/sweep-stale.d.ts +25 -0
  38. package/dist/lib/sweep-stale.d.ts.map +1 -0
  39. package/dist/lib/sweep-stale.js +179 -0
  40. package/dist/lib/sweep-stale.js.map +1 -0
  41. package/dist/lib/sweep-stale.test.d.ts +2 -0
  42. package/dist/lib/sweep-stale.test.d.ts.map +1 -0
  43. package/dist/lib/sweep-stale.test.js +130 -0
  44. package/dist/lib/sweep-stale.test.js.map +1 -0
  45. package/dist/skill/docs/changelog.md +71 -0
  46. package/dist/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  47. package/dist/skill/docs/compiler/config/index.md +21 -12
  48. package/dist/skill/docs/compiler/definitions/encryption.md +117 -1
  49. package/dist/skill/docs/compiler/definitions/index.md +39 -17
  50. package/dist/skill/docs/compiler/definitions/masking.md +32 -0
  51. package/dist/skill/docs/compiler/definitions/rate-limit.md +216 -0
  52. package/dist/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  53. package/dist/skill/docs/compiler/definitions/triggers.md +5 -0
  54. package/dist/skill/docs/stack/index.md +6 -0
  55. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +12 -0
  56. package/dist/skill/docs/stack/schedules/index.md +78 -0
  57. package/dist/skill/docs/stack/webhooks/inbound.md +62 -5
  58. package/package.json +1 -1
  59. package/src/skill/docs/changelog.md +71 -0
  60. package/src/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  61. package/src/skill/docs/compiler/config/index.md +21 -12
  62. package/src/skill/docs/compiler/definitions/encryption.md +117 -1
  63. package/src/skill/docs/compiler/definitions/index.md +39 -17
  64. package/src/skill/docs/compiler/definitions/masking.md +32 -0
  65. package/src/skill/docs/compiler/definitions/rate-limit.md +216 -0
  66. package/src/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  67. package/src/skill/docs/compiler/definitions/triggers.md +5 -0
  68. package/src/skill/docs/stack/index.md +6 -0
  69. package/src/skill/docs/stack/realtime/partyserver-rooms.md +12 -0
  70. package/src/skill/docs/stack/schedules/index.md +78 -0
  71. package/src/skill/docs/stack/webhooks/inbound.md +62 -5
@@ -2,6 +2,77 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ### Realtime: identity-gated Durable Object rooms (`roomIdEquals`)
6
+
7
+ Per-user Durable Object entrypoints (gateway / presence / inbox) can now declare
8
+ an identity gate on the binding — `access: { roomIdEquals: 'ctx.userId' }` (or
9
+ `'ctx.activeOrgId'`). The compiler emits a Worker-edge gate at
10
+ `/realtime/<kebab>/*` that 401s anonymous callers, 400s a missing segment, and
11
+ 403s unless the decoded room segment equals the server-resolved `ctx` id — a
12
+ string compare with no backing table or DB query. See
13
+ [PartyServer rooms → Per-room authorization](/stack/realtime/partyserver-rooms).
14
+
15
+ - Closes the cross-user hole that "no `access` declared" leaves open: a per-user
16
+ room without a gate falls through to the authenticated-only catchall, so any
17
+ authenticated user could open another user's room by guessing the id.
18
+ - The gate lives at the edge, not in the DO — a Durable Object has no session
19
+ and only sees client-settable headers, so it must never re-authorize from
20
+ request data (trusting an `x-user-id` header was the original spoof hole).
21
+ - Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted; anything else is a
22
+ compile-time error (fail-closed Zod + generator validation).
23
+
24
+ ### OAuth provider: spurious authorization-server warning silenced by default
25
+
26
+ The generated `oauthProvider({...})` now emits
27
+ `silenceWarnings: { oauthAuthServerConfig: true }` by default. The compiler
28
+ always serves the `/.well-known/oauth-authorization-server` discovery route when
29
+ the provider is enabled, so `@better-auth/oauth-provider`'s
30
+ "please ensure … exists" boot warning was always spurious. Override or extend it
31
+ via `plugins.oauthProvider.silenceWarnings`.
32
+
33
+ ### `defineSchedule` — cron jobs from a single source
34
+
35
+ Declare a cron schedule in `services/schedules/*.ts` and the compiler emits the
36
+ Worker's `scheduled()` handler + the matching `[triggers] crons` in
37
+ `wrangler.toml` — the trigger-side mirror of `defineQueue`. No separate cron
38
+ Worker, no hand-patching the generated entry (which a recompile would strip).
39
+ See [Schedules](/stack/schedules).
40
+
41
+ ```typescript
42
+ // services/schedules/sweepDigests.ts
43
+ export default defineSchedule({
44
+ name: "sweepDigests",
45
+ cron: "* * * * *",
46
+ execute: async ({ db, env, services }) => { await runDigestSweep(db, env, services); },
47
+ });
48
+ ```
49
+
50
+ - One `scheduled(event, env, ctx)` dispatcher runs every schedule whose cron
51
+ matches `event.cron`; failures are isolated per-schedule.
52
+ - The execute context (`{ db, env, services, cron, scheduledTime }`) runs
53
+ server-internal with `ctx.internal = true` and an audit actor of
54
+ `system:cron-<name>`, plus a `withInternalContext` helper for
55
+ `roles: ['INTERNAL']`-gated rows.
56
+
57
+ ### Rate limiting — the fifth security pillar
58
+
59
+ Per-operation request caps on every CRUD endpoint, backed by Cloudflare's
60
+ native [Rate Limiting binding](/compiler/definitions/rate-limit) — no extra
61
+ storage, no third-party libraries. Applied to every resource by default
62
+ (read 1000/60s, write 200/60s), overridable per-op, per-resource, or
63
+ project-wide; `false` opts out at any scope.
64
+
65
+ - One middleware per feature router maps method→op, keys the limit by
66
+ `<resource>:<op>:<userId>` (falling back to the client IP for anonymous
67
+ callers), and returns `429` + `Retry-After` when over the cap.
68
+ - Unique `(limit, period)` tuples collapse onto shared bindings — a project
69
+ that never declares `rateLimit` ships exactly two (`RL_1000_60`,
70
+ `RL_200_60`), emitted as GA `[[ratelimits]]` blocks in `wrangler.toml` and
71
+ typed `RateLimit` on `CloudflareBindings`.
72
+ - `period` is compile-time constrained to `10` or `60` (Cloudflare binding
73
+ limit); the check no-ops when a binding is absent, so local dev never
74
+ hard-depends on it.
75
+
5
76
  ### Envelope encryption — `q.text().encrypted()` (encryption pillar, Phase 1)
6
77
 
7
78
  Mark a text column `.encrypted()` and it is AES-256-GCM-encrypted at rest
@@ -64,6 +64,9 @@ See the [Templates](/compiler/getting-started/templates) page for a deeper guide
64
64
  quickback compile
65
65
  ```
66
66
 
67
+ Use `quickback compile --verbose` when a remote compile fails and you need the
68
+ underlying command, exit code, stderr/stdout tail, and compiler-suggested fixes.
69
+
67
70
  Reads your definitions and generates:
68
71
  - Database migrations (Drizzle)
69
72
  - API route handlers (Hono)
@@ -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
 
@@ -54,9 +54,125 @@ Each organization's data is encrypted under its own DEK, so one compromised key
54
54
 
55
55
  ## What this tier does and doesn't claim
56
56
 
57
- The envelope tier protects against **storage compromise**: backups, exports, dashboard access, leaked database tokens, SQL injection, and insiders with database read access all get ciphertext. The server *can* decrypt — that's the point; your actions still process the field. It does not protect against full Worker compromise (the sealed/E2EE tier in the encryption roadmap addresses that — see `apps/compiler/research/encryption-vault-spec.md`).
57
+ The envelope tier protects against **storage compromise**: backups, exports, dashboard access, leaked database tokens, SQL injection, and insiders with database read access all get ciphertext. The server *can* decrypt — that's the point; your actions still process the field. It does not protect against full Worker compromise — for that, use the **sealed tier** below, where the server structurally cannot read the value at all.
58
58
 
59
59
  Two practical notes:
60
60
 
61
61
  - **Action responses**: rows returned from `db.insert(...).returning()` inside your own actions contain ciphertext — decrypt explicitly with `ctx.crypto.decrypt()` if your action returns the field. Generated CRUD routes handle this automatically.
62
62
  - **No server-side equality lookups** on encrypted values (blind indexes are a roadmap item). If you need to filter by it, it probably shouldn't be encrypted — or it needs a separate non-sensitive derived column.
63
+
64
+ ---
65
+
66
+ # Sealed tier — end-to-end encryption
67
+
68
+ Mark a text column `.sealed()` instead of `.encrypted()` and you cross a line the envelope tier never claims: **the server cannot read the value.** It holds only ciphertext plus a content key *wrapped to a public key it has no private half for*. A full Worker compromise — leaked secrets, malicious code, a coerced admin — still yields nothing but ciphertext. Decryption happens only on the client, after a fresh step-up.
69
+
70
+ ```typescript
71
+ export default feature('candidates', {
72
+ columns: {
73
+ id: q.id(),
74
+ organizationId: q.scope('organization'), // required — keys are per-scope
75
+ name: q.text().required(),
76
+ governmentId: q.text().encrypted(), // envelope tier: server CAN read (to mask)
77
+ backgroundCheck: q.text({ maxLength: 8000 }).sealed(), // sealed tier: server CANNOT read
78
+ },
79
+ read: { access: { roles: ['member+'] } },
80
+ create: { access: { roles: ['admin+'] } },
81
+ });
82
+ ```
83
+
84
+ Use it for data that is legally sensitive and need-to-know, where you want a database breach **and the server itself** to yield only ciphertext: background checks, health findings, raw identity documents, anything you'd rather not be able to read by accident.
85
+
86
+ The page below is the *usage* view. For the on-the-wire contract — the versioned `qbseal:1` envelope format, the full `/seal/v1` lifecycle, the Argon2id floor, passkey expectations, canonical conformance vectors, and the first-party **Swift / Kotlin / TypeScript SDKs** (with install + usage) — see [Sealed protocol](/compiler/definitions/sealed-protocol).
87
+
88
+ ## The key model
89
+
90
+ Three nested keys. A breach of any layer above plaintext yields only more wrapped keys:
91
+
92
+ ```
93
+ USER key ──unwrap──▶ SCOPE private key ──unwrap──▶ content key ──decrypt──▶ plaintext
94
+ ```
95
+
96
+ - **USER key** — derived on the client from a **vault passphrase** (Argon2id → an Ed25519 signing key + an X25519 wrap key). This is **never** the Better Auth login password — reusing the login password would collapse the zero-knowledge property back to server-trust. The server stores only the Ed25519 *public* key (to verify step-ups) and the Argon2id params.
97
+ - **SCOPE keypair** — one per scope (per organization). The content key is wrapped to the scope's public key, so any authorized reader can be granted access without re-encrypting the data.
98
+ - **Content key** — a random AES-256-GCM key, one per sealed value, wrapped to the scope.
99
+
100
+ A **writer** needs only the scope's *public* key — no key of their own. Only **readers** (staff doing a reveal) need a grant of the scope private key, wrapped to their USER key.
101
+
102
+ ## The client ships with your backend
103
+
104
+ For any project with a `.sealed()` column the compiler emits the E2EE client **into your project** — there's nothing to `npm install`:
105
+
106
+ ```
107
+ src/
108
+ ├─ lib/
109
+ │ ├─ seal-routes.ts # server: the /seal/v1/* reveal rails (verify-only)
110
+ │ └─ seal-client/ # client: the browser SDK you import — emitted for you
111
+ │ └─ index.ts sdk.ts flow.ts wrap.ts kdf.ts envelope.ts ...
112
+ ```
113
+
114
+ `@noble/curves` and `@noble/hashes` are added to your `package.json` automatically. The client is emitted from the *same compiler version* as the server routes, so the wire format (`qbseal:` envelopes, the step-up message, the key-wrap method) can never drift between the two — a class of silent decrypt-time bug that a separately-versioned package would reintroduce.
115
+
116
+ ## Writing a sealed value
117
+
118
+ The writer seals the plaintext to the scope's public key, then writes the result like any other field. The server stores ciphertext and is none the wiser.
119
+
120
+ ```typescript
121
+ import { SealClient } from './lib/seal-client';
122
+
123
+ const seal = new SealClient(transport); // transport = POST to /seal/v1/*
124
+
125
+ // Fetches the scope's PUBLIC key and seals to it — the writer needs no key.
126
+ const sealed = await seal.sealField(
127
+ 'scope:organization:org_123',
128
+ new TextEncoder().encode('Background check: clear'),
129
+ );
130
+
131
+ // Write it like any field. At rest this is a `qbseal:` sealed-cell envelope.
132
+ await api.post('/api/v1/candidates', { name: 'Ada', backgroundCheck: sealed });
133
+ ```
134
+
135
+ ## Revealing a sealed value
136
+
137
+ A reveal is a deliberate, audited, **step-up-gated** action — not an ambient read. The SDK runs the whole handshake; you provide the reader's passphrase-derived session:
138
+
139
+ ```typescript
140
+ // Derive the reader's keys once from their vault passphrase (NOT their login password).
141
+ const session = seal.session(passphrase, enrollment);
142
+
143
+ const plaintext = await seal.reveal({
144
+ session,
145
+ scopeRef: 'scope:organization:org_123',
146
+ vaultItemId: candidate.id,
147
+ });
148
+ new TextDecoder().decode(plaintext); // "Background check: clear"
149
+ ```
150
+
151
+ Behind that one call:
152
+
153
+ 1. **`/seal/v1/my-grant`** → the reader's wrapped scope private key.
154
+ 2. **`/seal/v1/challenge`** → a fresh, single-use nonce bound to this reader + item.
155
+ 3. The client signs a **step-up proof** over the nonce (Ed25519 from the passphrase, or a passkey assertion whose WebAuthn challenge *is* the nonce).
156
+ 4. **`/seal/v1/reveal`** verifies the proof, writes an append-only reveal-log entry, and mints a short-lived (≤180s) `scope:seal:reveal` capability.
157
+ 5. **`/seal/v1/key`** (bearer that capability) passes three fail-closed gates — tenant, capability, live-grant — and returns the still-wrapped content key.
158
+ 6. The client unwraps the scope key, unwraps the content key, and decrypts. **None of this touches the server with a readable key.**
159
+
160
+ Passkey reveal is the same call as `revealWithPasskey({ ..., getAssertion })`, where `getAssertion(nonce)` runs the WebAuthn ceremony.
161
+
162
+ ## Rules the compiler enforces
163
+
164
+ Sealed values are opaque references at rest, so they're fenced off from every surface that would need to read them — these are compile errors:
165
+
166
+ - **Never** in a view projection, `?search`, or a `masking` rule (there's no plaintext to project, search, or redact — it leaves the system *only* through the reveal rails).
167
+ - No `.filterable()` / `.searchable()` / `.unique()` / defaults / `embeddings.fields` (same reasons as the envelope tier).
168
+ - The table **must** carry a `q.scope('organization')` column — keys are per-scope.
169
+ - Reading a sealed column server-side is a **type error**: the column is branded `$type<SealedValue>()`, an opaque non-string, so `db.select()` on it won't typecheck. The server's structural inability to read it is enforced by `tsc`, not convention.
170
+ - Sealed projects **force-enable** KV-backed JWT revocation (so a revoked reader's in-flight reveal token dies); a project with sealed columns and no KV binding **fails to compile**.
171
+
172
+ ## What this tier does and doesn't claim
173
+
174
+ The sealed tier protects against **full Worker compromise** — leaked secrets, malicious or buggy server code, a coerced operator. All of them get ciphertext; the keys to read it never exist server-side. What it asks in return:
175
+
176
+ - **A reveal needs a real second factor.** The vault passphrase (or passkey) is separate from login and never leaves the client. Lose it with no recovery grant and the data is unrecoverable *by design* — that's the guarantee, not a bug. Recovery/escrow and rotation re-granting are roadmap.
177
+ - **No server-side processing.** Your actions can't read, mask, search, or index a sealed value — it's plaintext only in a client that just revealed it. If the server needs to process the field, you want the envelope tier instead.
178
+ - **Passkey reveal** verify logic is in place but should be exercised with a real browser/authenticator before production; the passphrase lane is fully round-trip tested.
@@ -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
@@ -199,6 +199,38 @@ read: {
199
199
 
200
200
  `query` replaces the legacy per-capability flags (`filterable`, `searchable`, `sortable`). Setting any of those is rejected at compile time with a migration hint.
201
201
 
202
+ ## Egress protection
203
+
204
+ Masking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths — a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:
205
+
206
+ - **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).
207
+ - **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (`sql\`…\${record.col}\``) are fine — only the storage/payload sinks are flagged.
208
+ - **Realtime → webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.
209
+
210
+ ### Revealing a value on purpose: `unmask()`
211
+
212
+ When an action legitimately needs the raw value (e.g. calling an external API with a token), route it through `unmask()` — the sanctioned, audited reveal. It returns the raw value and records a best-effort `masked_reveal` entry in the audit database when one is configured.
213
+
214
+ ```typescript
215
+ import { unmask } from '../../../lib/masking-reveal';
216
+
217
+ // in an action's execute():
218
+ const token = await unmask(c, record.apiToken, 'apiToken');
219
+ await fetch(externalUrl, { headers: { Authorization: `Bearer ${token}` } });
220
+ ```
221
+
222
+ ### Opting a column out: `egress: 'allow'`
223
+
224
+ If a column is masked for display tidiness rather than secrecy, opt it out of both the compile-time block and the action scan:
225
+
226
+ ```typescript
227
+ masking: {
228
+ shortCode: { type: 'redact', show: { roles: ['admin'] }, egress: 'allow' },
229
+ }
230
+ ```
231
+
232
+ `egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/docs/compiler/definitions/encryption).
233
+
202
234
  ## Complete Example
203
235
 
204
236
  ```typescript
@@ -0,0 +1,216 @@
1
+ # Rate Limit - Per-Operation Request Caps
2
+
3
+ Per-operation request caps for every CRUD endpoint. Backed by Cloudflare's native [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) — no extra storage, no third-party libraries.
4
+
5
+ ## Defaults
6
+
7
+ Every resource gets these limits automatically (per authenticated user, per minute):
8
+
9
+ | Operation | Default |
10
+ |-----------|---------|
11
+ | `read` | 1000 / 60s |
12
+ | `create` | 200 / 60s |
13
+ | `update` | 200 / 60s |
14
+ | `delete` | 200 / 60s |
15
+
16
+ Numbers are loose enough that no legitimate user-driven traffic hits them, but tight enough to catch a runaway script before it burns the day's D1 budget. Override per-op or opt out wherever the defaults don't fit.
17
+
18
+ ## Override one operation
19
+
20
+ ```typescript
21
+ // features/claims/claims.ts
22
+ export default defineTable(claims, {
23
+ firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
24
+ rateLimit: {
25
+ delete: { limit: 5, period: 60 }, // tighter than the 200/60s default
26
+ },
27
+ // read / create / update keep shipped defaults
28
+ });
29
+ ```
30
+
31
+ ## Disable rate-limiting on a resource
32
+
33
+ ```typescript
34
+ // features/telemetry/events.ts
35
+ export default defineTable(telemetryEvents, {
36
+ rateLimit: false, // high-volume sink, skip enforcement
37
+ });
38
+ ```
39
+
40
+ ## Project-wide overrides
41
+
42
+ ```typescript
43
+ // quickback.config.ts
44
+ export default defineConfig({
45
+ // ...
46
+ rateLimit: {
47
+ read: { limit: 500, period: 60 }, // tighter project-wide read default
48
+ },
49
+ });
50
+ ```
51
+
52
+ ## Disable globally
53
+
54
+ ```typescript
55
+ // quickback.config.ts
56
+ export default defineConfig({
57
+ // ...
58
+ rateLimit: false, // e.g. when behind a WAF that handles request shaping
59
+ });
60
+ ```
61
+
62
+ ## Configuration shape
63
+
64
+ ```typescript
65
+ rateLimit?: {
66
+ read?: { limit: number, period: 10 | 60 };
67
+ create?: { limit: number, period: 10 | 60 };
68
+ update?: { limit: number, period: 10 | 60 };
69
+ delete?: { limit: number, period: 10 | 60 };
70
+ } | false
71
+ ```
72
+
73
+ - `period` must be `10` or `60` (Cloudflare binding constraint — anything else is a compile-time error).
74
+ - `limit` is a positive integer.
75
+ - Omit an op to inherit the project default (or shipped default).
76
+ - Set `false` at resource or project level to opt out.
77
+
78
+ ## Resolution order
79
+
80
+ 1. Project `rateLimit: false` → no enforcement anywhere
81
+ 2. Resource `rateLimit: false` → no enforcement on this resource
82
+ 3. Resource per-op override
83
+ 4. Project per-op default
84
+ 5. Quickback shipped defaults (1000 / 200 above)
85
+
86
+ Default-using resources collapse onto two shared bindings (`RL_1000_60`, `RL_200_60`), so a project that never declares `rateLimit` still ships exactly two rate-limit bindings — not one per resource.
87
+
88
+ ## How requests are keyed
89
+
90
+ Each handler composes a key as `<resource>:<op>:<userId>`. For routes that opt into PUBLIC access (no `userId`), the key falls back to the client's `cf-connecting-ip` header, then to the literal `'anon'` if that header is absent too.
91
+
92
+ This means:
93
+
94
+ - A single user is rate-limited per resource per op — heavy `read` traffic on `claims` doesn't slow their `update` traffic on `applications`.
95
+ - One noisy user can't starve another — keys are scoped by `userId`.
96
+ - Anonymous traffic hitting PUBLIC routes is keyed by IP, which works behind a CDN but is trivially bypassed by a botnet — pair PUBLIC routes with auth-required mutations or a Cloudflare WAF rule for hostile traffic.
97
+
98
+ ## How limits compile
99
+
100
+ The compiler walks every resource, collects unique `(limit, period)` tuples, and emits one Cloudflare binding per tuple to `wrangler.toml`:
101
+
102
+ ```toml
103
+ [[unsafe.bindings]]
104
+ name = "RL_1000_60"
105
+ type = "ratelimit"
106
+ namespace_id = "60001000"
107
+ simple = { limit = 1000, period = 60 }
108
+
109
+ [[unsafe.bindings]]
110
+ name = "RL_200_60"
111
+ type = "ratelimit"
112
+ namespace_id = "60000200"
113
+ simple = { limit = 200, period = 60 }
114
+ ```
115
+
116
+ Each generated CRUD handler invokes `c.env.RL_<L>_<P>.limit({ key })` between the auth gate and the access check. Hitting the limit returns:
117
+
118
+ ```http
119
+ HTTP/1.1 429 Too Many Requests
120
+ Retry-After: 60
121
+ Content-Type: application/json
122
+
123
+ { "error": "Rate limit exceeded", "code": "RATE_LIMITED", "retryAfter": 60 }
124
+ ```
125
+
126
+ ## Batch endpoints
127
+
128
+ Batch routes (`POST /batch`, `PATCH /batch`, `DELETE /batch`, `PUT /batch`) count as **a single request** against their op's limit, not N. A batch of 100 records consumes one token, not one hundred. This matches how most rate-limit configurations are actually written (caps on request volume, not row volume).
129
+
130
+ ## Actions
131
+
132
+ Custom actions (record-based and standalone) inherit rate limits without configuration:
133
+
134
+ - **Record-based actions** (e.g. `POST /api/v1/claims/:id/approve`) inherit the resource's `update` (write) bucket. A user who hits the write limit on `claims` is also blocked from `approve`.
135
+ - **Standalone actions** (e.g. `POST /api/v1/twilioIncoming`) inherit the project-default `update` bucket — they don't belong to a resource.
136
+
137
+ Override either with the action's `rateLimit` field:
138
+
139
+ ```typescript
140
+ // features/claims/actions/approve.ts
141
+ export default defineAction({
142
+ description: 'Approve a claim',
143
+ input: z.object({ claimId: z.string() }),
144
+ access: { roles: ['admin'] },
145
+ rateLimit: { limit: 5, period: 60 }, // tighter than resource update bucket
146
+ execute: async ({ db, input }) => { /* ... */ },
147
+ });
148
+ ```
149
+
150
+ ```typescript
151
+ // features/integrations/actions/twilioIncoming.ts
152
+ export default defineAction({
153
+ description: 'Webhook from Twilio',
154
+ path: '/twilioIncoming',
155
+ method: 'POST',
156
+ input: z.object({ /* ... */ }),
157
+ access: { roles: ['PUBLIC'] },
158
+ rateLimit: { limit: 1000, period: 10 }, // tolerate burst from Twilio
159
+ execute: async ({ input }) => { /* ... */ },
160
+ });
161
+ ```
162
+
163
+ Set `rateLimit: false` to opt the action out of enforcement entirely.
164
+
165
+ **Key composition** — actions get their own keyspace so a generic resource bucket and an action's bucket never share counters:
166
+
167
+ | Action kind | Key shape |
168
+ |-------------|-----------|
169
+ | Record-based | `<resource>:action:<actionName>:<userId\|cf-connecting-ip\|anon>` |
170
+ | Standalone | `standalone:<path>:<userId\|cf-connecting-ip\|anon>` |
171
+
172
+ The `:action:` infix is what keeps `update` (resource bucket) and `approve` (action bucket) from sharing counters when they happen to land on the same binding name.
173
+
174
+ ## Cardinality — how many bindings ship
175
+
176
+ Cloudflare bindings are sized at compile time (limit + period are baked in), so the compiler emits one binding per **unique `(limit, period)` tuple**, not one per resource. A project of 50 resources that all use the defaults still ships exactly two rate-limit bindings.
177
+
178
+ | Configuration | Bindings emitted |
179
+ |---------------|------------------|
180
+ | All defaults | 2 (`RL_1000_60` for reads, `RL_200_60` for writes) |
181
+ | One project-wide read override (`read: { limit: 500, period: 60 }`) | 3 (`RL_500_60`, `RL_1000_60` ← only if some resource opts back into the default, `RL_200_60`) |
182
+ | Five resources tightening `delete` to `{ limit: 5, period: 60 }` | 3 (defaults + `RL_5_60` shared) |
183
+ | Ten distinct per-action overrides at unique tuples | 12 (defaults + ten action buckets) |
184
+
185
+ **Practical caps.** Cloudflare workers have generous binding limits (hundreds), so this is unlikely to be a real ceiling — but it's the reason every distinct `(limit, period)` you write on a `rateLimit` config widens the binding set, even when the same resource declares the same tuple multiple times. Resource-level configs that share a tuple share a binding and simply produce different runtime keys.
186
+
187
+ **Key cardinality is separate.** Each binding holds an independent counter per key. A binding called via `claims:read:user_123` and `applications:read:user_123` consumes two separate counters in the same binding — fan-out cost lives in Cloudflare's distributed counter store, not in your binding count. The user-perceivable limit is "per (resource, op, user)", regardless of how many resources share the binding.
188
+
189
+ ## Runtime support
190
+
191
+ | Runtime | Rate limiting |
192
+ |---------|---------------|
193
+ | `cloudflare` | Backed by Cloudflare's native [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) |
194
+ | `bun` | In-process fixed-window counter (`src/lib/rate-limit-memory.ts`). Same generated check code, same 429 response — single-instance only |
195
+
196
+ On Bun, the compiler emits `src/lib/rate-limit-memory.ts` and wires up a per-binding shim in the server's fetch handler. Each `RL_<limit>_<period>` shim delegates to a process-memory token bucket, so the same `c.env.RL_*.limit({ key })` call site that targets the Cloudflare binding works unchanged.
197
+
198
+ **Multi-instance Bun deployments** need either a load balancer with sticky sessions (so the same user keeps hitting the same instance and its bucket) or the Cloudflare runtime (which has cross-instance counters out of the box). The in-memory shim does not coordinate across processes.
199
+
200
+ ## Compile-time validation
201
+
202
+ The compiler errors on:
203
+
204
+ 1. `period` other than `10` or `60`
205
+ 2. Non-integer or non-positive `limit`
206
+ 3. Unknown ops (e.g. `list` instead of `read`)
207
+
208
+ ## Disabling vs. tightening — when to use which
209
+
210
+ | Goal | Configuration |
211
+ |------|---------------|
212
+ | One op needs a tighter cap (e.g. `delete`) | Resource override on that op only |
213
+ | One op needs a looser cap (high-volume reads) | Resource override raising the limit |
214
+ | One resource is a high-volume sink | `rateLimit: false` on the resource |
215
+ | Whole project is behind a WAF | `rateLimit: false` at project level |
216
+ | App-wide tighter default (e.g. expensive reads) | Project-level override of that op |