@quickback-dev/cli 0.60.9 → 0.61.1

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 (77) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +10 -1
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.d.ts +7 -0
  5. package/dist/docs/content.d.ts.map +1 -0
  6. package/dist/docs/content.js +737 -0
  7. package/dist/docs/content.js.map +1 -0
  8. package/dist/index.js +1 -1
  9. package/dist/lib/compiler-stubs.d.ts +4 -0
  10. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  11. package/dist/lib/compiler-stubs.js +4 -0
  12. package/dist/lib/compiler-stubs.js.map +1 -1
  13. package/dist/lib/file-loader.d.ts +11 -0
  14. package/dist/lib/file-loader.d.ts.map +1 -1
  15. package/dist/lib/file-loader.js +35 -0
  16. package/dist/lib/file-loader.js.map +1 -1
  17. package/dist/lib/helpers.d.ts +39 -0
  18. package/dist/lib/helpers.d.ts.map +1 -0
  19. package/dist/lib/helpers.js +299 -0
  20. package/dist/lib/helpers.js.map +1 -0
  21. package/dist/skill/SKILL.md +3 -0
  22. package/dist/skill/docs/api/errors.md +1 -0
  23. package/dist/skill/docs/api/query-params.md +26 -0
  24. package/dist/skill/docs/changelog/index.md +85 -0
  25. package/dist/skill/docs/configure/auth.md +17 -12
  26. package/dist/skill/docs/configure/domains.md +1 -1
  27. package/dist/skill/docs/configure/index.md +6 -6
  28. package/dist/skill/docs/define/actions/defining.md +37 -1
  29. package/dist/skill/docs/define/actions/index.md +18 -0
  30. package/dist/skill/docs/define/areas.md +90 -7
  31. package/dist/skill/docs/define/feature.md +88 -27
  32. package/dist/skill/docs/define/index.md +7 -1
  33. package/dist/skill/docs/define/scopes.md +1 -1
  34. package/dist/skill/docs/define/security.md +10 -0
  35. package/dist/skill/docs/define/transitions.md +11 -35
  36. package/dist/skill/docs/platform/auth/jwt-optimization.md +15 -3
  37. package/dist/skill/docs/platform/database/d1.md +6 -1
  38. package/dist/skill/docs/platform/email/index.md +112 -0
  39. package/dist/skill/docs/platform/index.md +1 -0
  40. package/dist/skill/docs/platform/realtime/index.md +17 -0
  41. package/dist/skill/docs/platform/webhooks/outbound.md +31 -6
  42. package/dist/skill/docs/start/deploy-browser.md +15 -6
  43. package/dist/skill/docs/start/first-api.md +16 -0
  44. package/dist/skill/docs/ui/account/features/admin.md +29 -5
  45. package/dist/skill/docs/ui/account/features/index.md +22 -0
  46. package/dist/skill/docs/ui/admin/connecting.md +6 -4
  47. package/dist/skill/docs/ui/admin/index.md +49 -10
  48. package/dist/skill/docs/ui/admin/security.md +6 -7
  49. package/package.json +2 -10
  50. package/src/skill/SKILL.md +3 -0
  51. package/src/skill/docs/api/errors.md +1 -0
  52. package/src/skill/docs/api/query-params.md +26 -0
  53. package/src/skill/docs/changelog/index.md +85 -0
  54. package/src/skill/docs/configure/auth.md +17 -12
  55. package/src/skill/docs/configure/domains.md +1 -1
  56. package/src/skill/docs/configure/index.md +6 -6
  57. package/src/skill/docs/define/actions/defining.md +37 -1
  58. package/src/skill/docs/define/actions/index.md +18 -0
  59. package/src/skill/docs/define/areas.md +90 -7
  60. package/src/skill/docs/define/feature.md +88 -27
  61. package/src/skill/docs/define/index.md +7 -1
  62. package/src/skill/docs/define/scopes.md +1 -1
  63. package/src/skill/docs/define/security.md +10 -0
  64. package/src/skill/docs/define/transitions.md +11 -35
  65. package/src/skill/docs/platform/auth/jwt-optimization.md +15 -3
  66. package/src/skill/docs/platform/database/d1.md +6 -1
  67. package/src/skill/docs/platform/email/index.md +112 -0
  68. package/src/skill/docs/platform/index.md +1 -0
  69. package/src/skill/docs/platform/realtime/index.md +17 -0
  70. package/src/skill/docs/platform/webhooks/outbound.md +31 -6
  71. package/src/skill/docs/start/deploy-browser.md +15 -6
  72. package/src/skill/docs/start/first-api.md +16 -0
  73. package/src/skill/docs/ui/account/features/admin.md +29 -5
  74. package/src/skill/docs/ui/account/features/index.md +22 -0
  75. package/src/skill/docs/ui/admin/connecting.md +6 -4
  76. package/src/skill/docs/ui/admin/index.md +49 -10
  77. package/src/skill/docs/ui/admin/security.md +6 -7
@@ -1,35 +1,56 @@
1
1
  # feature() — the canonical form
2
2
 
3
- `feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. The older `q.table()` + `defineTable()` pair still exists underneath (it's what `feature()` expands into), but it means two exports and two concepts for something a feature file treats as one unit.
3
+ `feature()` is **the** way to write a Quickback feature: one file, one default export, the table and its security contract together. It expands at compile time into `q.table()` + `defineTable()`, which stays available for the cases that need it — see [When to use which](#when-to-use-which).
4
4
 
5
- ## Before
5
+ ## Quick reference
6
6
 
7
- ```ts title="quickback/features/contacts.ts"
8
- import { q, defineTable } from "@quickback/compiler";
9
-
10
- export const contacts = q.table("contacts", {
11
- id: q.id(),
12
- organizationId: q.text().required().index(),
13
- address: q.text().required().index(),
14
- name: q.text().optional(),
15
- ...q.audit(),
16
- ...q.softDelete(),
17
- });
7
+ One object. Everything a table exposes is a key in it, and every key is optional
8
+ except `columns`.
18
9
 
