@quickback-dev/cli 0.47.8 → 0.47.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +3 -1
  2. package/dist/codex/AGENTS.md +290 -0
  3. package/dist/commands/codex.d.ts +16 -0
  4. package/dist/commands/codex.d.ts.map +1 -0
  5. package/dist/commands/codex.js +159 -0
  6. package/dist/commands/codex.js.map +1 -0
  7. package/dist/commands/compile.d.ts +5 -0
  8. package/dist/commands/compile.d.ts.map +1 -1
  9. package/dist/commands/compile.js +14 -4
  10. package/dist/commands/compile.js.map +1 -1
  11. package/dist/commands/create.d.ts.map +1 -1
  12. package/dist/commands/create.js +1 -1
  13. package/dist/commands/create.js.map +1 -1
  14. package/dist/commands/dev.d.ts +16 -0
  15. package/dist/commands/dev.d.ts.map +1 -0
  16. package/dist/commands/dev.js +117 -0
  17. package/dist/commands/dev.js.map +1 -0
  18. package/dist/commands/init.d.ts +6 -0
  19. package/dist/commands/init.d.ts.map +1 -0
  20. package/dist/commands/init.js +405 -0
  21. package/dist/commands/init.js.map +1 -0
  22. package/dist/docs/content.d.ts.map +1 -1
  23. package/dist/docs/content.js +25 -10
  24. package/dist/docs/content.js.map +1 -1
  25. package/dist/index.js +10 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/api-client.d.ts +13 -1
  28. package/dist/lib/api-client.d.ts.map +1 -1
  29. package/dist/lib/api-client.js +47 -20
  30. package/dist/lib/api-client.js.map +1 -1
  31. package/dist/lib/api-client.test.js +78 -0
  32. package/dist/lib/api-client.test.js.map +1 -1
  33. package/dist/lib/file-loader.d.ts +13 -2
  34. package/dist/lib/file-loader.d.ts.map +1 -1
  35. package/dist/lib/file-loader.js +51 -15
  36. package/dist/lib/file-loader.js.map +1 -1
  37. package/dist/lib/sweep-stale.d.ts +25 -0
  38. package/dist/lib/sweep-stale.d.ts.map +1 -0
  39. package/dist/lib/sweep-stale.js +179 -0
  40. package/dist/lib/sweep-stale.js.map +1 -0
  41. package/dist/lib/sweep-stale.test.d.ts +2 -0
  42. package/dist/lib/sweep-stale.test.d.ts.map +1 -0
  43. package/dist/lib/sweep-stale.test.js +130 -0
  44. package/dist/lib/sweep-stale.test.js.map +1 -0
  45. package/dist/skill/docs/changelog.md +71 -0
  46. package/dist/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  47. package/dist/skill/docs/compiler/config/index.md +21 -12
  48. package/dist/skill/docs/compiler/definitions/encryption.md +117 -1
  49. package/dist/skill/docs/compiler/definitions/index.md +39 -17
  50. package/dist/skill/docs/compiler/definitions/masking.md +32 -0
  51. package/dist/skill/docs/compiler/definitions/rate-limit.md +216 -0
  52. package/dist/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  53. package/dist/skill/docs/compiler/definitions/triggers.md +5 -0
  54. package/dist/skill/docs/stack/index.md +6 -0
  55. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +12 -0
  56. package/dist/skill/docs/stack/schedules/index.md +78 -0
  57. package/dist/skill/docs/stack/webhooks/inbound.md +62 -5
  58. package/package.json +1 -1
  59. package/src/skill/docs/changelog.md +71 -0
  60. package/src/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  61. package/src/skill/docs/compiler/config/index.md +21 -12
  62. package/src/skill/docs/compiler/definitions/encryption.md +117 -1
  63. package/src/skill/docs/compiler/definitions/index.md +39 -17
  64. package/src/skill/docs/compiler/definitions/masking.md +32 -0
  65. package/src/skill/docs/compiler/definitions/rate-limit.md +216 -0
  66. package/src/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  67. package/src/skill/docs/compiler/definitions/triggers.md +5 -0
  68. package/src/skill/docs/stack/index.md +6 -0
  69. package/src/skill/docs/stack/realtime/partyserver-rooms.md +12 -0
  70. package/src/skill/docs/stack/schedules/index.md +78 -0
  71. package/src/skill/docs/stack/webhooks/inbound.md +62 -5
