@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
@@ -1,12 +1,13 @@
1
1
  import { createId, normalizeMailboxAddress } from "@open-workspace/core/module";
2
- import type { Address, Email as ParsedEmail } from "postal-mime";
2
+ import type { Address } from "postal-mime";
3
3
 
4
4
  import { headerValues } from "../../shared/mail-headers";
5
- import type { MailAddress, StoredAttachment } from "../mailbox/model";
5
+ import type { StoredAttachment } from "../mailbox/model";
6
6
  import type { Email, NewEmail, PendingInbound } from "../mailbox/schema";
7
7
  import { inboundHeaderMetadata } from "./auth-headers";
8
8
  import { shouldDetachInboundReply } from "./inbound-threading";
9
9
  import { linkDomains, MAX_LINK_DOMAINS } from "./link-domains";
10
+ import { plainBody } from "./plain-body";
10
11
  import { parseReplyText } from "./quote-parser";
11
12
  import {
12
13
  address,
@@ -15,8 +16,9 @@ import {
15
16
  listPostAddress,
16
17
  messageIds,
17
18
  } from "./rfc";
19
+ import { messagePrefix } from "./storage-keys";
18
20
 
19
- function flattenAddresses(values: Address[] | undefined): MailAddress[] {
21
+ function flattenAddresses(values: Address[] | undefined) {
20
22
  return (values ?? []).flatMap((value) =>
21
23
  value.group
22
24
  ? value.group.map((mailbox) => address(mailbox.address, mailbox.name))
@@ -80,7 +82,23 @@ export function inboundMessageId(deliveryId: string) {
80
82
  */
81
83
  const postalMime = () => import("postal-mime").then((module) => module.default);
82
84
 
83
- async function parseMime(bytes: ArrayBuffer): Promise<ParsedEmail> {
85
+ /**
86
+ * The From address of a raw message, parsed from its headers alone (as
87
+ * delivery parses it); null without one or when the headers don't parse.
88
+ */
89
+ export async function rawFromAddress(rawMime: ArrayBuffer) {
90
+ const PostalMime = await postalMime();
91
+
92
+ try {
93
+ return (
94
+ (await PostalMime.parse(rawHeaderText(rawMime))).from?.address || null
95
+ );
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ async function parseMime(bytes: ArrayBuffer) {
84
102
  const PostalMime = await postalMime();
85
103
 
86
104
  try {
@@ -109,7 +127,7 @@ export function prepareUnprocessableInboundEmail(input: {
109
127
  job: PendingInbound;
110
128
  reason: string;
111
129
  rawMimeR2Key: string | null;
112
- }): NewEmail {
130
+ }) {
113
131
  const messageId = inboundMessageId(input.job.id);
114
132
  const fromAddress = input.job.envelopeFrom || "unknown@invalid";
115
133
 
@@ -145,7 +163,7 @@ export function prepareUnprocessableInboundEmail(input: {
145
163
  timelineAt: input.job.receivedAt,
146
164
  transportState: "received",
147
165
  deliveryStatusJson: [],
148
- };
166
+ } satisfies NewEmail;
149
167
  }
150
168
 
151
169
  /** What parsing a delivery reads of it: a queued delivery, or an imported message. */
@@ -159,15 +177,31 @@ export type InboundMessageSource = Pick<
159
177
  | "receivedAt"
160
178
  >;
161
179
 
180
+ /**
181
+ * Text bodies live in the mailbox's SQLite rows (HTML and attachments in
182
+ * R2), and a row must stay well under the Durable Object's 2 MB limit: a
183
+ * plain-text body beyond this is cut (the raw message keeps all of it).
184
+ */
185
+ const MAX_STORED_TEXT_CHARACTERS = 200_000;
186
+
187
+ function clampText(value: string | null) {
188
+ return value && value.length > MAX_STORED_TEXT_CHARACTERS
189
+ ? value.slice(0, MAX_STORED_TEXT_CHARACTERS)
190
+ : value;
191
+ }
192
+
162
193
  export async function prepareInboundEmail(input: {
163
194
  env: Env;
164
195
  mailboxId: string;
165
196
  job: InboundMessageSource;
166
197
  rawMime: ArrayBuffer;
198
+ /** The source thread groups imported messages even when their parent arrives later. */
199
+ fallbackConversationId?: string | null;
167
200
  resolveParent: (inReplyTo: string[], references: string[]) => Email | null;
168
- }): Promise<{ email: NewEmail; linkDomains: string[] }> {
201
+ }) {
169
202
  const { job } = input;
170
203
  const parsed = await parseMime(input.rawMime);
204
+ const sentAt = Date.parse(parsed.date ?? "");
171
205
  const inReplyTo = messageIds(parsed.inReplyTo);
172
206
  const references = messageIds(parsed.references);
173
207
  const parent = input.resolveParent(inReplyTo, references);
@@ -202,22 +236,10 @@ export async function prepareInboundEmail(input: {
202
236
 
203
237
  const messageId = inboundMessageId(job.id);
204
238
 
205
- const plainBody = parsed.text?.trim()
206
- ? parsed.text
207
- : parsed.html
208
- ? (await import("html-to-text")).convert(parsed.html, {
209
- wordwrap: false,
210
- selectors: [
211
- { selector: "img", format: "skip" },
212
- { selector: "style", format: "skip" },
213
- ],
214
- })
215
- : "";
216
-
217
- const replyText = parseReplyText(plainBody);
239
+ const replyText = parseReplyText(plainBody(parsed.text, parsed.html));
218
240
 
219
241
  const bodyHtmlR2Key = parsed.html
220
- ? `mailboxes/${input.mailboxId}/messages/${messageId}/body.html`
242
+ ? `${messagePrefix(input.mailboxId, messageId)}body.html`
221
243
  : null;
222
244
 
223
245
  if (bodyHtmlR2Key && parsed.html) {
@@ -228,9 +250,9 @@ export async function prepareInboundEmail(input: {
228
250
 
229
251
  // Each attachment is its own R2 object, so they are stored concurrently.
230
252
  const attachments = await Promise.all(
231
- parsed.attachments.map(async (file, index): Promise<StoredAttachment> => {
253
+ parsed.attachments.map(async (file, index) => {
232
254
  const id = `att_${messageId}_${index}`;
233
- const r2Key = `mailboxes/${input.mailboxId}/messages/${messageId}/attachments/${id}`;
255
+ const r2Key = `${messagePrefix(input.mailboxId, messageId)}attachments/${id}`;
234
256
  const bytes = attachmentBytes(file.content);
235
257
  await input.env.MAIL_STORAGE.put(r2Key, bytes, {
236
258
  httpMetadata: { contentType: file.mimeType },
@@ -247,14 +269,16 @@ export async function prepareInboundEmail(input: {
247
269
  delivery: "attached",
248
270
  downloadTokenHash: null,
249
271
  downloadExpiresAt: null,
250
- };
272
+ } satisfies StoredAttachment;
251
273
  })
252
274
  );
253
275
 
254
276
  const email: NewEmail = {
255
277
  id: messageId,
256
278
  conversationId:
257
- parent && !detached ? parent.conversationId : createId("conv"),
279
+ parent && !detached
280
+ ? parent.conversationId
281
+ : (input.fallbackConversationId ?? createId("conv")),
258
282
  direction: "incoming",
259
283
  messageIdHeader: messageIds(parsed.messageId)[0] ?? null,
260
284
  inReplyToJson: inReplyTo,
@@ -265,11 +289,17 @@ export async function prepareInboundEmail(input: {
265
289
  ccJson: cc,
266
290
  bccJson: bcc,
267
291
  subject: parsed.subject?.trim() || "(no subject)",
268
- preview: replyText.bodyText.replaceAll(/\s+/gu, " ").trim().slice(0, 220),
269
- bodyText: replyText.bodyText,
270
- quotedText: replyText.quotedText,
292
+ // A message that is all quote (a bare forward) previews the quote.
293
+ preview: (replyText.bodyText || replyText.quotedText || "")
294
+ .replaceAll(/\s+/gu, " ")
295
+ .trim()
296
+ .slice(0, 220),
297
+ bodyText: clampText(replyText.bodyText),
298
+ quotedText: clampText(replyText.quotedText),
271
299
  bodyHtmlR2Key,
272
300
  rawMimeR2Key: job.rawObjectKey,
301
+ rawSize: input.rawMime.byteLength,
302
+ sentAt: Number.isFinite(sentAt) ? new Date(sentAt) : null,
273
303
  attachmentsJson: attachments,
274
304
  listId: parsedListId,
275
305
  listPostAddress: parsedListPost,
@@ -96,10 +96,7 @@ export function parseCymruAsName(value: string) {
96
96
  return name.slice(0, 120) || null;
97
97
  }
98
98
 
99
- async function ptrIntel(
100
- resolve: DnsResolver,
101
- ip: string
102
- ): Promise<IpIntel["ptr"]> {
99
+ async function ptrIntel(resolve: DnsResolver, ip: string) {
103
100
  const answer = await resolve(reverseDnsName(ip), "PTR");
104
101
  const names = [...new Set(answer.records)].filter(Boolean).slice(0, 5);
105
102
  const [firstName] = names;
@@ -112,7 +109,7 @@ async function ptrIntel(
112
109
  fcrdns:
113
110
  answer.status === "ok" || answer.status === "nxdomain" ? false : null,
114
111
  generic: null,
115
- };
112
+ } satisfies IpIntel["ptr"];
116
113
  }
117
114
 
118
115
  const forwardType = ip.includes(":") ? "AAAA" : "A";
@@ -141,13 +138,10 @@ async function ptrIntel(
141
138
  confirmed,
142
139
  fcrdns: confirmed ? true : answered ? false : null,
143
140
  generic: isGenericPtr(confirmed ?? firstName, ip),
144
- };
141
+ } satisfies IpIntel["ptr"];
145
142
  }
146
143
 
147
- async function networkIntel(
148
- resolve: DnsResolver,
149
- ip: string
150
- ): Promise<IpIntel["network"]> {
144
+ async function networkIntel(resolve: DnsResolver, ip: string) {
151
145
  const empty = {
152
146
  asn: null,
153
147
  asName: null,
@@ -167,7 +161,7 @@ async function networkIntel(
167
161
  return {
168
162
  status: origin.status === "ok" ? "nxdomain" : origin.status,
169
163
  ...empty,
170
- };
164
+ } satisfies IpIntel["network"];
171
165
  }
172
166
 
173
167
  const name = await resolve(`AS${parsed.asn}.asn.cymru.com`, "TXT");
@@ -176,20 +170,17 @@ async function networkIntel(
176
170
  status: "ok",
177
171
  ...parsed,
178
172
  asName: name.records.map(parseCymruAsName).find(Boolean) ?? null,
179
- };
173
+ } satisfies IpIntel["network"];
180
174
  }
181
175
 
182
176
  /** PTR → forward confirmation and Team Cymru origin → AS name, in parallel. */
183
- export async function lookupIpIntel(
184
- resolve: DnsResolver,
185
- ip: string
186
- ): Promise<IpIntel> {
177
+ export async function lookupIpIntel(resolve: DnsResolver, ip: string) {
187
178
  const [ptr, network] = await Promise.all([
188
179
  ptrIntel(resolve, ip),
189
180
  networkIntel(resolve, ip),
190
181
  ]);
191
182
 
192
- return { ptr, network };
183
+ return { ptr, network } satisfies IpIntel;
193
184
  }
194
185
 
195
186
  export function heloMatchesPtr(helo: string | null, ptr: IpIntel["ptr"]) {
@@ -11,7 +11,7 @@ export function isolateCache<T>(
11
11
  let entry: { value: Promise<T>; expiresAt: number } | null = null;
12
12
 
13
13
  return {
14
- get(binding: D1Database): Promise<T> {
14
+ get(binding: D1Database) {
15
15
  const now = Date.now();
16
16
 
17
17
  if (entry && entry.expiresAt > now) return entry.value;
@@ -1,24 +1,45 @@
1
1
  import { mailboxStub } from "../mailbox";
2
- import { repeatUntil } from "./repeat";
2
+ import { archiveMailboxNow } from "./archive";
3
+ import { deleteRichImages } from "./rich-content";
4
+ import { signatureImagePrefix } from "./signatures";
5
+ import { mailboxPrefix } from "./storage-keys";
3
6
 
4
- /** Deletes the mailbox's objects a page at a time, until a listing comes back empty. */
5
- async function deleteMailboxObjects(bucket: R2Bucket, mailboxId: string) {
6
- const prefix = `mailboxes/${mailboxId}/`;
7
+ /**
8
+ * Deletes the mailbox's objects a page at a time, except raw copies the
9
+ * mail archive doesn't have yet (`keep`): those stay in the bucket.
10
+ */
11
+ async function deleteMailboxObjects(
12
+ bucket: R2Bucket,
13
+ mailboxId: string,
14
+ keep: Set<string>
15
+ ) {
16
+ const prefix = mailboxPrefix(mailboxId);
17
+ let cursor: string | undefined;
7
18
 
8
- await repeatUntil(Number.POSITIVE_INFINITY, async () => {
9
- const page = await bucket.list({ prefix, limit: 1000 });
10
- const keys = page.objects.map((object) => object.key);
19
+ do {
20
+ // oxlint-disable-next-line eslint/no-await-in-loop -- R2 lists one page at a time
21
+ const page = await bucket.list({ prefix, limit: 1000, cursor });
11
22
 
12
- if (!keys.length) return true;
13
- await bucket.delete(keys);
23
+ const keys = page.objects
24
+ .map((object) => object.key)
25
+ .filter((key) => !keep.has(key));
14
26
 
15
- return undefined;
16
- });
27
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
28
+ if (keys.length) await bucket.delete(keys);
29
+ cursor = page.truncated ? page.cursor : undefined;
30
+ } while (cursor);
17
31
  }
18
32
 
19
33
  export async function deleteMailboxStorage(env: Env, mailboxId: string) {
34
+ // Archive what's still open first, so its raw copies can go too. Those
35
+ // that still fail stay until the archive's retry copies them, which then
36
+ // deletes them.
37
+ const keep = await archiveMailboxNow(env, mailboxId);
38
+
20
39
  await Promise.all([
21
40
  mailboxStub(env, mailboxId).deleteMailboxData(),
22
- deleteMailboxObjects(env.MAIL_STORAGE, mailboxId),
41
+ deleteMailboxObjects(env.MAIL_STORAGE, mailboxId, keep),
42
+ // The signature's row goes with the mailbox's (foreign key); its images here.
43
+ deleteRichImages(env.MAIL_STORAGE, signatureImagePrefix(mailboxId)),
23
44
  ]);
24
45
  }
@@ -1,8 +1,6 @@
1
- type ActiveMailboxSessionRow = {
2
- id: string;
3
- token_hash: string;
4
- user_id: string;
5
- };
1
+ import { createDb, inJsonList } from "@open-workspace/core/module";
2
+ import { mailboxAccess, sessions, users } from "@open-workspace/core/schema";
3
+ import { and, eq, gt } from "drizzle-orm";
6
4
 
7
5
  export type ActiveMailboxSession = {
8
6
  id: string;
@@ -10,74 +8,50 @@ export type ActiveMailboxSession = {
10
8
  userId: string;
11
9
  };
12
10
 
13
- type MailboxUserRow = {
14
- id: string;
15
- name: string;
16
- };
17
-
18
- function idList(ids: string[]) {
19
- return JSON.stringify([...new Set(ids)]);
20
- }
21
-
22
- export async function listActiveMailboxSessions(
23
- db: D1Database,
11
+ export function listActiveMailboxSessions(
12
+ binding: D1Database,
24
13
  mailboxId: string,
25
14
  sessionIds: string[],
26
15
  now: number
27
- ): Promise<ActiveMailboxSession[]> {
28
- if (!sessionIds.length) return [];
29
-
30
- // D1 allows only 100 bound parameters, so the complete ID set is bound as
31
- // one JSON value and expanded by SQLite instead of generating a large IN.
32
- const result = await db
33
- .prepare(`
34
- with requested_sessions(id) as (
35
- select cast(value as text) from json_each(?)
16
+ ) {
17
+ if (!sessionIds.length) return Promise.resolve([]);
18
+
19
+ return createDb(binding)
20
+ .select({
21
+ id: sessions.id,
22
+ tokenHash: sessions.tokenHash,
23
+ userId: sessions.userId,
24
+ })
25
+ .from(sessions)
26
+ .innerJoin(users, eq(users.id, sessions.userId))
27
+ .innerJoin(mailboxAccess, eq(mailboxAccess.userId, sessions.userId))
28
+ .where(
29
+ and(
30
+ inJsonList(sessions.id, sessionIds),
31
+ eq(mailboxAccess.mailboxId, mailboxId),
32
+ gt(sessions.expiresAt, new Date(now)),
33
+ eq(users.status, "active")
34
+ )
36
35
  )
37
- select
38
- session.id,
39
- session.token_hash,
40
- session.user_id
41
- from requested_sessions requested
42
- inner join sessions session on session.id = requested.id
43
- inner join users user on user.id = session.user_id
44
- inner join mailbox_access member
45
- on member.user_id = session.user_id
46
- and member.mailbox_id = ?
47
- where session.expires_at > ?
48
- and user.status = 'active'
49
- `)
50
- .bind(idList(sessionIds), mailboxId, now)
51
- .all<ActiveMailboxSessionRow>();
52
-
53
- return result.results.map((session) => ({
54
- id: session.id,
55
- tokenHash: session.token_hash,
56
- userId: session.user_id,
57
- }));
36
+ .all();
58
37
  }
59
38
 
60
- export async function listMailboxUsersByIds(
61
- db: D1Database,
39
+ export function listMailboxUsersByIds(
40
+ binding: D1Database,
62
41
  mailboxId: string,
63
42
  userIds: string[]
64
43
  ) {
65
- if (!userIds.length) return [];
66
-
67
- const result = await db
68
- .prepare(`
69
- with requested_users(id) as (
70
- select cast(value as text) from json_each(?)
44
+ if (!userIds.length) return Promise.resolve([]);
45
+
46
+ return createDb(binding)
47
+ .select({ id: users.id, name: users.name })
48
+ .from(mailboxAccess)
49
+ .innerJoin(users, eq(users.id, mailboxAccess.userId))
50
+ .where(
51
+ and(
52
+ eq(mailboxAccess.mailboxId, mailboxId),
53
+ inJsonList(mailboxAccess.userId, userIds)
54
+ )
71
55
  )
72
- select user.id, user.name
73
- from requested_users requested
74
- inner join mailbox_access member
75
- on member.user_id = requested.id
76
- and member.mailbox_id = ?
77
- inner join users user on user.id = member.user_id
78
- `)
79
- .bind(idList(userIds), mailboxId)
80
- .all<MailboxUserRow>();
81
-
82
- return result.results;
56
+ .all();
83
57
  }
@@ -1,24 +1,26 @@
1
1
  import {
2
2
  createDb,
3
3
  mailboxAddressSql,
4
- mailboxAccess,
5
- mailboxes,
6
- teamMembership,
7
- users,
8
4
  emailDomain,
9
5
  normalizeEmail,
10
6
  normalizeMailboxAddress,
11
7
  } from "@open-workspace/core/module";
8
+ import {
9
+ mailboxAccess,
10
+ mailboxes,
11
+ teamMembership,
12
+ users,
13
+ } from "@open-workspace/core/schema";
12
14
  import type { ListPostingPolicy } from "@open-workspace/core/shared";
13
15
  import { and, eq, sql } from "drizzle-orm";
14
16
 
15
- import { mailboxStub } from "../mailbox";
16
17
  import { parseInboundAuthentication } from "./auth-headers";
17
- import { rawHeaderText } from "./inbound";
18
- import { inboundDeliveryId } from "./inbound-delivery";
18
+ import { rawFromAddress, rawHeaderText } from "./inbound";
19
19
 
20
20
  export type MailingList = {
21
21
  id: string;
22
+ /** The list's own address, not an alias or plus address mail came by. */
23
+ address: string;
22
24
  teamId: string;
23
25
  listPosting: ListPostingPolicy;
24
26
  };
@@ -49,15 +51,7 @@ async function memberMailboxIds(db: D1Database, teamId: string) {
49
51
  * Cloudflare. Anything else may be forged and grants no posting rights.
50
52
  */
51
53
  async function verifiedSender(rawMime: ArrayBuffer) {
52
- let from: string | null = null;
53
-
54
- try {
55
- const { default: PostalMime } = await import("postal-mime");
56
- from =
57
- (await PostalMime.parse(rawHeaderText(rawMime))).from?.address ?? null;
58
- } catch {
59
- return null;
60
- }
54
+ const from = await rawFromAddress(rawMime);
61
55
 
62
56
  if (!from) return null;
63
57
 
@@ -86,7 +80,7 @@ async function mayPost(
86
80
  const orm = createDb(db);
87
81
 
88
82
  const [mailbox] = await orm
89
- .select({ id: mailboxes.id })
83
+ .select({ id: mailboxes.id, aliasOf: mailboxes.aliasOf })
90
84
  .from(mailboxes)
91
85
  .where(sql`${mailboxAddressSql} = ${sender}`)
92
86
  .limit(1);
@@ -108,7 +102,8 @@ async function mayPost(
108
102
  )
109
103
  .where(
110
104
  and(
111
- eq(mailboxAccess.mailboxId, mailbox.id),
105
+ // Posting from an alias counts as posting from its mailbox.
106
+ eq(mailboxAccess.mailboxId, mailbox.aliasOf ?? mailbox.id),
112
107
  eq(mailboxAccess.canSend, true)
113
108
  )
114
109
  )
@@ -118,58 +113,34 @@ async function mayPost(
118
113
  }
119
114
 
120
115
  /**
121
- * Copies mail sent to a team's mailing list into each member's own mailbox.
122
- * The copies share one stored original and never leave the workspace.
116
+ * Who gets mail sent to a team's mailing list: each member's own mailbox,
117
+ * with the list's address to mark the copies by (whichever of its
118
+ * addresses the mail was sent to). Null when the post is refused, which
119
+ * this says to the sender. The copies never leave the workspace.
123
120
  */
124
- export async function deliverToList(input: {
121
+ export async function listRecipients(input: {
125
122
  env: Env;
126
123
  list: MailingList;
127
- message: { from: string; to: string; setReject(reason: string): void };
124
+ message: { setReject(reason: string): void };
128
125
  raw: ArrayBuffer;
129
- receivedAt: number;
130
126
  }) {
131
127
  const { env, list, message, raw } = input;
128
+ const listAddress = normalizeMailboxAddress(list.address);
132
129
 
133
130
  if (!(await mayPost(env.DB, list, raw))) {
134
- message.setReject(
135
- `You are not allowed to post to ${normalizeMailboxAddress(message.to)}`
136
- );
131
+ message.setReject(`You are not allowed to post to ${listAddress}`);
137
132
 
138
- return;
133
+ return null;
139
134
  }
140
135
 
141
- const recipients = await memberMailboxIds(env.DB, list.teamId);
136
+ const targets = await memberMailboxIds(env.DB, list.teamId);
142
137
 
143
- if (!recipients.length) return;
144
- const listAddress = normalizeMailboxAddress(message.to);
138
+ // No one would get it: say so rather than accept and lose it.
139
+ if (!targets.length) {
140
+ message.setReject(`${listAddress} has no members`);
145
141
 
146
- const deliveryId = await inboundDeliveryId({
147
- mailboxId: list.id,
148
- envelopeFrom: message.from,
149
- envelopeTo: message.to,
150
- raw,
151
- });
142
+ return null;
143
+ }
152
144
 
153
- const objectKey = `lists/${list.id}/raw/${deliveryId}.eml`;
154
- await Promise.all(
155
- recipients.map(async (mailboxId) =>
156
- mailboxStub(env, mailboxId).enqueueInbound({
157
- id: await inboundDeliveryId({
158
- mailboxId,
159
- envelopeFrom: message.from,
160
- envelopeTo: message.to,
161
- raw,
162
- }),
163
- mailboxId,
164
- rawObjectKey: objectKey,
165
- envelopeFrom: message.from,
166
- envelopeTo: message.to,
167
- listAddress,
168
- receivedAt: input.receivedAt,
169
- })
170
- )
171
- );
172
- await env.MAIL_STORAGE.put(objectKey, raw, {
173
- httpMetadata: { contentType: "message/rfc822" },
174
- });
145
+ return { targets, listAddress };
175
146
  }
@@ -91,7 +91,7 @@ export function securityWarnings(input: {
91
91
  delivery?: DeliveryFacts | null;
92
92
  /** Trusted senders keep only danger-level warnings. */
93
93
  trusted?: boolean;
94
- }): SecurityWarning[] {
94
+ }) {
95
95
  const warnings: SecurityWarning[] = [];
96
96
  const spamhaus = input.intel?.spamhaus;
97
97
  const dbl = spamhaus?.dbl.listings ?? [];
@@ -150,10 +150,17 @@ export function securityWarnings(input: {
150
150
  }
151
151
  }
152
152
 
153
- if (input.authentication?.verdict === "suspicious") {
153
+ const verdict = input.authentication?.verdict;
154
+
155
+ // From the workspace's own domain, mail that isn't proven to be is how a
156
+ // colleague is impersonated: a danger, which trusting them doesn't hide.
157
+ if (
158
+ verdict === "suspicious" ||
159
+ (!input.external && verdict === "unverified")
160
+ ) {
154
161
  warnings.push({
155
162
  kind: "unverified_sender",
156
- severity: "caution",
163
+ severity: input.external ? "caution" : "danger",
157
164
  domain: input.fromDomain,
158
165
  });
159
166
  }
@@ -198,9 +205,13 @@ export function messageSecurity(input: {
198
205
  listId?: string | null;
199
206
  delivery?: DeliveryFacts | null;
200
207
  trusted?: boolean;
201
- }): MessageSecurity {
208
+ }) {
202
209
  const auth = input.authentication;
203
210
 
211
+ // Trusting an address quiets warnings only for mail proven to be from it:
212
+ // spoofed, it is warned about as from anyone.
213
+ const trusted = Boolean(input.trusted) && auth?.verdict === "verified";
214
+
204
215
  const fromDomain =
205
216
  addressDomain(input.fromAddress) ?? auth?.fromDomain ?? null;
206
217
 
@@ -246,10 +257,10 @@ export function messageSecurity(input: {
246
257
  replyTo: input.replyTo,
247
258
  listId: input.listId,
248
259
  delivery: input.delivery,
249
- trusted: input.trusted,
260
+ trusted,
250
261
  }),
251
262
  firstTimeSender: Boolean(
252
- !input.trusted &&
263
+ !trusted &&
253
264
  external &&
254
265
  history &&
255
266
  history.inboundCount <= 1 &&
@@ -260,6 +271,6 @@ export function messageSecurity(input: {
260
271
  replyTo: input.replyTo ?? [],
261
272
  listId: input.listId ?? null,
262
273
  }),
263
- trusted: Boolean(input.trusted),
264
- };
274
+ trusted,
275
+ } satisfies MessageSecurity;
265
276
  }