19
- export default defineTable(contacts, {
20
- firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
21
- // "+" role expansion requires auth.roleHierarchy in quickback.config.ts
22
- read: { access: { roles: ["member+"] } },
23
- create: { access: { roles: ["member+"] } },
24
- update: { access: { roles: ["member+"] } },
25
- delete: { access: { roles: ["admin+"] }, mode: "soft" },
26
- guards: { createable: ["address", "name"] },
10
+ {/* doc-compile: skip — key map, not a config: every value is an empty placeholder. The compiled forms are in the fences below and on each key's own page. */}
11
+ ```ts
12
+ feature("name", {
13
+ columns: {}, // q.* column helpers — the Drizzle schema
14
+
15
+ // Security — the five pillars
16
+ firewall: {}, // which ROWS (auto-derived from organizationId / ownerId / teamId)
17
+ read: {}, // who may read + `views` — named column projections
18
+ create: {}, // who may write
19
+ update: {},
20
+ delete: {}, // + `mode: "soft" | "hard"`
21
+ guards: {}, // which FIELDS a caller may set
22
+ masking: {}, // which VALUES come back redacted
23
+ rateLimit: {}, // per-operation caps
24
+
25
+ // Endpoints beyond CRUD — declared here, not written as action files
26
+ transitions: {}, // guarded state changes → POST /:id/{name}
27
+ triggers: {}, // before/after hooks on every write
28
+ owns: {}, // composition boundary → atomic parent+children writes
29
+ realtime: {}, // broadcast insert/update/delete
30
+ embeddings: {}, // vectors generated on write
31
+
32
+ // Placement + presentation
33
+ path: "", // route base (defaults to the feature name)
34
+ namespace: {}, // hoisted route prefix + admission gate
35
+ displayColumn: "", defaultSort: {}, inputHints: {}, layouts: {}, references: {},
27
36
  });
28
-
29
- export type Contact = typeof contacts.$infer;
30
37
  ```
31
38
 
32
- ## After
39
+ | You want | Key | Page |
40
+ |---|---|---|
41
+ | Tenant isolation, role gates, field and value control | `firewall`, `read`/`create`/`update`/`delete`, `guards`, `masking` | [Security](/define/security) |
42
+ | A narrower shape for a broader audience | `read.views` | [Views](/define/views) |
43
+ | `publish` / `approve` / `checkIn` — a state change | `transitions` | [Transitions](/define/transitions) |
44
+ | A side-effect or data rule on every write | `triggers` | [Triggers](/define/triggers) |
45
+ | Parent plus its children written atomically | `owns` | [Changesets](/define/changesets) |
46
+ | Clients updated live | `realtime` | [Realtime](/platform/realtime/using-realtime) |
47
+ | Semantic search over the table | `embeddings` | [Embeddings](/platform/vector/using-embeddings) |
48
+ | The CMS to render it well | `displayColumn`, `defaultSort`, `inputHints`, `layouts` | [CMS](/ui/admin/table-views) |
49
+
50
+ The rest of this page is the form itself; [One object, not just
51
+ CRUD](#one-object-not-just-crud) shows the non-CRUD keys filled in.
52
+
53
+ ## The form
33
54
 
34
55
  ```ts title="quickback/features/contacts.ts"
35
56
  import { feature, q } from "@quickback/compiler";
@@ -37,13 +58,12 @@ import { feature, q } from "@quickback/compiler";
37
58
  export default feature("contacts", {
38
59
  columns: {
39
60
  id: q.id(),
40
- organizationId: q.text().required().index(),
61
+ organizationId: q.scope("organization"), // firewall auto-derives from this
41
62
  address: q.text().required().index(),
42
63
  name: q.text().optional(),
43
64
  ...q.audit(),
44
65
  ...q.softDelete(),
45
66
  },
46
- firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
47
67
  // "+" role expansion requires auth.roleHierarchy in quickback.config.ts
48
68
  read: { access: { roles: ["member+"] } },
49
69
  create: { access: { roles: ["member+"] } },
@@ -53,7 +73,48 @@ export default feature("contacts", {
53
73
  });
54
74
  ```
55
75
 
56
- Type inference still works — `typeof import("./contacts").default.$infer` gives you the `Contact` row type.
76
+ Type inference comes with it — `typeof import("./contacts").default.$infer` gives you the `Contact` row type.
77
+
78
+ ## One object, not just CRUD
79
+
80
+ The example above declares security and CRUD because that is the floor. The same
81
+ config object carries every other per-table capability — a live feed, a state
82
+ machine, a narrower projection, a write hook. They are keys next to `read:` and
83
+ `guards:`, not separate files or services, and each generates a real endpoint on
84
+ the same firewall → access → guards → masking pipeline.
85
+
86
+ {/* doc-compile: skip — shape sketch: `columns` is elided so the keys stay readable side by side, and `member+`/`admin+` need `auth.roleHierarchy` in quickback.config.ts. Each key's own page carries the compiled version. */}
87
+ ```ts
88
+ export default feature("episodes", {
89
+ columns: { /* … */ },
90
+ firewall: [{ field: "organizationId", equals: "ctx.activeOrgId" }],
91
+ read: {
92
+ access: { roles: ["member+"] },
93
+ views: { public: { fields: ["id", "title"], access: { roles: ["member+"] } } },
94
+ },
95
+ guards: { updatable: ["title"], protected: { isPublished: ["publish"] } },
96
+ masking: { submitterEmail: { type: "email", show: { roles: ["admin"] } } },
97
+ transitions: { publish: { field: "isPublished", from: false, to: true, access: { roles: ["admin+"] } } },
98
+ realtime: { enabled: true, onInsert: true, onUpdate: true },
99
+ embeddings: { fields: ["title", "summary"] },
100
+ });
101
+ ```
102
+
103
+ | Key | Gives you | Reference |
104
+ |---|---|---|
105
+ | `read.views` | Named column projections, each with its own route and access rule | [Views](/define/views) |
106
+ | `transitions` | Guarded state changes generated as real `POST /:id/{name}` actions — guards, stamps, `undo`, cascades | [Transitions](/define/transitions) |
107
+ | `triggers` | `before`/`after` hooks on write, lowered to a real SQL trigger or an application handler | [Triggers](/define/triggers) |
108
+ | `realtime` | Per-table broadcasts on insert/update/delete, audience-scoped | [Realtime](/platform/realtime/using-realtime) |
109
+ | `owns` | The composition boundary that turns on atomic parent-plus-children writes | [Changesets](/define/changesets) |
110
+ | `embeddings` | Vector embeddings generated on insert/update | [Embeddings](/platform/vector/using-embeddings) |
111
+ | `masking` / `rateLimit` / `namespace` | Field redaction, per-operation caps, a hoisted route prefix + gate | [Masking](/define/masking), [Rate limit](/define/rate-limit), [Areas](/define/areas) |
112
+ | `displayColumn` / `defaultSort` / `inputHints` / `layouts` / `references` | How the CMS renders the table — no runtime effect | [CMS](/ui/admin/table-views) |
113
+
114
+ Reach for these before writing an action file: an action is code you maintain,
115
+ these are declarations the compiler owns. See the full option list in
116
+ [Definitions Overview](/define#other-resource-options) and the "before you write
117
+ one" routing table at the top of [Actions](/define/actions).
57
118
 
58
119
  ## How it works
59
120
 
@@ -273,6 +273,9 @@ Beyond the five security layers, `defineTable` accepts a handful of declarative
273
273
  | Option | What it does | Full reference |
274
274
  |---|---|---|
275
275
  | `views` | Named column projections — `GET /resource/views/{name}` returns a subset of columns under its own access rule. | [Views](/define/views) |
276
+ | `transitions` | Guarded state changes — each entry generates a real `POST /resource/:id/{name}` action file, with guards, stamps, idempotency, `undo` inverses, and `onEnter` cascades. | [Transitions](/define/transitions) |
277
+ | `changesets` | An `owns` boundary — write the parent row and its owned relations in one atomic request, each op paying the child's own firewall, access, and guards. | [Changesets](/define/changesets) |
278
+ | `triggers` | `before`/`after` hooks on `insert`/`update`/`delete`, lowering either to a real SQL trigger in your migrations or to an application handler at the write chokepoint. | [Triggers](/define/triggers) |
276
279
  | `references` | Explicit FK target table for columns that don't follow the "Id"-stripped convention (e.g. `vendorId → contact`). | [CMS Schema Registry](/ui/admin/schema-registry) |
277
280
  | `displayColumn` | Column to use as the human-readable label in FK resolutions and CMS list views (auto-detected as `name`/`title`/`label` if not set). | [CMS Table Views](/ui/admin/table-views) |
278
281
  | `defaultSort` | Default sort order for CMS list rendering (`{ field, order: "asc" \| "desc" }`). | [CMS Table Views](/ui/admin/table-views) |
@@ -294,4 +297,7 @@ All options are optional — omit them and Quickback uses sensible defaults (aut
294
297
  6. [Rate Limit](/define/rate-limit) — Per-operation request caps
295
298
  7. [Views](/define/views) — Column-level security
296
299
  8. [Validation](/define/validation) — Field validation rules
297
- 9. [Actions](/define/actions) — Add custom business logic
300
+ 9. [Transitions](/define/transitions) — Guarded state changes, generated as real endpoints
301
+ 10. [Changesets](/define/changesets) — Atomic parent-plus-owned-relations writes
302
+ 11. [Triggers](/define/triggers) — Data rules and side-effects on write
303
+ 12. [Actions](/define/actions) — Custom business logic, for what the above can't express
@@ -635,7 +635,7 @@ The scope claim is trusted between proofs — it is never re-checked against the
635
635
 
636
636
  So removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:
637
637
 
638
- - **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/configure/auth).
638
+ - **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`, with its millisecond companion `sctMs`) is at or before it — no same-second gap. Both halves of the proof time are carried forward verbatim by the rolling refresh; a refresh never substitutes its own mint time for proof time. The check fails closed — a scope claim whose revocation state can't be read is not trusted either. See [auth config](/configure/auth).
639
639
  - **`via` arms** — for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.
640
640
 
641
641
  ## Reference
@@ -94,6 +94,16 @@ omitted from the generated request schemas entirely, so a client cannot even sen
94
94
  caller's role. Use it for data the caller may legitimately address but should not read
95
95
  in full.
96
96
 
97
+ **State changes** — `protected: { status: ["publish", "cancel", "refund"] }` removes the
98
+ column from the PATCH schema and names the only doors to it. Each name is an action:
99
+ either a [transition](/define/transitions) the compiler generates from
100
+ `transitions: { publish: { field: "status", from: "draft", to: "live", access: {...} } }`,
101
+ or an [action file](/define/actions) you write when the change needs real logic — a
102
+ `refund` that calls Stripe, then sets the column. Both carry their own `access` rule and
103
+ appear in OpenAPI; the transition additionally gets row guards, stamps, and an `undo`
104
+ inverse for free. Declare the transition when the change is state plus stamps; write the
105
+ action when it is genuinely imperative. Either beats leaving the column freely writable.
106
+
97
107
  ## Advanced authorization
98
108
 
99
109
  When roles are not enough — when access depends on a *relationship* between the caller
@@ -3,43 +3,19 @@
3
3
  ## Overview
4
4
 
5
5
  Most state changes follow the same shape: check the row is in a legal state,
6
- flip a column, stamp who/when, maybe cascade. Before transitions v2 every one
7
- of those was a hand-written action file — a podcast app had **ten files that
8
- were byte-identical except the table name** (`publish.ts` / `revertToDraft.ts`
9
- across five entities), and an events app had eight near-identical
10
- check-in/check-out files.
6
+ flip a column, stamp who/when, maybe cascade. Declare that shape on the table
7
+ and the compiler generates the action files — including `undo` inverses and
8
+ `onEnter` cascades.
11
9
 
12
- Transitions v2 collapses both patterns:
10
+ Two declaration sites:
13
11
 
14
- - **Action-level extensions** on `defineAction({ transition })` — guards,
15
- stamps, idempotency, compiler-applied writes.
16
- - **Table-level `transitions`** on `defineTable` — the compiler *generates*
17
- the action files, including `undo` inverses and `onEnter` cascades.
12
+ - **Table-level `transitions`** on `defineTable` — the compiler generates the
13
+ actions. Start here.
14
+ - **Action-level `transition`** on `defineAction` — the same guards, stamps,
15
+ idempotency, and compiler-applied writes, for an action you are writing
16
+ anyway.
18
17
 
19
- ## The marquee example: 10 files → 2 lines each
20
-
21
- Before (×10 files across episodes/shows/seasons/collections/profiles):
22
-
23
- ```typescript
24
- // actions/episodes/publish.ts — and nine siblings like it
25
- import { z } from "zod";
26
- import { eq } from "drizzle-orm";
27
- import { defineAction, episodes } from "../../.quickback/define-action.episodes";
28
-
29
- export default defineAction({
30
- description: "Publish an episode",
31
- input: z.object({}),
32
- access: { roles: ["admin+"] },
33
- async execute({ db, record }) {
34
- const [updated] = await db.update(episodes)
35
- .set({ isPublished: true })
36
- .where(eq(episodes.id, record.id)).returning();
37
- return updated;
38
- },
39
- });
40
- ```
41
-
42
- After — on each entity's `defineTable`:
18
+ ## Two lines per state change
43
19
 
44
20
  ```typescript
45
21
  // features/podcast/episodes.ts
@@ -62,7 +38,7 @@ export default defineTable(episodes, {
62
38
  });
63
39
  ```
64
40
 
65
- The generated actions mount exactly where the hand-written files did
41
+ The generated actions mount exactly where an authored file would
66
42
  (`POST /episodes/:id/publish`, operationId `episodesPublish`, same MCP tool
67
43
  name), ride the same OpenAPI/security-contract pipeline, and delete cleanly:
68
44
  **an explicit `actions/<name>.ts` file always wins** (the compiler warns about
@@ -27,9 +27,12 @@ The JWT encodes everything needed for auth middleware:
27
27
  | `userRole` | Global user role (when admin panel is enabled) |
28
28
  | `email` | User email |
29
29
  | `name` | User display name |
30
- | `iat` | Issued-at timestamp |
30
+ | `iat` | Issued-at timestamp (unix **seconds**, the standard claim) |
31
+ | `iatMs` | Issued-at in epoch **milliseconds** — Quickback ordering metadata, not a standard claim. Same clock sample as `iat`, set by the signer only. Lets [revocation](#revocation--revocationcheck-kv) order a token against a marker written in the same second |
31
32
  | `exp` | Expiry — **180 seconds** (3 minutes) after `iat` by default; set via [`auth.jwt.expiresIn`](/configure/auth) |
32
33
 
34
+ Scope-bearing tokens also carry `sct` (proof timestamp, unix seconds) and its millisecond companion `sctMs` — see [Scopes](/define/scopes). Read `iat` / `sct` from external tooling; `iatMs` / `sctMs` exist only so revocation can break ties inside a second.
35
+
33
36
  ### Signing
34
37
 
35
38
  JWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET` — the same secret you already set for Better Auth, so there is only one secret to manage.
@@ -113,7 +116,9 @@ auth: {
113
116
  },
114
117
  ```
115
118
 
116
- The fast-path then consults per-principal revocation timestamps in your project's existing `KV` binding (keys prefixed `qbrev:`, self-expiring) *before* trusting a token. A token is rejected when its mint timestamp (`iat`, or `sct` for the scope claim) predates the stored timestamp. Cost: 2+ edge-cached KV reads per bearer verify.
119
+ The fast-path then consults per-principal revocation timestamps in your project's existing `KV` binding (keys prefixed `qbrev:`, self-expiring) *before* trusting a token. A token is rejected when its mint timestamp (`iat`/`iatMs`, or `sct`/`sctMs` for the scope claim) is **at or before** the stored timestamp. Cost: 2+ edge-cached KV reads per bearer verify.
120
+
121
+ There is no same-second gap: markers are epoch milliseconds (written `m<ms>`, v0.61.0+), tokens carry millisecond companions, and the comparison denies a tie — so a token minted a few milliseconds *before* the revocation is rejected, while one legitimately re-minted *after* it in that same second is still accepted. Pre-v0.61.0 workers don't understand that marker format and read it as "not revoked" — don't roll back across the upgrade or share one KV namespace between versions; see [`revocationCheck`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy).
117
122
 
118
123
  Revocation stamps are written **automatically** on:
119
124
 
@@ -125,7 +130,14 @@ The generated `src/lib/jwt-revocation.ts` exports `revokeUserTokens`, `revokeMem
125
130
 
126
131
  > **Honest limits**
127
132
  >
128
- > The KV check revokes **per principal**, not per session; it **fails open** if KV is unreachable (degrading to the TTL bound rather than locking bearers out); and stamps propagate cross-PoP in roughly 60 seconds. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently. For fail-closed semantics, use `expiresIn: 30` instead.
133
+ > The KV check revokes **per principal**, not per session, and stamps propagate cross-PoP in roughly 60 seconds — "immediate" means seconds, not instantaneous.
134
+ >
135
+ > It **fails closed** for bearer auth: if the KV binding is missing or the read fails, the bearer is *not* authenticated — a signature is all that is known about it — and the caller gets a retryable **`503 AUTH_REVOCATION_UNAVAILABLE`**. Recovery is a **separate cookie-only request**, not a fallback inside the same one: a request carrying `Authorization` has its cookie stripped before session auth (bearer is an alternative to the cookie, not a supplement), so during a KV outage every JWT-bearer request gets the 503 until the client retries on its session cookie. A *revoked* token behaves the same way, and a cookie request re-checks membership and re-mints transparently.
136
+
137
+
138
+ > **Operational consequence**
139
+ >
140
+ > Enabling `revocationCheck: 'kv'` ties bearer-token availability to KV. Alert on `AUTH_REVOCATION_UNAVAILABLE` — a sustained rate means the binding is gone (check that every deployment target declares it) or KV itself is degraded. If you want the TTL bound *without* that coupling, leave `revocationCheck` at `'none'` and set `expiresIn: 30`.
129
141
 
130
142
 
131
143
  Full knob-by-knob reference: [Auth & JWT config → `revocationCheck`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy).
@@ -254,10 +254,15 @@ target:
254
254
  npm run deploy:dev # wrangler deploy --env dev
255
255
  npm run deploy:production # wrangler deploy --env production
256
256
 
257
- npm run db:migrate:dev:auth:remote # wrangler d1 migrations apply my-app-auth-dev --remote
257
+ npm run db:migrate:dev:auth:remote # …apply my-app-auth-dev --remote --env dev
258
258
  npm run db:migrate:dev:remote # fan-out over every declared role
259
259
  ```
260
260
 
261
+ Every migration script carries `--env`. With the top-level blocks suppressed,
262
+ a bare database name has no scope to resolve in and wrangler fails with
263
+ `Couldn't find a D1 DB with the name or binding '<name>'` — so a hand-run
264
+ `wrangler d1 migrations apply` needs the flag too.
265
+
261
266
  The contract fails closed:
262
267
 
263
268
  - Better Auth is required, and a logical `dev` target must exist (it is what
@@ -0,0 +1,112 @@
1
+ # Email (Inbound)
2
+
3
+ `defineEmail` is the inbound-mail mirror of [`defineSchedule`](/platform/schedules). Drop a file in `services/email/` and the compiler emits a shared `deliverInboundEmail()` dispatcher. **Execute is provider-agnostic** — you parse RFC 822 bytes and write the store. Ingress is an adapter:
4
+
5
+ | Provider | Ingress | How it reaches `execute` |
6
+ |----------|---------|--------------------------|
7
+ | Cloudflare (`email.provider: 'cloudflare'`, default) | Email Routing → Worker `email()` | Compiler emits `email` on the Worker export. Buffers `message.raw` once, then calls `deliverInboundEmail`. |
8
+ | Amazon SES (`email.provider: 'aws-ses'`) | Receipt rule → S3 + SNS | Build the same `InboundEmailMessage` (`provider: 'ses'`, `raw` = the `.eml` bytes) and call `deliverInboundEmail(message, env)`. |
9
+
10
+ Outbound sending is a separate surface (`email.provider` already switches Cloudflare `send_email` vs AWS SES) — see [Email Configuration](/configure#email-configuration).
11
+
12
+ ## Define a handler
13
+
14
+ ```typescript
15
+ // services/email/inbound.ts
16
+ import { defineEmail } from "quickback";
17
+ import { ingestMessage } from "../../features/mail/lib/ingest";
18
+
19
+ export default defineEmail({
20
+ name: "inbound", // identifier + audit actor (system:email-<name>)
21
+ to: "paul@kardoe.com", // optional; omit to match every recipient
22
+ description: "Ingest inbound mail",
23
+ execute: async ({ message, db, env, services }) => {
24
+ // message.raw is already-buffered RFC 822 bytes (not a stream).
25
+ await ingestMessage(db, env, services, message.raw);
26
+ },
27
+ });
28
+ ```
29
+
30
+ One file per handler under `services/email/*.ts`. Files prefixed with `_` are ignored. `name` must be a valid camelCase identifier (it's used as a generated symbol and the audit actor). The same file is what runs on Cloudflare and on SES — do not import `ForwardableEmailMessage` or SES receipt types in `execute`.
31
+
32
+ ## Envelope matching
33
+
34
+ | `to` | Behavior |
35
+ |------|----------|
36
+ | omitted | Handler runs for every inbound message |
37
+ | `"user@example.com"` | Exact, case-insensitive match against `message.to` |
38
+
39
+ Multiple handlers can match the same message (a catch-all plus an address-specific handler). Failures are isolated so one throwing handler does not abort the others.
40
+
41
+ If **no** handler matches, the runner logs a warning and returns. It does **not** call Cloudflare `setReject()` — Email Routing can still fall through, and SES has already accepted the message.
42
+
43
+ ## Importing feature code
44
+
45
+ Email files live at `quickback/services/email/<name>.ts`, so imports are relative to **that** location. To reach a feature table, a feature `lib/` helper, or `db/`, climb up to the `quickback/` root first (`../../`):
46
+
47
+ ```typescript
48
+ // quickback/services/email/inbound.ts
49
+ import { messages } from "../../features/mail/messages";
50
+ import { ingestMessage } from "../../features/mail/lib/ingest";
51
+ import { parseRfc822 } from "../../lib/rfc822";
52
+ ```
53
+
54
+ Two `../` — up from `services/email/` to `quickback/`, then down into `features/` (or `lib/`, `db/`). The compiler relocates the handler into the generated `src/lib/email.ts` and **rewrites these paths to resolve from there automatically** — you always write them relative to your own source file, exactly as your editor resolves them.
55
+
56
+ > A single `../features/…` is the common mistake — from `services/email/` that resolves to `services/features/…`, which doesn't exist. Use `../../features/…`.
57
+
58
+
59
+ ## What the compiler emits
60
+
61
+ 1. **`deliverInboundEmail(message, env)`** in `src/lib/email.ts` — the shared dispatcher.
62
+ 2. **`email(cfMessage, env, ctx)`** on the Worker default export — Cloudflare adapter. Regenerated on every `quickback compile`.
63
+ 3. **No wrangler inbound binding.** Cloudflare: configure Email Routing in the dashboard. SES: Receipt rule + S3 + SNS; call `deliverInboundEmail` with the fetched `.eml`.
64
+ 4. The existing outbound `[[send_email]]` binding (Cloudflare) / SES plugin (aws-ses) is unchanged.
65
+
66
+ ## Execute context
67
+
68
+ | Field | Type | Notes |
69
+ |-------|------|-------|
70
+ | `message` | `InboundEmailMessage` | `{ provider, from, to, headers, raw }`. `raw` is `ArrayBuffer`. |
71
+ | `message.provider` | `'cloudflare' \| 'ses'` | Ingress tag for logs. Parse `raw`, don't branch on this. |
72
+ | `db` | Drizzle instance | The same DB the queue/schedule handlers get |
73
+ | `env` | `CloudflareBindings` | All worker bindings |
74
+ | `services` | `Services` | The services layer (`createServices(env)`) |
75
+ | `withInternalContext` | helper | Opt into the `INTERNAL` trust zone for `roles: ['INTERNAL']`-gated rows |
76
+
77
+ Cloudflare-only methods (`setReject`, `forward`, `reply`) are **not** on `InboundEmailMessage`. SES has already accepted the mail; Cloudflare fall-through is the adapter's job (it does not reject unmatched recipients).
78
+
79
+ ## Amazon SES inbound
80
+
81
+ SES cannot invoke a Worker `email()` export — receipt is S3 + SNS. After you verify the SNS signature and fetch the object:
82
+
83
+ ```typescript
84
+ import { deliverInboundEmail } from "../lib/email";
85
+
86
+ await deliverInboundEmail({
87
+ provider: "ses",
88
+ from: receipt.mail.source,
89
+ to: receipt.receipt.recipients[0],
90
+ headers: new Headers(/* from the .eml or commonHeaders */),
91
+ raw: await s3.getObject(bucket, key).arrayBuffer(),
92
+ }, env);
93
+ ```
94
+
95
+ `execute` does not change. MX, Receipt rules, the S3 bucket, and the SNS subscription stay in AWS — the compiler does not emit those.
96
+
97
+ ## Audit & trust
98
+
99
+ Inbound email runs are **server-internal**: there's no authenticated user, no request, no org scope. A delivered message gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:
100
+
101
+ ```typescript
102
+ execute: async ({ db, withInternalContext, message }) => {
103
+ // `db` here is unscoped — no firewall WHERE, no audit actor.
104
+
105
+ await withInternalContext(async ({ ctx, db, services }) => {
106
+ // ctx.internal = true, ctx.userId = "system:email-<name>"
107
+ // audited writes are attributable to e.g. system:email-inbound
108
+ });
109
+ },
110
+ ```
111
+
112
+ `withInternalContext` builds a context with `internal: true` and `userId: "system:email-<name>"`, so audited writes made through it are attributable to the handler and can reach `roles: ['INTERNAL']`-gated rows.
@@ -11,6 +11,7 @@
11
11
  | [Realtime](/platform/realtime) | Durable Objects | WebSocket for live updates |
12
12
  | [Queues](/platform/queues) | Cloudflare Queues | Background jobs, webhook delivery |
13
13
  | [Schedules](/platform/schedules) | Cron Triggers | `defineSchedule` cron jobs, server-internal |
14
+ | [Email](/platform/email) | Email Workers | `defineEmail` inbound handlers, server-internal |
14
15
  | [Vector & AI](/platform/vector) | Workers AI | Embeddings, semantic search |
15
16
  | [Webhooks](/platform/webhooks) | Hono + Queues | Signed inbound, retried outbound |
16
17
  | [Push](/platform/push) | Web Push | VAPID subscriptions, typed payloads |
@@ -90,6 +90,23 @@ export default feature("applications", {
90
90
  > `access.roles` — it still compiles but should be migrated.)
91
91
 
92
92
 
93
+ Omitting it fails the compile:
94
+
95
+ ```text
96
+ Resource "conversations" enables realtime broadcasts but declares no audience.
97
+ A broadcast fans out to every subscriber in the room, so the audience is not
98
+ optional. Declare realtime.access: { roles: [...] } naming who may receive it
99
+ (use roles: ['PUBLIC'] to broadcast to everyone in the room, deliberately).
100
+ ```
101
+
102
+ **The audience is a second read surface, and it does not inherit `read.access`.**
103
+ Whatever gates the REST read must gate the broadcast too, or the live channel
104
+ publishes rows the REST route would have withheld — private messages being the
105
+ usual casualty. Copy the read rule across, and where the read is gated by a
106
+ relationship (participants of a conversation, accepted followers), use
107
+ `access: { authzRole: "<relationship-role>" }` here rather than falling back to
108
+ `roles: ["AUTHENTICATED"]`, which reaches every signed-in subscriber.
109
+
93
110
  And enable the realtime **transport** in your database config. This is a
94
111
  project-level switch that stands up the Broadcaster Durable Object + the
95
112
  connection route; it does **not** by itself make any resource broadcast
@@ -170,13 +170,38 @@ Endpoints are scoped by `userId` or `organizationId`. Users can only manage thei
170
170
 
171
171
  ### URL Validation (anti-SSRF)
172
172
 
173
- Registered URLs are validated at registration and again before each delivery attempt. The default policy rejects:
173
+ The destination policy lives in `src/lib/webhooks/url-policy.ts` and runs at **four** points: on register, on update, and again immediately before **each** test send and **each** queued delivery attempt. Re-checking before every send is the point — a name that was public when it was registered can be re-pointed afterwards.
174
+
175
+ The default policy rejects:
174
176
 
175
177
  - Any scheme other than `https:` (matches Stripe, GitHub, and Slack webhook conventions)
176
- - Loopback hosts (`localhost`, `127.0.0.1`, `::1`)
177
- - Cloud metadata endpoints (`169.254.169.254`, `metadata.google.internal`)
178
- - RFC 1918 private ranges (`10/8`, `172.16/12`, `192.168/16`), `169.254/16`, and `0.0.0.0/8`
179
- - Hosts ending in `.internal` or `.local`
178
+ - URLs carrying credentials (`https://user:pass@host/`)
179
+ - Loopback, private, and reserved **IPv4** literals: `0/8`, `10/8`, `100.64/10` (CGNAT), `127/8`, `169.254/16` (link-local + cloud metadata), `172.16/12`, `192.0.0/24`, `192.0.2/24`, `192.88.99/24`, `192.168/16`, `198.18/15`, `198.51.100/24`, `203.0.113/24`, `224/4` (multicast), `240/4` (reserved), and the broadcast address — in any notation the URL parser accepts, including octal and decimal
180
+ - The equivalent **IPv6** literals: `::`, `::1`, unique-local `fc00::/7`, link-local `fe80::/10`, site-local `fec0::/10`, multicast `ff00::/8`, documentation `2001:db8::/32` and `3fff::/20`, `2001::/23` (Teredo), `2002::/16` (6to4), `64:ff9b::/96` (NAT64), `100::/64`, and IPv4-mapped forms such as `[::ffff:127.0.0.1]`
181
+ - Internal names: `localhost`, `metadata.goog`, anything ending in `.localhost`, `.local`, `.internal`, or `.home.arpa`, and any single-label host (`http://intranet/`)
182
+
183
+ > **Host names are resolved, not just pattern-matched.** For any name that survives the checks above, the runtime resolves both **A and AAAA** records and rejects the destination if **any** answer is a non-public address. One private record among several public ones is enough to refuse the whole name — that is the case a literal-only check misses.
184
+
185
+
186
+ Resolution is fail-closed. If the resolver errors, times out, returns a malformed answer, or is unavailable, the destination is **not** contacted:
187
+
188
+ | Outcome | Register / update | Queued delivery |
189
+ |---------|-------------------|-----------------|
190
+ | All answers public | Accepted | Delivered |
191
+ | Any answer non-public | `400` | Terminal failure, no retry |
192
+ | No A/AAAA records (NXDOMAIN) | `400` | Terminal failure, no retry |
193
+ | Resolver error, timeout, or malformed answer | `503` | Failed **attempt**, retried with backoff |
194
+ | Answer larger than 32 records | `503` | Failed **attempt**, retried with backoff |
195
+
196
+ DNS is always resolved through a fixed trusted resolver — an endpoint never gets to nominate who answers for it. An answer of more than 32 records is refused rather than truncated: silently cutting the list would let a zone owner pad it with public records and hide a private one past the cut.
197
+
198
+ > **A resolver outage fails deliveries permanently, and it fails them all at once.** The three retries above elapse in seconds, so a DNS outage lasting longer than that exhausts them and marks every in-flight delivery `failed` — across every endpoint and every project on the same resolver. There is no outbound replay endpoint (`/webhooks/v1/inbound/events/:id/retry` covers inbound events only), so those deliveries are not recoverable; the source event has to be re-emitted.
199
+ >
200
+ > This is the deliberate cost of fail-closed: the runtime will not contact a destination it could not verify. It also means outbound webhook failures are **correlated** — a shared dependency, not independent per-endpoint faults. Alert on a spike in `failed` deliveries rather than on any single endpoint.
201
+
202
+
203
+ > **This validates the DNS answer, not the socket.** It is not connection pinning, so a deployment that attaches private egress (a VPC, a tunnel, a service binding) must **also** enforce a network-layer egress policy. Application-level DNS validation cannot close the gap between the answer it checked and the address the runtime later connects to.
204
+
180
205
 
181
206
  Plaintext `http:` is rejected by default. To allow `http:` (e.g. for a self-hosted dev environment without TLS), set `webhookAllowInsecure: true` on the database provider config:
182
207
 
@@ -193,7 +218,7 @@ providers: {
193
218
  }
194
219
  ```
195
220
 
196
- The other validation rules (private/loopback/metadata blocking) still apply when this flag is on.
221
+ `webhookAllowInsecure` relaxes the **scheme and nothing else**. Every address rule above — including DNS resolution and the fail-closed behaviour — still applies when the flag is on. There is no configuration that permits a private destination.
197
222
 
198
223
  ### Redirect Handling
199
224
 
@@ -69,7 +69,12 @@ Blocked, fail-closed at the compile phase — the deploy stops with the reason,
69
69
 
70
70
  ## Connecting your Cloudflare account
71
71
 
72
- The first deploy starts with **Continue with Cloudflare** — a standard OAuth consent against Cloudflare's own dashboard, shown by the **Quickback** OAuth client. You pick the account, see exactly which permissions are requested, and can revoke at any time from Cloudflare under **My Profile → Access Management → Connected Applications** (or disconnect from Start).
72
+ Deploying takes two distinct grants, and the card labels them differently on purpose:
73
+
74
+ - **Continue with Cloudflare** signs you in to Quickback. Identity only — none of the deploy permissions below.
75
+ - **Grant deploy access** gives Quickback permission to deploy into your Cloudflare account — a standard OAuth consent against Cloudflare's own dashboard, shown by the **Quickback** OAuth client. You pick the account, see exactly which permissions are requested, and can revoke at any time from Cloudflare under **My Profile → Access Management → Connected Applications** (or disconnect from Start).
76
+
77
+ One click covers both: if you weren't signed in yet, sign-in chains straight into the deploy consent. First-time users see two Cloudflare screens back to back; after that, Cloudflare skips consent screens it has already approved, so re-authenticating is a ribbon of silent redirects.
73
78
 
74
79
  What's requested, and why:
75
80
 
@@ -85,7 +90,7 @@ What's requested, and why:
85
90
 
86
91
  Nothing broader is requested — no zone, DNS, billing, or account-management access.
87
92
 
88
- If you cancel at Cloudflare's consent screen — or Cloudflare ends the attempt for any other reason — you land back in Start with the card explaining what happened and a **Try Cloudflare again** button. Nothing is stored on a cancelled attempt, and a connection you already had is left untouched.
93
+ If you cancel at Cloudflare's consent screen — or Cloudflare ends the attempt for any other reason — you land back in Start with the card explaining what happened and a **Try again** button. Nothing is stored on a cancelled attempt, and a connection you already had is left untouched.
89
94
 
90
95
  ## Connection states and recovery
91
96
 
@@ -93,10 +98,10 @@ The deploy card is the whole connection UI: it reports the state of your Cloudfl
93
98
 
94
99
  | What you see | What happened | What to do |
95
100
  |---|---|---|
96
- | **Connect your Cloudflare account** | No connection stored | **Continue with Cloudflare** |
101
+ | "Grant Quickback permission to deploy…" | Signed in, but no deploy permission stored yet | **Grant deploy access** |
97
102
  | Masked email badge, green | Connected and healthy | Deploy |
98
- | "This connection expires in N minutes" | The access token is near the end of its life | Nothing yet — reconnect when it lapses |
99
- | Badge turns amber, "· reconnect" | Token expired, grant revoked in Cloudflare, or the connection was deleted | **Reconnect Cloudflare** — one consent, same connection record |
103
+ | Badge turns amber, "· reconnect" | Grant revoked in Cloudflare, or the connection was deleted (plain expiry never surfaces — tokens refresh server-side) | **Reconnect Cloudflare** — one consent, same connection record |
104
+ | "…also linked to a different Quickback login" | This Cloudflare account is connected under another Quickback account too — apps deployed there are listed there, not here | Nothing, unless an app you expected is missing: sign in with the Quickback account you deployed it from |
100
105
  | "This Cloudflare connection can't …" | The grant is missing a permission a deploy needs (an older connection, or a scope your OAuth client didn't allow) | **Reconnect Cloudflare** to grant the rest |
101
106
  | "This Cloudflare login isn't a member of any account" | The identity you connected belongs to no Cloudflare account | Create or join an account in the Cloudflare dashboard, then reconnect |
102
107
  | "Couldn't reach the deploy service…" | Transient failure talking to Quickback or Cloudflare | **Try again** |
@@ -114,6 +119,8 @@ Deploy is disabled while a reconnect is pending, so a deploy never starts on a c
114
119
 
115
120
  Connect a second Cloudflare login with **Connect another** and the card grows a login picker above the account picker. Start remembers which one you deployed with last and preselects it.
116
121
 
122
+ To make every Cloudflare login land on the **same** Quickback account (rather than each minting its own), link them under **Connected accounts** in the [Account UI](/ui/account) — after that, "Continue with Cloudflare" signs you in to that one account no matter which Cloudflare identity your dashboard is holding.
123
+
117
124
  ### Disconnecting vs. revoking
118
125
 
119
126
  Two different things, and you usually want both:
@@ -129,7 +136,9 @@ The OAuth token never reaches your browser, the chat model, or the compiler. It
129
136
  - bound to its connection record (the ciphertext is unusable if copied elsewhere);
130
137
  - decrypted only inside the API calls of an active deploy, then discarded.
131
138
 
132
- Tokens expire; when one does, Start shows a reconnect prompt and a fresh consent re-issues it onto the same connection. Revoking in Cloudflare kills the token immediately — the stored ciphertext becomes useless, and the card turns the next failed call into that same reconnect prompt. See [Connection states and recovery](#connection-states-and-recovery) for the full set.
139
+ The grant is standing permission carried by short-lived credentials. The token that can actually touch your account expires every hour; the deploy service refreshes it server-side, so expiry never reaches you as a prompt — a leaked working token goes stale within the hour either way. What persists is the sealed refresh token, which can only mint the next short-lived token.
140
+
141
+ Revoking in Cloudflare (**My Profile → Access Management → Connected Applications**) kills the whole chain immediately — the stored ciphertext becomes useless, and the card turns the next failed call into a reconnect prompt. See [Connection states and recovery](#connection-states-and-recovery) for the full set.
133
142
 
134
143
  ## Secrets on the deployed app
135
144
 
@@ -436,3 +436,19 @@ POST /candidates
436
436
  3. **All layers work together** - Firewall -> Access -> Guards -> Masking
437
437
  4. **Code is readable and auditable** - no magic, just TypeScript
438
438
  5. **Type-safe from definition to API** - Drizzle schema drives everything
439
+
440
+ ## Keep going in the same file
441
+
442
+ Everything above is one config object, and it takes more keys than security and
443
+ CRUD. Each adds a real endpoint on the same pipeline, so reach for these before
444
+ writing a custom action:
445
+
446
+ - [`transitions`](/define/transitions) — a guarded state change (`publish`,
447
+ `approve`, `checkIn`) generated as `POST /candidates/:id/{name}`
448
+ - [`realtime`](/platform/realtime/using-realtime) — broadcast inserts, updates,
449
+ and deletes to subscribed clients
450
+ - [`triggers`](/define/triggers) — run a data rule or side-effect on every write
451
+ - [`owns`](/define/changesets) — write a parent row and its children atomically
452
+
453
+ The `views` you already declared are the same idea: a whole endpoint from a few
454
+ lines. See [the full option list](/define#other-resource-options).