@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,700 @@
1
+ import {
2
+ inJsonList,
3
+ createDb,
4
+ insertRowSlices,
5
+ mailboxAddressSql,
6
+ } from "@open-workspace/core/module";
7
+ import { mailboxes } from "@open-workspace/core/schema";
8
+ import { and, asc, desc, eq, inArray, like, or, sql } from "drizzle-orm";
9
+ import { z } from "zod";
10
+
11
+ import { mailArchiveEntries } from "../db/schema";
12
+ import {
13
+ ARCHIVE_STAGING_PREFIX,
14
+ archiveObjectKey,
15
+ archiveRetryDue,
16
+ archiveStagingKey,
17
+ sentEml,
18
+ } from "./archive-object";
19
+ import type { ArchiveDirection, SentMessage } from "./archive-object";
20
+ import { mailboxPrefix, objectMailboxId } from "./storage-keys";
21
+
22
+ /**
23
+ * The optional write-once mail archive (`Email({ archive })`): every
24
+ * received and sent message is copied as .eml to MAIL_ARCHIVE, a separate
25
+ * bucket with a lock rule, and journaled in D1. Archiving never holds up or
26
+ * fails mail: what can't be copied right away is retried hourly, and a copy
27
+ * with nowhere else to come from is staged in MAIL_STORAGE first.
28
+ */
29
+
30
+ type Entry = typeof mailArchiveEntries.$inferSelect;
31
+
32
+ type Bytes = Uint8Array<ArrayBuffer>;
33
+
34
+ type NewEntry = {
35
+ id: string;
36
+ mailboxId: string;
37
+ direction: ArchiveDirection;
38
+ sourceKey: string | null;
39
+ createdAt: Date;
40
+ };
41
+
42
+ const OPEN = ["pending", "failed"] as const;
43
+
44
+ /** Copies per cron run; about 4 subrequests each. */
45
+ const RETRY_BATCH = 100;
46
+
47
+ /**
48
+ * A copy still failing this long after the message came or went is given
49
+ * up (`abandoned`), so it can't hold the retries of newer ones back; it
50
+ * stays listed under Administration → Mail archive with its error.
51
+ */
52
+ const ABANDON_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
53
+
54
+ /** Staging listings an hourly pass goes through, 1,000 copies each. */
55
+ const STAGING_PAGES = 5;
56
+
57
+ /** The message is gone for good: retrying can't archive it. */
58
+ class ArchiveSourceGone extends Error {}
59
+
60
+ async function sha256Hex(bytes: Bytes) {
61
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
62
+
63
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(
64
+ ""
65
+ );
66
+ }
67
+
68
+ /** Records messages to archive; idempotent. */
69
+ async function registerArchiveEntries(env: Env, entries: NewEntry[]) {
70
+ const db = createDb(env.DB);
71
+ const updatedAt = new Date();
72
+
73
+ await Promise.all(
74
+ insertRowSlices(mailArchiveEntries, entries).map((part) =>
75
+ db
76
+ .insert(mailArchiveEntries)
77
+ .values(
78
+ part.map((entry) => ({
79
+ ...entry,
80
+ archiveKey: archiveObjectKey(
81
+ entry.direction,
82
+ entry.id,
83
+ entry.createdAt
84
+ ),
85
+ updatedAt,
86
+ }))
87
+ )
88
+ .onConflictDoNothing()
89
+ )
90
+ );
91
+ }
92
+
93
+ /** Records one message; false when the archive is off or D1 refused. Never throws. */
94
+ async function recordEntry(env: Env, entry: NewEntry) {
95
+ if (!env.MAIL_ARCHIVE) return false;
96
+
97
+ try {
98
+ await registerArchiveEntries(env, [entry]);
99
+
100
+ return true;
101
+ } catch (error) {
102
+ // The hourly pass finds a staged copy without a row (adoptStaged).
103
+ console.error(`Could not record ${entry.id} for the mail archive`, error);
104
+
105
+ return false;
106
+ }
107
+ }
108
+
109
+ /** Writes the object once; an object already there must be this one. */
110
+ async function writeArchive(
111
+ bucket: R2Bucket,
112
+ target: { archiveKey: string; mailboxId: string; direction: string },
113
+ bytes: Bytes
114
+ ) {
115
+ const sha256 = await sha256Hex(bytes);
116
+
117
+ const written = await bucket.put(target.archiveKey, bytes, {
118
+ httpMetadata: { contentType: "message/rfc822" },
119
+ customMetadata: {
120
+ sha256,
121
+ mailboxId: target.mailboxId,
122
+ direction: target.direction,
123
+ },
124
+ sha256,
125
+ onlyIf: { etagDoesNotMatch: "*" },
126
+ });
127
+
128
+ // Already there, e.g. an earlier try stored it before it could record so.
129
+ if (!written) {
130
+ const existing = await bucket.head(target.archiveKey);
131
+
132
+ if (existing?.customMetadata?.sha256 !== sha256) {
133
+ throw new Error(
134
+ `${target.archiveKey} is already archived with different content`
135
+ );
136
+ }
137
+ }
138
+
139
+ return sha256;
140
+ }
141
+
142
+ async function storedBytes(env: Env, entry: Entry) {
143
+ const object =
144
+ entry.sourceKey && (await env.MAIL_STORAGE.get(entry.sourceKey));
145
+
146
+ if (object) return new Uint8Array(await object.arrayBuffer());
147
+
148
+ if (entry.direction === "outgoing") {
149
+ // The send may still be writing its copy. No other attempt can attest to it.
150
+ throw new Error("No saved copy for this send attempt");
151
+ }
152
+
153
+ throw new ArchiveSourceGone("The message is missing from mail storage");
154
+ }
155
+
156
+ /**
157
+ * A retried copy's source under a mailbox that was deleted meanwhile: the
158
+ * mailbox kept it only until it was archived or given up on
159
+ * (mailbox-deletion.ts), so nothing else deletes it.
160
+ */
161
+ async function deleteOrphanedSource(env: Env, sourceKey: string) {
162
+ const owner = objectMailboxId(sourceKey);
163
+
164
+ if (!owner) return;
165
+
166
+ try {
167
+ const [exists] = await createDb(env.DB)
168
+ .select({ id: mailboxes.id })
169
+ .from(mailboxes)
170
+ .where(eq(mailboxes.id, owner))
171
+ .limit(1);
172
+
173
+ if (!exists) await env.MAIL_STORAGE.delete(sourceKey);
174
+ } catch (error) {
175
+ console.error(`Could not clean up ${sourceKey} for the archive`, error);
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Copies one recorded message. Never throws: a failure is recorded for
181
+ * Administration → Mail archive and retried. `load` defaults to the stored
182
+ * copy.
183
+ */
184
+ async function archiveEntry(env: Env, id: string, load?: () => Promise<Bytes>) {
185
+ const bucket = env.MAIL_ARCHIVE;
186
+
187
+ if (!bucket) return false;
188
+ const db = createDb(env.DB);
189
+ let createdAt: Date | null = null;
190
+ let stagingKey: string | null = null;
191
+ let mailboxSource: string | null = null;
192
+
193
+ try {
194
+ const [entry] = await db
195
+ .select()
196
+ .from(mailArchiveEntries)
197
+ .where(eq(mailArchiveEntries.id, id))
198
+ .limit(1);
199
+
200
+ if (!entry) throw new Error("The message is not recorded for archiving");
201
+
202
+ if (entry.status === "archived") return true;
203
+ createdAt = entry.createdAt;
204
+
205
+ if (entry.sourceKey?.startsWith(ARCHIVE_STAGING_PREFIX)) {
206
+ stagingKey = entry.sourceKey;
207
+ } else {
208
+ mailboxSource = entry.sourceKey;
209
+ }
210
+
211
+ const bytes = await (load ? load() : storedBytes(env, entry));
212
+ const sha256 = await writeArchive(bucket, entry, bytes);
213
+ const now = new Date();
214
+
215
+ await db
216
+ .update(mailArchiveEntries)
217
+ .set({
218
+ status: "archived",
219
+ sha256,
220
+ size: bytes.byteLength,
221
+ lastError: null,
222
+ archivedAt: now,
223
+ updatedAt: now,
224
+ })
225
+ .where(eq(mailArchiveEntries.id, id));
226
+
227
+ if (entry.sourceKey?.startsWith(ARCHIVE_STAGING_PREFIX)) {
228
+ await env.MAIL_STORAGE.delete(entry.sourceKey).catch(() => undefined);
229
+ } else if (!load && entry.sourceKey) {
230
+ await deleteOrphanedSource(env, entry.sourceKey);
231
+ }
232
+
233
+ return true;
234
+ } catch (error) {
235
+ const message = (
236
+ error instanceof Error ? error.message : String(error)
237
+ ).slice(0, 500);
238
+
239
+ console.error("Mail archive copy failed", id, message);
240
+
241
+ const abandoned =
242
+ error instanceof ArchiveSourceGone ||
243
+ (createdAt !== null &&
244
+ Date.now() - createdAt.getTime() >= ABANDON_AFTER_MS);
245
+
246
+ // A staged copy given up on isn't kept, nor a deleted mailbox's copy,
247
+ // which it kept only for the archive.
248
+ if (abandoned && stagingKey) {
249
+ await env.MAIL_STORAGE.delete(stagingKey).catch(() => undefined);
250
+ } else if (abandoned && mailboxSource) {
251
+ await deleteOrphanedSource(env, mailboxSource);
252
+ }
253
+
254
+ await db
255
+ .update(mailArchiveEntries)
256
+ .set({
257
+ status: abandoned ? "abandoned" : "failed",
258
+ attempts: sql`${mailArchiveEntries.attempts} + 1`,
259
+ lastError: message,
260
+ updatedAt: new Date(),
261
+ })
262
+ .where(
263
+ and(
264
+ eq(mailArchiveEntries.id, id),
265
+ inArray(mailArchiveEntries.status, OPEN)
266
+ )
267
+ )
268
+ .then(
269
+ () => undefined,
270
+ () => console.error("Could not record the archive failure", id)
271
+ );
272
+
273
+ return false;
274
+ }
275
+ }
276
+
277
+ const stagedMetadata = z.object({
278
+ mailboxId: z.string(),
279
+ direction: z.enum(["incoming", "outgoing"]),
280
+ createdAt: z.coerce.number(),
281
+ });
282
+
283
+ /**
284
+ * Archives a message as it is received or sent. Never throws. A copy that
285
+ * fails with nowhere to retry from (sent mail, or a message D1 couldn't
286
+ * record) is staged in MAIL_STORAGE, where the hourly pass finds it.
287
+ */
288
+ async function archiveNow(
289
+ env: Env,
290
+ entry: NewEntry,
291
+ bytes: Bytes,
292
+ recorded: boolean
293
+ ) {
294
+ const bucket = env.MAIL_ARCHIVE;
295
+
296
+ if (!bucket) return;
297
+
298
+ if (recorded) {
299
+ if (await archiveEntry(env, entry.id, () => Promise.resolve(bytes))) {
300
+ return;
301
+ }
302
+
303
+ if (entry.sourceKey) return;
304
+ } else {
305
+ // No row: archive it now, and stage it all the same, so the hourly pass
306
+ // gives it its row (or retries the copy).
307
+ try {
308
+ const archiveKey = archiveObjectKey(
309
+ entry.direction,
310
+ entry.id,
311
+ entry.createdAt
312
+ );
313
+
314
+ await writeArchive(bucket, { ...entry, archiveKey }, bytes);
315
+ } catch (error) {
316
+ console.error(`Mail archive copy of ${entry.id} failed`, error);
317
+ }
318
+ }
319
+
320
+ const stagingKey = archiveStagingKey(entry.id);
321
+
322
+ try {
323
+ await env.MAIL_STORAGE.put(stagingKey, bytes, {
324
+ httpMetadata: { contentType: "message/rfc822" },
325
+ customMetadata: {
326
+ mailboxId: entry.mailboxId,
327
+ direction: entry.direction,
328
+ createdAt: String(entry.createdAt.getTime()),
329
+ },
330
+ });
331
+
332
+ if (recorded) {
333
+ await createDb(env.DB)
334
+ .update(mailArchiveEntries)
335
+ .set({ sourceKey: stagingKey })
336
+ .where(eq(mailArchiveEntries.id, entry.id));
337
+ }
338
+ } catch (error) {
339
+ console.error(`Could not stage ${entry.id} for the mail archive`, error);
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Received mail: recorded before the delivery is stored, so a retry finds
345
+ * its raw copy and the purge keeps that copy until it's archived, then
346
+ * copied. `store` stores it; only its errors reach the caller. Mail that
347
+ * isn't stored (a forward's) has no `sourceKey` and no `store`: a copy
348
+ * that fails is staged like sent mail.
349
+ */
350
+ export async function receiveArchived(
351
+ env: Env,
352
+ delivery: {
353
+ id: string;
354
+ mailboxId: string;
355
+ sourceKey: string | null;
356
+ receivedAt: number;
357
+ },
358
+ raw: ArrayBuffer,
359
+ store?: () => Promise<void>
360
+ ) {
361
+ const entry: NewEntry = {
362
+ id: delivery.id,
363
+ mailboxId: delivery.mailboxId,
364
+ direction: "incoming",
365
+ sourceKey: delivery.sourceKey,
366
+ createdAt: new Date(delivery.receivedAt),
367
+ };
368
+
369
+ const recorded = await recordEntry(env, entry);
370
+ await store?.();
371
+ await archiveNow(env, entry, new Uint8Array(raw), recorded);
372
+ }
373
+
374
+ /**
375
+ * Every message the workspace sends goes through here: it hands `message`
376
+ * to Email Sending and keeps exactly that as sent, with the Message-ID it
377
+ * got back (`sentEml`) and the time it was sent. A stored message keeps it
378
+ * at `sent.rawKey` (its `rawMimeR2Key`, which backups, JMAP and the archive
379
+ * read); the archive copies it too. The archive entry is recorded before
380
+ * sending, so the hourly pass can retry from this attempt's saved bytes.
381
+ * Keeping and archiving never fail the send. `sent.id` names one attempt.
382
+ * `onSent` runs as soon as Email Sending took the message, before it is
383
+ * kept and archived: a stored message records it was sent there, so the
384
+ * copies don't widen the window in which it looks unsent.
385
+ */
386
+ export async function sendArchived(
387
+ env: Env,
388
+ sent: { id: string; mailboxId: string; rawKey?: string },
389
+ message: SentMessage,
390
+ onSent?: (result: { messageId: string }) => void
391
+ ) {
392
+ const entry: NewEntry | null = env.MAIL_ARCHIVE
393
+ ? {
394
+ id: sent.id,
395
+ mailboxId: sent.mailboxId,
396
+ direction: "outgoing",
397
+ sourceKey: sent.rawKey ?? null,
398
+ createdAt: new Date(),
399
+ }
400
+ : null;
401
+
402
+ const recorded = entry ? await recordEntry(env, entry) : false;
403
+ let result: Awaited<ReturnType<Env["EMAIL"]["send"]>>;
404
+
405
+ try {
406
+ result = await env.EMAIL.send(message);
407
+ } catch (error) {
408
+ // No copy of this attempt will ever exist: the row would wait a week and
409
+ // then show as a lost copy. A resend is an attempt of its own.
410
+ if (recorded) {
411
+ await createDb(env.DB)
412
+ .delete(mailArchiveEntries)
413
+ .where(eq(mailArchiveEntries.id, sent.id))
414
+ .catch((cause: unknown) => {
415
+ console.error(`Could not drop ${sent.id} from the archive`, cause);
416
+ });
417
+ }
418
+
419
+ throw error;
420
+ }
421
+
422
+ onSent?.(result);
423
+
424
+ if (!entry && !sent.rawKey) {
425
+ return { ...result, rawKey: null, rawSize: null, sentAt: null };
426
+ }
427
+
428
+ const sentAt = entry?.createdAt ?? new Date();
429
+ let bytes: Bytes;
430
+
431
+ try {
432
+ bytes = sentEml(
433
+ { id: sent.id, date: sentAt, messageId: result.messageId },
434
+ message
435
+ );
436
+ } catch (error) {
437
+ console.error(`Could not keep sent message ${sent.id}`, error);
438
+
439
+ return { ...result, rawKey: null, rawSize: null, sentAt: null };
440
+ }
441
+
442
+ let rawKey: string | null = null;
443
+
444
+ if (sent.rawKey) {
445
+ try {
446
+ await env.MAIL_STORAGE.put(sent.rawKey, bytes, {
447
+ httpMetadata: { contentType: "message/rfc822" },
448
+ });
449
+ rawKey = sent.rawKey;
450
+ } catch (error) {
451
+ console.error(`Could not keep sent message ${sent.id}`, error);
452
+ }
453
+ }
454
+
455
+ if (entry) {
456
+ try {
457
+ await archiveNow(env, { ...entry, sourceKey: rawKey }, bytes, recorded);
458
+ } catch (error) {
459
+ console.error(`Could not archive sent message ${sent.id}`, error);
460
+ }
461
+ }
462
+
463
+ // The MIME Date header is serialized with second precision.
464
+ return {
465
+ ...result,
466
+ rawKey,
467
+ rawSize: bytes.byteLength,
468
+ sentAt: new Date(Math.floor(sentAt.getTime() / 1000) * 1000),
469
+ };
470
+ }
471
+
472
+ /** Raw copies that must outlive object cleanup until they are archived. */
473
+ export async function keysAwaitingArchive(env: Env, keys: string[]) {
474
+ if (!env.MAIL_ARCHIVE || !keys.length) return new Set<string>();
475
+ const db = createDb(env.DB);
476
+
477
+ const rows = await db
478
+ .select({ key: mailArchiveEntries.sourceKey })
479
+ .from(mailArchiveEntries)
480
+ .where(
481
+ and(
482
+ inJsonList(mailArchiveEntries.sourceKey, keys),
483
+ inArray(mailArchiveEntries.status, OPEN)
484
+ )
485
+ );
486
+
487
+ return new Set(rows.flatMap((row) => (row.key ? [row.key] : [])));
488
+ }
489
+
490
+ /**
491
+ * Tries now the open entries whose copy a mailbox keeps: its own, and a
492
+ * list's archived from its member's copy. The raw copies that still
493
+ * aren't archived, which its deletion keeps.
494
+ */
495
+ export async function archiveMailboxNow(env: Env, mailboxId: string) {
496
+ if (!env.MAIL_ARCHIVE) return new Set<string>();
497
+ const db = createDb(env.DB);
498
+
499
+ const kept = and(
500
+ or(
501
+ eq(mailArchiveEntries.mailboxId, mailboxId),
502
+ like(mailArchiveEntries.sourceKey, `${mailboxPrefix(mailboxId)}%`)
503
+ ),
504
+ inArray(mailArchiveEntries.status, OPEN)
505
+ );
506
+
507
+ const open = await db
508
+ .select({ id: mailArchiveEntries.id })
509
+ .from(mailArchiveEntries)
510
+ .where(kept);
511
+
512
+ for (const { id } of open) {
513
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one message in memory at a time
514
+ await archiveEntry(env, id);
515
+ }
516
+
517
+ const left = await db
518
+ .select({ key: mailArchiveEntries.sourceKey })
519
+ .from(mailArchiveEntries)
520
+ .where(kept);
521
+
522
+ return new Set(left.flatMap((row) => (row.key ? [row.key] : [])));
523
+ }
524
+
525
+ /**
526
+ * Staged copies D1 has no row for, or a row that doesn't point at them yet:
527
+ * a few listings of 1,000 a pass, looked up in D1 together.
528
+ */
529
+ async function adoptStaged(env: Env) {
530
+ const db = createDb(env.DB);
531
+ let cursor: string | undefined;
532
+
533
+ for (let page = 0; page < STAGING_PAGES; page += 1) {
534
+ // oxlint-disable-next-line eslint/no-await-in-loop -- R2 lists one page at a time
535
+ const listing = await env.MAIL_STORAGE.list({
536
+ prefix: ARCHIVE_STAGING_PREFIX,
537
+ cursor,
538
+ include: ["customMetadata"],
539
+ });
540
+
541
+ const staged = listing.objects.flatMap((object) => {
542
+ const metadata = stagedMetadata.safeParse(object.customMetadata);
543
+
544
+ return metadata.success
545
+ ? [
546
+ {
547
+ key: object.key,
548
+ id: object.key.slice(
549
+ ARCHIVE_STAGING_PREFIX.length,
550
+ -".eml".length
551
+ ),
552
+ ...metadata.data,
553
+ },
554
+ ]
555
+ : [];
556
+ });
557
+
558
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
559
+ const rows = await db
560
+ .select({
561
+ id: mailArchiveEntries.id,
562
+ status: mailArchiveEntries.status,
563
+ sourceKey: mailArchiveEntries.sourceKey,
564
+ })
565
+ .from(mailArchiveEntries)
566
+ .where(
567
+ inJsonList(
568
+ mailArchiveEntries.id,
569
+ staged.map((item) => item.id)
570
+ )
571
+ );
572
+
573
+ const byId = new Map(rows.map((row) => [row.id, row]));
574
+ const missing = staged.filter((item) => !byId.has(item.id));
575
+
576
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
577
+ await registerArchiveEntries(
578
+ env,
579
+ missing.map((item) => ({
580
+ id: item.id,
581
+ mailboxId: item.mailboxId,
582
+ direction: item.direction,
583
+ sourceKey: item.key,
584
+ createdAt: new Date(item.createdAt),
585
+ }))
586
+ );
587
+
588
+ // Archived some other way (e.g. the copy landed but D1 didn't hear of
589
+ // it), or given up on: the staged copy has no more use, and left there
590
+ // it would crowd newer ones out of these pages.
591
+ const done = staged.filter((item) => {
592
+ const status = byId.get(item.id)?.status;
593
+
594
+ return status === "archived" || status === "abandoned";
595
+ });
596
+
597
+ if (done.length) {
598
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
599
+ await env.MAIL_STORAGE.delete(done.map((item) => item.key));
600
+ }
601
+
602
+ for (const item of staged) {
603
+ const row = byId.get(item.id);
604
+
605
+ if (
606
+ row &&
607
+ OPEN.some((status) => status === row.status) &&
608
+ row.sourceKey !== item.key
609
+ ) {
610
+ // oxlint-disable-next-line eslint/no-await-in-loop -- rare: a row recorded before its copy was staged
611
+ await db
612
+ .update(mailArchiveEntries)
613
+ .set({ sourceKey: item.key })
614
+ .where(eq(mailArchiveEntries.id, item.id));
615
+ }
616
+ }
617
+
618
+ if (!listing.truncated) return;
619
+ cursor = listing.cursor;
620
+ }
621
+ }
622
+
623
+ /** The hourly cron and "Archive now": retries open entries; `force` skips the backoff. */
624
+ export async function runArchiveTick(
625
+ env: Env,
626
+ now = new Date(),
627
+ force = false
628
+ ) {
629
+ if (!env.MAIL_ARCHIVE) return;
630
+
631
+ try {
632
+ await adoptStaged(env);
633
+ } catch (error) {
634
+ // The retries below don't depend on it.
635
+ console.error("Mail archive could not adopt staged copies", error);
636
+ }
637
+
638
+ const open = await createDb(env.DB)
639
+ .select()
640
+ .from(mailArchiveEntries)
641
+ .where(inArray(mailArchiveEntries.status, OPEN))
642
+ // Least recently tried first, so failing copies take turns with the rest.
643
+ .orderBy(asc(mailArchiveEntries.updatedAt))
644
+ .limit(RETRY_BATCH * 3);
645
+
646
+ const due = open
647
+ .filter((entry) => force || archiveRetryDue(entry, now.getTime()))
648
+ .slice(0, RETRY_BATCH);
649
+
650
+ for (const entry of due) {
651
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one message in memory at a time
652
+ await archiveEntry(env, entry.id);
653
+ }
654
+ }
655
+
656
+ /** Administration → Mail archive. */
657
+ export async function archiveStatus(env: Env) {
658
+ const db = createDb(env.DB);
659
+
660
+ const [counts, open] = await Promise.all([
661
+ db
662
+ .select({
663
+ status: mailArchiveEntries.status,
664
+ count: sql<number>`count(*)`,
665
+ })
666
+ .from(mailArchiveEntries)
667
+ .groupBy(mailArchiveEntries.status),
668
+ db
669
+ .select({
670
+ id: mailArchiveEntries.id,
671
+ mailbox: mailboxAddressSql,
672
+ direction: mailArchiveEntries.direction,
673
+ status: mailArchiveEntries.status,
674
+ attempts: mailArchiveEntries.attempts,
675
+ lastError: mailArchiveEntries.lastError,
676
+ createdAt: mailArchiveEntries.createdAt,
677
+ })
678
+ .from(mailArchiveEntries)
679
+ .leftJoin(mailboxes, eq(mailboxes.id, mailArchiveEntries.mailboxId))
680
+ .where(inArray(mailArchiveEntries.status, [...OPEN, "abandoned"]))
681
+ .orderBy(desc(mailArchiveEntries.createdAt))
682
+ .limit(20),
683
+ ]);
684
+
685
+ const count = (status: Entry["status"]) =>
686
+ Number(counts.find((row) => row.status === status)?.count ?? 0);
687
+
688
+ return {
689
+ enabled: Boolean(env.MAIL_ARCHIVE),
690
+ years: env.MAIL_ARCHIVE_YEARS ? Number(env.MAIL_ARCHIVE_YEARS) : null,
691
+ archived: count("archived"),
692
+ pending: count("pending"),
693
+ failed: count("failed"),
694
+ abandoned: count("abandoned"),
695
+ open: open.map((entry) => ({
696
+ ...entry,
697
+ createdAt: entry.createdAt.getTime(),
698
+ })),
699
+ };
700
+ }