@open-workspace/email 0.4.2 → 0.5.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 (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,274 @@
1
+ import { createDb, normalizeMailboxAddress } from "@open-workspace/core/module";
2
+ import { mailboxes, users } from "@open-workspace/core/schema";
3
+ import { isAliasTarget } from "@open-workspace/core/shared";
4
+ import type { MailboxDelivery } from "@open-workspace/core/shared";
5
+ import { and, eq, inArray, or } from "drizzle-orm";
6
+
7
+ import { headerValues } from "../../shared/mail-headers";
8
+ import { parseInboundAuthentication } from "./auth-headers";
9
+ import { rawFromAddress, rawHeaderText } from "./inbound";
10
+ import { screenSender } from "./workspace-safety";
11
+
12
+ // Same header and limit as mailbox rules, so either kind of forward counts
13
+ // the other's hops.
14
+ export const MAX_FORWARD_HOPS = 3;
15
+
16
+ export const FORWARD_HOP_HEADER = "X-OpenWorkspace-Forwarded";
17
+
18
+ /**
19
+ * How many times this install already forwarded a message: the largest
20
+ * digits-only hop header. Other values ("-1000000") are ignored, never
21
+ * parsed, so a sender can't lift the limit.
22
+ */
23
+ export function forwardHops(raw: ArrayBuffer) {
24
+ return Math.max(
25
+ 0,
26
+ ...headerValues(rawHeaderText(raw), FORWARD_HOP_HEADER).flatMap((value) =>
27
+ /^\d{1,6}$/u.test(value) ? [Number(value)] : []
28
+ )
29
+ );
30
+ }
31
+
32
+ /** What resolving an address reads of a `mailboxes` row. */
33
+ export type AddressRow = {
34
+ id: string;
35
+ localPart: string;
36
+ catchAll: boolean;
37
+ delivery: MailboxDelivery;
38
+ aliasOf: string | null;
39
+ forwardTo: string[] | null;
40
+ };
41
+
42
+ /** `sam` for `sam+shop`; null without a tag. */
43
+ function plusBase(localPart: string) {
44
+ const plus = localPart.indexOf("+");
45
+
46
+ return plus > 0 ? localPart.slice(0, plus) : null;
47
+ }
48
+
49
+ /**
50
+ * Which of a domain's candidate rows takes mail for `localPart`: the exact
51
+ * address, else its plus base (`sam+shop` → `sam`), else the catch-all.
52
+ */
53
+ export function pickAddress<Row extends AddressRow>(
54
+ rows: readonly Row[],
55
+ localPart: string
56
+ ) {
57
+ const base = plusBase(localPart);
58
+
59
+ return (
60
+ rows.find((row) => row.localPart === localPart) ??
61
+ (base === null ? undefined : rows.find((row) => row.localPart === base)) ??
62
+ rows.find((row) => row.catchAll) ??
63
+ null
64
+ );
65
+ }
66
+
67
+ const routeColumns = {
68
+ id: mailboxes.id,
69
+ localPart: mailboxes.localPart,
70
+ domain: mailboxes.domain,
71
+ catchAll: mailboxes.catchAll,
72
+ teamId: mailboxes.teamId,
73
+ delivery: mailboxes.delivery,
74
+ listPosting: mailboxes.listPosting,
75
+ aliasOf: mailboxes.aliasOf,
76
+ forwardTo: mailboxes.forwardTo,
77
+ ownerUserId: mailboxes.ownerUserId,
78
+ };
79
+
80
+ type RouteRow = AddressRow & {
81
+ domain: string;
82
+ teamId: string | null;
83
+ listPosting: (typeof mailboxes.$inferSelect)["listPosting"];
84
+ };
85
+
86
+ export type InboundRoute =
87
+ | { kind: "mailbox"; mailbox: RouteRow }
88
+ | { kind: "forward"; id: string; forwardTo: string[] };
89
+
90
+ /**
91
+ * Where mail for a workspace address goes: the address itself, its plus
92
+ * base, or its domain's catch-all; an alias delivers into its mailbox. Null
93
+ * rejects it. One query, plus one for an alias's mailbox.
94
+ */
95
+ export async function resolveInboundRoute(db: D1Database, address: string) {
96
+ const recipient = normalizeMailboxAddress(address);
97
+ const at = recipient.lastIndexOf("@");
98
+ const localPart = recipient.slice(0, at);
99
+ const domain = recipient.slice(at + 1);
100
+ const base = plusBase(localPart);
101
+ const orm = createDb(db);
102
+
103
+ const rows = await orm
104
+ .select(routeColumns)
105
+ .from(mailboxes)
106
+ .where(
107
+ and(
108
+ eq(mailboxes.domain, domain),
109
+ or(
110
+ inArray(mailboxes.localPart, base ? [localPart, base] : [localPart]),
111
+ eq(mailboxes.catchAll, true)
112
+ )
113
+ )
114
+ );
115
+
116
+ const row = pickAddress(rows, localPart);
117
+
118
+ if (!row) return null;
119
+
120
+ if (row.delivery === "forward") {
121
+ // A disabled person's mail isn't sent on: the forward bounces as one
122
+ // without destinations does.
123
+ const [owner] = row.ownerUserId
124
+ ? await orm
125
+ .select({ status: users.status })
126
+ .from(users)
127
+ .where(eq(users.id, row.ownerUserId))
128
+ .limit(1)
129
+ : [];
130
+
131
+ return {
132
+ kind: "forward",
133
+ id: row.id,
134
+ forwardTo: owner?.status === "disabled" ? [] : (row.forwardTo ?? []),
135
+ } satisfies InboundRoute;
136
+ }
137
+
138
+ if (row.delivery !== "alias") {
139
+ return { kind: "mailbox", mailbox: row } satisfies InboundRoute;
140
+ }
141
+
142
+ if (!row.aliasOf) return null;
143
+
144
+ const [target] = await orm
145
+ .select(routeColumns)
146
+ .from(mailboxes)
147
+ .where(eq(mailboxes.id, row.aliasOf))
148
+ .limit(1);
149
+
150
+ return target && isAliasTarget(target.delivery)
151
+ ? ({ kind: "mailbox", mailbox: target } satisfies InboundRoute)
152
+ : null;
153
+ }
154
+
155
+ /**
156
+ * Why a message must not be forwarded, or null. Forwarding happens as mail
157
+ * arrives, before any mailbox's spam classifier runs, so it goes by what is
158
+ * known then: the hop limit, a sender blocked for the whole workspace, and
159
+ * mail that failed DMARC whose domain asks receivers to quarantine or reject
160
+ * it. Under `p=none` the domain asks for nothing, so the mail goes on and
161
+ * the destination's own filtering judges it, as with any other mail there.
162
+ * DMARC failures are refused, so the sender learns the mail didn't arrive;
163
+ * the rest is dropped, like spam that is never shown.
164
+ */
165
+ async function forwardRefusal(
166
+ db: D1Database,
167
+ message: { from: string },
168
+ raw: ArrayBuffer
169
+ ) {
170
+ if (forwardHops(raw) >= MAX_FORWARD_HOPS) {
171
+ return { reason: "forwarded too many times", bounce: false };
172
+ }
173
+
174
+ const headers = rawHeaderText(raw);
175
+ const from = await rawFromAddress(raw);
176
+
177
+ if (await screenSender(db, { from, envelopeFrom: message.from })) {
178
+ return { reason: "blocked sender", bounce: false };
179
+ }
180
+
181
+ const { dmarc } = parseInboundAuthentication({
182
+ raw: headers,
183
+ fromAddress: from,
184
+ envelopeFrom: message.from,
185
+ });
186
+
187
+ if (
188
+ dmarc?.result === "fail" &&
189
+ (dmarc.policy === "quarantine" || dmarc.policy === "reject")
190
+ ) {
191
+ return {
192
+ reason: `failed DMARC, and ${dmarc.headerFrom ?? "its domain"} asks to ${dmarc.policy} such mail`,
193
+ bounce: true,
194
+ };
195
+ }
196
+
197
+ return null;
198
+ }
199
+
200
+ /**
201
+ * Forwards a message unchanged through Email Routing, so the original
202
+ * sender stays and its DKIM signature still verifies: never to the sender
203
+ * itself, and each forward adds one to the hop header. Email Routing itself
204
+ * refuses a destination that hasn't confirmed Cloudflare's email, so this
205
+ * tries every destination and logs the ones it refused.
206
+ */
207
+ export async function forwardInbound(input: {
208
+ env: Env;
209
+ message: ForwardableEmailMessage;
210
+ raw: ArrayBuffer;
211
+ forwardTo: string[];
212
+ /** Archives the mail once at least one forward went out; never throws. */
213
+ archive: () => Promise<void>;
214
+ }) {
215
+ const { env, message, raw } = input;
216
+ const recipient = normalizeMailboxAddress(message.to);
217
+ const refusal = await forwardRefusal(env.DB, message, raw);
218
+
219
+ if (refusal?.bounce) {
220
+ message.setReject(`Not forwarded: the message ${refusal.reason}`);
221
+
222
+ return;
223
+ }
224
+
225
+ // Accepted and dropped, like spam that is never shown: the sender learns
226
+ // nothing about the address or its block.
227
+ if (refusal) {
228
+ console.warn(`Not forwarding mail for ${recipient}: ${refusal.reason}`);
229
+
230
+ return;
231
+ }
232
+
233
+ const sender = normalizeMailboxAddress(message.from);
234
+
235
+ const destinations = input.forwardTo.filter(
236
+ (destination) => normalizeMailboxAddress(destination) !== sender
237
+ );
238
+
239
+ if (!destinations.length) {
240
+ message.setReject(`${recipient} has no other address to forward to`);
241
+
242
+ return;
243
+ }
244
+
245
+ const hops = String(forwardHops(raw) + 1);
246
+
247
+ const results = await Promise.allSettled(
248
+ destinations.map((destination) =>
249
+ message.forward(destination, new Headers({ [FORWARD_HOP_HEADER]: hops }))
250
+ )
251
+ );
252
+
253
+ for (const [index, result] of results.entries()) {
254
+ if (result.status === "rejected") {
255
+ console.error(
256
+ `Could not forward mail for ${recipient} to ${destinations[index]}`,
257
+ result.reason
258
+ );
259
+ }
260
+ }
261
+
262
+ // Only mail that went out is archived: refused mail, and mail whose every
263
+ // forward failed (the sender gets a bounce), isn't kept.
264
+ if (results.some((result) => result.status === "fulfilled")) {
265
+ await input.archive();
266
+ }
267
+
268
+ // When every forward failed (none confirmed, say), throwing doesn't make
269
+ // the sending server try again: Cloudflare answers it 521 5.3.0, and the
270
+ // sender gets a bounce.
271
+ if (results.every((result) => result.status === "rejected")) {
272
+ throw new Error(`Forwarding mail for ${recipient} failed`);
273
+ }
274
+ }
@@ -0,0 +1,230 @@
1
+ import { z } from "zod";
2
+
3
+ import {
4
+ ruleActionConflict,
5
+ ruleActionSchema,
6
+ } from "../../shared/mail-rule-actions";
7
+ import type { Email } from "../mailbox/schema";
8
+
9
+ /**
10
+ * Mailbox rules: deterministic conditions and actions run on live
11
+ * deliveries. Conditions only read fields stored with every message, so
12
+ * "test on recent mail" evaluates exactly what delivery evaluates.
13
+ */
14
+
15
+ const text = z.string().trim().min(1).max(320);
16
+
17
+ export const ruleConditionSchema = z.discriminatedUnion("type", [
18
+ z.object({
19
+ type: z.literal("from"),
20
+ op: z.enum(["contains", "equals", "domain"]),
21
+ value: text,
22
+ }),
23
+ z.object({
24
+ type: z.literal("recipient"),
25
+ op: z.enum(["contains", "equals"]),
26
+ value: text,
27
+ }),
28
+ z.object({
29
+ type: z.literal("subject"),
30
+ op: z.enum(["contains", "equals"]),
31
+ value: text,
32
+ }),
33
+ z.discriminatedUnion("op", [
34
+ z.object({ type: z.literal("listId"), op: z.literal("exists") }),
35
+ z.object({
36
+ type: z.literal("listId"),
37
+ op: z.literal("contains"),
38
+ value: text,
39
+ }),
40
+ ]),
41
+ z.object({ type: z.literal("hasAttachment") }),
42
+ ]);
43
+
44
+ export const ruleInputSchema = z.object({
45
+ name: z.string().trim().min(1).max(120),
46
+ enabled: z.boolean().default(true),
47
+ match: z.enum(["all", "any"]).default("all"),
48
+ conditions: z.array(ruleConditionSchema).min(1).max(10),
49
+ actions: z
50
+ .array(ruleActionSchema)
51
+ .min(1)
52
+ .max(10)
53
+ .superRefine((actions, context) => {
54
+ actions.forEach((action, index) => {
55
+ const message = ruleActionConflict(
56
+ action.type,
57
+ actions.slice(0, index)
58
+ );
59
+
60
+ if (message) {
61
+ context.addIssue({ code: "custom", path: [index], message });
62
+ }
63
+ });
64
+ }),
65
+ stopProcessing: z.boolean().default(false),
66
+ });
67
+
68
+ export const ruleTestSchema = ruleInputSchema.pick({
69
+ match: true,
70
+ conditions: true,
71
+ });
72
+
73
+ export type RuleCondition = z.infer<typeof ruleConditionSchema>;
74
+
75
+ export { ruleActionSchema };
76
+
77
+ export type { RuleAction } from "../../shared/mail-rule-actions";
78
+
79
+ export type RuleInput = z.infer<typeof ruleInputSchema>;
80
+
81
+ export type RuleSubject = Pick<
82
+ Email,
83
+ | "fromJson"
84
+ | "toJson"
85
+ | "ccJson"
86
+ | "envelopeTo"
87
+ | "subject"
88
+ | "listId"
89
+ | "attachmentsJson"
90
+ >;
91
+
92
+ const lower = (value: string) => value.toLocaleLowerCase("en-US");
93
+
94
+ function textMatches(
95
+ op: "contains" | "equals",
96
+ actual: string,
97
+ expected: string
98
+ ) {
99
+ return op === "equals"
100
+ ? lower(actual) === lower(expected)
101
+ : lower(actual).includes(lower(expected));
102
+ }
103
+
104
+ export function conditionMatches(condition: RuleCondition, email: RuleSubject) {
105
+ switch (condition.type) {
106
+ case "from": {
107
+ const senders = email.fromJson.map((item) => item.address);
108
+ const { op } = condition;
109
+
110
+ if (op === "domain") {
111
+ const domain = lower(condition.value.replace(/^@/u, ""));
112
+
113
+ return senders.some((address) => {
114
+ const host = lower(address.split("@").at(-1) ?? "");
115
+
116
+ return host === domain || host.endsWith(`.${domain}`);
117
+ });
118
+ }
119
+
120
+ return senders.some((address) =>
121
+ textMatches(op, address, condition.value)
122
+ );
123
+ }
124
+
125
+ // To, Cc, and the address the mail was delivered to (Bcc, forwards).
126
+ case "recipient": {
127
+ return [
128
+ ...email.toJson.map((item) => item.address),
129
+ ...email.ccJson.map((item) => item.address),
130
+ ...(email.envelopeTo ? [email.envelopeTo] : []),
131
+ ].some((address) => textMatches(condition.op, address, condition.value));
132
+ }
133
+
134
+ case "subject": {
135
+ return textMatches(condition.op, email.subject, condition.value);
136
+ }
137
+
138
+ case "listId": {
139
+ return condition.op === "exists"
140
+ ? Boolean(email.listId)
141
+ : Boolean(
142
+ email.listId &&
143
+ condition.value &&
144
+ lower(email.listId).includes(lower(condition.value))
145
+ );
146
+ }
147
+
148
+ default: {
149
+ return email.attachmentsJson.some(
150
+ (file) => file.disposition === "attachment"
151
+ );
152
+ }
153
+ }
154
+ }
155
+
156
+ export function ruleMatches(
157
+ rule: { match: "all" | "any"; conditions: RuleCondition[] },
158
+ email: RuleSubject
159
+ ) {
160
+ return rule.match === "all"
161
+ ? rule.conditions.every((condition) => conditionMatches(condition, email))
162
+ : rule.conditions.some((condition) => conditionMatches(condition, email));
163
+ }
164
+
165
+ export type RuleOutcome = {
166
+ /** Where the matching rules file the message; null leaves it to AI sorting. */
167
+ placement:
168
+ | { type: "folder"; folderId: string }
169
+ | { type: "archive" | "trash" | "spam" }
170
+ | null;
171
+ /** A "never Spam" rule matched: an AI spam verdict is ignored. */
172
+ notSpam: boolean;
173
+ markRead: boolean;
174
+ matchedRuleIds: string[];
175
+ };
176
+
177
+ /**
178
+ * Applies enabled rules in order. A later placement replaces an earlier
179
+ * one if its destination exists; "stop processing" ends the run after its rule.
180
+ */
181
+ export function evaluateRules(
182
+ rules: (RuleInput & { id: string })[],
183
+ email: RuleSubject,
184
+ folderExists: (id: string) => boolean
185
+ ) {
186
+ const outcome: RuleOutcome = {
187
+ placement: null,
188
+ notSpam: false,
189
+ markRead: false,
190
+ matchedRuleIds: [],
191
+ };
192
+
193
+ for (const rule of rules) {
194
+ if (!rule.enabled || !ruleMatches(rule, email)) continue;
195
+ outcome.matchedRuleIds.push(rule.id);
196
+
197
+ for (const action of rule.actions) {
198
+ switch (action.type) {
199
+ case "moveToFolder": {
200
+ if (folderExists(action.folderId)) {
201
+ outcome.placement = { type: "folder", folderId: action.folderId };
202
+ }
203
+
204
+ break;
205
+ }
206
+
207
+ case "archive":
208
+ case "trash":
209
+ case "spam": {
210
+ outcome.placement = { type: action.type };
211
+ break;
212
+ }
213
+
214
+ case "notSpam": {
215
+ outcome.notSpam = true;
216
+ break;
217
+ }
218
+
219
+ default: {
220
+ outcome.markRead = true;
221
+ break;
222
+ }
223
+ }
224
+ }
225
+
226
+ if (rule.stopProcessing) break;
227
+ }
228
+
229
+ return outcome;
230
+ }