@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
@@ -6,36 +6,45 @@ import {
6
6
  composerAttachmentLimitError,
7
7
  isComposerInlineImageContentType,
8
8
  } from "../../shared/mail";
9
+ import { escapeHtml, quotedContextHtml } from "../../shared/mail-html";
9
10
  import type { StoredAttachment } from "../mailbox/model";
10
11
  import type { Email, NewEmail } from "../mailbox/schema";
12
+ import { downloadExpiry, issueDownloadLink } from "./download-links";
11
13
  import {
12
14
  appendForwardedMessage,
13
15
  contextForNewRecipient,
14
- escapeHtml,
15
16
  externalizeLinkedInlineImages,
16
- htmlWithQuotedContext,
17
17
  resolveLinkedAttachmentPlaceholders,
18
+ selectedForwardFiles,
18
19
  textWithQuotedContext,
19
20
  } from "./outbound-content";
21
+ import { plainBody } from "./plain-body";
20
22
  import { address, replyThreadHeaders } from "./rfc";
23
+ import type { InlineImage } from "./rich-content";
21
24
  import type { composeSchema } from "./schemas";
25
+ import { messagePrefix } from "./storage-keys";
22
26
  import {
23
27
  copyStoredAttachmentToMessage,
24
28
  loadComposerUpload,
25
- loadComposerUploadMetadata,
26
29
  UploadValidationError,
27
30
  } from "./uploads";
28
31
 