@@ -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 |
@@ -10,6 +10,7 @@
10
10
  | [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |
11
11
  | [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |
12
12
  | [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |
13
+ | [Schedules](/stack/schedules) | Cron Triggers | `defineSchedule` cron jobs, server-internal |
13
14
  | [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |
14
15
  | [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |
15
16
  | [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |
@@ -35,6 +36,11 @@
35
36
  │ │ Queues │ │ Better Auth │ │
36
37
  │ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │
37
38
  │ └─────────────┘ └─────────────────────────────────┘ │
39
+ │ │
40
+ │ ┌─────────────┐ │
41
+ │ │ Schedules │ │
42
+ │ │ (Cron) │ │
43
+ │ └─────────────┘ │
38
44
  └─────────────────────────────────────────────────────────────┘
39
45
  ```
40
46
 
@@ -163,6 +163,16 @@ bindings: {
163
163
  access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
164
164
  },
165
165
 
166
+ // Identity-gated room — the roomId IS the caller's own id, with no backing
167
+ // table. A per-user gateway / presence / inbox keyed on `ctx.userId`:
168
+ // auto-emits a gate at /realtime/user-gateway/* that 403s unless the room
169
+ // segment equals the authenticated user's id. Use `ctx.activeOrgId` for a
170
+ // per-org room. No DB query — it's a string compare against ctx.
171
+ {
172
+ name: 'UserGateway', className: 'UserGateway', from: 'lib/UserGateway',
173
+ access: { roomIdEquals: 'ctx.userId' },
174
+ },
175
+
166
176
  // Genuinely public room (no auth, no row lookup) — opt out explicitly.
167
177
  { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',
168
178
  access: 'public' },
@@ -176,6 +186,7 @@ What the compiler emits:
176
186
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
177
187
  - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
178
188
  - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
189
+ - **`access: { roomIdEquals: 'ctx.userId' }`** — an **identity gate** for rooms with no backing table, where the roomId *is* the caller's own id. Emits `app.use('/realtime/<kebab>/*', …)` that 401s anonymous, 400s a missing segment, and 403s unless the decoded room segment equals `ctx.userId`. No schema import, no firewall, no DB query — a string compare against the server-resolved `ctx`. Use `'ctx.activeOrgId'` for a per-org room. This is the right gate for per-user gateways, presence, or inbox DOs keyed on `ns.idFromName(ctx.userId)`. Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted (validated at compile time); anything else is a build error. Distinct from `resource` because there's no row to firewall — it closes the cross-user hole that "no `access` declared" leaves open (any authenticated user could otherwise open another user's room via the catchall).
179
190
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
180
191
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)
181
192
 
@@ -189,6 +200,7 @@ If a room currently enforces access by hand inside `onConnect` / `onBeforeConnec
189
200
  2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.
190
201
  3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.
191
202
  4. **access depends on membership, not just tenant** (e.g. "is this user an attendee of the event that owns this page") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.
203
+ 5. **roomId is the caller's own identity** (a per-user gateway/presence/inbox where the room *is* `ctx.userId`, with no backing table) → `access: { roomIdEquals: 'ctx.userId' }` (or `'ctx.activeOrgId'`). Do **not** enforce this inside the DO from request data — a Durable Object has no session and only sees client-settable headers, so trusting an `x-user-id` header lets any authenticated user open another user's room. The gate belongs at the Worker edge, which is exactly what this arm emits.
192
204
 
193
205
  The declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.
194
206
 
@@ -0,0 +1,78 @@
1
+ # Schedules (Cron)
2
+
3
+ `defineSchedule` is the trigger-side mirror of [`defineQueue`](/stack/queues). Drop a file in `services/schedules/` and the compiler emits a Worker `scheduled()` (cron) handler plus the matching `[triggers] crons` in `wrangler.toml` — no separate cron Worker, no hand-patching the generated entry.
4
+
5
+ ## Define a schedule
6
+
7
+ ```typescript
8
+ // services/schedules/sweepDigests.ts
9
+ import { defineSchedule } from "quickback";
10
+
11
+ export default defineSchedule({
12
+ name: "sweepDigests", // identifier + audit actor (system:cron-<name>)
13
+ cron: "* * * * *", // Cloudflare cron syntax
14
+ description: "Send pending unread-email digests",
15
+ execute: async ({ db, env, services }) => {
16
+ await runDigestSweep(db, env, services);
17
+ },
18
+ });
19
+ ```
20
+
21
+ One file per schedule under `services/schedules/*.ts`. Files prefixed with `_` are ignored. `name` must be a valid camelCase identifier (it's used as a generated symbol and the audit actor).
22
+
23
+ ## What the compiler emits
24
+
25
+ 1. **`scheduled(event, env, ctx)`** in the Worker's default export, dispatching to every schedule whose cron matches `event.cron`. Multiple schedules can share a cron; a failure in one is isolated from the others.
26
+ 2. **`[triggers] crons = [...]`** in `wrangler.toml` — one deduped, sorted list across all schedules.
27
+ 3. **`src/lib/schedules.ts`** — the generated runner. Regenerated on every `quickback compile`, so there's nothing to hand-maintain.
28
+
29
+ ## Execute context
30
+
31
+ | Field | Type | Notes |
32
+ |-------|------|-------|
33
+ | `db` | Drizzle instance | The same DB the queue handlers get |
34
+ | `env` | `CloudflareBindings` | All worker bindings |
35
+ | `services` | `Services` | The services layer (`createServices(env)`) |
36
+ | `cron` | `string` | The cron pattern that fired |
37
+ | `scheduledTime` | `number` | `event.scheduledTime` (ms epoch) |
38
+ | `withInternalContext` | helper | Opt into the `INTERNAL` trust zone for `roles: ['INTERNAL']`-gated rows |
39
+
40
+ ## Audit & trust
41
+
42
+ Cron runs are **server-internal**: there's no authenticated user, no request, no org scope. A fired tick gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:
43
+
44
+ ```typescript
45
+ execute: async ({ db, withInternalContext }) => {
46
+ // `db` here is unscoped — no firewall WHERE, no audit actor.
47
+
48
+ // Opt into the INTERNAL trust zone for cross-tenant work:
49
+ await withInternalContext(async ({ ctx, db, services }) => {
50
+ // ctx.internal = true, ctx.userId = "system:cron-<name>"
51
+ // audited writes are attributable to e.g. system:cron-sweepDigests
52
+ });
53
+ },
54
+ ```
55
+
56
+ `withInternalContext` builds a context with `internal: true` and `userId: "system:cron-<name>"`, so audited writes made through it are attributable to the schedule (e.g. `system:cron-sweepDigests`) and can reach `roles: ['INTERNAL']`-gated rows. Reach for it whenever the schedule legitimately operates across tenants.
57
+
58
+ ## Failure isolation
59
+
60
+ The generated `scheduled()` dispatcher runs every schedule whose cron matches `event.cron` concurrently (`Promise.all`), and each handler's errors are caught individually — one failing schedule logs `[Cron] Schedule error` and the others still run to completion. A cron with no registered handler logs `[Cron] No schedule registered` and returns.
61
+
62
+ ## Cron syntax
63
+
64
+ Standard Cloudflare cron (`minute hour day-of-month month day-of-week`):
65
+
66
+ | Pattern | Runs |
67
+ |---------|------|
68
+ | `* * * * *` | every minute |
69
+ | `0 * * * *` | top of every hour |
70
+ | `0 0 * * *` | daily at 00:00 UTC |
71
+ | `*/5 * * * *` | every 5 minutes |
72
+
73
+ See Cloudflare's [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) docs for the full grammar and limits.
74
+
75
+ ## See also
76
+
77
+ - [Queues](/stack/queues) — the async-message counterpart (`defineQueue`)
78
+ - [Triggers](/compiler/definitions/triggers) — row-level lifecycle hooks (distinct from cron)
@@ -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.10",
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",