@open-workspace/email 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -6,7 +6,7 @@ import {
6
6
  import type { ReplyAction, ReplyPlan } from "../../shared/mail";
7
7
  import type { MailAddress } from "../mailbox/model";
8
8
  import type { Email } from "../mailbox/schema";
9
- import { uniqueParticipantAddresses } from "./participants";
9
+ import { dedupeRecipientFields } from "./recipients";
10
10
 
11
11
  export type {
12
12
  ReplyAction,
@@ -14,8 +14,43 @@ export type {
14
14
  ReplyPlan,
15
15
  } from "../../shared/mail";
16
16
 
17
- function uniqueAddresses(values: MailAddress[], ownAddress: string) {
18
- return uniqueParticipantAddresses(values, ownAddress);
17
+ /**
18
+ * The configured address for this recipient, including plus addressing.
19
+ * An exact address wins over its plus base, as it does during delivery.
20
+ */
21
+ function ownMailboxAddress(
22
+ address: string,
23
+ own: ReadonlySet<string>,
24
+ deliveredTo: string | null = null
25
+ ) {
26
+ const normalized = normalizeMailboxAddress(address);
27
+
28
+ if (own.has(normalized) || normalized === deliveredTo) return normalized;
29
+ const at = normalized.lastIndexOf("@");
30
+ const plus = normalized.indexOf("+");
31
+
32
+ if (plus <= 0 || plus >= at) return null;
33
+ const base = normalized.slice(0, plus) + normalized.slice(at);
34
+
35
+ return own.has(base) ? base : null;
36
+ }
37
+
38
+ /** Each address once, leaving out the mailbox's own. */
39
+ function uniqueAddresses(
40
+ values: MailAddress[],
41
+ isOwn: (address: string) => boolean
42
+ ) {
43
+ const result = new Set<string>();
44
+
45
+ for (const value of values) {
46
+ const normalized = normalizeEmail(value.address);
47
+
48
+ if (normalized && !isOwn(normalized)) {
49
+ result.add(normalized);
50
+ }
51
+ }
52
+
53
+ return [...result];
19
54
  }
20
55
 
21
56
  function without(values: string[], excluded: string[]) {
@@ -27,12 +62,14 @@ function without(values: string[], excluded: string[]) {
27
62
  type ReplySource = Pick<
28
63
  Email,
29
64
  | "direction"
65
+ | "envelopeTo"
30
66
  | "messageIdHeader"
31
67
  | "transportState"
32
68
  | "fromJson"
33
69
  | "replyToJson"
34
70
  | "toJson"
35
71
  | "ccJson"
72
+ | "bccJson"
36
73
  | "listId"
37
74
  | "listPostAddress"
38
75
  >;
@@ -45,30 +82,54 @@ export function canReplyFrom(
45
82
  return Boolean(email.messageIdHeader) && email.transportState === "submitted";
46
83
  }
47
84
 
85
+ /**
86
+ * How a message can be answered from a mailbox. `ownAddresses` are all of
87
+ * the mailbox's addresses (the one replies come from, its own and its
88
+ * aliases'); none of them, nor a plus address of one, is a recipient.
89
+ */
48
90
  export function buildReplyPlan(
49
- ownAddress: string,
91
+ ownAddresses: readonly string[],
50
92
  email: ReplySource
51
- ): ReplyPlan {
93
+ ) {
94
+ const own = new Set(
95
+ ownAddresses.map((address) => normalizeMailboxAddress(address))
96
+ );
97
+
98
+ // A catch-all owns the exact delivery address for this reply. A list's
99
+ // envelope can instead be the address everyone should reply to.
100
+ const deliveredTo =
101
+ email.direction === "incoming" && !email.listId && email.envelopeTo
102
+ ? normalizeMailboxAddress(email.envelopeTo)
103
+ : null;
104
+
105
+ const isOwn = (address: string) =>
106
+ Boolean(ownMailboxAddress(address, own, deliveredTo));
107
+
52
108
  if (email.direction === "outgoing") {
53
- const to = uniqueAddresses(email.toJson, ownAddress);
54
- const cc = without(uniqueAddresses(email.ccJson, ownAddress), to);
109
+ const to = uniqueAddresses(email.toJson, isOwn);
110
+ const cc = without(uniqueAddresses(email.ccJson, isOwn), to);
55
111
  const participants = [...to, ...cc];
56
112
 
113
+ // With no other visible recipients, continue to the original destinations
114
+ // in their original fields (a note to self or a blind mailing).
115
+ const recipients = participants.length
116
+ ? { to, cc }
117
+ : dedupeRecipientFields({
118
+ to: email.toJson.map((item) => item.address),
119
+ cc: email.ccJson.map((item) => item.address),
120
+ bcc: email.bccJson.map((item) => item.address),
121
+ });
122
+
123
+ const actions: ReplyAction[] = canReplyFrom(email)
124
+ ? [{ mode: "continue", label: "Continue", ...recipients }]
125
+ : [];
126
+
57
127
  return {
58
128
  defaultMode: "continue",
59
129
  isGroup: participants.length > 1,
60
130
  participants,
61
- actions: canReplyFrom(email)
62
- ? [
63
- {
64
- mode: "continue",
65
- label: "Continue",
66
- to,
67
- cc,
68
- },
69
- ]
70
- : [],
71
- };
131
+ actions,
132
+ } satisfies ReplyPlan;
72
133
  }
73
134
 
74
135
  // List managers commonly rewrite Reply-To to the list itself. A private
@@ -79,12 +140,12 @@ export function buildReplyPlan(
79
140
  : email.replyToJson.length
80
141
  ? email.replyToJson
81
142
  : email.fromJson,
82
- ownAddress
143
+ isOwn
83
144
  );
84
145
 
85
146
  const visibleParticipants = uniqueAddresses(
86
147
  [...email.fromJson, ...email.toJson, ...email.ccJson],
87
- ownAddress
148
+ isOwn
88
149
  );
89
150
 
90
151
  const replyAllParticipants = uniqueAddresses(
@@ -97,16 +158,14 @@ export function buildReplyPlan(
97
158
  ...email.toJson,
98
159
  ...email.ccJson,
99
160
  ],
100
- ownAddress
161
+ isOwn
101
162
  );
102
163
 
103
164
  const visibleIsGroup =
104
165
  Boolean(email.listId) || replyAllParticipants.length > 1;
105
166
 
106
- const own = normalizeMailboxAddress(ownAddress);
107
-
108
167
  const visibleRecipients = [...email.toJson, ...email.ccJson].some(
109
- (recipient) => normalizeMailboxAddress(recipient.address) === own
168
+ (recipient) => isOwn(recipient.address)
110
169
  );
111
170
 
112
171
  const undisclosedLocalRecipient = !email.listId && !visibleRecipients;
@@ -125,7 +184,7 @@ export function buildReplyPlan(
125
184
  email.listPostAddress
126
185
  ? [{ address: email.listPostAddress, name: null }]
127
186
  : [],
128
- ownAddress
187
+ isOwn
129
188
  ).slice(0, 1);
130
189
 
131
190
  if (!email.listId && visibleIsGroup) {
@@ -161,5 +220,44 @@ export function buildReplyPlan(
161
220
  ? replyTargets
162
221
  : visibleParticipants,
163
222
  actions,
164
- };
223
+ } satisfies ReplyPlan;
224
+ }
225
+
226
+ /** Prefer the delivery envelope. Imported mail can identify its mailbox by To/Cc instead. */
227
+ export function replyAlias<Alias extends { address: string }>(
228
+ source: Pick<
229
+ Email,
230
+ "direction" | "envelopeTo" | "fromJson" | "toJson" | "ccJson"
231
+ >,
232
+ mailboxAddress: string,
233
+ aliases: readonly Alias[]
234
+ ) {
235
+ if (!aliases.length) return null;
236
+
237
+ const own = new Set(
238
+ [mailboxAddress, ...aliases.map((alias) => alias.address)].map(
239
+ normalizeMailboxAddress
240
+ )
241
+ );
242
+
243
+ const address =
244
+ source.direction === "outgoing"
245
+ ? source.fromJson[0]?.address
246
+ : source.envelopeTo;
247
+
248
+ let matched = address ? ownMailboxAddress(address, own) : null;
249
+
250
+ if (source.direction === "incoming" && !source.envelopeTo) {
251
+ // A primary address alongside an alias is ambiguous too.
252
+ for (const recipient of [...source.toJson, ...source.ccJson]) {
253
+ const candidate = ownMailboxAddress(recipient.address, own);
254
+
255
+ if (!candidate) continue;
256
+
257
+ if (matched && matched !== candidate) return null;
258
+ matched = candidate;
259
+ }
260
+ }
261
+
262
+ return aliases.find((alias) => alias.address === matched) ?? null;
165
263
  }
@@ -1,8 +1,6 @@
1
1
  import { normalizeEmail } from "@open-workspace/core/module";
2
2
  import type { Header } from "postal-mime";
3
3
 
4
- import type { MailAddress } from "../mailbox/model";
5
-
6
4
  const MAX_REFERENCE_IDS = 100;
7
5
  const MAX_REFERENCE_BYTES = 12 * 1024;
8
6
  const MAX_MESSAGE_ID_BYTES = 900;
@@ -37,10 +35,23 @@ export function boundedMessageIds(values: string[]) {
37
35
  return newestFirst.reverse();
38
36
  }
39
37
 
38
+ /**
39
+ * The one form a Message-ID is stored and compared in, `<id@host>`, as a
40
+ * received header has it, whatever form it came in: Email Sending's answer
41
+ * and its delivery events may leave the brackets off.
42
+ */
43
+ export function storedMessageId(value: string | null | undefined) {
44
+ const id = value?.trim().replaceAll(/^<|>$/gu, "");
45
+
46
+ return id ? `<${id}>` : null;
47
+ }
48
+
40
49
  export function messageIds(value: string | undefined) {
41
50
  if (!value) return [];
42
51
  const bracketed = value.match(/<[^<>]+>/gu);
43
- const values = bracketed ?? value.split(/\s+/u);
52
+
53
+ const values =
54
+ bracketed ?? value.split(/\s+/u).flatMap((id) => storedMessageId(id) ?? []);
44
55
 
45
56
  return boundedMessageIds(values);
46
57
  }
@@ -66,10 +77,7 @@ export function replyThreadHeaders(parent: {
66
77
  };
67
78
  }
68
79
 
69
- export function address(
70
- email: string,
71
- name: string | null = null
72
- ): MailAddress {
80
+ export function address(email: string, name: string | null = null) {
73
81
  return { address: normalizeEmail(email), name: name?.trim() || null };
74
82
  }
75
83
 
@@ -0,0 +1,207 @@
1
+ import type { z } from "zod";
2
+
3
+ import { isComposerInlineImageContentType } from "../../shared/mail";
4
+ import { escapeHtml } from "../../shared/mail-html";
5
+ import { MAX_RICH_IMAGE_BYTES } from "../../shared/rich-content";
6
+ import type { RichImage, StoredImageRef } from "../../shared/rich-content";
7
+ import type { richContentFields } from "./schemas";
8
+ import {
9
+ copyStoredAttachmentToMessage,
10
+ loadComposerUpload,
11
+ UploadValidationError,
12
+ } from "./uploads";
13
+
14
+ /**
15
+ * Saved rich content (signatures, auto-replies): HTML
16
+ * from the composer's editor whose images live in R2 under an owner prefix
17
+ * that never expires, sent as inline `cid:` attachments.
18
+ */
19
+
20
+ /** An image to send inline, with the R2 object it is copied from. */
21
+ export type InlineImage = RichImage & { r2Key: string };
22
+
23
+ export type RichContentInput = z.infer<z.ZodObject<typeof richContentFields>>;
24
+
25
+ function referencedImages<T extends { contentId: string }>(
26
+ html: string,
27
+ images: readonly T[]
28
+ ) {
29
+ return images.filter((image) => html.includes(`cid:${image.contentId}`));
30
+ }
31
+
32
+ /** Whether saving `content` should delete it instead: no text and no image. */
33
+ export function isEmptyRichContent(content: RichContentInput) {
34
+ return (
35
+ !content.text.trim() &&
36
+ !referencedImages(content.html, content.images).length
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Stores the images of `content` under `prefix`: new composer uploads are
42
+ * copied in, and images it keeps must be among the `previous` ones. Returns
43
+ * the images its HTML uses. Once the content itself is saved, call
44
+ * `deleteRichImages(prefix, keep)` to drop the ones no longer used.
45
+ */
46
+ export function storeRichImages(input: {
47
+ env: Env;
48
+ userId: string;
49
+ prefix: string;
50
+ previous: readonly RichImage[];
51
+ content: RichContentInput;
52
+ }) {
53
+ const { content } = input;
54
+
55
+ return Promise.all(
56
+ referencedImages(content.html, content.images).map(async (image) => {
57
+ if (!image.uploadId) {
58
+ const kept = input.previous.find(
59
+ (candidate) => candidate.contentId === image.contentId
60
+ );
61
+
62
+ if (!kept) throw new UploadValidationError("Image was not found");
63
+
64
+ return kept;
65
+ }
66
+
67
+ // Upload keys carry the uploader's id, so only their own uploads load.
68
+ const upload = await loadComposerUpload({
69
+ env: input.env,
70
+ mailboxId: content.uploadMailboxId ?? "",
71
+ userId: input.userId,
72
+ uploadId: image.uploadId,
73
+ });
74
+
75
+ if (!isComposerInlineImageContentType(upload.contentType)) {
76
+ throw new UploadValidationError(
77
+ "Images must be PNG, JPEG, GIF, or WebP"
78
+ );
79
+ }
80
+
81
+ if (upload.size > MAX_RICH_IMAGE_BYTES) {
82
+ throw new UploadValidationError("Images are limited to 1 MB each");
83
+ }
84
+
85
+ await copyStoredAttachmentToMessage({
86
+ env: input.env,
87
+ sourceKey: upload.r2Key,
88
+ destinationKey: `${input.prefix}${image.contentId}`,
89
+ contentType: upload.contentType,
90
+ });
91
+
92
+ return {
93
+ contentId: image.contentId,
94
+ filename: upload.filename,
95
+ contentType: upload.contentType,
96
+ size: upload.size,
97
+ };
98
+ })
99
+ );
100
+ }
101
+
102
+ /** Deletes the objects under `prefix` except `keep` (content ids). */
103
+ export async function deleteRichImages(
104
+ bucket: R2Bucket,
105
+ prefix: string,
106
+ keep: ReadonlySet<string> = new Set()
107
+ ) {
108
+ // ponytail: one page; saved content holds far fewer than 1000 images.
109
+ const page = await bucket.list({ prefix, limit: 1000 });
110
+
111
+ const stale = page.objects
112
+ .map((object) => object.key)
113
+ .filter((key) => !keep.has(key.slice(prefix.length)));
114
+
115
+ if (stale.length) await bucket.delete(stale);
116
+ }
117
+
118
+ /** The images `html` uses, to send inline from their objects under `prefix`. */
119
+ export function inlineImages(
120
+ prefix: string,
121
+ html: string,
122
+ images: readonly RichImage[]
123
+ ) {
124
+ return referencedImages(html, images).map((image) => ({
125
+ ...image,
126
+ r2Key: `${prefix}${image.contentId}`,
127
+ }));
128
+ }
129
+
130
+ /**
131
+ * The message with rich content appended after a blank line, and the images
132
+ * it uses to send inline. A text-only body gets an HTML part, so they show.
133
+ */
134
+ export function appendRichContent<
135
+ T extends { bodyText: string; bodyHtml?: string },
136
+ >(
137
+ message: T,
138
+ content: { html: string; text: string; images: readonly RichImage[] },
139
+ prefix: string
140
+ ) {
141
+ const body = message.bodyText.trimEnd();
142
+
143
+ const bodyHtml =
144
+ message.bodyHtml ??
145
+ (body ? `<div style="white-space:pre-wrap">${escapeHtml(body)}</div>` : "");
146
+
147
+ return {
148
+ ...message,
149
+ bodyText: body ? `${body}\n\n${content.text}` : content.text,
150
+ bodyHtml: `${bodyHtml}<div data-rich-content><br>${content.html}</div>`,
151
+ inlineImages: inlineImages(prefix, content.html, content.images),
152
+ };
153
+ }
154
+
155
+ /**
156
+ * The saved images a composed message refers to (its editor inserted them
157
+ * without uploading them again), each from one of `sources`, the content the
158
+ * sender may use, once per image. A reference to an image that isn't there
159
+ * (the signature changed since the editor opened, or it is someone else's)
160
+ * is left out, and its content id returned in `missing`.
161
+ */
162
+ export function referencedStoredImages(
163
+ refs: readonly StoredImageRef[],
164
+ sources: readonly {
165
+ ownerId: string;
166
+ prefix: string;
167
+ images: readonly RichImage[];
168
+ }[]
169
+ ) {
170
+ const images = new Map<string, InlineImage>();
171
+ const missing = new Set<string>();
172
+
173
+ for (const ref of refs) {
174
+ const source = sources.find(
175
+ (candidate) => candidate.ownerId === ref.ownerId
176
+ );
177
+
178
+ const image = source?.images.find(
179
+ (candidate) => candidate.contentId === ref.contentId
180
+ );
181
+
182
+ if (source && image) {
183
+ images.set(image.contentId, {
184
+ ...image,
185
+ r2Key: `${source.prefix}${image.contentId}`,
186
+ });
187
+ } else {
188
+ missing.add(ref.contentId);
189
+ }
190
+ }
191
+
192
+ return { images: [...images.values()], missing };
193
+ }
194
+
195
+ /** `html` without the `img` elements showing these `cid:` images. */
196
+ export function withoutCidImages(
197
+ html: string,
198
+ contentIds: ReadonlySet<string>
199
+ ) {
200
+ if (!contentIds.size) return html;
201
+
202
+ return html.replaceAll(/<img\b[^>]*>/giu, (tag) => {
203
+ const source = /\ssrc\s*=\s*["']cid:([^"']+)["']/iu.exec(tag)?.[1];
204
+
205
+ return source && contentIds.has(source) ? "" : tag;
206
+ });
207
+ }