@quickback-dev/cli 0.47.7 → 0.47.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) 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 +20 -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/SKILL.md +1 -0
  46. package/dist/skill/docs/changelog.md +79 -0
  47. package/dist/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  48. package/dist/skill/docs/compiler/definitions/encryption.md +117 -1
  49. package/dist/skill/docs/compiler/definitions/masking.md +32 -0
  50. package/dist/skill/docs/compiler/definitions/rate-limit.md +216 -0
  51. package/dist/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  52. package/dist/skill/docs/compiler/definitions/triggers.md +169 -0
  53. package/dist/skill/docs/stack/webhooks/inbound.md +62 -5
  54. package/package.json +1 -1
  55. package/src/skill/SKILL.md +1 -0
  56. package/src/skill/docs/changelog.md +103 -0
  57. package/src/skill/docs/compiler/cloud-compiler/cli.md +3 -0
  58. package/src/skill/docs/compiler/definitions/encryption.md +117 -1
  59. package/src/skill/docs/compiler/definitions/masking.md +32 -0
  60. package/src/skill/docs/compiler/definitions/rate-limit.md +216 -0
  61. package/src/skill/docs/compiler/definitions/sealed-protocol.md +332 -0
  62. package/src/skill/docs/compiler/definitions/triggers.md +174 -0
  63. package/src/skill/docs/stack/schedules/index.md +60 -0
  64. 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.
