@open-workspace/email 0.4.2 → 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 (266) 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.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -1,12 +1,10 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
2
 
3
- import {
4
- officePreviewExtension,
5
- officePreviewKey,
6
- } from "../../shared/office-preview";
3
+ import { officePreviewExtension } from "../../shared/office-preview";
7
4
  import { convertOfficeDocument } from "./office-conversion";
8
5
  import type { OfficeConversionResult } from "./office-conversion";
9
6
  import { repeatUntil } from "./repeat";
7
+ import { officePreviewKey } from "./storage-keys";
10
8
 
11
9
  export class OfficePreviewContainer extends DurableObject<Env> {
12
10
  private conversion: Promise<OfficeConversionResult> | null = null;
@@ -28,10 +26,7 @@ export class OfficePreviewContainer extends DurableObject<Env> {
28
26
  }
29
27
  }
30
28
 
31
- private async runConversion(
32
- sourceKey: string,
33
- extension: string
34
- ): Promise<OfficeConversionResult> {
29
+ private async runConversion(sourceKey: string, extension: string) {
35
30
  if (await this.env.MAIL_STORAGE.head(officePreviewKey(sourceKey))) {
36
31
  return "ready";
37
32
  }
@@ -2,7 +2,10 @@ import {
2
2
  LINKED_ATTACHMENT_TEXT_PREFIX,
3
3
  linkedAttachmentTextToken,
4
4
  } from "../../shared/mail";
5
+ import { escapeHtml, quotedContextHtml } from "../../shared/mail-html";
6
+ import type { StoredAttachment } from "../mailbox/model";
5
7
  import type { Email } from "../mailbox/schema";
8
+ import { forwardDownloads } from "./forward-downloads";
6
9
 
7
10
  const MAX_CONTEXT_CHARACTERS = 24_000;
8
11
 
@@ -13,19 +16,14 @@ type ContentSource = Pick<
13
16
  | "ccJson"
14
17
  | "subject"
15
18
  | "timelineAt"
19
+ | "direction"
16
20
  | "bodyText"
21
+ | "quotedText"
17
22
  | "preview"
23
+ | "bodyHtmlR2Key"
24
+ | "requestFingerprint"
18
25
  >;
19
26
 
20
- export function escapeHtml(value: string) {
21
- return value
22
- .replaceAll("&", "&amp;")
23
- .replaceAll("<", "&lt;")
24
- .replaceAll(">", "&gt;")
25
- .replaceAll('"', "&quot;")
26
- .replaceAll("'", "&#039;");
27
- }
28
-
29
27
  function displayAddress(email: ContentSource) {
30
28
  const from = email.fromJson[0];
31
29
 
@@ -34,13 +32,8 @@ function displayAddress(email: ContentSource) {
34
32
  return from.name ? `${from.name} <${from.address}>` : from.address;
35
33
  }
36
34
 
37
- function clippedBody(email: ContentSource) {
38
- const value =
39
- email.bodyText?.trim() || email.preview.trim() || "No text body";
40
-
41
- if (value.length <= MAX_CONTEXT_CHARACTERS) return value;
42
-
43
- return `${value.slice(0, MAX_CONTEXT_CHARACTERS).trimEnd()}\n[Context truncated]`;
35
+ function sourceBody(email: ContentSource) {
36
+ return messageText(email).trim() || email.preview.trim() || "No text body";
44
37
  }
45
38
 
46
39
  function metadataLines(email: ContentSource) {
@@ -58,40 +51,94 @@ function metadataLines(email: ContentSource) {
58
51
  }
59
52
 
60
53
  export function contextForNewRecipient(email: ContentSource) {
61
- return [...metadataLines(email), "", clippedBody(email)].join("\n");
62
- }
54
+ const body = sourceBody(email);
63
55
 
64
- export function forwardedMessageText(email: ContentSource) {
65
- return [
66
- "Forwarded message",
67
- ...metadataLines(email),
68
- "",
69
- clippedBody(email),
70
- ].join("\n");
56
+ const context =
57
+ body.length > MAX_CONTEXT_CHARACTERS
58
+ ? `${body.slice(0, MAX_CONTEXT_CHARACTERS).trimEnd()}\n[Context truncated]`
59
+ : body;
60
+
61
+ return [...metadataLines(email), "", context].join("\n");
71
62
  }
72
63
 
73
- export function forwardedMessageHtml(email: ContentSource) {
74
- const metadata = metadataLines(email)
75
- .map((line) => `<div>${escapeHtml(line)}</div>`)
76
- .join("");
64
+ export function selectedForwardFiles(
65
+ files: StoredAttachment[],
66
+ selection?: readonly string[] | null
67
+ ) {
68
+ if (!selection) return files;
69
+ const selected = new Set(selection);
77
70
 
78
- return `<section data-forwarded-message><strong>Forwarded message</strong>${metadata}<pre style="white-space:pre-wrap">${escapeHtml(clippedBody(email))}</pre></section>`;
71
+ return files.filter((file) => selected.has(file.id));
79
72
  }
80
73
 
81
- export function appendForwardedMessage(
74
+ export async function appendForwardedMessage(
75
+ bucket: R2Bucket,
82
76
  bodyText: string,
83
77
  bodyHtml: string | undefined,
84
- forwarded: ContentSource | null
78
+ forwarded: (ContentSource & Pick<Email, "attachmentsJson">) | null,
79
+ selected: ReadonlyMap<string, string>
85
80
  ) {
86
81
  if (!forwarded) return { bodyText, bodyHtml };
87
- const text = forwardedMessageText(forwarded);
88
- const nextText = `${bodyText.trimEnd()}${bodyText.trimEnd() ? "\n\n" : ""}${text}`;
82
+ const originalText = sourceBody(forwarded);
83
+ let text = originalText;
84
+ let html = "";
85
+
86
+ const stored = forwarded.bodyHtmlR2Key
87
+ ? await bucket.get(forwarded.bodyHtmlR2Key)
88
+ : null;
89
+
90
+ if (forwarded.bodyHtmlR2Key && !stored) {
91
+ throw new Error("Could not load the forwarded message HTML");
92
+ }
93
+
94
+ if (stored) {
95
+ const { forwardHtmlContent } = await import("./forward-html");
96
+ const rich = forwardHtmlContent(await stored.text(), originalText);
97
+
98
+ if (rich) {
99
+ text = rich.text;
100
+ html = rich.html + quotedContextHtml(separateHtmlQuote(forwarded));
101
+ }
102
+ }
103
+
104
+ ({ text, html } = await forwardDownloads(
105
+ text,
106
+ html,
107
+ forwarded.attachmentsJson,
108
+ selected
109
+ ));
110
+
111
+ const metadata = metadataLines(forwarded);
112
+ const quoted = ["Forwarded message", ...metadata, "", text].join("\n");
113
+ const note = bodyText.trimEnd();
114
+ const nextText = note ? `${note}\n\n${quoted}` : quoted;
115
+
116
+ if (!bodyHtml && !html) return { bodyText: nextText, bodyHtml: undefined };
117
+
118
+ const headings = metadata
119
+ .map((line) => `<div>${escapeHtml(line)}</div>`)
120
+ .join("");
121
+
122
+ const pre = (value: string) =>
123
+ `<pre style="white-space:pre-wrap">${escapeHtml(value)}</pre>`;
124
+
125
+ if (!html) {
126
+ html = pre(text);
127
+
128
+ // A plain-text original may contain a file marker in its quoted HTML alternative too.
129
+ for (const id of selected.values()) {
130
+ html = html.replaceAll(
131
+ linkedAttachmentTextToken(id),
132
+ `<span data-linked-attachment="${id}"></span>`
133
+ );
134
+ }
135
+ }
136
+
137
+ const section = `<section data-forwarded-message><strong>Forwarded message</strong>${headings}${html}</section>`;
89
138
 
90
139
  return {
91
140
  bodyText: nextText,
92
- bodyHtml: bodyHtml
93
- ? `${bodyHtml}${forwardedMessageHtml(forwarded)}`
94
- : undefined,
141
+ bodyHtml: (bodyHtml ?? (note ? pre(note) : "")) + section,
95
142
  };
96
143
  }
97
144
 
@@ -109,46 +156,73 @@ export function textWithQuotedContext(
109
156
  return `${bodyText.trimEnd()}${bodyText.trimEnd() ? "\n\n" : ""}${quote}`;
110
157
  }
111
158
 
112
- export function htmlWithQuotedContext(
113
- bodyHtml: string,
114
- quotedText: string | null
159
+ /**
160
+ * A stored message's whole text, as received or sent: the parser keeps an
161
+ * incoming message's text after its first quote apart (`quotedText`), and
162
+ * a sent one quotes what it answers below the person's own text.
163
+ */
164
+ export function messageText(
165
+ email: Pick<Email, "direction" | "bodyText" | "quotedText">
115
166
  ) {
116
- if (!quotedText) return bodyHtml;
167
+ const bodyText = email.bodyText ?? "";
168
+
169
+ if (email.direction === "outgoing") {
170
+ return textWithQuotedContext(bodyText, email.quotedText);
171
+ }
172
+
173
+ // The parser trims both parts: the quote goes back a blank line below.
174
+ return [bodyText, email.quotedText].filter(Boolean).join("\n\n");
175
+ }
117
176
 
118
- return `${bodyHtml}<blockquote><pre style="white-space:pre-wrap">${escapeHtml(quotedText)}</pre></blockquote>`;
177
+ /** A locally composed message keeps its quote apart. Imported MIME already includes it in its HTML. */
178
+ export function separateHtmlQuote(message: {
179
+ requestFingerprint?: string | null;
180
+ quotedText?: string | null;
181
+ }) {
182
+ return message.requestFingerprint ? (message.quotedText ?? null) : null;
119
183
  }
120
184
 
121
- export function externalizeLinkedInlineImages(
185
+ export async function externalizeLinkedInlineImages(
122
186
  bodyHtml: string,
123
187
  attachments: {
188
+ id: string;
124
189
  disposition: "attachment" | "inline";
125
190
  contentId: string | null;
126
191
  filename: string;
127
192
  downloadUrl: string;
128
193
  }[]
129
194
  ) {
130
- let nextHtml = bodyHtml;
131
-
132
- for (const attachment of attachments) {
133
- if (attachment.disposition !== "inline" || !attachment.contentId) continue;
134
-
135
- const escapedContentId = attachment.contentId.replaceAll(
136
- /[.*+?^${}()|[\]\\]/gu,
137
- "\\$&"
138
- );
139
-
140
- const image = new RegExp(
141
- `<img(?=[^>]*\\bsrc=(["'])cid:${escapedContentId}\\1)[^>]*>`,
142
- "giu"
143
- );
144
-
145
- nextHtml = nextHtml.replaceAll(
146
- image,
147
- `<a href="${escapeHtml(attachment.downloadUrl)}">${escapeHtml(attachment.filename)}</a>`
148
- );
149
- }
150
-
151
- return nextHtml;
195
+ const placedIds = new Set<string>();
196
+
197
+ const images = new Map(
198
+ attachments.flatMap((file) =>
199
+ file.disposition === "inline" && file.contentId
200
+ ? [[file.contentId, file] as const]
201
+ : []
202
+ )
203
+ );
204
+
205
+ if (!images.size) return { html: bodyHtml, placedIds };
206
+
207
+ const rewritten = new HTMLRewriter()
208
+ .on("img[src]", {
209
+ element(element) {
210
+ const src = element.getAttribute("src")?.trim();
211
+
212
+ if (!src || !/^cid:/iu.test(src)) return;
213
+ const file = images.get(src.slice(4));
214
+
215
+ if (!file) return;
216
+ element.replace(
217
+ `<a href="${escapeHtml(file.downloadUrl)}">${escapeHtml(file.filename)}</a>`,
218
+ { html: true }
219
+ );
220
+ placedIds.add(file.id);
221
+ },
222
+ })
223
+ .transform(new Response(bodyHtml));
224
+
225
+ return { html: await rewritten.text(), placedIds };
152
226
  }
153
227
 
154
228
  type PositionedLinkedAttachment = {
@@ -1,8 +1,6 @@
1
+ import { quotedContextHtml } from "../../shared/mail-html";
1
2
  import type { Email } from "../mailbox/schema";
2
- import {
3
- htmlWithQuotedContext,
4
- textWithQuotedContext,
5
- } from "./outbound-content";
3
+ import { separateHtmlQuote, textWithQuotedContext } from "./outbound-content";
6
4
  import { dedupeRecipientFields } from "./recipients";
7
5
 
8
6
  export function emailDestinations(
@@ -14,15 +12,16 @@ export function emailDestinations(
14
12
  bcc: message.bccJson.map((item) => item.address),
15
13
  });
16
14
 
17
- if (to.length) {
18
- return {
19
- to,
20
- cc: cc.length ? cc : undefined,
21
- bcc: bcc.length ? bcc : undefined,
22
- };
23
- }
15
+ // Email Sending needs a recipient in To, Cc or Bcc, not a To: an empty
16
+ // one is left out.
17
+ const copies = {
18
+ cc: cc.length ? cc : undefined,
19
+ bcc: bcc.length ? bcc : undefined,
20
+ };
21
+
22
+ if (to.length) return { to, ...copies };
24
23
 
25
- if (cc.length) return { cc, bcc: bcc.length ? bcc : undefined };
24
+ if (cc.length) return { cc, bcc: copies.bcc };
26
25
 
27
26
  if (bcc.length) return { bcc };
28
27
  throw new Error("Queued message has no recipients");
@@ -36,7 +35,7 @@ export async function prepareOutboundDelivery(env: Env, message: Email) {
36
35
  : undefined;
37
36
 
38
37
  const html = storedHtml
39
- ? htmlWithQuotedContext(storedHtml, message.quotedText)
38
+ ? storedHtml + quotedContextHtml(separateHtmlQuote(message))
40
39
  : undefined;
41
40
 
42
41
  const attachments: EmailAttachment[] = await Promise.all(
@@ -82,15 +81,19 @@ export async function prepareOutboundDelivery(env: Env, message: Email) {
82
81
  headers.References = message.referencesJson.join(" ");
83
82
  }
84
83
 
84
+ const text = textWithQuotedContext(
85
+ message.bodyText ?? "",
86
+ message.quotedText
87
+ );
88
+
85
89
  return {
86
90
  from: { name: from.name ?? "", email: from.address },
87
91
  ...emailDestinations(message),
88
92
  replyTo: message.replyToJson[0]?.address,
89
93
  subject: message.subject,
90
- text:
91
- textWithQuotedContext(message.bodyText ?? "", message.quotedText) ||
92
- undefined,
93
- html,
94
+ text: text || undefined,
95
+ // Email Sending requires a text or HTML part, even for a file-only email.
96
+ html: html ?? (!text && attachments.length ? "<p><br></p>" : undefined),
94
97
  attachments: attachments.length ? attachments : undefined,
95
98
  headers,
96
99
  };
@@ -2,6 +2,7 @@ import {
2
2
  deferWebhookTask,
3
3
  queueWebhookEvent,
4
4
  } from "@open-workspace/core/module";
5
+ import { waitUntil } from "cloudflare:workers";
5
6
 
6
7
  import {
7
8
  EMAIL_SENT_EVENT,
@@ -10,6 +11,7 @@ import {
10
11
  } from "../../shared/webhooks";
11
12
  import { mailboxStub } from "../mailbox";
12
13
  import type { Email } from "../mailbox/schema";
14
+ import type { SendingDraft } from "../mailbox/support";
13
15
  import {
14
16
  discardPreparedObjects,
15
17
  messageIdForRequest,
@@ -18,6 +20,7 @@ import {
18
20
  } from "./outbound";
19
21
  import type { OutgoingMessageInput } from "./outbound";
20
22
  import { discardComposerUploads } from "./uploads";
23
+ import { shareSpamVerdicts } from "./workspace-safety";
21
24
 
22
25
  export class OutgoingRequestConflictError extends Error {}
23
26
 
@@ -25,12 +28,11 @@ function deferComposerUploadCleanup(input: {
25
28
  env: Env;
26
29
  compose: OutgoingMessageInput;
27
30
  uploadIds: string[];
28
- defer: (task: Promise<unknown>) => void;
29
31
  }) {
30
32
  const uploadIds = [...new Set(input.uploadIds)];
31
33
 
32
34
  if (!uploadIds.length) return;
33
- input.defer(
35
+ waitUntil(
34
36
  discardComposerUploads({
35
37
  env: input.env,
36
38
  mailboxId: input.compose.mailboxId,
@@ -44,10 +46,9 @@ export function deferEmailSentWebhook(input: {
44
46
  env: Env;
45
47
  mailboxId: string;
46
48
  email: Pick<Email, "id" | "timelineAt" | "transportState">;
47
- defer: (task: Promise<unknown>) => void;
48
49
  }) {
49
50
  if (input.email.transportState !== "submitted") return;
50
- deferWebhookTask(input.defer, () =>
51
+ deferWebhookTask(() =>
51
52
  queueWebhookEvent(input.env, {
52
53
  eventId: emailWebhookEventId(
53
54
  EMAIL_SENT_EVENT,
@@ -66,6 +67,7 @@ export function deferEmailSentWebhook(input: {
66
67
  }
67
68
 
68
69
  export async function submitOutgoing(input: {
70
+ draft?: SendingDraft;
69
71
  env: Env;
70
72
  requestUrl: string;
71
73
  fromAddress: string;
@@ -75,7 +77,6 @@ export async function submitOutgoing(input: {
75
77
  related: Email | null;
76
78
  forwarded: Email | null;
77
79
  includeRelatedContext: boolean;
78
- defer: (task: Promise<unknown>) => void;
79
80
  }) {
80
81
  const { compose } = input;
81
82
  const stub = mailboxStub(input.env, compose.mailboxId);
@@ -103,7 +104,6 @@ export async function submitOutgoing(input: {
103
104
  env: input.env,
104
105
  mailboxId: compose.mailboxId,
105
106
  email: existing,
106
- defer: input.defer,
107
107
  });
108
108
 
109
109
  return { email: existing, inserted: false };
@@ -127,15 +127,32 @@ export async function submitOutgoing(input: {
127
127
  let submission: Awaited<ReturnType<typeof stub.submitOutgoing>>;
128
128
 
129
129
  try {
130
- submission = await stub.submitOutgoing(prepared.email);
130
+ submission = await stub.submitOutgoing(
131
+ prepared.email,
132
+ compose.userId,
133
+ input.draft
134
+ );
131
135
  } catch (error) {
132
- await discardPreparedObjects(input.env, prepared.storageKeys);
136
+ // The mailbox may have stored the message before failing (its send was
137
+ // cut off): its files are then the message's, kept. Unsure, keep them.
138
+ const stored = await stub.getEmail(id).then(
139
+ (email) => email !== null,
140
+ () => true
141
+ );
142
+
143
+ if (!stored) await discardPreparedObjects(input.env, prepared.storageKeys);
133
144
  throw error;
134
145
  }
135
146
 
136
147
  if (submission.outcome !== "inserted") {
137
148
  await discardPreparedObjects(input.env, prepared.storageKeys);
138
149
 
150
+ if (submission.outcome === "draftChanged") {
151
+ throw new OutgoingRequestConflictError(
152
+ "This draft changed or was removed. Reopen it before sending."
153
+ );
154
+ }
155
+
139
156
  if (submission.outcome === "conflict") {
140
157
  // Do not clean the losing request's composer uploads. Only prepared
141
158
  // message-scoped copies belong to this failed submission attempt.
@@ -145,6 +162,15 @@ export async function submitOutgoing(input: {
145
162
  }
146
163
  }
147
164
 
165
+ // A reply from Spam told the mailbox its senders aren't spam.
166
+ if (submission.verdicts?.length) {
167
+ await shareSpamVerdicts(
168
+ input.env.DB,
169
+ compose.mailboxId,
170
+ submission.verdicts
171
+ );
172
+ }
173
+
148
174
  deferComposerUploadCleanup({
149
175
  ...input,
150
176
  uploadIds: prepared.composerUploadIds,
@@ -153,7 +179,6 @@ export async function submitOutgoing(input: {
153
179
  env: input.env,
154
180
  mailboxId: compose.mailboxId,
155
181
  email: submission.email,
156
- defer: input.defer,
157
182
  });
158
183
 
159
184
  return {