@quickback-dev/cli 0.47.8 → 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 +15 -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/docs/changelog.md +19 -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/stack/webhooks/inbound.md +62 -5
- package/package.json +1 -1
- package/src/skill/docs/changelog.md +43 -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 +5 -0
- package/src/skill/docs/stack/schedules/index.md +60 -0
- package/src/skill/docs/stack/webhooks/inbound.md +62 -5
|
@@ -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 |
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
# Sealed protocol (qbseal:1)
|
|
2
|
+
|
|
3
|
+
This is the **protocol reference** for the [SEALED tier](/compiler/definitions/encryption#sealed-tier--end-to-end-encryption) — the on-the-wire contract a client speaks to the generated `/seal/v1` surface. Quickback ships first-party clients — TypeScript (emitted into your project), **Swift, and Kotlin** — so you usually don't implement this yourself; jump to [Client SDKs](#client-sdks). The format is also **language-agnostic and versioned**, so you can build a Go or server-side client against this spec and the [conformance vectors](#conformance-vectors) instead of reading emitted source.
|
|
4
|
+
|
|
5
|
+
> **Stability.** The wire version is **`qbseal:1`**. The version is carried *in every envelope* (`qbseal:1:…`). `qbseal:1` is stable: no field is removed or repurposed within a major version. A breaking change ships as `qbseal:2` — a new prefix a `:1` decoder rejects fail-closed, never a silent change at decrypt time. New optional fields may be added within `:1` only if older readers ignore them safely. A server that needs to retire `:1` does so by re-sealing data to `:2` and announcing a deprecation window; it never reinterprets a `:1` envelope.
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
## Key model
|
|
9
|
+
|
|
10
|
+
Three nested keys; a breach of any layer above plaintext yields only more wrapped keys.
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
USER key ──unwrap──▶ SCOPE private key ──unwrap──▶ content key ──decrypt──▶ plaintext
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
| Key | Lives | Derivation |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| **USER** | client only | `Argon2id(vault passphrase, salt)` → HKDF-split into an Ed25519 signing key + an X25519 wrap key. **Never** the login password. |
|
|
19
|
+
| **SCOPE** | private half wrapped per-user; public half on the server | random X25519 keypair, one per scope (per org). |
|
|
20
|
+
| **Content (CK)** | wrapped to the scope | random AES-256-GCM key, one per sealed value. |
|
|
21
|
+
|
|
22
|
+
A **writer** needs only the scope *public* key. A **reader** needs a grant of the scope private key, wrapped to their USER key.
|
|
23
|
+
|
|
24
|
+
## Crypto primitives
|
|
25
|
+
|
|
26
|
+
All standard; no hand-rolled constructions. A conforming port maps each to its platform library (CryptoKit, BouncyCastle, WebCrypto, …).
|
|
27
|
+
|
|
28
|
+
| Purpose | Primitive | Parameters |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| USER-key KDF | **Argon2id** | floor below; output 32 bytes |
|
|
31
|
+
| KDF domain split | **HKDF-SHA256** | `info = "qbseal-ed25519-v1"` and `"qbseal-x25519-v1"`, no salt, L=32 |
|
|
32
|
+
| Signing key | **Ed25519** | seed = HKDF ed25519 output |
|
|
33
|
+
| Wrap key | **X25519** | seed = HKDF x25519 output |
|
|
34
|
+
| Step-up proof | **Ed25519** sign/verify | over the [step-up message](#step-up-message) |
|
|
35
|
+
| Sealed box (wrap a key to a pubkey) | **X25519 ECDH → HKDF-SHA256 → AES-256-GCM** | see below |
|
|
36
|
+
| Content / key encryption | **AES-256-GCM** | 12-byte IV, 16-byte tag appended to ciphertext |
|
|
37
|
+
|
|
38
|
+
### Argon2id floor
|
|
39
|
+
|
|
40
|
+
The server **rejects** enrollment params below this floor (a weak-KDF verifier is offline-brute-forceable, and the public key is stored). These are the OWASP Argon2id minimums:
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{ "memoryKiB": 19456, "iterations": 2, "parallelism": 1 }
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
A client MAY choose stronger params; it MUST send the params it used (the server re-derives nothing — it only verifies the Ed25519 proof and stores the params for the client to re-derive at reveal time).
|
|
47
|
+
|
|
48
|
+
### Sealed box
|
|
49
|
+
|
|
50
|
+
Wrapping a key (a content key, or a scope private key) to an X25519 public key — the analogue of libsodium's `crypto_box_seal`:
|
|
51
|
+
|
|
52
|
+
1. Generate an ephemeral X25519 keypair `eph`.
|
|
53
|
+
2. `shared = X25519(eph.secret, recipientPub)`.
|
|
54
|
+
3. `wrapKey = HKDF-SHA256(ikm = shared, salt = eph.pub ‖ recipientPub, info = "qbseal-box-v1", L = 32)`.
|
|
55
|
+
4. `ct = AES-256-GCM(wrapKey, iv, plaintext)`.
|
|
56
|
+
5. Envelope: `{ alg: "x25519-aesgcm", eph, iv, ct }` (all base64url).
|
|
57
|
+
|
|
58
|
+
To open: recompute `shared = X25519(recipientSecret, eph.pub)`, re-derive `wrapKey` (salt uses the same `eph.pub ‖ recipientPub`), AES-GCM-decrypt.
|
|
59
|
+
|
|
60
|
+
### Step-up message
|
|
61
|
+
|
|
62
|
+
The message an Ed25519 step-up proof signs. Each field is **independently SHA-256-hashed then joined** — fixed-width, delimiter-free, so the `scope:<kind>:<id>` colons in `scopeRef` can't be re-segmented to forge a proof for a different target:
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
message = utf8(
|
|
66
|
+
"qbseal-stepup:v1:" +
|
|
67
|
+
b64url(sha256(utf8(scopeRef))) + ":" +
|
|
68
|
+
b64url(sha256(utf8(vaultItemId))) + ":" +
|
|
69
|
+
b64url(sha256(utf8(nonce)))
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The `nonce` is the server-issued [challenge](#3-challenge). The proof is `Ed25519.sign(message, userEd25519Secret)`, sent base64url.
|
|
74
|
+
|
|
75
|
+
## Envelope wire format
|
|
76
|
+
|
|
77
|
+
Every sealed blob is `qbseal:<version>:<base64url(json)>`. Three payload shapes:
|
|
78
|
+
|
|
79
|
+
```jsonc
|
|
80
|
+
// a key wrapped to an X25519 public key
|
|
81
|
+
{ "alg": "x25519-aesgcm", "eph": "<b64url>", "iv": "<b64url>", "ct": "<b64url>" }
|
|
82
|
+
|
|
83
|
+
// content encrypted under a content key
|
|
84
|
+
{ "alg": "aes-256-gcm", "iv": "<b64url>", "ct": "<b64url>" }
|
|
85
|
+
|
|
86
|
+
// a SEALED CELL — the compound value written into a .sealed() column.
|
|
87
|
+
// The server STRUCTURALLY SPLITS this (decode only, never decrypts) into
|
|
88
|
+
// vault_items.ct (content) + wrapped_ck_owner (wrappedCk).
|
|
89
|
+
{ "alg": "sealed-cell",
|
|
90
|
+
"content": { "alg": "aes-256-gcm", ... },
|
|
91
|
+
"wrappedCk": { "alg": "x25519-aesgcm", ... } }
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The decoder rejects a non-`qbseal:` string, an unknown version, an envelope over 64 KiB, or a malformed body — all fail-closed.
|
|
95
|
+
|
|
96
|
+
## The `/seal/v1` lifecycle
|
|
97
|
+
|
|
98
|
+
All routes are `POST`, JSON in/out, mounted at `/seal/v1`, and require an authenticated session with an **active organization** (`requireOrg` → 401/403). Errors use the standard Quickback error envelope. Most write routes accept `"dryRun": true` to validate + preview without persisting.
|
|
99
|
+
|
|
100
|
+
`scopeRef` grammar is `scope:<kind>:<id>` (org/event/relationship) or `user:<id>`; the server validates it (`assertRefGrammar`).
|
|
101
|
+
|
|
102
|
+
### Key-admin authorization (who may enroll / grant / rotate / revoke)
|
|
103
|
+
|
|
104
|
+
`enroll`, `grant`, `rotate`, and `revoke` are gated by **`hasKeyAdminForScope`**:
|
|
105
|
+
|
|
106
|
+
- `userRole === "sysadmin"` always passes; **or**
|
|
107
|
+
- a verified `ctx.scope.seal` claim **for the exact `scopeRef`** carrying a key-admin-tier scoped role (configurable via `encryption.seal.keyAdminRoles`; the literal `"key-admin"` scoped role always qualifies).
|
|
108
|
+
|
|
109
|
+
Scoped roles live **only** on `ctx.scope.seal`, never `ctx.roles` — a forged `ctx.roles` entry can't satisfy the gate. There is **no automatic** role→grant: the server holds no key material, so it cannot wrap the scope key to a new reader itself. Instead a reader self-publishes their public key via [`/grant-request`](#10-grant-request) and a key-admin fulfils it via [`/grant`](#5-grant) — see [role→grant](#rolegrant-readers-request-key-admins-fulfil). Minting the key-admin scope claim is done through the normal [scopes](/compiler/definitions/scopes) machinery — that policy (which role becomes key-admin for which scope) is yours to declare.
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
### 1. `/scope-key` — get a scope's public key (writers)
|
|
114
|
+
|
|
115
|
+
Any tenant member who can write the scope needs it. Returns the **current** (highest `keyVersion`) public key.
|
|
116
|
+
|
|
117
|
+
```jsonc
|
|
118
|
+
// → { scopeRef }
|
|
119
|
+
// ← { scopeRef, publicKey: "<b64url X25519>", keyVersion: 1 }
|
|
120
|
+
```
|
|
121
|
+
404 (existence-oracle parity) if the scope is unknown *or* has no key yet.
|
|
122
|
+
|
|
123
|
+
### 2. `/enroll` — create a scope's seal key (key-admin)
|
|
124
|
+
|
|
125
|
+
Trust-on-first-use: **first write wins**, never overwrites. Persists `seal_keys` (the scope public key). `organizationId` is stamped server-side.
|
|
126
|
+
|
|
127
|
+
```jsonc
|
|
128
|
+
// → { scopeRef, publicKey: "<b64url X25519>" } // client generated the keypair
|
|
129
|
+
// ← { enrolled: true, scopeRef, keyVersion: 1 }
|
|
130
|
+
```
|
|
131
|
+
409 if a key already exists for the scope (use `/rotate`).
|
|
132
|
+
|
|
133
|
+
### 3. `/challenge` — issue a step-up nonce (any member)
|
|
134
|
+
|
|
135
|
+
A single-use, **(issuing-user, scopeRef, vaultItemId)-bound** nonce, stored in KV (`expirationTtl` **120 s**). Bound to the item's owning scopeRef so it can only answer a reveal for *that* item; bound to the issuing user so another user can't burn it.
|
|
136
|
+
|
|
137
|
+
```jsonc
|
|
138
|
+
// → { vaultItemId }
|
|
139
|
+
// ← { nonce: "<b64url 32B>", scopeRef, vaultItemId, expiresIn: 120 }
|
|
140
|
+
```
|
|
141
|
+
503 fail-closed if no KV binding (sealed deployments require it).
|
|
142
|
+
|
|
143
|
+
### 4. `/reveal` — prove step-up, mint a reveal token (reader)
|
|
144
|
+
|
|
145
|
+
Verifies the step-up proof, writes a **committed** append-only reveal-log row, then mints a short-lived capability. The proof is consumed (single-use); the token is **not** the key.
|
|
146
|
+
|
|
147
|
+
```jsonc
|
|
148
|
+
// → { vaultItemId, fieldRef?, stepUp: <StepUpProof> }
|
|
149
|
+
// ← { revealToken: "<JWT ≤180s>", scope, vaultItemId, expiresIn: 180 }
|
|
150
|
+
```
|
|
151
|
+
`StepUpProof` is one of:
|
|
152
|
+
```jsonc
|
|
153
|
+
{ "kind": "passphrase", "nonce": "<from /challenge>",
|
|
154
|
+
"argon2": { "proof": "<b64url Ed25519 sig over the step-up message>",
|
|
155
|
+
"memoryKiB": 19456, "iterations": 2, "parallelism": 1 } }
|
|
156
|
+
|
|
157
|
+
{ "kind": "passkey", "nonce": "<from /challenge>",
|
|
158
|
+
"assertion": <WebAuthn AuthenticationResponseJSON> } // see Passkey step-up
|
|
159
|
+
```
|
|
160
|
+
Gates, all fail-closed and in order: **(a)** tenant load, **(b)** any presented `ctx.scope.seal` claim must match the item's scopeRef, **(c)** structural step-up (single-use nonce, bound message), **(d)** `assertGrantLive` (D1 read — owner reveal needs no grant; otherwise a live `seal_key_grant` for the scope, or an audience `vault_grant`).
|
|
161
|
+
|
|
162
|
+
### 5. `/key` — fetch the wrapped key (bearer the reveal token)
|
|
163
|
+
|
|
164
|
+
The **separate** post-mint route (never folded into `/reveal`). Re-runs three independent gates — tenant, capability (`ctx.scope.seal` only), `assertGrantLive` (D1, **prior to and independent of** any KV revocation check, which fails *open*) — writes a committed `delivered` reveal-log row, and returns the still-wrapped material.
|
|
165
|
+
|
|
166
|
+
```jsonc
|
|
167
|
+
// → { vaultItemId } (Authorization: Bearer <revealToken>)
|
|
168
|
+
// ← { wrappedKey: "<qbseal envelope>", ct: "<qbseal content envelope>",
|
|
169
|
+
// wrapMethod: "owner" | "scope" | "audience" }
|
|
170
|
+
```
|
|
171
|
+
The client unwraps per `wrapMethod` (see [`/my-grant`](#6-my-grant)) and decrypts `ct`. **No readable key ever touches the server.**
|
|
172
|
+
|
|
173
|
+
### 6. `/my-grant` — the caller's own wrapped scope private key (reader)
|
|
174
|
+
|
|
175
|
+
For `wrapMethod: "scope"`, the client first unwraps the scope private key with its USER key, then the CK. User-scoped; 404 if not granted.
|
|
176
|
+
|
|
177
|
+
```jsonc
|
|
178
|
+
// → { scopeRef }
|
|
179
|
+
// ← { wrappedPrivateKey: "<qbseal envelope>", wrapMethod: "scope" }
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### 7. `/grant` — enroll a reader + store their wrapped scope key (key-admin)
|
|
183
|
+
|
|
184
|
+
The combined **enrollment + grant** endpoint. The server **never wraps** — it persists the client-supplied opaque blob. Exactly one live grant per `(scopeRef, userId)` (it revokes any prior live grant first).
|
|
185
|
+
|
|
186
|
+
```jsonc
|
|
187
|
+
// → { scopeRef, userId, wrappedPrivateKey: "<qbseal envelope>", wrapMethod: "scope",
|
|
188
|
+
// wrapMeta?,
|
|
189
|
+
// // OPTIONAL passphrase-reveal enrollment (the step-up verifier):
|
|
190
|
+
// stepUp?: { kind: "passphrase", publicKey: "<b64url Ed25519>",
|
|
191
|
+
// salt: "<b64url>", argon2: { memoryKiB, iterations, parallelism } } }
|
|
192
|
+
// ← { granted: true, scopeRef, userId, stepUpEnrolled: boolean }
|
|
193
|
+
```
|
|
194
|
+
`stepUp.argon2` is floor-checked **at enrollment** (a weak verifier is rejected here, not just at reveal). The `stepUpPublicKey` + params are stored zero-knowledge; the passphrase never leaves the client.
|
|
195
|
+
|
|
196
|
+
### 8. `/revoke` — sever future access (key-admin)
|
|
197
|
+
|
|
198
|
+
Two forms: `{ scopeRef, userId }` (revoke a scope-key grant) or `{ vaultItemId, audienceRef }` (revoke an audience grant). Severs the future D1 key-fetch **and** kills in-flight tokens via KV revocation. It does **not** recall an already-unwrapped key — the response surfaces `rotationRecommended` when that matters.
|
|
199
|
+
|
|
200
|
+
### 9. `/rotate` — add a new key version + re-grant worklist (key-admin)
|
|
201
|
+
|
|
202
|
+
Append-only `INSERT` of a new `seal_keys` version, and returns the **re-grant worklist** — the live readers and their X25519 public keys.
|
|
203
|
+
|
|
204
|
+
```jsonc
|
|
205
|
+
// → { scopeRef, publicKey: "<new b64url X25519>" } // client generated the new keypair
|
|
206
|
+
// ← { rotated: true, scopeRef, keyVersion: 2,
|
|
207
|
+
// regrant: [{ userId, userPublicKey }, …], // re-wrap the NEW scope key to each
|
|
208
|
+
// missingPublicKey: [userId, …] } // readers granted before key capture
|
|
209
|
+
```
|
|
210
|
+
The key-admin's client wraps the **new** scope private key to each `regrant[].userPublicKey` and calls [`/grant`](#5-grant) per reader (which revokes the stale grant and inserts the fresh one). The server holds no key material, so it can only hand back the wrap targets — it never re-wraps. Older `seal_keys` versions remain readable, so existing sealed values keep decrypting until re-sealed. Readers in `missingPublicKey` re-request via [`/grant-request`](#10-grant-request).
|
|
211
|
+
|
|
212
|
+
### 10. `/grant-request` — request access to a scope (any member)
|
|
213
|
+
|
|
214
|
+
A reader who has a role for a scope but no grant publishes their X25519 USER public key. Requesting only publishes public material + intent; **fulfilling is the key-admin-gated action**. One pending request per `(scope, user)`; a fresh request replaces the pending key.
|
|
215
|
+
|
|
216
|
+
```jsonc
|
|
217
|
+
// → { scopeRef, userPublicKey: "<b64url X25519>" }
|
|
218
|
+
// ← { requested: true, scopeRef }
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### 11. `/grant-requests` — list pending requests (key-admin)
|
|
222
|
+
|
|
223
|
+
```jsonc
|
|
224
|
+
// → { scopeRef }
|
|
225
|
+
// ← { scopeRef, requests: [{ userId, userPublicKey, requestedAt }, …] }
|
|
226
|
+
```
|
|
227
|
+
The key-admin wraps the scope key to each `userPublicKey` and calls [`/grant`](#5-grant), which **auto-resolves** the matching pending request.
|
|
228
|
+
|
|
229
|
+
### 12. `/recovery/enroll` — escrow the scope key under a recovery code (key-admin)
|
|
230
|
+
|
|
231
|
+
A key-admin (holding the scope private key) wraps it to a key derived from a **recovery code** and escrows the blob. The server stores only the opaque recovery-wrapped material — the recovery code, held by the client, is what makes it usable; the server can never unwrap it. One live recovery per scope key version.
|
|
232
|
+
|
|
233
|
+
```jsonc
|
|
234
|
+
// → { scopeRef, wrappedPrivateKey: "<qbseal envelope, scope key wrapped to the recovery key>" }
|
|
235
|
+
// ← { enrolled: true, scopeRef, keyVersion: 1 }
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### 13. `/recovery/use` — retrieve the recovery blob (key-admin)
|
|
239
|
+
|
|
240
|
+
Returns the live recovery-wrapped scope key (and appends a `recovery` entry to the reveal log). The client unwraps it with the recovery-code key to recover the scope private key, then re-grants readers. The returned blob is **useless without the recovery code** — the server gates *who* may fetch it, the code gates whether it can be unwrapped.
|
|
241
|
+
|
|
242
|
+
```jsonc
|
|
243
|
+
// → { scopeRef }
|
|
244
|
+
// ← { scopeRef, keyVersion, wrappedPrivateKey: "<qbseal envelope>" } // 404 parity if none
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
#### role→grant: readers request, key-admins fulfil
|
|
248
|
+
|
|
249
|
+
Because the server holds no key material, it cannot mint a grant when a user gains a role. The supported pattern: the reader calls `/grant-request` (publishing their public key); a key-admin lists pending requests with `/grant-requests`, wraps the scope key to each, and `/grant`s them — which auto-resolves the request. Who is allowed to *request* (the "role" half) is your access policy; the cryptographic *fulfilment* is always key-admin-gated.
|
|
250
|
+
|
|
251
|
+
## Passkey step-up
|
|
252
|
+
|
|
253
|
+
When the passkey plugin is enabled, `/reveal` verifies a WebAuthn assertion whose **challenge is the server nonce** (not Better Auth's login challenge). The native ceremony must produce an `AuthenticationResponseJSON` (the `@simplewebauthn/browser` `startAuthentication` shape) for these expectations:
|
|
254
|
+
|
|
255
|
+
| Field | Value |
|
|
256
|
+
|---|---|
|
|
257
|
+
| `challenge` | the `/challenge` `nonce` **as the base64url string** (the client signs the b64url text, the server passes `expectedChallenge = nonce`) |
|
|
258
|
+
| `rpID` | the passkey plugin's `rpID` — i.e. `crossSubDomainCookies.domain` (leading dot stripped) when configured, else the host of `env.ACCOUNT_URL` |
|
|
259
|
+
| `userVerification` | **required** (`requireUserVerification: true` — a reveal is a deliberate re-auth) |
|
|
260
|
+
| origin | the resolved account origin (mirrors the `passkey({ rpID, origin })` plugin) |
|
|
261
|
+
|
|
262
|
+
The credential is looked up in the **auth** database (`passkey` table) and the signature counter is clone-checked. Conformance for passkey is **verify-based** at the server; the client's job is to bind `challenge = nonce` exactly.
|
|
263
|
+
|
|
264
|
+
## Conformance vectors
|
|
265
|
+
|
|
266
|
+
Canonical vectors live at **`packages/seal-client/vectors/qbseal-v1.json`**, generated from the reference TS SDK (`bun packages/seal-client/scripts/generate-vectors.ts`) and self-validated against it (`src/vectors.test.ts`). Every input (passphrase, salt, key seeds, IVs, ephemerals) is fixed, so the file is byte-stable and each vector reproduces from its inputs alone.
|
|
267
|
+
|
|
268
|
+
| Group | Pins | Determinism |
|
|
269
|
+
|---|---|---|
|
|
270
|
+
| `kdf` | passphrase + salt + params → Ed25519/X25519 public keys | full |
|
|
271
|
+
| `stepUpMessage` | `(scopeRef, vaultItemId, nonce)` → signed message | full |
|
|
272
|
+
| `stepUpSign` | a signature that **verifies** against the message + pubkey | verify-based (signing may be randomized) |
|
|
273
|
+
| `aesGcm` | key + IV + plaintext → ciphertext (+tag) | full |
|
|
274
|
+
| `sealedBoxOpen` | recipient secret + box → plaintext | open-direction (canonical) |
|
|
275
|
+
| `reveal` | passphrase → keys; owner + scope unwrap paths → plaintext | open-direction (canonical) |
|
|
276
|
+
| `envelope` | `qbseal:1:` sealed-cell decodes structurally | full |
|
|
277
|
+
|
|
278
|
+
A port verifies the open-direction vectors exactly, and proves its *seal* direction by round-tripping through its own open. Vectors are the **cross-language byte-for-byte guarantee** — CI runs every client (TypeScript, Swift, and Kotlin) against this one file and fails on drift.
|
|
279
|
+
|
|
280
|
+
## Client SDKs
|
|
281
|
+
|
|
282
|
+
You don't have to implement the crypto. Quickback ships first-party clients, each gated in CI against the conformance vectors above — so they agree byte-for-byte with the server and with each other.
|
|
283
|
+
|
|
284
|
+
| Platform | Package | Distribution | Crypto |
|
|
285
|
+
|---|---|---|---|
|
|
286
|
+
| Web / Worker / Node | `@quickback-dev/seal-client` | **emitted** into your project at `src/lib/seal-client/` (for any project with a `.sealed()` column) | `@noble` + WebCrypto |
|
|
287
|
+
| iOS / macOS | **`QuickbackSeal`** | SwiftPM — `apps/seal-sdk/swift` | CryptoKit + vendored Argon2 |
|
|
288
|
+
| JVM / Android | **`dev.quickback.seal`** | Gradle — `apps/seal-sdk/kotlin` | BouncyCastle |
|
|
289
|
+
|
|
290
|
+
All three expose the same shape: a `SealClient` over a transport you implement on your HTTP client (URLSession / OkHttp / Ktor / fetch). The transport just POSTs to `/seal/v1/*`; the SDK does the crypto and the reveal handshake.
|
|
291
|
+
|
|
292
|
+
### Swift (iOS / macOS)
|
|
293
|
+
|
|
294
|
+
```swift
|
|
295
|
+
// Package.swift
|
|
296
|
+
.package(url: "https://github.com/paulstenhouse/quickback-compiler.git", branch: "main")
|
|
297
|
+
// target dependency: .product(name: "QuickbackSeal", package: "quickback-compiler")
|
|
298
|
+
```
|
|
299
|
+
```swift
|
|
300
|
+
import QuickbackSeal
|
|
301
|
+
|
|
302
|
+
let seal = SealClient(transport: myTransport) // POSTs to /seal/v1/*
|
|
303
|
+
let sealed = try await seal.sealField(scopeRef: scope, // WRITE — no key needed
|
|
304
|
+
plaintext: Data("Background check: clear".utf8))
|
|
305
|
+
|
|
306
|
+
let session = try seal.session(passphrase: vaultPass, saltB64url: salt, argon2: .defaults)
|
|
307
|
+
let plaintext = try await seal.reveal(session: session, scopeRef: scope, vaultItemId: id)
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
### Kotlin (JVM / Android)
|
|
311
|
+
|
|
312
|
+
```kotlin
|
|
313
|
+
// build.gradle.kts — composite build or a published artifact from apps/seal-sdk/kotlin
|
|
314
|
+
import dev.quickback.seal.SealClient
|
|
315
|
+
|
|
316
|
+
val seal = SealClient(myTransport)
|
|
317
|
+
val sealed = seal.sealField(scope, "Background check: clear".toByteArray()) // WRITE
|
|
318
|
+
|
|
319
|
+
val session = seal.session(vaultPass, saltB64url, Argon2Params.DEFAULTS)
|
|
320
|
+
val plaintext = seal.reveal(session, scope, vaultItemId) // REVEAL
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Passkey reveal is the same call as `revealWithPasskey(…, getAssertion)`, where `getAssertion(nonce)` runs the platform WebAuthn ceremony with `challenge = nonce`. Full details, the transport contract, and the conformance harness live in [`apps/seal-sdk/README`](https://github.com/paulstenhouse/quickback-compiler/tree/main/apps/seal-sdk). The SDKs are versioned **with** the compiler in the same repo, so the wire format never drifts from the server you're talking to.
|
|
324
|
+
|
|
325
|
+
## Not yet wired
|
|
326
|
+
|
|
327
|
+
Honest gaps, fail-closed until built — a client should not assume these exist:
|
|
328
|
+
|
|
329
|
+
- **Content-key re-encryption on rotation** — `/rotate` versions the scope key and re-grants *readers*, and older key versions stay readable, so nothing breaks. But existing sealed *values* keep their content keys wrapped to the old scope key until a client re-seals them; there's no bulk re-encrypt-and-crypto-shred-the-old-version flow yet.
|
|
330
|
+
- **Audience grants beyond reveal** — `vault_grant` audience reveals are honored at `/reveal`/`/key`, but there's no first-class management surface yet.
|
|
331
|
+
|
|
332
|
+
These will arrive as additive `:1` routes (no wire-format break) with their own vectors.
|
|
@@ -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 |
|
|
@@ -0,0 +1,60 @@
|
|
|
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. The execute context runs with `ctx.internal = true` and an audit actor of **`system:cron-<name>`**, so any audited writes are attributable to the schedule that made them (e.g. `system:cron-sweepDigests`). Use `withInternalContext` when the schedule legitimately operates across tenants and needs to touch `INTERNAL`-gated resources.
|
|
43
|
+
|
|
44
|
+
## Cron syntax
|
|
45
|
+
|
|
46
|
+
Standard Cloudflare cron (`minute hour day-of-month month day-of-week`):
|
|
47
|
+
|
|
48
|
+
| Pattern | Runs |
|
|
49
|
+
|---------|------|
|
|
50
|
+
| `* * * * *` | every minute |
|
|
51
|
+
| `0 * * * *` | top of every hour |
|
|
52
|
+
| `0 0 * * *` | daily at 00:00 UTC |
|
|
53
|
+
| `*/5 * * * *` | every 5 minutes |
|
|
54
|
+
|
|
55
|
+
See Cloudflare's [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) docs for the full grammar and limits.
|
|
56
|
+
|
|
57
|
+
## See also
|
|
58
|
+
|
|
59
|
+
- [Queues](/stack/queues) — the async-message counterpart (`defineQueue`)
|
|
60
|
+
- [Triggers](/compiler/definitions/triggers) — row-level lifecycle hooks (distinct from cron)
|