@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,644 @@
1
+ import {
2
+ createDb,
3
+ restoredReaderIds,
4
+ mailboxAddressSql,
5
+ } from "@open-workspace/core/module";
6
+ import type {
7
+ BackupSnapshot,
8
+ Database,
9
+ ModuleBackup,
10
+ } from "@open-workspace/core/module";
11
+ import { mailboxes } from "@open-workspace/core/schema";
12
+ import { and, asc, eq, gt } from "drizzle-orm";
13
+ import { z } from "zod";
14
+
15
+ import {
16
+ transportStates,
17
+ deliveryStatuses,
18
+ MAX_COMPOSER_ATTACHMENT_BYTES,
19
+ MAX_COMPOSER_ATTACHMENT_COUNT,
20
+ } from "../../shared/mail";
21
+ import type { MailboxState } from "../../shared/mail";
22
+ import { importPlacements } from "../../shared/mail-import";
23
+ import { IMPORT_MAIL_SCOPE } from "../../shared/permissions";
24
+ import {
25
+ importCopyKey,
26
+ importedEmailId,
27
+ importedConversationId,
28
+ importRawMessage,
29
+ } from "../mail/import";
30
+ import { prepareOutboundDelivery } from "../mail/outbound-delivery";
31
+ import { messagePrefix } from "../mail/storage-keys";
32
+ import { mailboxStub } from "../mailbox";
33
+ import type { StoredAttachment } from "../mailbox/model";
34
+ import type { Email } from "../mailbox/schema";
35
+ import { serializeEml } from "./eml";
36
+ import {
37
+ backupFileParts,
38
+ linkedAttachment,
39
+ restoreFileParts,
40
+ stageBackupPart,
41
+ } from "./file-parts";
42
+ import type { BackupFile } from "./file-parts";
43
+ import {
44
+ mailboxAt,
45
+ mailboxPieces,
46
+ writeMailboxDrafts,
47
+ pieceScopes,
48
+ userRef,
49
+ userRefs,
50
+ restorePiece,
51
+ WORKSPACE_FOLDER,
52
+ workspacePieces,
53
+ writePieces,
54
+ } from "./settings-backup";
55
+
56
+ /**
57
+ * Mail's part of a backup snapshot: a folder per address that keeps mail,
58
+ * with one line per message, and each message's `.eml` object stored once,
59
+ * then the address's settings and drafts (settings-backup.ts).
60
+ * The mailbox keeps each stored message's hash, so later snapshots write
61
+ * its line from the mailbox's rows alone, and read and store only new mail.
62
+ */
63
+
64
+ /** Rows a batch lists; those with a stored hash cost nothing more. */
65
+ const BATCH_ROWS = 5000;
66
+
67
+ /** New messages a batch reads and stores, about 3 subrequests each. */
68
+ const BATCH_NEW = 100;
69
+
70
+ /**
71
+ * Addresses a batch goes through at most, about 7 subrequests each (its
72
+ * mail, settings and drafts), so a workspace with many small or empty
73
+ * mailboxes still takes few batches, and a batch stays near the ~300
74
+ * subrequests core's job allows one (MAX_BATCHES).
75
+ */
76
+ const BATCH_MAILBOXES = 10;
77
+
78
+ const EML = { extension: "eml", contentType: "message/rfc822" };
79
+
80
+ /** The mail index row written to each snapshot and read by the restore route. */
81
+ const mailBackupLine = z.object({
82
+ attachments: z
83
+ .array(linkedAttachment)
84
+ .max(MAX_COMPOSER_ATTACHMENT_COUNT)
85
+ .refine(
86
+ (files) =>
87
+ files.reduce((n, f) => n + f.file.size, 0) <=
88
+ MAX_COMPOSER_ATTACHMENT_BYTES
89
+ )
90
+ .optional(),
91
+ id: z.string().min(1).max(200),
92
+ object: z.string(),
93
+ subject: z.string(),
94
+ placement: z.enum(importPlacements),
95
+ folder: z.string().trim().min(1).max(80).nullable(),
96
+ readers: z.array(userRef),
97
+ transport: z.object({
98
+ transportState: z.enum(transportStates),
99
+ transportError: z.string().nullable(),
100
+ deliveryStatusJson: z.array(
101
+ z.object({
102
+ recipient: z.string(),
103
+ status: z.enum(deliveryStatuses),
104
+ eventId: z.string(),
105
+ eventAt: z.number(),
106
+ smtpCode: z.string().nullable(),
107
+ detail: z.string().nullable(),
108
+ })
109
+ ),
110
+ }),
111
+ thread: z.string().min(1).max(200),
112
+ direction: z.enum(["incoming", "outgoing"]),
113
+ envelopeTo: z.string().optional(),
114
+ listId: z.string().optional(),
115
+ listPostAddress: z.string().optional(),
116
+ received_at: z.iso.datetime(),
117
+ });
118
+
119
+ type MailBackupLine = z.infer<typeof mailBackupLine>;
120
+
121
+ /** Sent is a message direction. The custom folder belongs to the conversation in every state. */
122
+ function backupPlacement(
123
+ state: MailboxState,
124
+ direction: "incoming" | "outgoing"
125
+ ) {
126
+ if (state !== "active") return state;
127
+
128
+ return direction === "outgoing" ? "sent" : "inbox";
129
+ }
130
+
131
+ /**
132
+ * A message's `.eml`, and whether it is final: its hash may then stand for
133
+ * it in every later snapshot. One rebuilt without its attachments, or sent
134
+ * mail before Email Sending gave it its Message-ID (unless its send failed
135
+ * for good), isn't: the next snapshot builds it again.
136
+ */
137
+ type MessageBytes = { bytes: Uint8Array<ArrayBuffer>; final: boolean };
138
+
139
+ async function sentMessageBytes(
140
+ env: Env,
141
+ email: Email,
142
+ error: (message: string) => void
143
+ ) {
144
+ let delivery: Awaited<ReturnType<typeof prepareOutboundDelivery>>;
145
+ let complete = true;
146
+
147
+ try {
148
+ delivery = await prepareOutboundDelivery(env, email);
149
+ } catch (cause) {
150
+ // A missing attachment must not cost the backup the message itself.
151
+ error(
152
+ `${email.id}: ${cause instanceof Error ? cause.message : String(cause)}; kept without attachments`
153
+ );
154
+ complete = false;
155
+ delivery = await prepareOutboundDelivery(env, {
156
+ ...email,
157
+ attachmentsJson: [],
158
+ });
159
+ }
160
+
161
+ const bytes = serializeEml({
162
+ id: email.id,
163
+ from: email.fromJson,
164
+ to: email.toJson,
165
+ cc: email.ccJson,
166
+ bcc: email.bccJson,
167
+ replyTo: email.replyToJson,
168
+ subject: email.subject,
169
+ date: email.timelineAt,
170
+ messageId: email.messageIdHeader,
171
+ inReplyTo: email.inReplyToJson,
172
+ references: email.referencesJson,
173
+ text: delivery.text,
174
+ html: delivery.html,
175
+ attachments: (delivery.attachments ?? []).map((attachment) => ({
176
+ ...attachment,
177
+ // SAFETY: prepareOutboundDelivery reads each attachment with R2's
178
+ // arrayBuffer(); EmailAttachment's type only allows more.
179
+ content: attachment.content as ArrayBuffer,
180
+ })),
181
+ });
182
+
183
+ return {
184
+ bytes,
185
+ // Failed mail can be cached until the next delivery attempt.
186
+ final:
187
+ complete &&
188
+ (email.direction !== "outgoing" ||
189
+ Boolean(email.messageIdHeader) ||
190
+ email.transportState === "failed"),
191
+ } satisfies MessageBytes;
192
+ }
193
+
194
+ async function messageBytes(
195
+ env: Env,
196
+ stub: ReturnType<typeof mailboxStub>,
197
+ id: string,
198
+ rawMimeR2Key: string | null,
199
+ error: (message: string) => void
200
+ ) {
201
+ if (rawMimeR2Key) {
202
+ const object = await env.MAIL_STORAGE.get(rawMimeR2Key);
203
+
204
+ if (object) {
205
+ return {
206
+ bytes: new Uint8Array(await object.arrayBuffer()),
207
+ final: true,
208
+ } satisfies MessageBytes;
209
+ }
210
+
211
+ error(`${id}: raw message is missing, rebuilt from its fields`);
212
+ }
213
+
214
+ const email = await stub.getEmail(id);
215
+
216
+ if (!email) return null;
217
+ const message = await sentMessageBytes(env, email, error);
218
+
219
+ // If an archived original was missing, look for it again next snapshot.
220
+ return rawMimeR2Key ? { ...message, final: false } : message;
221
+ }
222
+
223
+ /** The next address after `afterId` that keeps mail (a mailing list keeps none). */
224
+ async function nextMailbox(db: Database, afterId: string | null) {
225
+ const [row] = await db
226
+ .select({ id: mailboxes.id, address: mailboxAddressSql })
227
+ .from(mailboxes)
228
+ .where(
229
+ and(
230
+ eq(mailboxes.delivery, "inbox"),
231
+ afterId ? gt(mailboxes.id, afterId) : undefined
232
+ )
233
+ )
234
+ .orderBy(asc(mailboxes.id))
235
+ .limit(1);
236
+
237
+ return row ?? null;
238
+ }
239
+
240
+ const cursorSchema = z.union([
241
+ z.object({ workspace: z.literal(true), skip: z.number() }),
242
+ z.object({
243
+ mailbox: z.string(),
244
+ address: z.string(),
245
+ after: z.string().nullable(),
246
+ /** Set once its mail is written: the next of its settings pieces. */
247
+ settings: z.number().optional(),
248
+ drafts: z
249
+ .object({ userId: z.string(), id: z.string() })
250
+ .nullable()
251
+ .optional(),
252
+ }),
253
+ ]);
254
+
255
+ /**
256
+ * One batch: pages of mailboxes' messages, each followed by its settings
257
+ * and drafts (settings-backup.ts), from the cursor's mailbox on, until it
258
+ * has listed BATCH_ROWS rows, stored BATCH_NEW new objects or gone through
259
+ * BATCH_MAILBOXES addresses; after the last address, the workspace's
260
+ * settings.
261
+ */
262
+ async function exportMail(env: Env, snapshot: BackupSnapshot) {
263
+ const db = createDb(env.DB);
264
+ let refs: ReturnType<typeof userRefs> | undefined;
265
+
266
+ const position = snapshot.cursor
267
+ ? cursorSchema.parse(JSON.parse(snapshot.cursor))
268
+ : null;
269
+
270
+ if (position && "workspace" in position) {
271
+ const { next } = await writePieces(
272
+ snapshot,
273
+ WORKSPACE_FOLDER,
274
+ await workspacePieces(env),
275
+ position.skip,
276
+ BATCH_NEW
277
+ );
278
+
279
+ return next === null
280
+ ? null
281
+ : JSON.stringify({ workspace: true, skip: next });
282
+ }
283
+
284
+ let mailbox = position
285
+ ? { id: position.mailbox, address: position.address }
286
+ : await nextMailbox(db, null);
287
+
288
+ let after = position?.after ?? null;
289
+ let settings = position?.settings;
290
+ let draftsAfter = position?.drafts;
291
+ let rowsLeft = BATCH_ROWS;
292
+ let newLeft = BATCH_NEW;
293
+
294
+ for (
295
+ let visited = 0;
296
+ mailbox && visited < BATCH_MAILBOXES && rowsLeft > 0 && newLeft > 0;
297
+ visited += 1
298
+ ) {
299
+ if (settings === undefined && draftsAfter === undefined) {
300
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one mailbox after another, within the batch's budget
301
+ const page = await messagePage(
302
+ env,
303
+ snapshot,
304
+ mailbox,
305
+ after,
306
+ {
307
+ rows: rowsLeft,
308
+ new: newLeft,
309
+ },
310
+ (refs ??= userRefs(db))
311
+ );
312
+
313
+ rowsLeft -= page.rows;
314
+ newLeft -= page.new;
315
+
316
+ if (page.last) {
317
+ return JSON.stringify({
318
+ mailbox: mailbox.id,
319
+ address: mailbox.address,
320
+ after: page.last,
321
+ });
322
+ }
323
+
324
+ settings = 0;
325
+ }
326
+
327
+ if (settings !== undefined) {
328
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
329
+ const pieces = await mailboxPieces(
330
+ env,
331
+ mailbox.id,
332
+ (refs ??= userRefs(db))
333
+ );
334
+
335
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
336
+ const written = await writePieces(
337
+ snapshot,
338
+ mailbox.address,
339
+ pieces,
340
+ settings,
341
+ newLeft
342
+ );
343
+
344
+ newLeft -= written.stored;
345
+
346
+ if (written.next !== null) {
347
+ return JSON.stringify({
348
+ mailbox: mailbox.id,
349
+ address: mailbox.address,
350
+ after: null,
351
+ settings: written.next,
352
+ });
353
+ }
354
+ }
355
+
356
+ // oxlint-disable-next-line eslint/no-await-in-loop -- resume this mailbox before visiting the next
357
+ const drafts = await writeMailboxDrafts(
358
+ env,
359
+ snapshot,
360
+ mailbox,
361
+ (refs ??= userRefs(db)),
362
+ draftsAfter ?? null,
363
+ newLeft,
364
+ BATCH_NEW
365
+ );
366
+
367
+ newLeft -= drafts.stored;
368
+
369
+ if (drafts.more) {
370
+ return JSON.stringify({
371
+ mailbox: mailbox.id,
372
+ address: mailbox.address,
373
+ after: null,
374
+ drafts: drafts.last,
375
+ });
376
+ }
377
+
378
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
379
+ mailbox = await nextMailbox(db, mailbox.id);
380
+ after = null;
381
+ settings = undefined;
382
+ draftsAfter = undefined;
383
+ }
384
+
385
+ if (!mailbox) return JSON.stringify({ workspace: true, skip: 0 });
386
+
387
+ return JSON.stringify({
388
+ mailbox: mailbox.id,
389
+ address: mailbox.address,
390
+ after,
391
+ settings,
392
+ });
393
+ }
394
+
395
+ /**
396
+ * One page of a mailbox's messages from `after`, within the batch's budget:
397
+ * what it listed and stored, and the last message when more follow.
398
+ */
399
+ async function messagePage(
400
+ env: Env,
401
+ snapshot: BackupSnapshot,
402
+ mailbox: { id: string; address: string },
403
+ after: string | null,
404
+ budget: { rows: number; new: number },
405
+ refs: ReturnType<typeof userRefs>
406
+ ) {
407
+ const stub = mailboxStub(env, mailbox.id);
408
+
409
+ const [{ rows, more, cost }, ref] = await Promise.all([
410
+ stub.listBackupEmails(after, budget.rows, budget.new),
411
+ refs,
412
+ ]);
413
+
414
+ const stored: Parameters<typeof stub.setBackupHashes>[0] = [];
415
+ const lines: MailBackupLine[] = [];
416
+
417
+ for (const row of rows) {
418
+ let sha256 = row.backupSha256;
419
+ let { attachments } = row;
420
+
421
+ if (row.pending) {
422
+ try {
423
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one message in memory at a time; a message may be 25 MiB
424
+ const message = await messageBytes(
425
+ env,
426
+ stub,
427
+ row.id,
428
+ row.pending.rawMimeR2Key,
429
+ snapshot.error
430
+ );
431
+
432
+ if (!message) continue;
433
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
434
+ sha256 = await snapshot.putObject(message.bytes, EML);
435
+
436
+ attachments = [];
437
+ const files: Record<string, BackupFile> = {};
438
+ let complete = message.final;
439
+
440
+ for (const attachment of row.pending.linked) {
441
+ try {
442
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one attachment at a time per Worker
443
+ const file = await backupFileParts(
444
+ env.MAIL_STORAGE,
445
+ attachment.r2Key,
446
+ snapshot
447
+ );
448
+
449
+ files[attachment.id] = file;
450
+ attachments.push({
451
+ downloadTokenHash: attachment.downloadTokenHash,
452
+ filename: attachment.filename,
453
+ contentType: attachment.contentType,
454
+ file,
455
+ });
456
+ } catch (cause) {
457
+ complete = false;
458
+ snapshot.error(
459
+ `${row.id} ${attachment.filename}: ${String(cause)}; kept message without this file`
460
+ );
461
+ }
462
+ }
463
+
464
+ if (complete) {
465
+ stored.push({
466
+ id: row.id,
467
+ source: row.pending.source,
468
+ sha256,
469
+ files: attachments.length ? files : undefined,
470
+ });
471
+ }
472
+ } catch (cause) {
473
+ // Left out of this snapshot; the next one tries again.
474
+ snapshot.error(
475
+ `${mailbox.address} ${row.id}: ${cause instanceof Error ? cause.message : String(cause)}`
476
+ );
477
+ continue;
478
+ }
479
+ }
480
+
481
+ lines.push({
482
+ id: row.id,
483
+ object: `${sha256}.${EML.extension}`,
484
+ attachments: attachments.length ? attachments : undefined,
485
+ placement: backupPlacement(row.mailboxState, row.direction),
486
+ folder: row.folderName,
487
+ readers: row.readers.map(ref),
488
+ transport: {
489
+ transportState: row.transportState,
490
+ transportError: row.transportError,
491
+ deliveryStatusJson: row.deliveryStatusJson,
492
+ },
493
+ thread: row.conversationId,
494
+ direction: row.direction,
495
+ envelopeTo: row.envelopeTo ?? undefined,
496
+ listId: row.listId ?? undefined,
497
+ listPostAddress: row.listPostAddress ?? undefined,
498
+ received_at: row.timelineAt.toISOString(),
499
+ subject: row.subject,
500
+ });
501
+ }
502
+
503
+ // After the objects, so a hash the mailbox holds always names one.
504
+ if (stored.length) await stub.setBackupHashes(stored);
505
+ snapshot.writeLines(mailbox.address, lines);
506
+
507
+ return {
508
+ rows: rows.length,
509
+ new: cost,
510
+ last: more ? (rows.at(-1)?.id ?? null) : null,
511
+ };
512
+ }
513
+
514
+ /**
515
+ * Core's `mailboxSaved` hook: an address that no longer keeps mail (now an
516
+ * alias, a forward or a list) is left out of snapshots, so the hashes its
517
+ * mailbox holds are forgotten; if it keeps mail again, its messages are
518
+ * stored again instead of naming objects the sweep may have deleted.
519
+ */
520
+ export async function forgetBackupHashes(env: Env, mailboxId: string) {
521
+ const [row] = await createDb(env.DB)
522
+ .select({ delivery: mailboxes.delivery })
523
+ .from(mailboxes)
524
+ .where(eq(mailboxes.id, mailboxId))
525
+ .limit(1);
526
+
527
+ if (row && row.delivery !== "inbox") {
528
+ await mailboxStub(env, mailboxId).clearBackupHashes();
529
+ }
530
+ }
531
+
532
+ export const mailBackup: ModuleBackup = {
533
+ export: exportMail,
534
+ /** A message goes in as `import` puts one into any mailbox; a piece as its routes write it. */
535
+ restoreScopes: (item) => pieceScopes(item) ?? [IMPORT_MAIL_SCOPE],
536
+ /** Adds a message to the mailbox at its folder's address, unless it is there. */
537
+ async restore(c, item) {
538
+ const part = await stageBackupPart(
539
+ c.env.MAIL_STORAGE,
540
+ c.get("user").id,
541
+ item
542
+ );
543
+
544
+ if (part) return part;
545
+ const piece = await restorePiece(c, item);
546
+
547
+ if (piece) return piece;
548
+ const { folder, line, object } = item;
549
+ const parsed = mailBackupLine.safeParse(line);
550
+
551
+ if (!parsed.success || !object) {
552
+ return { status: "skipped", reason: "not a message line" };
553
+ }
554
+
555
+ const message = parsed.data;
556
+ const mailbox = await mailboxAt(c.env, folder);
557
+
558
+ if (!mailbox) return { status: "skipped", reason: `no mailbox ${folder}` };
559
+
560
+ const files: StoredAttachment[] = [];
561
+ const importKey = `backup:${message.id}`;
562
+ const thread = `backup:${message.thread}`;
563
+ const stub = mailboxStub(c.env, mailbox.id);
564
+ const keys: string[] = [];
565
+
566
+ try {
567
+ if (message.attachments?.length) {
568
+ const restoredId = await importedEmailId(importKey);
569
+
570
+ if (
571
+ await stub.findImported(
572
+ restoredId,
573
+ { emailId: message.id, conversationId: message.thread },
574
+ await importedConversationId(thread),
575
+ importCopyKey(object, message.direction)
576
+ )
577
+ ) {
578
+ return { status: "exists" };
579
+ }
580
+
581
+ for (const [index, attachment] of message.attachments.entries()) {
582
+ const id = `att_${restoredId}_linked_${index}`;
583
+ // Concurrent restores of different snapshots must never overwrite the winner's file.
584
+ const r2Key = `${messagePrefix(mailbox.id, restoredId)}attachments/${id}_${crypto.randomUUID()}`;
585
+ keys.push(r2Key);
586
+ // oxlint-disable-next-line eslint/no-await-in-loop -- stream one attachment before opening the next
587
+ await restoreFileParts(
588
+ c.env.MAIL_STORAGE,
589
+ c.get("user").id,
590
+ r2Key,
591
+ attachment.file,
592
+ { httpMetadata: { contentType: attachment.contentType } }
593
+ );
594
+ files.push({
595
+ id,
596
+ r2Key,
597
+ filename: attachment.filename,
598
+ contentType: attachment.contentType,
599
+ size: attachment.file.size,
600
+ disposition: "attachment",
601
+ delivery: "download_link",
602
+ contentId: null,
603
+ // The hash identifies the old URL in the saved MIME. A restored
604
+ // file gets a usable link only when someone sends the message again.
605
+ downloadExpiresAt: null,
606
+ downloadTokenHash: attachment.downloadTokenHash,
607
+ });
608
+ }
609
+ }
610
+
611
+ const result = await importRawMessage({
612
+ env: c.env,
613
+ mailbox,
614
+ raw: object,
615
+ importKey,
616
+ linkedFiles: files,
617
+ receivedAt: Date.parse(message.received_at),
618
+ placement: message.placement,
619
+ folderName: message.folder,
620
+ seenBy: await restoredReaderIds(c.env.DB, message.readers),
621
+ thread,
622
+ direction: message.direction,
623
+ original: {
624
+ emailId: message.id,
625
+ conversationId: message.thread,
626
+ envelopeTo: message.envelopeTo ?? null,
627
+ listId: message.listId ?? null,
628
+ listPostAddress: message.listPostAddress ?? null,
629
+ ...message.transport,
630
+ },
631
+ });
632
+
633
+ if (result.status === "imported") keys.length = 0;
634
+
635
+ if (result.status === "unprocessable") {
636
+ return { status: "skipped", reason: result.reason };
637
+ }
638
+
639
+ return { status: result.status === "duplicate" ? "exists" : "restored" };
640
+ } finally {
641
+ if (keys.length) await stub.forgetDraftFiles(keys);
642
+ }
643
+ },
644
+ };