@open-workspace/email 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,682 @@
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
+ const result = await env.EMAIL.send(message);
404
+ onSent?.(result);
405
+
406
+ if (!entry && !sent.rawKey) {
407
+ return { ...result, rawKey: null, rawSize: null, sentAt: null };
408
+ }
409
+
410
+ const sentAt = entry?.createdAt ?? new Date();
411
+ let bytes: Bytes;
412
+
413
+ try {
414
+ bytes = sentEml(
415
+ { id: sent.id, date: sentAt, messageId: result.messageId },
416
+ message
417
+ );
418
+ } catch (error) {
419
+ console.error(`Could not keep sent message ${sent.id}`, error);
420
+
421
+ return { ...result, rawKey: null, rawSize: null, sentAt: null };
422
+ }
423
+
424
+ let rawKey: string | null = null;
425
+
426
+ if (sent.rawKey) {
427
+ try {
428
+ await env.MAIL_STORAGE.put(sent.rawKey, bytes, {
429
+ httpMetadata: { contentType: "message/rfc822" },
430
+ });
431
+ rawKey = sent.rawKey;
432
+ } catch (error) {
433
+ console.error(`Could not keep sent message ${sent.id}`, error);
434
+ }
435
+ }
436
+
437
+ if (entry) {
438
+ try {
439
+ await archiveNow(env, { ...entry, sourceKey: rawKey }, bytes, recorded);
440
+ } catch (error) {
441
+ console.error(`Could not archive sent message ${sent.id}`, error);
442
+ }
443
+ }
444
+
445
+ // The MIME Date header is serialized with second precision.
446
+ return {
447
+ ...result,
448
+ rawKey,
449
+ rawSize: bytes.byteLength,
450
+ sentAt: new Date(Math.floor(sentAt.getTime() / 1000) * 1000),
451
+ };
452
+ }
453
+
454
+ /** Raw copies that must outlive object cleanup until they are archived. */
455
+ export async function keysAwaitingArchive(env: Env, keys: string[]) {
456
+ if (!env.MAIL_ARCHIVE || !keys.length) return new Set<string>();
457
+ const db = createDb(env.DB);
458
+
459
+ const rows = await db
460
+ .select({ key: mailArchiveEntries.sourceKey })
461
+ .from(mailArchiveEntries)
462
+ .where(
463
+ and(
464
+ inJsonList(mailArchiveEntries.sourceKey, keys),
465
+ inArray(mailArchiveEntries.status, OPEN)
466
+ )
467
+ );
468
+
469
+ return new Set(rows.flatMap((row) => (row.key ? [row.key] : [])));
470
+ }
471
+
472
+ /**
473
+ * Tries now the open entries whose copy a mailbox keeps: its own, and a
474
+ * list's archived from its member's copy. The raw copies that still
475
+ * aren't archived, which its deletion keeps.
476
+ */
477
+ export async function archiveMailboxNow(env: Env, mailboxId: string) {
478
+ if (!env.MAIL_ARCHIVE) return new Set<string>();
479
+ const db = createDb(env.DB);
480
+
481
+ const kept = and(
482
+ or(
483
+ eq(mailArchiveEntries.mailboxId, mailboxId),
484
+ like(mailArchiveEntries.sourceKey, `${mailboxPrefix(mailboxId)}%`)
485
+ ),
486
+ inArray(mailArchiveEntries.status, OPEN)
487
+ );
488
+
489
+ const open = await db
490
+ .select({ id: mailArchiveEntries.id })
491
+ .from(mailArchiveEntries)
492
+ .where(kept);
493
+
494
+ for (const { id } of open) {
495
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one message in memory at a time
496
+ await archiveEntry(env, id);
497
+ }
498
+
499
+ const left = await db
500
+ .select({ key: mailArchiveEntries.sourceKey })
501
+ .from(mailArchiveEntries)
502
+ .where(kept);
503
+
504
+ return new Set(left.flatMap((row) => (row.key ? [row.key] : [])));
505
+ }
506
+
507
+ /**
508
+ * Staged copies D1 has no row for, or a row that doesn't point at them yet:
509
+ * a few listings of 1,000 a pass, looked up in D1 together.
510
+ */
511
+ async function adoptStaged(env: Env) {
512
+ const db = createDb(env.DB);
513
+ let cursor: string | undefined;
514
+
515
+ for (let page = 0; page < STAGING_PAGES; page += 1) {
516
+ // oxlint-disable-next-line eslint/no-await-in-loop -- R2 lists one page at a time
517
+ const listing = await env.MAIL_STORAGE.list({
518
+ prefix: ARCHIVE_STAGING_PREFIX,
519
+ cursor,
520
+ include: ["customMetadata"],
521
+ });
522
+
523
+ const staged = listing.objects.flatMap((object) => {
524
+ const metadata = stagedMetadata.safeParse(object.customMetadata);
525
+
526
+ return metadata.success
527
+ ? [
528
+ {
529
+ key: object.key,
530
+ id: object.key.slice(
531
+ ARCHIVE_STAGING_PREFIX.length,
532
+ -".eml".length
533
+ ),
534
+ ...metadata.data,
535
+ },
536
+ ]
537
+ : [];
538
+ });
539
+
540
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
541
+ const rows = await db
542
+ .select({
543
+ id: mailArchiveEntries.id,
544
+ status: mailArchiveEntries.status,
545
+ sourceKey: mailArchiveEntries.sourceKey,
546
+ })
547
+ .from(mailArchiveEntries)
548
+ .where(
549
+ inJsonList(
550
+ mailArchiveEntries.id,
551
+ staged.map((item) => item.id)
552
+ )
553
+ );
554
+
555
+ const byId = new Map(rows.map((row) => [row.id, row]));
556
+ const missing = staged.filter((item) => !byId.has(item.id));
557
+
558
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
559
+ await registerArchiveEntries(
560
+ env,
561
+ missing.map((item) => ({
562
+ id: item.id,
563
+ mailboxId: item.mailboxId,
564
+ direction: item.direction,
565
+ sourceKey: item.key,
566
+ createdAt: new Date(item.createdAt),
567
+ }))
568
+ );
569
+
570
+ // Archived some other way (e.g. the copy landed but D1 didn't hear of
571
+ // it), or given up on: the staged copy has no more use, and left there
572
+ // it would crowd newer ones out of these pages.
573
+ const done = staged.filter((item) => {
574
+ const status = byId.get(item.id)?.status;
575
+
576
+ return status === "archived" || status === "abandoned";
577
+ });
578
+
579
+ if (done.length) {
580
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
581
+ await env.MAIL_STORAGE.delete(done.map((item) => item.key));
582
+ }
583
+
584
+ for (const item of staged) {
585
+ const row = byId.get(item.id);
586
+
587
+ if (
588
+ row &&
589
+ OPEN.some((status) => status === row.status) &&
590
+ row.sourceKey !== item.key
591
+ ) {
592
+ // oxlint-disable-next-line eslint/no-await-in-loop -- rare: a row recorded before its copy was staged
593
+ await db
594
+ .update(mailArchiveEntries)
595
+ .set({ sourceKey: item.key })
596
+ .where(eq(mailArchiveEntries.id, item.id));
597
+ }
598
+ }
599
+
600
+ if (!listing.truncated) return;
601
+ cursor = listing.cursor;
602
+ }
603
+ }
604
+
605
+ /** The hourly cron and "Archive now": retries open entries; `force` skips the backoff. */
606
+ export async function runArchiveTick(
607
+ env: Env,
608
+ now = new Date(),
609
+ force = false
610
+ ) {
611
+ if (!env.MAIL_ARCHIVE) return;
612
+
613
+ try {
614
+ await adoptStaged(env);
615
+ } catch (error) {
616
+ // The retries below don't depend on it.
617
+ console.error("Mail archive could not adopt staged copies", error);
618
+ }
619
+
620
+ const open = await createDb(env.DB)
621
+ .select()
622
+ .from(mailArchiveEntries)
623
+ .where(inArray(mailArchiveEntries.status, OPEN))
624
+ // Least recently tried first, so failing copies take turns with the rest.
625
+ .orderBy(asc(mailArchiveEntries.updatedAt))
626
+ .limit(RETRY_BATCH * 3);
627
+
628
+ const due = open
629
+ .filter((entry) => force || archiveRetryDue(entry, now.getTime()))
630
+ .slice(0, RETRY_BATCH);
631
+
632
+ for (const entry of due) {
633
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one message in memory at a time
634
+ await archiveEntry(env, entry.id);
635
+ }
636
+ }
637
+
638
+ /** Administration → Mail archive. */
639
+ export async function archiveStatus(env: Env) {
640
+ const db = createDb(env.DB);
641
+
642
+ const [counts, open] = await Promise.all([
643
+ db
644
+ .select({
645
+ status: mailArchiveEntries.status,
646
+ count: sql<number>`count(*)`,
647
+ })
648
+ .from(mailArchiveEntries)
649
+ .groupBy(mailArchiveEntries.status),
650
+ db
651
+ .select({
652
+ id: mailArchiveEntries.id,
653
+ mailbox: mailboxAddressSql,
654
+ direction: mailArchiveEntries.direction,
655
+ status: mailArchiveEntries.status,
656
+ attempts: mailArchiveEntries.attempts,
657
+ lastError: mailArchiveEntries.lastError,
658
+ createdAt: mailArchiveEntries.createdAt,
659
+ })
660
+ .from(mailArchiveEntries)
661
+ .leftJoin(mailboxes, eq(mailboxes.id, mailArchiveEntries.mailboxId))
662
+ .where(inArray(mailArchiveEntries.status, [...OPEN, "abandoned"]))
663
+ .orderBy(desc(mailArchiveEntries.createdAt))
664
+ .limit(20),
665
+ ]);
666
+
667
+ const count = (status: Entry["status"]) =>
668
+ Number(counts.find((row) => row.status === status)?.count ?? 0);
669
+
670
+ return {
671
+ enabled: Boolean(env.MAIL_ARCHIVE),
672
+ years: env.MAIL_ARCHIVE_YEARS ? Number(env.MAIL_ARCHIVE_YEARS) : null,
673
+ archived: count("archived"),
674
+ pending: count("pending"),
675
+ failed: count("failed"),
676
+ abandoned: count("abandoned"),
677
+ open: open.map((entry) => ({
678
+ ...entry,
679
+ createdAt: entry.createdAt.getTime(),
680
+ })),
681
+ };
682
+ }