29
- const DOWNLOAD_TTL_MS = 30 * 24 * 60 * 60 * 1000;
30
-
31
- export type OutgoingMessageInput = z.infer<typeof composeSchema> & {
32
+ // Stored image references are resolved to `inlineImages` by the routes.
33
+ export type OutgoingMessageInput = Omit<
34
+ z.infer<typeof composeSchema>,
35
+ "storedImages"
36
+ > & {
37
+ forwardedAttachmentIds?: string[];
32
38
  /** Set by the route from the authenticated session. */
33
39
  userId: string;
40
+ /** Saved images (rich-content.ts) the body uses, sent inline like composer images. */
41
+ inlineImages?: InlineImage[];
34
42
  };
35
43
 
36
44
  type PreparedAttachment = StoredAttachment & {
37
45
  downloadUrl: string | null;
38
46
  sourceUploadId?: string;
47
+ forwardPlaceholder?: string;
39
48
  sourceObjectKey?: string;
40
49
  };
41
50
 
@@ -43,7 +52,14 @@ export class ComposerAttachmentLimitError extends Error {}
43
52
 
44
53
  type OutgoingAttachmentDraft = Pick<
45
54
  OutgoingMessageInput,
46
- "attachments" | "bodyHtml" | "bodyText" | "mailboxId" | "subject" | "userId"
55
+ | "attachments"
56
+ | "bodyHtml"
57
+ | "bodyText"
58
+ | "mailboxId"
59
+ | "subject"
60
+ | "userId"
61
+ | "inlineImages"
62
+ | "forwardedAttachmentIds"
47
63
  >;
48
64
 
49
65
  export async function discardPreparedObjects(env: Env, storageKeys: string[]) {
@@ -65,7 +81,7 @@ export function outgoingRequestFingerprint(compose: OutgoingMessageInput) {
65
81
 
66
82
  export { attachmentsRequiringDownloadLinks };
67
83
 
68
- export function withDownloadLinks(
84
+ export async function withDownloadLinks(
69
85
  bodyText: string,
70
86
  bodyHtml: string | undefined,
71
87
  attachments: PreparedAttachment[],
@@ -75,7 +91,8 @@ export function withDownloadLinks(
75
91
  bodyText,
76
92
  bodyHtml,
77
93
  attachments: attachments.map((attachment) => ({
78
- uploadId: attachment.sourceUploadId ?? null,
94
+ uploadId:
95
+ attachment.sourceUploadId ?? attachment.forwardPlaceholder ?? null,
79
96
  filename: attachment.filename,
80
97
  downloadUrl: attachment.downloadUrl,
81
98
  })),
@@ -97,8 +114,9 @@ export function withDownloadLinks(
97
114
 
98
115
  const fallbackTextLinks = links.filter(
99
116
  (attachment) =>
100
- !attachment.sourceUploadId ||
101
- !positioned.textPlacedUploadIds.has(attachment.sourceUploadId)
117
+ !positioned.textPlacedUploadIds.has(
118
+ attachment.sourceUploadId ?? attachment.forwardPlaceholder ?? ""
119
+ )
102
120
  );
103
121
 
104
122
  const textBlock = fallbackTextLinks.length
@@ -120,23 +138,16 @@ export function withDownloadLinks(
120
138
  return { bodyText: nextText, bodyHtml: positionedHtml };
121
139
  }
122
140
 
123
- const inlineImagePlacements = new Set(
124
- links.flatMap((attachment) =>
125
- attachment.disposition === "inline" &&
126
- attachment.contentId &&
127
- positionedHtml.includes(`cid:${attachment.contentId}`)
128
- ? [attachment.id]
129
- : []
130
- )
141
+ const { html: nextHtml, placedIds } = await externalizeLinkedInlineImages(
142
+ positionedHtml,
143
+ links
131
144
  );
132
145
 
133
- const nextHtml = externalizeLinkedInlineImages(positionedHtml, links);
134
-
135
146
  const fallbackHtmlLinks = links.filter(
136
147
  (attachment) =>
137
- (!attachment.sourceUploadId ||
138
- !positioned.htmlPlacedUploadIds.has(attachment.sourceUploadId)) &&
139
- !inlineImagePlacements.has(attachment.id)
148
+ !positioned.htmlPlacedUploadIds.has(
149
+ attachment.sourceUploadId ?? attachment.forwardPlaceholder ?? ""
150
+ ) && !placedIds.has(attachment.id)
140
151
  );
141
152
 
142
153
  if (!fallbackHtmlLinks.length) {
@@ -163,25 +174,47 @@ export async function messageIdForRequest(
163
174
  return `msg_${await hashToken(`${mailboxId}:${requestId}`)}`;
164
175
  }
165
176
 
166
- function loadPreparedComposerAttachments(input: {
177
+ async function loadPreparedComposerAttachments(input: {
167
178
  env: Env;
168
179
  compose: OutgoingAttachmentDraft;
169
180
  storagePrefix: string;
170
181
  finalized: boolean;
171
182
  }) {
172
- const loadUpload = input.finalized
173
- ? loadComposerUpload
174
- : loadComposerUploadMetadata;
183
+ const uploads = input.compose.attachments;
184
+
185
+ const savedImages = (input.compose.inlineImages ?? []).map(
186
+ (image, offset) => {
187
+ const id = `att_${uploads.length + offset + 1}`;
188
+
189
+ return {
190
+ id,
191
+ sourceObjectKey: image.r2Key,
192
+ r2Key: `${input.storagePrefix}/attachments/${id}`,
193
+ filename: image.filename,
194
+ contentType: image.contentType,
195
+ size: image.size,
196
+ contentId: image.contentId,
197
+ disposition: "inline",
198
+ delivery: "attached",
199
+ downloadTokenHash: null,
200
+ downloadExpiresAt: null,
201
+ downloadUrl: null,
202
+ } satisfies PreparedAttachment;
203
+ }
204
+ );
175
205
 
176
- return Promise.all(
177
- input.compose.attachments.map(async (file, index) => {
206
+ const uploaded = await Promise.all(
207
+ uploads.map(async (file, index) => {
178
208
  try {
179
- const upload = await loadUpload({
180
- env: input.env,
181
- mailboxId: input.compose.mailboxId,
182
- userId: input.compose.userId,
183
- uploadId: file.uploadId,
184
- });
209
+ const upload = await loadComposerUpload(
210
+ {
211
+ env: input.env,
212
+ mailboxId: input.compose.mailboxId,
213
+ userId: input.compose.userId,
214
+ uploadId: file.uploadId,
215
+ },
216
+ { unfinished: !input.finalized }
217
+ );
185
218
 
186
219
  if (
187
220
  file.disposition === "inline" &&
@@ -216,9 +249,14 @@ function loadPreparedComposerAttachments(input: {
216
249
  }
217
250
  })
218
251
  );
252
+
253
+ const prepared: PreparedAttachment[] = [...uploaded, ...savedImages];
254
+
255
+ return prepared;
219
256
  }
220
257
 
221
- function planOutgoingAttachments(input: {
258
+ async function planOutgoingAttachments(input: {
259
+ env: Env;
222
260
  compose: OutgoingAttachmentDraft;
223
261
  uploaded: PreparedAttachment[];
224
262
  forwarded: Email | null;
@@ -228,36 +266,58 @@ function planOutgoingAttachments(input: {
228
266
  }) {
229
267
  // A persisted forward gets message-owned copies. Preflight has no storage
230
268
  // prefix and only needs attachment metadata for the delivery plan.
231
- const forwardedAttachments: PreparedAttachment[] = (
232
- input.forwarded?.attachmentsJson ?? []
233
- ).map((file, index) => {
234
- const id = `fwd_att_${index + 1}`;
269
+ const sourceFiles = input.forwarded?.attachmentsJson ?? [];
270
+ const selection = input.compose.forwardedAttachmentIds;
271
+ const files = selectedForwardFiles(sourceFiles, selection);
272
+
273
+ if (selection && files.length !== selection.length) {
274
+ throw new UploadValidationError(
275
+ "A selected forwarded attachment is no longer available"
276
+ );
277
+ }
235
278
 
236
- return {
237
- ...file,
238
- id,
239
- r2Key: input.storagePrefix
240
- ? `${input.storagePrefix}/attachments/${id}`
241
- : file.r2Key,
242
- sourceObjectKey: input.storagePrefix ? file.r2Key : undefined,
243
- contentId: null,
244
- disposition: "attachment",
245
- delivery: "attached",
246
- downloadTokenHash: null,
247
- downloadExpiresAt: null,
248
- downloadUrl: null,
249
- };
250
- });
279
+ const placeholders = new Map<string, string>();
280
+
281
+ const forwardedAttachments: PreparedAttachment[] = files.map(
282
+ (file, index) => {
283
+ const id = `fwd_att_${index + 1}`;
284
+ placeholders.set(file.id, id);
285
+
286
+ return {
287
+ ...file,
288
+ id,
289
+ forwardPlaceholder: id,
290
+ r2Key: input.storagePrefix
291
+ ? `${input.storagePrefix}/attachments/${id}`
292
+ : file.r2Key,
293
+ sourceObjectKey: input.storagePrefix ? file.r2Key : undefined,
294
+ contentId: null,
295
+ disposition: "attachment",
296
+ delivery: "attached",
297
+ downloadTokenHash: null,
298
+ downloadExpiresAt: null,
299
+ downloadUrl: null,
300
+ };
301
+ }
302
+ );
251
303
 
252
304
  const attachments = [...input.uploaded, ...forwardedAttachments];
253
- const limitError = composerAttachmentLimitError(attachments);
305
+
306
+ // The composer's limits are on what the person attached: saved images
307
+ // (a signature's), which follow the uploads in `uploaded`, don't count.
308
+ const limitError = composerAttachmentLimitError([
309
+ ...input.uploaded.slice(0, input.compose.attachments.length),
310
+ ...forwardedAttachments,
311
+ ]);
254
312
 
255
313
  if (limitError) throw new ComposerAttachmentLimitError(limitError);
256
314
 
257
- const forwardedContent = appendForwardedMessage(
258
- input.compose.bodyText,
315
+ const forwardedContent = await appendForwardedMessage(
316
+ input.env.MAIL_STORAGE,
317
+ plainBody(input.compose.bodyText, input.compose.bodyHtml),
259
318
  input.compose.bodyHtml,
260
- input.forwarded
319
+ input.forwarded,
320
+ placeholders
261
321
  );
262
322
 
263
323
  const quotedText =
@@ -269,7 +329,7 @@ function planOutgoingAttachments(input: {
269
329
  subject: input.compose.subject,
270
330
  bodyText: textWithQuotedContext(forwardedContent.bodyText, quotedText),
271
331
  bodyHtml: forwardedContent.bodyHtml
272
- ? htmlWithQuotedContext(forwardedContent.bodyHtml, quotedText)
332
+ ? forwardedContent.bodyHtml + quotedContextHtml(quotedText)
273
333
  : undefined,
274
334
  attachments,
275
335
  });
@@ -277,6 +337,7 @@ function planOutgoingAttachments(input: {
277
337
  return {
278
338
  attachments,
279
339
  forwardedContent,
340
+ placeholders,
280
341
  linkedIds,
281
342
  quotedText,
282
343
  };
@@ -296,13 +357,17 @@ export async function preflightOutgoingAttachments(input: {
296
357
  finalized: false,
297
358
  });
298
359
 
299
- const plan = planOutgoingAttachments({
360
+ const plan = await planOutgoingAttachments({
300
361
  ...input,
301
362
  uploaded,
302
363
  });
303
364
 
304
365
  return {
305
366
  externalizedAttachments: plan.linkedIds.size,
367
+ linkedForwardedIds: Array.from(plan.placeholders).flatMap(
368
+ ([sourceId, outgoingId]) =>
369
+ plan.linkedIds.has(outgoingId) ? [sourceId] : []
370
+ ),
306
371
  linkedUploadIds: uploaded.flatMap((attachment) =>
307
372
  plan.linkedIds.has(attachment.id) && attachment.sourceUploadId
308
373
  ? [attachment.sourceUploadId]
@@ -327,8 +392,8 @@ export async function prepareOutgoingEmail(input: {
327
392
  }) {
328
393
  const { compose, id, related } = input;
329
394
  const storageAttempt = randomToken();
330
- const storagePrefix = `mailboxes/${compose.mailboxId}/messages/${id}/attempts/${storageAttempt}`;
331
- const expiresAt = new Date(input.now.getTime() + DOWNLOAD_TTL_MS);
395
+ const storagePrefix = `${messagePrefix(compose.mailboxId, id)}attempts/${storageAttempt}`;
396
+ const expiresAt = downloadExpiry(input.now);
332
397
 
333
398
  const uploaded = await loadPreparedComposerAttachments({
334
399
  env: input.env,
@@ -337,7 +402,8 @@ export async function prepareOutgoingEmail(input: {
337
402
  finalized: true,
338
403
  });
339
404
 
340
- const plan = planOutgoingAttachments({
405
+ const plan = await planOutgoingAttachments({
406
+ env: input.env,
341
407
  compose,
342
408
  uploaded,
343
409
  forwarded: input.forwarded,
@@ -351,22 +417,22 @@ export async function prepareOutgoingEmail(input: {
351
417
  const attachments: PreparedAttachment[] = await Promise.all(
352
418
  plan.attachments.map(async (file) => {
353
419
  if (!linkedIds.has(file.id)) return file;
354
- const token = `${compose.mailboxId}.${id}.${file.id}.${randomToken()}`;
355
420
 
356
421
  return {
357
422
  ...file,
358
423
  delivery: "download_link" as const,
359
- downloadTokenHash: await hashToken(token),
360
- downloadExpiresAt: expiresAt.getTime(),
361
- downloadUrl: new URL(
362
- `/api/downloads/mail/${encodeURIComponent(token)}`,
363
- input.requestUrl
364
- ).toString(),
424
+ ...(await issueDownloadLink(
425
+ input.requestUrl,
426
+ compose.mailboxId,
427
+ id,
428
+ file.id,
429
+ expiresAt
430
+ )),
365
431
  };
366
432
  })
367
433
  );
368
434
 
369
- const content = withDownloadLinks(
435
+ const content = await withDownloadLinks(
370
436
  forwardedContent.bodyText,
371
437
  forwardedContent.bodyHtml,
372
438
  attachments,
@@ -450,8 +516,13 @@ export async function prepareOutgoingEmail(input: {
450
516
  quotedText,
451
517
  bodyHtmlR2Key,
452
518
  attachmentsJson: attachments.map(
453
- ({ downloadUrl: _, sourceUploadId: __, sourceObjectKey: ___, ...file }) =>
454
- file
519
+ ({
520
+ downloadUrl: _,
521
+ sourceUploadId: __,
522
+ sourceObjectKey: ___,
523
+ forwardPlaceholder: _placeholder,
524
+ ...file
525
+ }) => file
455
526
  ),
456
527
  listId: continuedList?.listId ?? null,
457
528
  listPostAddress: continuedList?.listPostAddress ?? null,
@@ -1,3 +1,7 @@
1
+ import { createDb, mailboxAddressSql } from "@open-workspace/core/module";
2
+ import { mailboxes } from "@open-workspace/core/schema";
3
+ import { eq } from "drizzle-orm";
4
+
1
5
  import {
2
6
  forwardSubject,
3
7
  MAX_MAIL_RECIPIENTS,
@@ -6,13 +10,9 @@ import {
6
10
  import type { ReplyActionMode } from "../../shared/mail";
7
11
  import { mailboxStub } from "../mailbox";
8
12
  import type { Email } from "../mailbox/schema";
9
- import {
10
- hasNewRecipients,
11
- shouldDetachOutboundReply,
12
- } from "./outbound-threading";
13
+ import { shouldDetachOutboundReply } from "./outbound-threading";
13
14
  import { dedupeRecipientFields, recipientCount } from "./recipients";
14
- import type { RecipientFields } from "./recipients";
15
- import { buildReplyPlan, canReplyFrom } from "./reply-plan";
15
+ import { buildReplyPlan, canReplyFrom, replyAlias } from "./reply-plan";
16
16
 
17
17
  type OutgoingContextCode = "BAD_REQUEST" | "NOT_FOUND" | "NOT_READY";
18
18
 
@@ -49,6 +49,14 @@ export async function resolveForwardContext(input: {
49
49
  };
50
50
  }
51
51
 
52
+ /** A mailbox's aliases: addresses a reply may come from instead of its own. */
53
+ export function mailboxAliases(db: D1Database, mailboxId: string) {
54
+ return createDb(db)
55
+ .select({ address: mailboxAddressSql, displayName: mailboxes.displayName })
56
+ .from(mailboxes)
57
+ .where(eq(mailboxes.aliasOf, mailboxId));
58
+ }
59
+
52
60
  export async function resolveReplyContext(input: {
53
61
  env: Env;
54
62
  mailboxId: string;
@@ -56,14 +64,8 @@ export async function resolveReplyContext(input: {
56
64
  sourceEmailId: string;
57
65
  mode: ReplyActionMode;
58
66
  cc?: string[];
59
- bcc: string[];
60
- }): Promise<{
61
- source: Email;
62
- recipients: RecipientFields;
63
- subject: string;
64
- detached: boolean;
65
- includeRelatedContext: boolean;
66
- }> {
67
+ bcc?: string[];
68
+ }) {
67
69
  const stub = mailboxStub(input.env, input.mailboxId);
68
70
  const source = await stub.getEmail(input.sourceEmailId);
69
71
 
@@ -83,7 +85,12 @@ export async function resolveReplyContext(input: {
83
85
  );
84
86
  }
85
87
 
86
- const plan = buildReplyPlan(input.ownAddress, source);
88
+ const { plan, from, ownAddress } = await replySourceContext(
89
+ input.env.DB,
90
+ input.mailboxId,
91
+ input.ownAddress,
92
+ source
93
+ );
87
94
 
88
95
  const action = plan.actions.find(
89
96
  (candidate) => candidate.mode === input.mode
@@ -100,33 +107,56 @@ export async function resolveReplyContext(input: {
100
107
  const recipients = dedupeRecipientFields({
101
108
  to: action.to,
102
109
  cc: input.cc ?? action.cc,
103
- bcc: input.bcc,
110
+ bcc: input.bcc ?? action.bcc ?? [],
104
111
  });
105
112
 
106
- if (recipientCount(recipients) > MAX_MAIL_RECIPIENTS) {
113
+ const count = recipientCount(recipients);
114
+
115
+ if (!count) {
107
116
  throw new OutgoingContextError(
108
117
  400,
109
118
  "BAD_REQUEST",
110
- `An email can have at most ${MAX_MAIL_RECIPIENTS} recipients across To, Cc, and Bcc`
119
+ "Add at least one recipient in To, Cc, or Bcc"
111
120
  );
112
121
  }
113
122
 
114
- const history = await stub.getConversation(source.conversationId);
123
+ if (count > MAX_MAIL_RECIPIENTS) {
124
+ throw new OutgoingContextError(
125
+ 400,
126
+ "BAD_REQUEST",
127
+ `An email can have at most ${MAX_MAIL_RECIPIENTS} recipients across To, Cc, and Bcc`
128
+ );
129
+ }
115
130
 
116
131
  return {
132
+ from,
133
+ detached: shouldDetachOutboundReply({ ownAddress, plan, ...recipients }),
117
134
  source,
118
135
  recipients,
119
136
  subject: replySubject(source.subject),
120
- detached: shouldDetachOutboundReply({
121
- ownAddress: input.ownAddress,
122
- plan,
123
- to: recipients.to,
124
- cc: recipients.cc,
125
- }),
126
- includeRelatedContext: hasNewRecipients({
127
- ownAddress: input.ownAddress,
128
- history,
129
- ...recipients,
130
- }),
137
+ includeRelatedContext: await stub.hasNewConversationRecipients(
138
+ source.conversationId,
139
+ ownAddress,
140
+ recipients
141
+ ),
131
142
  };
132
143
  }
144
+
145
+ /** Computes the reply actions and sending identity from all of the mailbox's addresses. */
146
+ export async function replySourceContext(
147
+ db: D1Database,
148
+ mailboxId: string,
149
+ mailboxAddress: string,
150
+ source: Email
151
+ ) {
152
+ const aliases = await mailboxAliases(db, mailboxId);
153
+ const from = replyAlias(source, mailboxAddress, aliases);
154
+ const ownAddress = from?.address ?? mailboxAddress;
155
+
156
+ const plan = buildReplyPlan(
157
+ [mailboxAddress, ...aliases.map((alias) => alias.address)],
158
+ source
159
+ );
160
+
161
+ return { from, ownAddress, plan };
162
+ }
@@ -83,11 +83,8 @@ export function participantLabels(
83
83
  export function suggestParticipants(
84
84
  messages: Iterable<ParticipantSource>,
85
85
  ownAddress: string,
86
- query: string,
87
- limit: number,
88
- /** Blocked or reported correspondents are never suggested. */
89
- exclude: (address: string) => boolean = () => false
90
- ): ParticipantSuggestion[] {
86
+ query: string
87
+ ) {
91
88
  const own = normalizeMailboxAddress(ownAddress);
92
89
  const needle = query.trim().toLocaleLowerCase("en-US");
93
90
  const result = new Map<string, ParticipantSuggestion>();
@@ -101,17 +98,17 @@ export function suggestParticipants(
101
98
  ]) {
102
99
  const address = normalizeEmail(participant.address);
103
100
 
104
- if (
105
- !address ||
106
- normalizeMailboxAddress(address) === own ||
107
- result.has(address) ||
108
- exclude(address.toLocaleLowerCase("en-US"))
109
- ) {
101
+ if (!address || normalizeMailboxAddress(address) === own) continue;
102
+ const name = participant.name?.trim() || null;
103
+ const known = result.get(address);
104
+
105
+ // The latest mail to someone, sent to a bare address, keeps the name
106
+ // older mail gives them.
107
+ if (known) {
108
+ known.name ??= name;
110
109
  continue;
111
110
  }
112
111
 
113
- const name = participant.name?.trim() || null;
114
-
115
112
  if (
116
113
  needle &&
117
114
  !address.toLocaleLowerCase("en-US").includes(needle) &&
@@ -121,8 +118,6 @@ export function suggestParticipants(
121
118
  }
122
119
 
123
120
  result.set(address, { address, name });
124
-
125
- if (result.size >= limit) return [...result.values()];
126
121
  }
127
122
  }
128
123
 
@@ -0,0 +1,39 @@
1
+ import { compile } from "html-to-text";
2
+
3
+ import { linkedAttachmentTextToken } from "../../shared/mail";
4
+
5
+ /** Drafts keep upload markers for sending. Readers see the filenames in their place. */
6
+ export function readableDraftText(
7
+ text: string | null | undefined,
8
+ files: readonly { uploadId: string; filename: string }[] | undefined
9
+ ) {
10
+ let body = text ?? "";
11
+
12
+ for (const file of files ?? []) {
13
+ body = body.replaceAll(
14
+ linkedAttachmentTextToken(file.uploadId),
15
+ () => file.filename
16
+ );
17
+ }
18
+
19
+ return body;
20
+ }
21
+
22
+ let convert: ReturnType<typeof compile> | undefined;
23
+
24
+ /** The authored text, including a readable alternative for HTML-only mail. */
25
+ export function plainBody(text?: string | null, html?: string | null) {
26
+ if (text?.trim()) return text;
27
+
28
+ if (!html) return "";
29
+
30
+ convert ??= compile({
31
+ wordwrap: false,
32
+ selectors: [
33
+ { selector: "img", format: "skip" },
34
+ { selector: "style", format: "skip" },
35
+ ],
36
+ });
37
+
38
+ return convert(html);
39
+ }
@@ -0,0 +1,17 @@
1
+ import { assertProxyableRemoteUrl } from "./remote-proxy";
2
+
3
+ /**
4
+ * The one rule for where the Worker POSTs pushes, the app's Web Push and
5
+ * JMAP's alike. Push goes to whatever push service the subscriber uses, so
6
+ * any public HTTPS host is accepted (a self-hosted Mozilla autopush
7
+ * included). What is refused is what the image proxy refuses: credentials
8
+ * in the URL, localhost, private and internal addresses, and internal-only
9
+ * names. Checked when it is registered and again before each delivery.
10
+ */
11
+ export function isPublicPushEndpoint(endpoint: string) {
12
+ try {
13
+ return assertProxyableRemoteUrl(endpoint).protocol === "https:";
14
+ } catch {
15
+ return false;
16
+ }
17
+ }