@open-workspace/email 0.4.2 → 0.5.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 (268) 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-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,934 @@
1
+ /** Incoming mail: the delivery queue, screening and classification, storing it, and what follows (notifications, auto-reply). */
2
+ import {
3
+ aiObjectRunner,
4
+ createId,
5
+ deferWebhookTask,
6
+ queueWebhookEvent,
7
+ } from "@open-workspace/core/module";
8
+ import type { AiModel } from "@open-workspace/core/module";
9
+ import { and, asc, eq, lte, isNotNull, or, sql } from "drizzle-orm";
10
+
11
+ import type { MailboxPushJob } from "../../shared/mail";
12
+ import {
13
+ EMAIL_RECEIVED_EVENT,
14
+ EMAIL_WEBHOOK_SOURCE,
15
+ emailWebhookEventId,
16
+ } from "../../shared/webhooks";
17
+ import {
18
+ classifyInboundEmail,
19
+ EmailAiClassificationError,
20
+ MAILBOX_AI_MAX_ATTEMPTS,
21
+ } from "../mail/ai-classification";
22
+ import { classificationSignals } from "../mail/classification-signals";
23
+ import type { ClassificationSignals } from "../mail/classification-signals";
24
+ import { deliveryFacts } from "../mail/delivery-facts";
25
+ import {
26
+ inboundMessageId,
27
+ MissingRawMimeError,
28
+ prepareInboundEmail,
29
+ prepareUnprocessableInboundEmail,
30
+ rawMessageId,
31
+ readInboundRawMime,
32
+ UnprocessableInboundEmailError,
33
+ } from "../mail/inbound";
34
+ import { messageSecurity } from "../mail/message-security";
35
+ import type { RuleOutcome } from "../mail/rules";
36
+ import { spamhausDqsKey, workspaceIdentity } from "../mail/security-settings";
37
+ import type { WorkspaceIdentity } from "../mail/security-settings";
38
+ import { collectSenderIntel } from "../mail/sender-intel";
39
+ import { messagePrefix } from "../mail/storage-keys";
40
+ import {
41
+ screenSender,
42
+ workspaceFeedbackSummary,
43
+ } from "../mail/workspace-safety";
44
+ import { storeEmail } from "./email-index";
45
+ import { decideDelivery } from "./inbound-decision";
46
+ import * as autoReplies from "./mailbox-auto-reply";
47
+ import * as mailboxRules from "./mailbox-rules";
48
+ import * as mailboxStorage from "./mailbox-storage";
49
+ import type {
50
+ EmailAiClassification,
51
+ EmailScreening,
52
+ SenderIntel,
53
+ } from "./model";
54
+ import { prepareOfficePreviews } from "./office-preview-jobs";
55
+ import { fileConversations } from "./placement";
56
+ import {
57
+ conversations,
58
+ emailReadStates,
59
+ emails,
60
+ folders,
61
+ pendingInbound,
62
+ } from "./schema";
63
+ import type { Email, NewEmail, PendingInbound } from "./schema";
64
+ import {
65
+ senderFeedbackSummary,
66
+ senderHistory,
67
+ senderStatuses,
68
+ } from "./senders";
69
+ import type {
70
+ InboundDeliveryInput,
71
+ InboundScreening,
72
+ MailboxContext,
73
+ } from "./support";
74
+ import {
75
+ ALARM_WAKE_DELAY_MS,
76
+ INBOUND_ALARM_BATCH_SIZE,
77
+ MAX_UNFINISHED_INBOUND_ATTEMPTS,
78
+ isPastRetryAge,
79
+ retryDelay,
80
+ } from "./support";
81
+
82
+ export function queueIncomingNotification(m: MailboxContext, email: Email) {
83
+ if (email.direction !== "incoming") return;
84
+ const sender = email.fromJson[0];
85
+
86
+ const job: MailboxPushJob = {
87
+ type: "dispatch",
88
+ mailboxId: m.state.id.name ?? "unknown-mailbox",
89
+ messageId: email.id,
90
+ occurredAt: Date.now(),
91
+ sender: sender?.name || sender?.address || "Unknown sender",
92
+ subject: email.subject,
93
+ };
94
+
95
+ return m.env.PUSH_NOTIFICATIONS.send(job);
96
+ }
97
+
98
+ export function retryStoredInboundNotification(
99
+ m: MailboxContext,
100
+ job: PendingInbound,
101
+ now: number,
102
+ cause: unknown
103
+ ) {
104
+ if (isPastRetryAge(job, now)) {
105
+ m.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
106
+ console.error(
107
+ `Stopped retrying notification for inbound delivery ${job.id}`,
108
+ cause
109
+ );
110
+
111
+ return;
112
+ }
113
+
114
+ const attempts = job.attempts + 1;
115
+ m.db
116
+ .update(pendingInbound)
117
+ .set({
118
+ attempts,
119
+ nextAttemptAt: new Date(now + retryDelay(attempts)),
120
+ })
121
+ .where(eq(pendingInbound.id, job.id))
122
+ .run();
123
+ console.error(
124
+ `Could not queue notification for inbound delivery ${job.id}`,
125
+ cause
126
+ );
127
+ }
128
+
129
+ /**
130
+ * What follows storing a delivery: its webhook, the update, the push
131
+ * notification and the auto-reply, then the delivery is done. Until then
132
+ * the pending row stays, so a killed alarm runs these again; the
133
+ * auto-reply log keeps a sender to one reply.
134
+ *
135
+ * `autoReply` is the message's MIME to answer, `"read"` to read it again
136
+ * (a retry), or null for an unreadable message, which isn't answered.
137
+ */
138
+ export async function finishStoredInbound(
139
+ m: MailboxContext,
140
+ job: PendingInbound,
141
+ email: Email,
142
+ now: number,
143
+ announce: boolean,
144
+ autoReply: ArrayBuffer | "read" | null
145
+ ) {
146
+ try {
147
+ const mailboxId = m.state.id.name ?? "unknown-mailbox";
148
+ deferWebhookTask(() =>
149
+ queueWebhookEvent(m.env, {
150
+ eventId: emailWebhookEventId(EMAIL_RECEIVED_EVENT, mailboxId, email.id),
151
+ eventType: EMAIL_RECEIVED_EVENT,
152
+ occurredAt: email.timelineAt.getTime(),
153
+ source: {
154
+ kind: EMAIL_WEBHOOK_SOURCE,
155
+ mailboxId,
156
+ messageId: email.id,
157
+ },
158
+ })
159
+ );
160
+
161
+ if (announce) void m.announce({ delivered: true });
162
+
163
+ const conversation = m.db
164
+ .select({ mailboxState: conversations.mailboxState })
165
+ .from(conversations)
166
+ .where(eq(conversations.id, email.conversationId))
167
+ .all()[0];
168
+
169
+ // Only Inbox and custom folders notify: at delivery a conversation is
170
+ // elsewhere only because spam screening or a rule put it there. Mail a
171
+ // rule marked read for everyone doesn't notify either.
172
+ const markedRead = m.db
173
+ .select({ emailId: emailReadStates.emailId })
174
+ .from(emailReadStates)
175
+ .where(eq(emailReadStates.emailId, email.id))
176
+ .limit(1)
177
+ .all()[0];
178
+
179
+ if (conversation?.mailboxState === "active" && !markedRead) {
180
+ await queueIncomingNotification(m, email);
181
+ }
182
+
183
+ if (autoReply) {
184
+ // Never able to fail the delivery.
185
+ await (
186
+ autoReply === "read"
187
+ ? readInboundRawMime(m.env, job)
188
+ : Promise.resolve(autoReply)
189
+ )
190
+ .then((rawMime) => autoReplies.maybeAutoReply(m, job, email, rawMime))
191
+ .catch((error) => {
192
+ console.error(`Auto-reply check failed for ${email.id}`, error);
193
+ });
194
+ }
195
+
196
+ m.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
197
+ } catch (error) {
198
+ retryStoredInboundNotification(m, job, now, error);
199
+ }
200
+ }
201
+
202
+ export async function enqueueInbound(
203
+ m: MailboxContext,
204
+ input: InboundDeliveryInput
205
+ ) {
206
+ const receivedAt = new Date(input.receivedAt);
207
+
208
+ if (Number.isNaN(receivedAt.getTime())) {
209
+ throw new Error("Inbound delivery has an invalid receipt time");
210
+ }
211
+
212
+ if (m.state.id.name && m.state.id.name !== input.mailboxId) {
213
+ throw new Error("Inbound delivery targeted the wrong mailbox object");
214
+ }
215
+
216
+ const queuedAt = new Date();
217
+ // Keep the alarm just ahead of the due time. Scheduling it for "now" can
218
+ // wake it on the setAlarm await before the synchronous insert below runs.
219
+ const alarmAt = queuedAt.getTime() + ALARM_WAKE_DELAY_MS;
220
+ await m.scheduleAlarm(alarmAt);
221
+ const messageId = inboundMessageId(input.id);
222
+
223
+ const queued = m.db.transaction((tx) => {
224
+ const existing = tx
225
+ .select({ id: emails.id })
226
+ .from(emails)
227
+ .where(eq(emails.id, messageId))
228
+ .all()[0];
229
+
230
+ if (existing) return false;
231
+
232
+ const result = tx
233
+ .insert(pendingInbound)
234
+ .values({
235
+ id: input.id,
236
+ rawObjectKey: input.rawObjectKey,
237
+ envelopeFrom: input.envelopeFrom,
238
+ envelopeTo: input.envelopeTo,
239
+ listAddress: input.listAddress ?? null,
240
+ receivedAt,
241
+ nextAttemptAt: queuedAt,
242
+ })
243
+ .onConflictDoNothing()
244
+ .returning({ id: pendingInbound.id })
245
+ .all();
246
+
247
+ return result.length > 0;
248
+ });
249
+
250
+ // An alarm finishing meanwhile may have dropped its own wake (see
251
+ // `scheduleRemainingWork`) before it could see this row.
252
+ if (queued) await m.scheduleAlarm(alarmAt);
253
+
254
+ return { messageId, queued };
255
+ }
256
+
257
+ /**
258
+ * DNS intelligence and receiver signals for a parsed delivery, gathered
259
+ * before AI classification so the model can use them. The signals fail
260
+ * open; the sender screen doesn't (`screenSender` throws, and the delivery
261
+ * is retried).
262
+ */
263
+ export async function inboundSenderSignals(
264
+ m: MailboxContext,
265
+ email: NewEmail,
266
+ links: string[]
267
+ ) {
268
+ let identity: WorkspaceIdentity = { domains: [], names: new Map() };
269
+ let dqsKey: string | null = null;
270
+ const from = email.fromJson[0] ?? { address: "", name: null };
271
+
272
+ const block = await screenSender(
273
+ m.env.DB,
274
+ { from: from.address, envelopeFrom: email.envelopeFrom ?? null },
275
+ m.db
276
+ );
277
+
278
+ try {
279
+ [identity, dqsKey] = await Promise.all([
280
+ workspaceIdentity(m.env.DB),
281
+ spamhausDqsKey(m.env),
282
+ ]);
283
+ } catch (error) {
284
+ console.error("Could not read workspace identity for sender checks", error);
285
+ }
286
+
287
+ const stored = email.authenticationResultsJson;
288
+ const authentication = stored ?? null;
289
+
290
+ const status = from.address
291
+ ? senderStatuses(m.db, [from.address]).get(from.address.toLocaleLowerCase())
292
+ : undefined;
293
+
294
+ const trusted = Boolean(status?.trustedAt) && !block;
295
+ let intel: SenderIntel | null = null;
296
+
297
+ try {
298
+ intel = await collectSenderIntel({
299
+ authentication,
300
+ fromAddress: from.address,
301
+ linkDomains: links,
302
+ workspaceDomains: identity.domains,
303
+ dqsKey,
304
+ bucket: m.env.MAIL_STORAGE,
305
+ });
306
+ } catch (error) {
307
+ console.error(
308
+ `Could not collect sender intelligence for ${email.id}`,
309
+ error
310
+ );
311
+ }
312
+
313
+ const history = senderHistory(m.db, [from.address]).get(
314
+ from.address.toLocaleLowerCase()
315
+ );
316
+
317
+ const delivery = deliveryFacts({
318
+ authentication,
319
+ deliveredTo: email.envelopeTo ?? null,
320
+ to: (email.toJson ?? []).map((item) => item.address),
321
+ cc: (email.ccJson ?? []).map((item) => item.address),
322
+ listId: email.listId ?? null,
323
+ workspaceDomains: identity.domains,
324
+ isKnownAddressee: (address) => isKnownAddressee(m, address),
325
+ });
326
+
327
+ const security = messageSecurity({
328
+ fromAddress: from.address,
329
+ fromName: from.name,
330
+ authentication,
331
+ listUnsubscribe: null,
332
+ workspaceDomains: identity.domains,
333
+ internalNames: identity.names,
334
+ intel,
335
+ // Counted as if this message were already stored.
336
+ history: {
337
+ inboundCount: (history?.inboundCount ?? 0) + 1,
338
+ outboundCount: history?.outboundCount ?? 0,
339
+ },
340
+ replyTo: (email.replyToJson ?? []).map((item) => item.address),
341
+ listId: email.listId ?? null,
342
+ delivery,
343
+ trusted,
344
+ });
345
+
346
+ const screening: InboundScreening = { block, trusted };
347
+
348
+ let workspaceFeedback: Awaited<
349
+ ReturnType<typeof workspaceFeedbackSummary>
350
+ > | null = null;
351
+
352
+ const mailboxId = m.state.id.name;
353
+
354
+ if (from.address && mailboxId && !block) {
355
+ try {
356
+ workspaceFeedback = await workspaceFeedbackSummary(
357
+ m.env.DB,
358
+ mailboxId,
359
+ from.address
360
+ );
361
+ } catch (error) {
362
+ console.error(`Could not read workspace feedback for ${email.id}`, error);
363
+ }
364
+ }
365
+
366
+ return {
367
+ intel,
368
+ delivery,
369
+ screening,
370
+ signals: classificationSignals({
371
+ authentication,
372
+ intel,
373
+ firstTimeSender: security.firstTimeSender,
374
+ warnings: security.warnings,
375
+ feedback: from.address ? senderFeedbackSummary(m.db, from.address) : null,
376
+ workspaceFeedback,
377
+ delivery,
378
+ }),
379
+ };
380
+ }
381
+
382
+ /** Mail written to this address already reached the mailbox from at least two senders. */
383
+ export function isKnownAddressee(m: MailboxContext, address: string) {
384
+ const sender = sql<string>`lower(json_extract(${emails.fromJson}, '$[0].address'))`;
385
+
386
+ const recipientIs = (column: typeof emails.toJson | typeof emails.ccJson) =>
387
+ sql`exists (select 1 from json_each(${column}) recipient
388
+ where lower(json_extract(recipient.value, '$.address')) = ${address.toLocaleLowerCase()})`;
389
+
390
+ const matches = m.db
391
+ .selectDistinct({ sender })
392
+ .from(emails)
393
+ .where(
394
+ and(
395
+ eq(emails.direction, "incoming"),
396
+ isNotNull(sender),
397
+ or(recipientIs(emails.toJson), recipientIs(emails.ccJson))
398
+ )
399
+ )
400
+ .limit(2)
401
+ .all();
402
+
403
+ return matches.length === 2;
404
+ }
405
+
406
+ export async function classifyInbound(
407
+ m: MailboxContext,
408
+ rawMime: ArrayBuffer,
409
+ signals: ClassificationSignals | null,
410
+ offerFolders: boolean
411
+ ) {
412
+ let ai: AiModel | null;
413
+
414
+ try {
415
+ ai = await m.classificationModel();
416
+ } catch (error) {
417
+ throw new EmailAiClassificationError(
418
+ "The classification model is misconfigured",
419
+ { cause: error }
420
+ );
421
+ }
422
+
423
+ if (!ai) return null;
424
+ const configuration = mailboxRules.aiConfiguration(m);
425
+
426
+ // A rule already decided where the message goes: the model only
427
+ // judges spam.
428
+ const customFolders = offerFolders
429
+ ? m.db
430
+ .select({ id: folders.id, name: folders.name })
431
+ .from(folders)
432
+ .orderBy(asc(folders.sortOrder), asc(folders.name))
433
+ .all()
434
+ : [];
435
+
436
+ return classifyInboundEmail({
437
+ rawMime,
438
+ folders: customFolders,
439
+ configuration,
440
+ signals,
441
+ model: ai.id,
442
+ run: aiObjectRunner(ai),
443
+ });
444
+ }
445
+
446
+ /**
447
+ * Stores an incoming message where decideDelivery puts it, in one
448
+ * transaction with its conversation's placement and a rule's "Mark read"
449
+ * for `readers`, so a retry never finds the message stored but not filed.
450
+ */
451
+ export function insertClassifiedInboundEmail(
452
+ m: MailboxContext,
453
+ input: NewEmail,
454
+ screening: InboundScreening,
455
+ rules: RuleOutcome | null,
456
+ classification: EmailAiClassification | null,
457
+ readers: readonly string[]
458
+ ) {
459
+ const prepared = prepareOfficePreviews(input);
460
+
461
+ const stored = m.db.transaction((tx) => {
462
+ const folderExists = (folderId: string) =>
463
+ tx
464
+ .select({ id: folders.id })
465
+ .from(folders)
466
+ .where(eq(folders.id, folderId))
467
+ .all().length > 0;
468
+
469
+ // The conversation its threading headers name (the sender chose them).
470
+ const parent = tx
471
+ .select({
472
+ state: conversations.mailboxState,
473
+ folderId: conversations.folderId,
474
+ })
475
+ .from(conversations)
476
+ .where(eq(conversations.id, prepared.conversationId))
477
+ .all()[0];
478
+
479
+ const startsConversation = !tx
480
+ .select({ id: emails.id })
481
+ .from(emails)
482
+ .where(
483
+ and(
484
+ eq(emails.conversationId, prepared.conversationId),
485
+ eq(emails.direction, "incoming")
486
+ )
487
+ )
488
+ .limit(1)
489
+ .all()[0];
490
+
491
+ // AI sorting's folder, if it still exists.
492
+ const sorted =
493
+ classification?.folderId && !folderExists(classification.folderId)
494
+ ? { ...classification, folderId: null }
495
+ : classification;
496
+
497
+ const placement = decideDelivery({
498
+ blocked: Boolean(screening.block),
499
+ trusted: screening.trusted,
500
+ authenticated: input.authenticationResultsJson?.verdict === "verified",
501
+ rules,
502
+ classification: sorted,
503
+ parent: parent ?? null,
504
+ startsConversation,
505
+ folderExists,
506
+ });
507
+
508
+ // Spam or Trash kept apart records the conversation it named, to
509
+ // rejoin it when moved out (rejoinSplitConversations).
510
+ const email = placement.split
511
+ ? {
512
+ ...prepared,
513
+ conversationId: createId("conv"),
514
+ splitFromConversationId:
515
+ placement.state === "spam" || placement.state === "trash"
516
+ ? prepared.conversationId
517
+ : null,
518
+ }
519
+ : prepared;
520
+
521
+ const inserted = storeEmail(tx, m.state.storage.sql, {
522
+ ...email,
523
+ aiClassificationJson: sorted,
524
+ });
525
+
526
+ if (!inserted) return null;
527
+
528
+ fileConversations(
529
+ m.state.storage.sql,
530
+ [email.conversationId],
531
+ { mailboxState: placement.state, folderId: placement.folderId },
532
+ { stored: true }
533
+ );
534
+
535
+ if (placement.markRead) {
536
+ const readAt = new Date();
537
+
538
+ for (const userId of new Set(readers)) {
539
+ tx.insert(emailReadStates)
540
+ .values({ userId, emailId: inserted.id, readAt })
541
+ .onConflictDoNothing()
542
+ .run();
543
+ }
544
+ }
545
+
546
+ return (
547
+ tx.select().from(emails).where(eq(emails.id, inserted.id)).all()[0] ??
548
+ null
549
+ );
550
+ });
551
+
552
+ m.forgetParticipants();
553
+
554
+ return stored;
555
+ }
556
+
557
+ /**
558
+ * One message reaches a person once: a copy from a team list is dropped when
559
+ * the same message already arrived directly (or the reverse), and a list
560
+ * copy of the person's own post is dropped next to the sent message.
561
+ */
562
+ export function isDuplicateDelivery(
563
+ m: MailboxContext,
564
+ job: PendingInbound,
565
+ rawMime: ArrayBuffer
566
+ ) {
567
+ const messageId = rawMessageId(rawMime);
568
+
569
+ if (!messageId) return false;
570
+ const existing = m.getEmailByMessageId(messageId);
571
+
572
+ if (!existing) return false;
573
+
574
+ return existing.direction === "incoming" || Boolean(job.listAddress);
575
+ }
576
+
577
+ export async function processInboundJobs(m: MailboxContext, now: number) {
578
+ const jobs = m.db
579
+ .select()
580
+ .from(pendingInbound)
581
+ .where(lte(pendingInbound.nextAttemptAt, new Date(now)))
582
+ .orderBy(asc(pendingInbound.nextAttemptAt), asc(pendingInbound.receivedAt))
583
+ // MIME parsing can be memory-heavy; the next due row schedules a quick
584
+ // follow-up, so one delivery per wake keeps peak memory bounded.
585
+ .limit(INBOUND_ALARM_BATCH_SIZE)
586
+ .all();
587
+
588
+ for (const job of jobs) {
589
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one delivery at a time keeps MIME parsing's peak memory bounded
590
+ await processInboundJob(m, job, now);
591
+ }
592
+ }
593
+
594
+ export async function processInboundJob(
595
+ m: MailboxContext,
596
+ job: PendingInbound,
597
+ now: number
598
+ ) {
599
+ const messageId = inboundMessageId(job.id);
600
+ const existing = m.getEmail(messageId);
601
+
602
+ if (existing) {
603
+ // A stand-in for unreadable mail (storeStandIn) isn't answered on a
604
+ // retry either: only a reading records a delivery's facts.
605
+ await finishStoredInbound(
606
+ m,
607
+ job,
608
+ existing,
609
+ now,
610
+ false,
611
+ existing.deliveryJson ? "read" : null
612
+ );
613
+
614
+ return;
615
+ }
616
+
617
+ if (job.attempts > 0 && isPastRetryAge(job, now)) {
618
+ // Earlier attempts ended without an outcome (the alarm was killed
619
+ // mid-parse, say); this message is not parsed again.
620
+ await storeUnparsedInbound(
621
+ m,
622
+ job,
623
+ now,
624
+ "Message processing did not finish within 24 hours"
625
+ );
626
+
627
+ return;
628
+ }
629
+
630
+ if (job.unfinishedAttempts >= MAX_UNFINISHED_INBOUND_ATTEMPTS) {
631
+ // Processing it got the alarm killed every time: other mail goes first.
632
+ await storeUnparsedInbound(
633
+ m,
634
+ job,
635
+ now,
636
+ `Message processing did not finish in ${MAX_UNFINISHED_INBOUND_ATTEMPTS} attempts`
637
+ );
638
+
639
+ return;
640
+ }
641
+
642
+ await recordInboundAttempt(m, job, now);
643
+
644
+ try {
645
+ const rawMime = await readInboundRawMime(m.env, job);
646
+
647
+ if (isDuplicateDelivery(m, job, rawMime)) {
648
+ m.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
649
+ // Its original copy isn't kept (once archived, if it's to be), nor
650
+ // what an earlier attempt's reading stored.
651
+ await mailboxStorage.forgetObjects(m, [job.rawObjectKey]);
652
+ await forgetParsedFiles(m, messageId);
653
+
654
+ return;
655
+ }
656
+
657
+ const prepared = await prepareInboundEmail({
658
+ env: m.env,
659
+ mailboxId: m.state.id.name ?? "unknown-mailbox",
660
+ job,
661
+ rawMime,
662
+ resolveParent: (inReplyTo, references) =>
663
+ m.resolveParent(inReplyTo, references),
664
+ });
665
+
666
+ const { intel, delivery, signals, screening } = await inboundSenderSignals(
667
+ m,
668
+ prepared.email,
669
+ prepared.linkDomains
670
+ );
671
+
672
+ const screeningJson: EmailScreening | null = screening.block
673
+ ? { blocked: screening.block.workspace ? "workspace" : "mailbox" }
674
+ : null;
675
+
676
+ const email: NewEmail = {
677
+ ...prepared.email,
678
+ senderIntelJson: intel,
679
+ deliveryJson: delivery,
680
+ screeningJson,
681
+ };
682
+
683
+ // Blocked senders get no rules: they go to Spam whatever a rule says.
684
+ const rules = screening.block
685
+ ? null
686
+ : mailboxRules.inboundRules(m, email, job.id);
687
+
688
+ let classification: EmailAiClassification | null = null;
689
+
690
+ // Blocked senders, and mail a rule sends to Spam, need no model.
691
+ const skipAi =
692
+ Boolean(screening.block) || rules?.placement?.type === "spam";
693
+
694
+ try {
695
+ if (!skipAi) {
696
+ classification = await classifyInbound(
697
+ m,
698
+ rawMime,
699
+ signals,
700
+ !rules?.placement
701
+ );
702
+ }
703
+ } catch (error) {
704
+ if (!(error instanceof EmailAiClassificationError)) throw error;
705
+ const aiAttempts = job.aiAttempts + 1;
706
+
707
+ if (aiAttempts < MAILBOX_AI_MAX_ATTEMPTS) {
708
+ m.db
709
+ .update(pendingInbound)
710
+ .set({
711
+ // The model failed, not the delivery: the attempt recorded
712
+ // before parsing is given back.
713
+ attempts: job.attempts,
714
+ unfinishedAttempts: job.unfinishedAttempts,
715
+ aiAttempts,
716
+ nextAttemptAt: new Date(now + retryDelay(aiAttempts)),
717
+ })
718
+ .where(eq(pendingInbound.id, job.id))
719
+ .run();
720
+ console.error(
721
+ `Could not classify inbound delivery ${job.id}; retrying`,
722
+ error
723
+ );
724
+
725
+ return;
726
+ }
727
+
728
+ console.error(
729
+ `Could not classify inbound delivery ${job.id}; delivering to Inbox`,
730
+ error
731
+ );
732
+ }
733
+
734
+ // Who "Mark read" marks it read for; a failing rule action never
735
+ // fails the delivery.
736
+ const readers = rules?.markRead
737
+ ? await mailboxRules.mailboxReaders(m).catch((error) => {
738
+ console.error(`Rule could not mark ${job.id} read`, error);
739
+
740
+ return [];
741
+ })
742
+ : [];
743
+
744
+ const stored = insertClassifiedInboundEmail(
745
+ m,
746
+ email,
747
+ screening,
748
+ rules,
749
+ classification,
750
+ readers
751
+ );
752
+
753
+ if (!stored) {
754
+ throw new Error("Parsed inbound email was not persisted");
755
+ }
756
+
757
+ await finishStoredInbound(m, job, stored, now, true, rawMime);
758
+ } catch (error) {
759
+ if (error instanceof UnprocessableInboundEmailError) {
760
+ await storeStandIn(m, job, now, {
761
+ reason: error.message,
762
+ rawMimeR2Key: job.rawObjectKey,
763
+ cause: error,
764
+ });
765
+ console.error(`Stored fallback for inbound delivery ${job.id}`, error);
766
+
767
+ return;
768
+ }
769
+
770
+ if (isPastRetryAge(job, now)) {
771
+ await storeStandIn(m, job, now, {
772
+ reason: "Message processing remained unavailable for 24 hours",
773
+ rawMimeR2Key:
774
+ error instanceof MissingRawMimeError ? null : job.rawObjectKey,
775
+ cause: error,
776
+ });
777
+ console.error(
778
+ `Stored infrastructure fallback for inbound delivery ${job.id}`,
779
+ error
780
+ );
781
+
782
+ return;
783
+ }
784
+
785
+ const attempts = job.attempts + 1;
786
+ m.db
787
+ .update(pendingInbound)
788
+ .set({
789
+ attempts,
790
+ // This attempt ended with a failure, not a killed alarm.
791
+ unfinishedAttempts: job.unfinishedAttempts,
792
+ nextAttemptAt: new Date(now + retryDelay(attempts)),
793
+ })
794
+ .where(eq(pendingInbound.id, job.id))
795
+ .run();
796
+ console.error(`Could not ingest inbound delivery ${job.id}`, error);
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Counts an attempt and backs the delivery off before it is parsed, and
802
+ * makes that durable: when parsing gets the alarm killed (CPU or memory),
803
+ * no catch runs, and the delivery must not stay first in line. The
804
+ * attempt also counts as unfinished until a path with an outcome gives
805
+ * that back (storing deletes the row; a failure restores the count).
806
+ */
807
+ export async function recordInboundAttempt(
808
+ m: MailboxContext,
809
+ job: PendingInbound,
810
+ now: number
811
+ ) {
812
+ const attempts = job.attempts + 1;
813
+ const nextAttemptAt = now + retryDelay(attempts);
814
+ m.db
815
+ .update(pendingInbound)
816
+ .set({
817
+ attempts,
818
+ unfinishedAttempts: job.unfinishedAttempts + 1,
819
+ nextAttemptAt: new Date(nextAttemptAt),
820
+ })
821
+ .where(eq(pendingInbound.id, job.id))
822
+ .run();
823
+ // The retry's wake, in case this alarm never gets to schedule it.
824
+ await m.scheduleAlarm(nextAttemptAt);
825
+ m.noteAttemptAlarm(nextAttemptAt);
826
+ await m.state.storage.sync();
827
+ }
828
+
829
+ /**
830
+ * Stores an unreadable message in a delivery's place. Its only sender is
831
+ * the envelope's, which is still screened: a blocked sender's goes to Spam
832
+ * without a notification, so unparseable mail can't get past a block.
833
+ */
834
+ export async function storeFallbackInbound(
835
+ m: MailboxContext,
836
+ job: PendingInbound,
837
+ fallback: NewEmail
838
+ ) {
839
+ const block = await screenSender(
840
+ m.env.DB,
841
+ { from: null, envelopeFrom: job.envelopeFrom || null },
842
+ m.db
843
+ );
844
+
845
+ return insertClassifiedInboundEmail(
846
+ m,
847
+ fallback,
848
+ { block, trusted: false },
849
+ null,
850
+ null,
851
+ []
852
+ );
853
+ }
854
+
855
+ /**
856
+ * Stores a delivery that is not parsed again as an unreadable message,
857
+ * with a link to its raw MIME. The delivery is backed off first, so a
858
+ * failure here (R2 or storage) waits its turn behind newer mail.
859
+ */
860
+ export async function storeUnparsedInbound(
861
+ m: MailboxContext,
862
+ job: PendingInbound,
863
+ now: number,
864
+ reason: string
865
+ ) {
866
+ await recordInboundAttempt(m, job, now);
867
+
868
+ try {
869
+ // Without an answer from R2 the link is kept: a missing object only
870
+ // makes the download fail.
871
+ const raw = await m.env.MAIL_STORAGE.head(job.rawObjectKey).then(
872
+ (object) => object !== null,
873
+ () => true
874
+ );
875
+
876
+ await storeStandIn(m, job, now, {
877
+ reason,
878
+ rawMimeR2Key: raw ? job.rawObjectKey : null,
879
+ });
880
+ console.error(`Stored fallback for unparsed inbound delivery ${job.id}`);
881
+ } catch (error) {
882
+ console.error(`Could not store unparsed inbound delivery ${job.id}`, error);
883
+ }
884
+ }
885
+
886
+ /**
887
+ * The one way a delivery that can't be read is stored: an unreadable
888
+ * message in its place (`storeFallbackInbound`), linking its raw MIME when
889
+ * there is one. What attempts that read it stored (its HTML body and
890
+ * attachments) goes, as the stand-in keeps neither.
891
+ */
892
+ async function storeStandIn(
893
+ m: MailboxContext,
894
+ job: PendingInbound,
895
+ now: number,
896
+ input: { reason: string; rawMimeR2Key: string | null; cause?: unknown }
897
+ ) {
898
+ const stored = await storeFallbackInbound(
899
+ m,
900
+ job,
901
+ prepareUnprocessableInboundEmail({
902
+ job,
903
+ reason: input.reason,
904
+ rawMimeR2Key: input.rawMimeR2Key,
905
+ })
906
+ );
907
+
908
+ if (!stored) {
909
+ throw new Error(
910
+ `The stand-in for inbound delivery ${job.id} was not stored`,
911
+ {
912
+ cause: input.cause,
913
+ }
914
+ );
915
+ }
916
+
917
+ await finishStoredInbound(m, job, stored, now, true, null);
918
+ await forgetParsedFiles(m, stored.id);
919
+ }
920
+
921
+ /**
922
+ * Queues the files a reading of message `emailId` stored (its HTML body and
923
+ * attachments, under its own prefix) for deletion; the queue keeps any a
924
+ * stored message still uses.
925
+ */
926
+ async function forgetParsedFiles(m: MailboxContext, emailId: string) {
927
+ const prefix = messagePrefix(m.state.id.name ?? "", emailId);
928
+ const listed = await m.env.MAIL_STORAGE.list({ prefix, limit: 1000 });
929
+
930
+ await mailboxStorage.forgetObjects(
931
+ m,
932
+ listed.objects.map((object) => object.key)
933
+ );
934
+ }