@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.
Files changed (61) 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 +12 -2
  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 +15 -5
  24. package/dist/docs/content.js.map +1 -1
  25. package/dist/index.js +4 -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 +11 -0
  34. package/dist/lib/file-loader.d.ts.map +1 -1
  35. package/dist/lib/file-loader.js +35 -0
  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 +19 -0
  46. package/dist/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  47. package/dist/skill/docs/compiler/definitions/encryption.md +117 -1
  48. package/dist/skill/docs/compiler/definitions/masking.md +32 -0
  49. package/dist/skill/docs/compiler/definitions/rate-limit.md +216 -0
  50. package/dist/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  51. package/dist/skill/docs/stack/webhooks/inbound.md +62 -5
  52. package/package.json +1 -1
  53. package/src/skill/docs/changelog.md +43 -0
  54. package/src/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  55. package/src/skill/docs/compiler/definitions/encryption.md +117 -1
  56. package/src/skill/docs/compiler/definitions/masking.md +32 -0
  57. package/src/skill/docs/compiler/definitions/rate-limit.md +216 -0
  58. package/src/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  59. package/src/skill/docs/compiler/definitions/triggers.md +5 -0
  60. package/src/skill/docs/stack/schedules/index.md +60 -0
  61. package/src/skill/docs/stack/webhooks/inbound.md +62 -5
@@ -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.
@@ -37,7 +37,8 @@ Use `onWebhookEvent()` in your action code to register handlers for specific eve
37
37
 
38
38
  ```typescript
39
39
  onWebhookEvent("stripe:checkout.session.completed", async (ctx) => {
40
- const { type, data, provider, env } = ctx;
40
+ const { type, data, event, provider, env } = ctx;
41
+ // ctx.event is the full Stripe envelope; ctx.data is event.data.object
41
42
  await createSubscription(data, env);
42
43
  });
43
44
 
@@ -51,11 +52,31 @@ onWebhookEvent("stripe:*", async (ctx) => {
51
52
 
52
53
  | Field | Type | Description |
53
54
  |-------|------|-------------|
54
- | `type` | `string` | Full event type (e.g., `stripe:checkout.session.completed`) |
55
- | `data` | `unknown` | Parsed event payload |
55
+ | `type` | `string` | Event type (e.g., `checkout.session.completed`) |
56
+ | `data` | `unknown` | The convenience slice of the payload. For Stripe this is `event.data.object`. |
57
+ | `event` | `unknown` | The **full event envelope**, exactly as the provider sent it — nothing dropped. For Stripe this carries `account` (Connect connected-account id), `id`, `livemode`, `api_version`, `request`, etc. |
56
58
  | `provider` | `string` | Provider name (e.g., `stripe`) |
57
59
  | `env` | `CloudflareBindings` | Cloudflare environment bindings |
58
60
 
61
+ For `stripe:` patterns the context is typed automatically: `ctx.event` is a
62
+ `StripeWebhookEvent` and `ctx.data` is its `data.object`, so `ctx.event.account`,
63
+ `ctx.event.id`, and `ctx.event.livemode` are all typed with no cast.
64
+
65
+ ```typescript
66
+ onWebhookEvent("stripe:invoice.paid", async (ctx) => {
67
+ ctx.event.account; // string | undefined — the acct_… (Connect)
68
+ ctx.event.id; // string — evt_…
69
+ ctx.event.livemode; // boolean
70
+ ctx.data; // event.data.object (Record<string, unknown>)
71
+ });
72
+ ```
73
+
74
+ `data.object` is an open record. Cast it when you need inner-field typing:
75
+
76
+ ```typescript
77
+ const session = ctx.data as import("stripe").Stripe.Checkout.Session;
78
+ ```
79
+
59
80
  **Execution order:**
60
81
  1. Specific handlers run first (exact match on event type)
61
82
  2. Wildcard handlers run after
@@ -80,6 +101,41 @@ The signed payload is `<timestamp>.<raw_body>`. Verification checks:
80
101
  - HMAC matches
81
102
  - Timestamp is within 5 minutes (prevents replay attacks)
82
103
 
104
+ #### Stripe Connect
105
+
106
+ The single-secret model is exactly what a Connect platform needs. With Standard
107
+ connected accounts and direct charges, each of your customers connects their own
108
+ Stripe account, and **one** webhook endpoint on your platform receives events
109
+ from **all** connected accounts — every delivery signed with your **one**
110
+ platform signing secret.
111
+
112
+ 1. In the Stripe Dashboard, add a webhook endpoint pointing at
113
+ `https://<your-api>/webhooks/v1/inbound/stripe` and enable **"Listen to
114
+ events on Connected accounts."**
115
+ 2. Set that endpoint's signing secret as `STRIPE_WEBHOOK_SECRET` (one secret
116
+ covers every connected account — no per-account configuration).
117
+
118
+ To know **which connected account** an event belongs to, read the top-level
119
+ `event.account` (an `acct_…` id) off the envelope via `ctx.event.account`. It is
120
+ **not** inside `event.data.object`.
121
+
122
+ ```typescript
123
+ onWebhookEvent("stripe:checkout.session.completed", async (ctx) => {
124
+ const connectedAccount = ctx.event.account; // acct_… — which organizer
125
+ if (!connectedAccount) return; // platform-account event, ignore
126
+
127
+ // Route to the org that owns this connected account, and validate the match.
128
+ const org = await findOrgByStripeAccount(connectedAccount, ctx.env);
129
+ if (!org) throw new Error(`Unknown connected account ${connectedAccount}`);
130
+
131
+ await fulfillOrder(ctx.data, org, ctx.env);
132
+ });
133
+ ```
134
+
135
+ `ctx.data` remains `event.data.object` (the Checkout Session) for convenience;
136
+ `ctx.event` gives you the rest of the envelope — `account`, `id`, `livemode`,
137
+ `api_version`, `request` — so nothing about the delivery is lost.
138
+
83
139
  ### Custom Providers
84
140
 
85
141
  Providers implement this interface:
@@ -90,8 +146,9 @@ interface InboundProvider {
90
146
  verifySignature(payload: string, signature: string, secret: string): Promise<boolean>;
91
147
  parseEvent(payload: string): {
92
148
  type: string;
93
- data: unknown;
94
- externalId?: string;
149
+ data: unknown; // convenience slice (e.g. Stripe's data.object)
150
+ externalId?: string; // provider event id, for idempotency
151
+ envelope?: unknown; // full event envelope, when available
95
152
  };
96
153
  }
97
154
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.47.8",
3
+ "version": "0.47.9",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -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
@@ -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 (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.