@quickback-dev/cli 0.47.7 → 0.47.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/codex/AGENTS.md +290 -0
- package/dist/commands/codex.d.ts +16 -0
- package/dist/commands/codex.d.ts.map +1 -0
- package/dist/commands/codex.js +159 -0
- package/dist/commands/codex.js.map +1 -0
- package/dist/commands/compile.d.ts +5 -0
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +12 -2
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/create.d.ts.map +1 -1
- package/dist/commands/create.js +1 -1
- package/dist/commands/create.js.map +1 -1
- package/dist/commands/dev.d.ts +16 -0
- package/dist/commands/dev.d.ts.map +1 -0
- package/dist/commands/dev.js +117 -0
- package/dist/commands/dev.js.map +1 -0
- package/dist/commands/init.d.ts +6 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +405 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +20 -5
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/api-client.d.ts +13 -1
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js +47 -20
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/api-client.test.js +78 -0
- package/dist/lib/api-client.test.js.map +1 -1
- package/dist/lib/file-loader.d.ts +11 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +35 -0
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/sweep-stale.d.ts +25 -0
- package/dist/lib/sweep-stale.d.ts.map +1 -0
- package/dist/lib/sweep-stale.js +179 -0
- package/dist/lib/sweep-stale.js.map +1 -0
- package/dist/lib/sweep-stale.test.d.ts +2 -0
- package/dist/lib/sweep-stale.test.d.ts.map +1 -0
- package/dist/lib/sweep-stale.test.js +130 -0
- package/dist/lib/sweep-stale.test.js.map +1 -0
- package/dist/skill/SKILL.md +1 -0
- package/dist/skill/docs/changelog.md +79 -0
- package/dist/skill/docs/compiler/cloud-compiler/cli.md +3 -0
- package/dist/skill/docs/compiler/definitions/encryption.md +117 -1
- package/dist/skill/docs/compiler/definitions/masking.md +32 -0
- package/dist/skill/docs/compiler/definitions/rate-limit.md +216 -0
- package/dist/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
- package/dist/skill/docs/compiler/definitions/triggers.md +169 -0
- package/dist/skill/docs/stack/webhooks/inbound.md +62 -5
- package/package.json +1 -1
- package/src/skill/SKILL.md +1 -0
- package/src/skill/docs/changelog.md +103 -0
- package/src/skill/docs/compiler/cloud-compiler/cli.md +3 -0
- package/src/skill/docs/compiler/definitions/encryption.md +117 -1
- package/src/skill/docs/compiler/definitions/masking.md +32 -0
- package/src/skill/docs/compiler/definitions/rate-limit.md +216 -0
- package/src/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
- package/src/skill/docs/compiler/definitions/triggers.md +174 -0
- package/src/skill/docs/stack/schedules/index.md +60 -0
- package/src/skill/docs/stack/webhooks/inbound.md +62 -5
|
@@ -2,6 +2,49 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
### `defineSchedule` — cron jobs from a single source
|
|
6
|
+
|
|
7
|
+
Declare a cron schedule in `services/schedules/*.ts` and the compiler emits the
|
|
8
|
+
Worker's `scheduled()` handler + the matching `[triggers] crons` in
|
|
9
|
+
`wrangler.toml` — the trigger-side mirror of `defineQueue`. No separate cron
|
|
10
|
+
Worker, no hand-patching the generated entry (which a recompile would strip).
|
|
11
|
+
See [Schedules](/stack/schedules).
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
// services/schedules/sweepDigests.ts
|
|
15
|
+
export default defineSchedule({
|
|
16
|
+
name: "sweepDigests",
|
|
17
|
+
cron: "* * * * *",
|
|
18
|
+
execute: async ({ db, env, services }) => { await runDigestSweep(db, env, services); },
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- One `scheduled(event, env, ctx)` dispatcher runs every schedule whose cron
|
|
23
|
+
matches `event.cron`; failures are isolated per-schedule.
|
|
24
|
+
- The execute context (`{ db, env, services, cron, scheduledTime }`) runs
|
|
25
|
+
server-internal with `ctx.internal = true` and an audit actor of
|
|
26
|
+
`system:cron-<name>`, plus a `withInternalContext` helper for
|
|
27
|
+
`roles: ['INTERNAL']`-gated rows.
|
|
28
|
+
|
|
29
|
+
### Rate limiting — the fifth security pillar
|
|
30
|
+
|
|
31
|
+
Per-operation request caps on every CRUD endpoint, backed by Cloudflare's
|
|
32
|
+
native [Rate Limiting binding](/compiler/definitions/rate-limit) — no extra
|
|
33
|
+
storage, no third-party libraries. Applied to every resource by default
|
|
34
|
+
(read 1000/60s, write 200/60s), overridable per-op, per-resource, or
|
|
35
|
+
project-wide; `false` opts out at any scope.
|
|
36
|
+
|
|
37
|
+
- One middleware per feature router maps method→op, keys the limit by
|
|
38
|
+
`<resource>:<op>:<userId>` (falling back to the client IP for anonymous
|
|
39
|
+
callers), and returns `429` + `Retry-After` when over the cap.
|
|
40
|
+
- Unique `(limit, period)` tuples collapse onto shared bindings — a project
|
|
41
|
+
that never declares `rateLimit` ships exactly two (`RL_1000_60`,
|
|
42
|
+
`RL_200_60`), emitted as GA `[[ratelimits]]` blocks in `wrangler.toml` and
|
|
43
|
+
typed `RateLimit` on `CloudflareBindings`.
|
|
44
|
+
- `period` is compile-time constrained to `10` or `60` (Cloudflare binding
|
|
45
|
+
limit); the check no-ops when a binding is absent, so local dev never
|
|
46
|
+
hard-depends on it.
|
|
47
|
+
|
|
5
48
|
### Envelope encryption — `q.text().encrypted()` (encryption pillar, Phase 1)
|
|
6
49
|
|
|
7
50
|
Mark a text column `.encrypted()` and it is AES-256-GCM-encrypted at rest
|
|
@@ -24,6 +67,66 @@ See [Encryption](/compiler/definitions/encryption).
|
|
|
24
67
|
- The sealed (E2EE) and vault tiers remain compile-gated until built —
|
|
25
68
|
roadmap in `apps/compiler/research/encryption-vault-spec.md`.
|
|
26
69
|
|
|
70
|
+
|
|
71
|
+
### Postgres-style table triggers (`defineTable` / `feature` `triggers:`)
|
|
72
|
+
|
|
73
|
+
Tables can now declare `before`/`after` triggers on `insert`/`update`/
|
|
74
|
+
`delete`, with two lowering lanes and a per-trigger compile report. See
|
|
75
|
+
[Triggers](/compiler/definitions/triggers) for the full reference.
|
|
76
|
+
|
|
77
|
+
- **`sql:` entries** compile to real SQLite `CREATE TRIGGER` statements,
|
|
78
|
+
shipped in the journaled features migration (content-addressed — an
|
|
79
|
+
unchanged trigger set appends nothing; removing a trigger drops it on the
|
|
80
|
+
next migrate). They fire for **every** write path including raw SQL, run
|
|
81
|
+
atomically with the triggering statement (the only transactional option
|
|
82
|
+
on D1), support `when:` guards and `RAISE(ABORT, ...)` rejection, and
|
|
83
|
+
`OLD.`/`NEW.` column references are validated at compile time. The
|
|
84
|
+
compiler owns the `BEGIN`/`END` frame — emitted uppercase, since
|
|
85
|
+
lowercase `begin` breaks remote D1's statement splitter. On soft-delete
|
|
86
|
+
tables, `*Delete` events map to the `deleted_at` transition (plus a
|
|
87
|
+
hard-delete variant) and `*Update` events exclude it, so a soft delete
|
|
88
|
+
fires delete triggers exactly once. D1 only.
|
|
89
|
+
- **`handler:` entries** run as application hooks at the audit-wrapper
|
|
90
|
+
write chokepoint (REST CRUD + actions). `before*` hooks are synchronous
|
|
91
|
+
and can mutate the payload or throw to reject — the write never executes
|
|
92
|
+
and the request gets `TRIGGER_REJECTED` (422); audit fields are
|
|
93
|
+
re-stamped after hooks and cannot be forged. `after*` hooks run once per
|
|
94
|
+
returned row and are **awaited** — a throw surfaces as
|
|
95
|
+
`TRIGGER_AFTER_FAILED` (500) with `details.committed: true` since the
|
|
96
|
+
write already persisted. Handlers get `{ table, op, values|row, ctx, db,
|
|
97
|
+
env }`; the `db` is audit-wrapped at cascade depth + 1, so hook writes
|
|
98
|
+
stamp audit fields, emit live-view deltas, and fire nested triggers,
|
|
99
|
+
bounded by a depth cap of 5. Each table's drizzle object is auto-imported
|
|
100
|
+
into the generated registry under its authored name, and handler imports
|
|
101
|
+
are usage-filtered and hoisted.
|
|
102
|
+
|
|
103
|
+
The compile output includes a lowering/coverage report and fail-closed
|
|
104
|
+
warnings: `handler:` triggers do **not** fire for queue handlers, cron, or
|
|
105
|
+
raw SQL — guards that must hold universally should use `sql:` +
|
|
106
|
+
`RAISE(ABORT)`. `async: true` (queue-dispatched after-hooks) and
|
|
107
|
+
`withOld: true` (previous-row access) are reserved and rejected at compile
|
|
108
|
+
time until they ship.
|
|
109
|
+
|
|
110
|
+
Also in this change:
|
|
111
|
+
|
|
112
|
+
- New `trigger` error layer with `TRIGGER_REJECTED` / `TRIGGER_AFTER_FAILED`
|
|
113
|
+
codes in the generated error catalog, OpenAPI spec, and SDK types.
|
|
114
|
+
- Parser: function-valued properties in `defineTable`/`feature` configs now
|
|
115
|
+
parse as compile-time source carriers instead of failing the whole config
|
|
116
|
+
with "no dynamic expressions" — unblocks trigger handlers (and
|
|
117
|
+
function-form `access:` / custom masks) through the CLI source path.
|
|
118
|
+
- Fixed a column-injection bug where a comment merely mentioning a column
|
|
119
|
+
name (e.g. `"deleted_at"` in a docblock) suppressed audit/soft-delete
|
|
120
|
+
column injection for the table.
|
|
121
|
+
- Fixed a silent no-op: a project declaring `services/queues/*.ts` handlers
|
|
122
|
+
without embeddings or `additionalQueues` deployed a wired `queue` export
|
|
123
|
+
with no `[[queues.consumers]]` to feed it — the handlers were dead code.
|
|
124
|
+
The primary queue (and its typed env binding) is now emitted for
|
|
125
|
+
handlers-only projects, with a compile notice that Cloudflare Queues
|
|
126
|
+
requires the paid Workers plan. Queue emission remains strictly opt-in by
|
|
127
|
+
usage: projects with no queue-backed features (embeddings, queue
|
|
128
|
+
handlers, `additionalQueues`, webhooks) emit no queue configuration and
|
|
129
|
+
deploy on the free plan.
|
|
27
130
|
## v0.47.0 — June 11, 2026
|
|
28
131
|
|
|
29
132
|
### Breaking: zero-false-positive analyzer checks are now compile errors
|
|
@@ -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)
|
|
@@ -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
|
|
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.
|
|
@@ -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 |
|