@@ -0,0 +1,169 @@
1
+ # Triggers - Postgres-Style Table Triggers
2
+
3
+ Run logic when rows change — Postgres-style `before`/`after` triggers on `insert`/`update`/`delete`, declared per table.
4
+
5
+ Each trigger lowers one of two ways, and the compiler reports which:
6
+
7
+ | You write | Lowers to | Fires on |
8
+ |---|---|---|
9
+ | `sql:` | A real SQLite `CREATE TRIGGER` in your migrations | **Every** write path — REST, actions, queue handlers, cron, raw SQL. Atomic with the write. |
10
+ | `handler:` | An application hook at the audit-wrapper write chokepoint | Writes through the wrapped `db` — REST CRUD and actions. **Not** queue handlers, cron, or raw SQL. |
11
+
12
+ There is no auto-translation between the lanes: SQL bodies stay SQL, functions stay functions. Pick the lane by what the trigger must guarantee.
13
+
14
+ ## Basic Usage
15
+
16
+ ```typescript
17
+ // features/invoices/invoices.ts
18
+ import { feature, q } from '@quickback/compiler';
19
+
20
+ export default feature('invoices', {
21
+ columns: {
22
+ id: q.id(),
23
+ title: q.text({ maxLength: 200 }).required(),
24
+ notes: q.text({ maxLength: 2000 }).optional(),
25
+ total: q.int().default(0).required(),
26
+ status: q.enum(['draft', 'sent', 'paid']).default('draft').required(),
27
+ organizationId: q.scope('organization'),
28
+ },
29
+ read: { access: { roles: ['member'] } },
30
+ create: { access: { roles: ['member'] } },
31
+ update: { access: { roles: ['member'] } },
32
+ delete: { access: { roles: ['member'] }, mode: 'soft' },
33
+
34
+ triggers: {
35
+ beforeInsert: [
36
+ {
37
+ name: 'guardTotals',
38
+ handler: ({ values }) => {
39
+ if (values.total < 0) throw new Error('total must be >= 0');
40
+ return { notes: values.notes ?? 'created' }; // merge into the write
41
+ },
42
+ },
43
+ ],
44
+ afterInsert: [
45
+ {
46
+ // SQL lane — fires for raw SQL too, atomic with the insert
47
+ name: 'stampNotes',
48
+ sql: `UPDATE invoices SET notes = NEW.title WHERE id = NEW.id;`,
49
+ },
50
+ ],
51
+ beforeUpdate: [
52
+ {
53
+ // The universal-enforcement shape: WHEN guard + RAISE(ABORT)
54
+ name: 'lockPaid',
55
+ when: `OLD.status = 'paid' AND NEW.status != 'paid'`,
56
+ sql: `SELECT RAISE(ABORT, 'paid invoices cannot be reopened');`,
57
+ },
58
+ ],
59
+ },
60
+ });
61
+ ```
62
+
63
+ Events: `beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete`. Each event takes an array of named triggers; names must be unique per event.
64
+
65
+ ## SQL triggers (`sql:`)
66
+
67
+ The compiler wraps your statements in a `CREATE TRIGGER` named
68
+ `qb_trg_<table>_<event>_<name>` and ships it in the journaled features
69
+ migration — content-addressed, so an unchanged trigger set produces no new
70
+ migration, and removing a trigger from config drops it from the database on
71
+ the next migrate.
72
+
73
+ - Write **bare, `;`-terminated statements** — the compiler owns the
74
+ `BEGIN`/`END` frame. (It emits the frame uppercase; lowercase `begin`
75
+ breaks remote D1's statement splitter even though local D1 accepts it.)
76
+ - `OLD.column` / `NEW.column` references use **SQL column names**
77
+ (`deleted_at`, not `deletedAt`) and are validated against the table at
78
+ compile time.
79
+ - Optional `when:` is a SQL expression guard (`WHEN` clause).
80
+ - To reject a write, `SELECT RAISE(ABORT, 'message');` — this is the only
81
+ trigger form that blocks *every* write path, including raw SQL.
82
+ - SQL triggers run inside the triggering statement — the only
83
+ transactional option on D1, which has no `db.transaction()`.
84
+
85
+ Currently supported on `cloudflare-d1` only; declaring `sql:` triggers on
86
+ another database provider is a compile error.
87
+
88
+ ### Soft-delete mapping
89
+
90
+ On soft-delete tables (the default), `*Delete` events map to the
91
+ soft-delete *transition* — the compiler emits an
92
+ `AFTER UPDATE OF "deleted_at" ... WHEN NEW."deleted_at" IS NOT NULL AND
93
+ OLD."deleted_at" IS NULL` trigger, plus a plain `AFTER DELETE` variant so
94
+ raw-SQL hard deletes are still covered. `*Update` events get the inverse
95
+ guard, so a soft delete fires delete triggers exactly once and never
96
+ double-fires as an update.
97
+
98
+ ## Handler triggers (`handler:`)
99
+
100
+ Handlers run at the same write chokepoint that powers audit stamping and
101
+ Live Views, with full application context:
102
+
103
+ ```typescript
104
+ handler: ({ table, op, values /* before */, row /* after */, ctx, db, env }) => { ... }
105
+ ```
106
+
107
+ - **`before*` hooks are synchronous.** Return a partial object to merge
108
+ into the write payload, or throw to reject — the write never executes and
109
+ the request gets a structured `TRIGGER_REJECTED` (422) error. Audit
110
+ fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and
111
+ cannot be forged.
112
+ - **`after*` hooks run once per affected row and are awaited** before the
113
+ write's promise resolves. They may be `async`. A throw surfaces as
114
+ `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was
115
+ already persisted (no transactions on D1), so clients must not blind-retry.
116
+ - Handlers must be **inline arrow/function expressions**. Imports they
117
+ reference are hoisted into the generated registry, and each table's
118
+ drizzle object is auto-imported under its authored name — so this works
119
+ as written:
120
+
121
+ ```typescript
122
+ import { eq } from 'drizzle-orm';
123
+
124
+ // ...
125
+ afterUpdate: [
126
+ {
127
+ name: 'syncNotes',
128
+ handler: async ({ row, db }) => {
129
+ await db.update(invoices)
130
+ .set({ notes: `updated: ${row.title}` })
131
+ .where(eq(invoices.id, row.id));
132
+ },
133
+ },
134
+ ],
135
+ ```
136
+
137
+ `after*` hooks only receive rows when the write chain used `.returning()`
138
+ — generated CRUD routes and actions do.
139
+
140
+ ### Recursion
141
+
142
+ Trigger cascades are bounded in every lane:
143
+
144
+ - **Handler hooks**: the `db` a hook receives is re-wrapped at depth + 1.
145
+ A cascade deeper than 5 levels (a hook's write firing hooks that write
146
+ again, …) throws with the table/op that exceeded the cap.
147
+ - **SQL triggers**: SQLite's `recursive_triggers` pragma defaults off — a
148
+ trigger cannot re-enter itself, directly or through a cycle.
149
+
150
+ ### Coverage — read the compile report
151
+
152
+ Handler hooks do **not** fire for queue handlers, cron jobs, or raw SQL.
153
+ The compiler emits a per-trigger lowering report and warns at compile time
154
+ when a `before*` handler is used as a guard — if a rule must hold for every
155
+ write path, use the `sql:` lane with `RAISE(ABORT)`.
156
+
157
+ ## Choosing a lane
158
+
159
+ | Need | Use |
160
+ |---|---|
161
+ | Invariant that must hold universally (raw SQL included) | `sql:` with `RAISE(ABORT)` |
162
+ | Denormalized columns, counters, tombstones | `sql:` |
163
+ | Validation/derivation with application logic | `before*` `handler:` |
164
+ | Side-effects after a write (notify, write related rows) | `after*` `handler:` |
165
+ | Atomic with the write (D1 has no transactions) | `sql:` only |
166
+
167
+ Planned (not yet available — declaring them is a compile error rather than
168
+ a silent no-op): `async: true` queue-dispatched after-hooks with retries,
169
+ and `withOld: true` previous-row access on update/delete hooks.
@@ -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.7",
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",
@@ -265,6 +265,7 @@ The path layout mirrors the public docs site (https://docs.quickback.dev). Open
265
265
  - `masking` — types, `show:`, search/filter gating, auto-detection
266
266
  - `read` — `read.access`, `read.views`, `read.query`, pagination + filtering
267
267
  - `views` — named projections with column-level access
268
+ - `triggers` — Postgres-style table triggers: `sql:` → real SQLite trigger (all write paths, atomic), `handler:` → app hook at the write chokepoint (before mutate/reject, awaited after)
268
269
  - `actions` — record-based vs standalone, transitions, `unsafe:`, `whereRecord(table)`, `ActionError`, `authDb`
269
270
  - `validation` — minLength, max, enum, pattern, email
270
271
  - `concepts` — secure-by-default, defense in depth, request flow