@open-workspace/email 0.3.0 → 0.4.0

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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
package/README.md CHANGED
@@ -2,32 +2,32 @@
2
2
 
3
3
  Team mail for [OpenWorkspace](https://openworkspace.dev): personal and shared
4
4
  inboxes, mailing lists, delivery status, attachment and Office previews, PDF
5
- translation, sender authentication and safety, AI filing, realtime updates,
6
- and web push.
7
-
8
- ```ts
9
- // src/worker.ts
10
- import { createWorkspace } from "@open-workspace/core";
11
- import { email } from "@open-workspace/email";
12
- export { MailboxDO, OfficePreviewContainer } from "@open-workspace/email";
13
-
14
- export default createWorkspace({ domains: ["acme.com"], modules: [email()] });
15
- ```
5
+ translation, sender checks, AI filing, realtime updates and web push.
16
6
 
17
7
  ```ts
18
8
  // alchemy.run.ts
19
- OpenWorkspace({ name: "acme-workspace", main: "./src/worker.ts", modules: [Email({ domains: ["acme.com"] })] })
9
+ OpenWorkspace({
10
+ hostname: "mail.acme.com",
11
+ mailDomains: ["acme.com"],
12
+ modules: [Email()],
13
+ });
20
14
  ```
21
15
 
22
- `Email({ domains })` adds an R2 bucket, a SQLite Durable Object per mailbox,
23
- the Office-to-PDF preview container, and its queues. For each listed domain it
24
- turns on Email Routing, sends every address to the Worker, onboards the domain
25
- to Email Sending, and subscribes delivery events. Leave `domains` out to set
26
- those up in the dashboard.
16
+ `Email()` turns on Email Routing and Email Sending for each of the workspace's
17
+ `mailDomains`. Email Routing adds the zone's MX and SPF records and locks them,
18
+ so a zone with another provider's MX records must have them removed first, or
19
+ the deploy fails.
20
+
21
+ It takes one option, `pushContact`: the `mailto:` or `https:` contact push
22
+ services see. Without it they see the app's URL.
23
+
24
+ The module adds two permissions administrators can give to members: "Block
25
+ senders" and "Import mail". It reads one optional secret, `SPAMHAUS_DQS_KEY`,
26
+ for Spamhaus blocklist checks.
27
27
 
28
- Web push keys are minted by Alchemy on the first deploy (`VapidKeys`); push
29
- services see the app's URL as the contact unless `pushContact` is set.
28
+ ## Documentation
30
29
 
31
- Optional secrets: `R2_ACCESS_KEY_ID` and `R2_SECRET_ACCESS_KEY` (an R2 API token
32
- for the mail bucket) for direct attachment transfers; `SPAMHAUS_DQS_KEY`.
33
- Uploads that are never sent expire from the bucket after seven days.
30
+ - [Using mail](https://openworkspace.dev/docs/mail)
31
+ - [Migrating mail and people](https://openworkspace.dev/docs/migration)
32
+ - [MCP and JMAP](https://openworkspace.dev/docs/mcp-and-jmap)
33
+ - [Development](https://openworkspace.dev/docs/development)
@@ -0,0 +1,273 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
4
+
5
+ import * as Cloudflare from "@alchemy.run/cloudflare";
6
+ import { VapidKeys } from "@open-workspace/core/alchemy";
7
+ import type { WorkspaceModuleInfra } from "@open-workspace/core/alchemy";
8
+ import { AlchemyContext } from "alchemy/AlchemyContext";
9
+ import { Random } from "alchemy/Random";
10
+ import * as Effect from "effect/Effect";
11
+ import * as Option from "effect/Option";
12
+ import { z } from "zod";
13
+
14
+ import {
15
+ EMAIL_MODULE,
16
+ emailClasses,
17
+ emailQueueRoles,
18
+ JMAP_PATH,
19
+ } from "../shared/module.ts";
20
+ import { pdfjsAssetFolders, pdfjsAssetPath } from "../shared/pdfjs-assets.ts";
21
+
22
+ /** The package root, one up from alchemy/. */
23
+ const packageDir = resolve(import.meta.dirname, "..");
24
+
25
+ /** gotenberg/gotenberg:8.37.0, the multi-platform index. */
26
+ const officePreviewImage =
27
+ "docker.io/gotenberg/gotenberg@sha256:f29984bd1e226bf1b93ba90af06000afa8b315853e99d27b9aaa41b93f15c769";
28
+
29
+ const PackageManifest = z.object({ version: z.string().min(1) });
30
+
31
+ /** The PDF.js resources the viewer requests by filename, copied into the browser app. */
32
+ function pdfjsAssets() {
33
+ const pdfjsDir = dirname(
34
+ createRequire(import.meta.url).resolve("pdfjs-dist/package.json")
35
+ );
36
+
37
+ const { version } = PackageManifest.parse(
38
+ JSON.parse(readFileSync(join(pdfjsDir, "package.json"), "utf-8"))
39
+ );
40
+
41
+ return Object.values(pdfjsAssetFolders).map((folder) => ({
42
+ from: join(pdfjsDir, folder),
43
+ to: pdfjsAssetPath(version, folder),
44
+ }));
45
+ }
46
+
47
+ /** Email Sending events that update delivery status in the app. */
48
+ const deliveryEvents = [
49
+ "message.delivered",
50
+ "message.bounced",
51
+ "message.deferred",
52
+ "message.complained",
53
+ "message.failed",
54
+ "message.rejected",
55
+ ];
56
+
57
+ export type EmailInfraProps = {
58
+ /** Contact for push services (mailto: or https:); defaults to the app's URL. */
59
+ pushContact?: string;
60
+ };
61
+
62
+ /** Optional secrets the module reads, bound when set in the environment or `.env`. */
63
+ const emailSecrets = [
64
+ // Spamhaus Data Query Service key, for blocklist checks.
65
+ "SPAMHAUS_DQS_KEY",
66
+ ] as const;
67
+
68
+ function emailResources() {
69
+ return {
70
+ officePreviews: Cloudflare.Queues.Queue("OfficePreviews", {}),
71
+ pushNotifications: Cloudflare.Queues.Queue("PushNotifications", {}),
72
+ deliveryEvents: Cloudflare.Queues.Queue("DeliveryEvents", {}),
73
+ };
74
+ }
75
+
76
+ /**
77
+ * The mail bucket. Browsers upload attachments to it and download them from
78
+ * it with presigned URLs, so its CORS lets the app's origin PUT, GET and
79
+ * HEAD. Under `alchemy dev` the app and the local S3 endpoint share an
80
+ * origin, so the local bucket needs none.
81
+ */
82
+ const mailStorage = (origin: string, dev: boolean) => {
83
+ const props: Cloudflare.R2.BucketProps = {
84
+ // Uploads that were never sent.
85
+ lifecycleRules: [
86
+ {
87
+ id: "expire-composer-uploads",
88
+ prefix: "composer-uploads/",
89
+ deleteObjectsTransition: {
90
+ condition: { type: "Age", maxAge: 7 * 24 * 60 * 60 },
91
+ },
92
+ },
93
+ ],
94
+ };
95
+
96
+ if (!dev) {
97
+ props.cors = [
98
+ {
99
+ id: "direct-transfers",
100
+ allowedOrigins: [origin],
101
+ allowedMethods: ["GET", "PUT", "HEAD"],
102
+ allowedHeaders: ["Content-Type"],
103
+ maxAgeSeconds: 3600,
104
+ },
105
+ ];
106
+ }
107
+
108
+ return Cloudflare.R2.Bucket("MailStorage", props);
109
+ };
110
+
111
+ /** The contact push services see, bound only when configured. */
112
+ type PushSubjectEnv = { VAPID_SUBJECT?: string };
113
+
114
+ /** The module's Worker bindings; the Worker's `Env` is derived from them (`EmailEnv`). */
115
+ const emailEnv = (
116
+ props: EmailInfraProps,
117
+ resources: ReturnType<typeof emailResources>,
118
+ origin: string
119
+ ) =>
120
+ Effect.gen(function* () {
121
+ const alchemy = yield* Effect.serviceOption(AlchemyContext);
122
+ const dev = Option.isSome(alchemy) && alchemy.value.dev;
123
+ const vapid = yield* VapidKeys("VapidKeys", {});
124
+ // Signs the remote image proxy's tokens; minted once, kept in state.
125
+ const remoteKey = yield* Random("MailRemoteKey", { bytes: 32 });
126
+ const bucket = mailStorage(origin, dev);
127
+ // Push services see the configured contact; without one the Worker
128
+ // falls back to the app's URL, so the binding is left out.
129
+ const pushSubject: PushSubjectEnv = {};
130
+
131
+ if (props.pushContact) pushSubject.VAPID_SUBJECT = props.pushContact;
132
+
133
+ return {
134
+ /**
135
+ * S3 credentials for the mail bucket alone, as JSON, for presigned
136
+ * attachment transfers: from an API token Alchemy mints when
137
+ * deployed, the local S3 endpoint under `alchemy dev`.
138
+ */
139
+ MAIL_S3: Cloudflare.R2.S3Credentials(bucket, { access: "read-write" }),
140
+ /** Web Push keys Alchemy mints, and the contact push services see. */
141
+ VAPID_PUBLIC_KEY: vapid.publicKey,
142
+ VAPID_PRIVATE_KEY: vapid.privateKey,
143
+ ...pushSubject,
144
+ MAIL_STORAGE: bucket,
145
+ /** Signs the remote image proxy's tokens (mail/remote-token.ts). */
146
+ MAIL_REMOTE_KEY: remoteKey.text,
147
+ EMAIL: Cloudflare.Email.SendEmail("EMAIL"),
148
+ MAILBOX: Cloudflare.DurableObject("MAILBOX", {
149
+ className: emailClasses.MAILBOX,
150
+ }),
151
+ // Gotenberg straight from Docker Hub, pinned by digest. Cloudflare
152
+ // pulls it itself, so a deploy needs no local Docker. Only local
153
+ // Office uploads are converted: documents can't reach the network.
154
+ OFFICE_PREVIEW_CONTAINER: Cloudflare.Container("OfficePreview", {
155
+ className: emailClasses.OFFICE_PREVIEW_CONTAINER,
156
+ image: officePreviewImage,
157
+ registryId: "docker.io",
158
+ env: {
159
+ CHROMIUM_DISABLE_ROUTES: "true",
160
+ API_DISABLE_DOWNLOAD_FROM: "true",
161
+ WEBHOOK_DISABLE: "true",
162
+ LIBREOFFICE_DENY_LIST: ".*",
163
+ API_TIMEOUT: "90s",
164
+ },
165
+ maxInstances: 2,
166
+ }),
167
+ OFFICE_PREVIEWS: resources.officePreviews,
168
+ PUSH_NOTIFICATIONS: resources.pushNotifications,
169
+ };
170
+ });
171
+
172
+ /**
173
+ * The bindings `Email()` adds, as the Worker sees them: the module's part of
174
+ * `Env` (worker/bindings.d.ts).
175
+ */
176
+ export type EmailEnv = Cloudflare.InferEnv<
177
+ Effect.Success<ReturnType<typeof emailEnv>>
178
+ > &
179
+ Partial<Record<(typeof emailSecrets)[number], string>>;
180
+
181
+ /**
182
+ * The mail module's Cloudflare resources: the mail bucket, a SQLite Durable
183
+ * Object per mailbox, the Office preview container, its queues, and the
184
+ * outbound mail binding. For each of the workspace's `mailDomains` (each a zone
185
+ * in the account) it turns on Email Routing, which adds and locks the zone's
186
+ * MX and SPF records, sends every address to the Worker, onboards the domain
187
+ * to Email Sending, and queues its delivery events.
188
+ */
189
+ export function Email(props: EmailInfraProps = {}): WorkspaceModuleInfra {
190
+ const resources = emailResources();
191
+
192
+ const {
193
+ officePreviews,
194
+ pushNotifications,
195
+ deliveryEvents: deliveryEventsQueue,
196
+ } = resources;
197
+
198
+ return {
199
+ name: EMAIL_MODULE,
200
+ // index.ts default-exports `email()`, and exports the classes MAILBOX and OFFICE_PREVIEW_CONTAINER name.
201
+ server: {
202
+ entry: join(packageDir, "index.ts"),
203
+ classes: Object.values(emailClasses),
204
+ },
205
+ routes: [JMAP_PATH],
206
+ migrations: join(packageDir, "migrations"),
207
+ client: {
208
+ entry: join(packageDir, "src", "client.tsx"),
209
+ assets: pdfjsAssets(),
210
+ },
211
+ secrets: [...emailSecrets],
212
+ env: ({ origin }) => emailEnv(props, resources, origin),
213
+ consumers: [
214
+ // Each preview converts in a container; two at a time.
215
+ {
216
+ id: "OfficePreviewsConsumer",
217
+ role: emailQueueRoles.officePreviews,
218
+ queue: officePreviews,
219
+ settings: {
220
+ batchSize: 1,
221
+ maxConcurrency: 2,
222
+ maxRetries: 5,
223
+ maxWaitTimeMs: 1000,
224
+ },
225
+ },
226
+ {
227
+ id: "PushNotificationsConsumer",
228
+ role: emailQueueRoles.pushNotifications,
229
+ queue: pushNotifications,
230
+ settings: { batchSize: 10, maxRetries: 5, maxWaitTimeMs: 2000 },
231
+ },
232
+ {
233
+ id: "DeliveryEventsConsumer",
234
+ role: emailQueueRoles.deliveryEvents,
235
+ queue: deliveryEventsQueue,
236
+ settings: { batchSize: 10, maxRetries: 5, maxWaitTimeMs: 5000 },
237
+ },
238
+ ],
239
+ afterWorker: ({ workerName, config }) =>
240
+ Effect.gen(function* () {
241
+ // Email Routing, Email Sending and event subscriptions have no local
242
+ // emulation, so under `alchemy dev` (the dev, stack-test and e2e
243
+ // stacks) they would act on the real zones. Locally, sent mail goes
244
+ // to the EMAIL binding's local runtime instead.
245
+ const alchemy = yield* Effect.serviceOption(AlchemyContext);
246
+
247
+ if (Option.isSome(alchemy) && alchemy.value.dev) return;
248
+ const { queueId: deliveryQueueId } = yield* deliveryEventsQueue;
249
+
250
+ for (const domain of config.mailDomains) {
251
+ const id = domain.replaceAll(".", "-");
252
+
253
+ const routing = yield* Cloudflare.Email.Routing(`Routing-${id}`, {
254
+ zone: domain,
255
+ });
256
+
257
+ yield* Cloudflare.Email.CatchAll(`CatchAll-${id}`, {
258
+ zone: routing.zoneId,
259
+ actions: [{ type: "worker", value: [workerName] }],
260
+ });
261
+ yield* Cloudflare.Email.SendingSubdomain(`Sending-${id}`, {
262
+ zoneId: routing.zoneId,
263
+ name: domain,
264
+ });
265
+ yield* Cloudflare.Queues.Subscription(`DeliveryEvents-${id}`, {
266
+ source: { type: "email.sending", zoneId: routing.zoneId, domain },
267
+ events: deliveryEvents,
268
+ queueId: deliveryQueueId,
269
+ });
270
+ }
271
+ }),
272
+ };
273
+ }
@@ -0,0 +1,149 @@
1
+ CREATE TABLE `conversations` (
2
+ `id` text PRIMARY KEY NOT NULL,
3
+ `latest_email_id` text NOT NULL,
4
+ `timeline_at` integer NOT NULL,
5
+ `mailbox_state` text DEFAULT 'active' NOT NULL,
6
+ `folder_id` text,
7
+ `has_incoming` integer DEFAULT false NOT NULL,
8
+ `has_outgoing` integer DEFAULT false NOT NULL,
9
+ FOREIGN KEY (`latest_email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE no action,
10
+ FOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON UPDATE no action ON DELETE set null
11
+ );
12
+ --> statement-breakpoint
13
+ CREATE INDEX `conversations_timeline_idx` ON `conversations` (`timeline_at`,`latest_email_id`);--> statement-breakpoint
14
+ CREATE INDEX `conversations_inbox_timeline_idx` ON `conversations` (`mailbox_state`,`has_incoming`,`timeline_at`,`latest_email_id`);--> statement-breakpoint
15
+ CREATE INDEX `conversations_sent_timeline_idx` ON `conversations` (`mailbox_state`,`has_outgoing`,`timeline_at`,`latest_email_id`);--> statement-breakpoint
16
+ CREATE INDEX `conversations_folder_timeline_idx` ON `conversations` (`folder_id`,`timeline_at`,`latest_email_id`);--> statement-breakpoint
17
+ CREATE TABLE `email_read_states` (
18
+ `user_id` text NOT NULL,
19
+ `email_id` text NOT NULL,
20
+ `read_at` integer NOT NULL,
21
+ PRIMARY KEY(`user_id`, `email_id`),
22
+ FOREIGN KEY (`email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE cascade
23
+ );
24
+ --> statement-breakpoint
25
+ CREATE INDEX `email_read_states_email_idx` ON `email_read_states` (`email_id`);--> statement-breakpoint
26
+ CREATE TABLE `emails` (
27
+ `id` text PRIMARY KEY NOT NULL,
28
+ `request_fingerprint` text,
29
+ `conversation_id` text NOT NULL,
30
+ `direction` text NOT NULL,
31
+ `message_id_header` text,
32
+ `in_reply_to_json` text DEFAULT '[]' NOT NULL,
33
+ `references_json` text DEFAULT '[]' NOT NULL,
34
+ `from_json` text NOT NULL,
35
+ `reply_to_json` text DEFAULT '[]' NOT NULL,
36
+ `to_json` text DEFAULT '[]' NOT NULL,
37
+ `cc_json` text DEFAULT '[]' NOT NULL,
38
+ `bcc_json` text DEFAULT '[]' NOT NULL,
39
+ `subject` text DEFAULT '(no subject)' NOT NULL,
40
+ `preview` text DEFAULT '' NOT NULL,
41
+ `body_text` text,
42
+ `quoted_text` text,
43
+ `body_html_r2_key` text,
44
+ `raw_mime_r2_key` text,
45
+ `authentication_results_json` text,
46
+ `envelope_from` text,
47
+ `envelope_to` text,
48
+ `list_unsubscribe_json` text,
49
+ `sender_intel_json` text,
50
+ `ai_classification_json` text,
51
+ `delivery_json` text,
52
+ `screening_json` text,
53
+ `report_label` text,
54
+ `attachments_json` text DEFAULT '[]' NOT NULL,
55
+ `list_id` text,
56
+ `list_post_address` text,
57
+ `timeline_at` integer NOT NULL,
58
+ `transport_state` text NOT NULL,
59
+ `transport_error` text,
60
+ `delivery_status_json` text DEFAULT '[]' NOT NULL
61
+ );
62
+ --> statement-breakpoint
63
+ CREATE INDEX `emails_conversation_timeline_idx` ON `emails` (`conversation_id`,`timeline_at`,`id`);--> statement-breakpoint
64
+ CREATE INDEX `emails_message_id_header_idx` ON `emails` (`message_id_header`);--> statement-breakpoint
65
+ CREATE TABLE `folders` (
66
+ `id` text PRIMARY KEY NOT NULL,
67
+ `name` text NOT NULL,
68
+ `sort_order` integer DEFAULT 100 NOT NULL
69
+ );
70
+ --> statement-breakpoint
71
+ CREATE UNIQUE INDEX `folders_name_unique` ON `folders` (`name`);--> statement-breakpoint
72
+ CREATE INDEX `folders_order_idx` ON `folders` (`sort_order`,`name`);--> statement-breakpoint
73
+ CREATE TABLE `mailbox_ai_configuration` (
74
+ `id` text PRIMARY KEY NOT NULL,
75
+ `instructions` text DEFAULT '' NOT NULL,
76
+ `confidence_threshold` integer DEFAULT 75 NOT NULL,
77
+ `updated_at` integer NOT NULL
78
+ );
79
+ --> statement-breakpoint
80
+ CREATE TABLE `pending_inbound` (
81
+ `id` text PRIMARY KEY NOT NULL,
82
+ `raw_object_key` text NOT NULL,
83
+ `envelope_from` text NOT NULL,
84
+ `envelope_to` text NOT NULL,
85
+ `list_address` text,
86
+ `received_at` integer NOT NULL,
87
+ `attempts` integer DEFAULT 0 NOT NULL,
88
+ `ai_attempts` integer DEFAULT 0 NOT NULL,
89
+ `next_attempt_at` integer NOT NULL
90
+ );
91
+ --> statement-breakpoint
92
+ CREATE INDEX `pending_inbound_next_attempt_idx` ON `pending_inbound` (`next_attempt_at`,`received_at`);--> statement-breakpoint
93
+ CREATE TABLE `pending_object_deletions` (
94
+ `object_key` text PRIMARY KEY NOT NULL,
95
+ `attempts` integer DEFAULT 0 NOT NULL,
96
+ `next_attempt_at` integer NOT NULL
97
+ );
98
+ --> statement-breakpoint
99
+ CREATE INDEX `pending_object_deletions_next_attempt_idx` ON `pending_object_deletions` (`next_attempt_at`);--> statement-breakpoint
100
+ CREATE TABLE `pending_office_previews` (
101
+ `source_key` text PRIMARY KEY NOT NULL,
102
+ `email_id` text NOT NULL,
103
+ `attachment_id` text NOT NULL,
104
+ `attempts` integer DEFAULT 0 NOT NULL,
105
+ `next_attempt_at` integer NOT NULL
106
+ );
107
+ --> statement-breakpoint
108
+ CREATE INDEX `pending_office_previews_next_attempt_idx` ON `pending_office_previews` (`next_attempt_at`);--> statement-breakpoint
109
+ CREATE TABLE `sender_feedback` (
110
+ `id` text PRIMARY KEY NOT NULL,
111
+ `address` text NOT NULL,
112
+ `domain` text NOT NULL,
113
+ `email_id` text,
114
+ `label` text NOT NULL,
115
+ `user_id` text,
116
+ `created_at` integer NOT NULL
117
+ );
118
+ --> statement-breakpoint
119
+ CREATE INDEX `sender_feedback_address_idx` ON `sender_feedback` (`address`,`created_at`);--> statement-breakpoint
120
+ CREATE INDEX `sender_feedback_domain_idx` ON `sender_feedback` (`domain`);--> statement-breakpoint
121
+ CREATE TABLE `senders` (
122
+ `address` text PRIMARY KEY NOT NULL,
123
+ `domain` text NOT NULL,
124
+ `first_seen_at` integer,
125
+ `last_seen_at` integer,
126
+ `message_count` integer DEFAULT 0 NOT NULL,
127
+ `outbound_count` integer DEFAULT 0 NOT NULL,
128
+ `last_outbound_at` integer,
129
+ `blocked_at` integer,
130
+ `trusted_at` integer,
131
+ `reported_at` integer
132
+ );
133
+ --> statement-breakpoint
134
+ CREATE INDEX `senders_domain_idx` ON `senders` (`domain`);--> statement-breakpoint
135
+ CREATE TABLE `system_folder_order` (
136
+ `folder_id` text PRIMARY KEY NOT NULL,
137
+ `sort_order` integer NOT NULL
138
+ );
139
+ --> statement-breakpoint
140
+ CREATE TABLE `unsubscriptions` (
141
+ `list_key` text PRIMARY KEY NOT NULL,
142
+ `email_id` text,
143
+ `method` text NOT NULL,
144
+ `status` text NOT NULL,
145
+ `target` text,
146
+ `detail` text,
147
+ `user_id` text,
148
+ `created_at` integer NOT NULL
149
+ );
@@ -0,0 +1,12 @@
1
+ -- The search index, which the drizzle schema cannot express. A custom
2
+ -- migration (drizzle-kit generate --custom): later generates leave it as it
3
+ -- is. The mailbox fills it in the transaction that inserts each email
4
+ -- (worker/mailbox/email-index.ts).
5
+ CREATE VIRTUAL TABLE `email_search` USING fts5(
6
+ `email_id` UNINDEXED,
7
+ `conversation_id` UNINDEXED,
8
+ `subject`,
9
+ `addresses`,
10
+ `body`,
11
+ tokenize = 'unicode61 remove_diacritics 2'
12
+ );