@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -4,15 +4,28 @@ import type {
4
4
  MessageSecurity,
5
5
  } from "../../shared/mail-authentication";
6
6
  import { addressDomain } from "../../shared/mail-headers";
7
- import type { DeliveryFacts, SecurityWarning, SenderIntel } from "../../shared/mail-sender-intel";
7
+ import type {
8
+ DeliveryFacts,
9
+ SecurityWarning,
10
+ SenderIntel,
11
+ } from "../../shared/mail-sender-intel";
8
12
  import { addressedElsewhereWarning } from "./delivery-facts";
9
- import { embeddedAddress, impersonatedName, lookalikeOf } from "./impersonation";
13
+ import {
14
+ embeddedAddress,
15
+ impersonatedName,
16
+ lookalikeOf,
17
+ } from "./impersonation";
10
18
  import { organizationalDomain, relaxedAligned } from "./org-domain";
11
19
 
12
- export function isWorkspaceDomain(domain: string | null, workspaceDomains: readonly string[]) {
20
+ export function isWorkspaceDomain(
21
+ domain: string | null,
22
+ workspaceDomains: readonly string[]
23
+ ) {
13
24
  if (!domain) return false;
25
+
14
26
  return workspaceDomains.some((candidate) => {
15
27
  const name = candidate.toLocaleLowerCase();
28
+
16
29
  return domain === name || domain.endsWith(`.${name}`);
17
30
  });
18
31
  }
@@ -45,11 +58,17 @@ export function replyToMismatch(input: {
45
58
  }) {
46
59
  if (input.listId) return null;
47
60
  const fromOrg = organizationalDomain(input.fromAddress);
61
+
48
62
  if (!fromOrg) return null;
63
+
49
64
  for (const address of input.replyTo) {
50
65
  const domain = organizationalDomain(address);
51
- if (domain && domain !== fromOrg) return { address: address.toLocaleLowerCase(), domain };
66
+
67
+ if (domain && domain !== fromOrg) {
68
+ return { address: address.toLocaleLowerCase(), domain };
69
+ }
52
70
  }
71
+
53
72
  return null;
54
73
  }
55
74
 
@@ -76,6 +95,7 @@ export function securityWarnings(input: {
76
95
  const warnings: SecurityWarning[] = [];
77
96
  const spamhaus = input.intel?.spamhaus;
78
97
  const dbl = spamhaus?.dbl.listings ?? [];
98
+
79
99
  if (dbl.length) {
80
100
  const fromOrg = organizationalDomain(input.fromDomain);
81
101
  warnings.push({
@@ -86,38 +106,79 @@ export function securityWarnings(input: {
86
106
  senderDomain: dbl.some((listing) => listing.target === fromOrg),
87
107
  });
88
108
  }
109
+
89
110
  const zen = spamhaus?.zen.listings ?? [];
111
+
90
112
  if (zen.length && input.intel?.ip) {
91
113
  warnings.push({
92
114
  kind: "zen_listed",
93
- severity: zen.some((listing) => listing.severity === "abuse") ? "danger" : "caution",
115
+ severity: zen.some((listing) => listing.severity === "abuse")
116
+ ? "danger"
117
+ : "caution",
94
118
  ip: input.intel.ip,
95
119
  lists: [...new Set(zen.map((listing) => listing.list))],
96
120
  });
97
121
  }
122
+
98
123
  if (input.external) {
99
124
  const lookalike = lookalikeOf(input.fromDomain, input.workspaceDomains);
100
- if (lookalike) warnings.push({ kind: "lookalike_domain", severity: "danger", ...lookalike });
125
+
126
+ if (lookalike) {
127
+ warnings.push({
128
+ kind: "lookalike_domain",
129
+ severity: "danger",
130
+ ...lookalike,
131
+ });
132
+ }
133
+
101
134
  // Someone this mailbox has written to before (a colleague's personal
102
135
  // address) is an established correspondent, not an impersonator.
103
136
  const name = impersonatedName(input.fromName, input.internalNames);
137
+
104
138
  if (name && !(input.history && input.history.outboundCount > 0)) {
105
- warnings.push({ kind: "display_name_impersonation", severity: "danger", name });
139
+ warnings.push({
140
+ kind: "display_name_impersonation",
141
+ severity: "danger",
142
+ name,
143
+ });
106
144
  }
145
+
107
146
  const claimed = embeddedAddress(input.fromName, input.fromAddress);
108
- if (claimed) warnings.push({ kind: "embedded_address", severity: "caution", claimed });
147
+
148
+ if (claimed) {
149
+ warnings.push({ kind: "embedded_address", severity: "caution", claimed });
150
+ }
109
151
  }
152
+
110
153
  if (input.authentication?.verdict === "suspicious") {
111
- warnings.push({ kind: "unverified_sender", severity: "caution", domain: input.fromDomain });
154
+ warnings.push({
155
+ kind: "unverified_sender",
156
+ severity: "caution",
157
+ domain: input.fromDomain,
158
+ });
112
159
  }
160
+
113
161
  const mismatch = replyToMismatch({
114
162
  fromAddress: input.fromAddress,
115
163
  replyTo: input.replyTo ?? [],
116
164
  listId: input.listId ?? null,
117
165
  });
118
- if (mismatch) warnings.push({ kind: "reply_to_mismatch", severity: "caution", ...mismatch });
119
- const elsewhere = addressedElsewhereWarning(input.delivery ?? null, input.fromDomain);
166
+
167
+ if (mismatch) {
168
+ warnings.push({
169
+ kind: "reply_to_mismatch",
170
+ severity: "caution",
171
+ ...mismatch,
172
+ });
173
+ }
174
+
175
+ const elsewhere = addressedElsewhereWarning(
176
+ input.delivery ?? null,
177
+ input.fromDomain
178
+ );
179
+
120
180
  if (elsewhere) warnings.push(elsewhere);
181
+
121
182
  return warnings
122
183
  .filter((warning) => !input.trusted || warning.severity === "danger")
123
184
  .sort((left, right) => warningOrder[left.kind] - warningOrder[right.kind]);
@@ -139,19 +200,29 @@ export function messageSecurity(input: {
139
200
  trusted?: boolean;
140
201
  }): MessageSecurity {
141
202
  const auth = input.authentication;
142
- const fromDomain = addressDomain(input.fromAddress) ?? auth?.fromDomain ?? null;
203
+
204
+ const fromDomain =
205
+ addressDomain(input.fromAddress) ?? auth?.fromDomain ?? null;
206
+
143
207
  const passing = auth?.dkim.filter((dkim) => dkim.result === "pass") ?? [];
144
208
  const alignedDkim = passing.find((dkim) => dkim.aligned);
145
209
  const signedBy = (alignedDkim ?? passing[0])?.domain ?? null;
146
- const mailedBy = auth?.spf?.domain ?? addressDomain(auth?.envelopeFrom) ?? null;
210
+
211
+ const mailedBy =
212
+ auth?.spf?.domain ?? addressDomain(auth?.envelopeFrom) ?? null;
213
+
147
214
  let via: string | null = null;
215
+
148
216
  if (auth && auth.verdict !== "unavailable" && !alignedDkim) {
149
217
  const spfAligned = auth.spf?.result === "pass" && auth.spf.aligned;
150
218
  const candidate = signedBy ?? (spfAligned ? null : mailedBy);
151
- via = candidate && !relaxedAligned(candidate, fromDomain) ? candidate : null;
219
+ via =
220
+ candidate && !relaxedAligned(candidate, fromDomain) ? candidate : null;
152
221
  }
222
+
153
223
  const external = !isWorkspaceDomain(fromDomain, input.workspaceDomains);
154
224
  const history = input.history ?? null;
225
+
155
226
  return {
156
227
  verdict: auth?.verdict ?? "unavailable",
157
228
  verdictReason: auth?.verdictReason ?? "not_cloudflare",
@@ -178,7 +249,11 @@ export function messageSecurity(input: {
178
249
  trusted: input.trusted,
179
250
  }),
180
251
  firstTimeSender: Boolean(
181
- !input.trusted && external && history && history.inboundCount <= 1 && history.outboundCount === 0,
252
+ !input.trusted &&
253
+ external &&
254
+ history &&
255
+ history.inboundCount <= 1 &&
256
+ history.outboundCount === 0
182
257
  ),
183
258
  replyToMismatch: replyToMismatch({
184
259
  fromAddress: input.fromAddress,
@@ -1,8 +1,9 @@
1
1
  import type { SenderStatus, Unsubscription } from "../../shared/mail-feedback";
2
- import { workspaceBlockFor } from "../mailbox/senders";
3
2
  import type { Email } from "../mailbox/schema";
3
+ import { workspaceBlockFor } from "../mailbox/senders";
4
4
  import { headerAuthentication } from "./header-metadata";
5
- import { messageSecurity, type SenderHistory } from "./message-security";
5
+ import { messageSecurity } from "./message-security";
6
+ import type { SenderHistory } from "./message-security";
6
7
  import type { WorkspaceIdentity } from "./security-settings";
7
8
  import { storedSenderIntel } from "./sender-intel";
8
9
  import { unsubscribeListKey } from "./unsubscribe";
@@ -20,12 +21,19 @@ const emptySafetyContext: MessageSafetyContext = {
20
21
  };
21
22
 
22
23
  /** Block, trust and report state for the sender, with workspace blocks taking precedence. */
23
- export function senderStatus(email: Email, safety: MessageSafetyContext): SenderStatus | null {
24
+ export function senderStatus(
25
+ email: Email,
26
+ safety: MessageSafetyContext
27
+ ): SenderStatus | null {
24
28
  if (email.direction !== "incoming") return null;
25
29
  const address = email.fromJson[0]?.address.toLocaleLowerCase() ?? "";
26
30
  const local = safety.senders[address];
31
+
27
32
  return {
28
- block: workspaceBlockFor(address, safety.workspaceBlocks) ?? local?.block ?? null,
33
+ block:
34
+ workspaceBlockFor(address, safety.workspaceBlocks) ??
35
+ local?.block ??
36
+ null,
29
37
  trustedAt: local?.trustedAt ?? null,
30
38
  reportedAt: local?.reportedAt ?? null,
31
39
  };
@@ -33,7 +41,10 @@ export function senderStatus(email: Email, safety: MessageSafetyContext): Sender
33
41
 
34
42
  export function emailListKey(email: Email) {
35
43
  return email.direction === "incoming"
36
- ? unsubscribeListKey({ listId: email.listId, fromAddress: email.fromJson[0]?.address ?? null })
44
+ ? unsubscribeListKey({
45
+ listId: email.listId,
46
+ fromAddress: email.fromJson[0]?.address ?? null,
47
+ })
37
48
  : null;
38
49
  }
39
50
 
@@ -41,11 +52,12 @@ export function emailSecurity(
41
52
  email: Email,
42
53
  identity: WorkspaceIdentity,
43
54
  history: Record<string, SenderHistory>,
44
- safety: MessageSafetyContext = emptySafetyContext,
55
+ safety: MessageSafetyContext = emptySafetyContext
45
56
  ) {
46
57
  if (email.direction !== "incoming") return null;
47
58
  const from = email.fromJson[0] ?? { address: "", name: null };
48
59
  const status = senderStatus(email, safety);
60
+
49
61
  return messageSecurity({
50
62
  fromAddress: from.address,
51
63
  fromName: from.name,
@@ -1,4 +1,7 @@
1
- import { MAX_OFFICE_PREVIEW_BYTES, officePreviewKey } from "../../shared/office-preview";
1
+ import {
2
+ MAX_OFFICE_PREVIEW_BYTES,
3
+ officePreviewKey,
4
+ } from "../../shared/office-preview";
2
5
 
3
6
  export type OfficeConversionResult = "ready" | "failed";
4
7
 
@@ -6,33 +9,52 @@ export async function convertOfficeDocument(
6
9
  bucket: R2Bucket,
7
10
  send: (request: Request) => Promise<Response>,
8
11
  sourceKey: string,
9
- extension: string,
12
+ extension: string
10
13
  ): Promise<OfficeConversionResult> {
11
14
  const source = await bucket.get(sourceKey);
15
+
12
16
  if (!source) return "failed";
17
+
13
18
  // FormData buffers the upload in the Worker; cap it before reading the body.
14
19
  if (source.size > MAX_OFFICE_PREVIEW_BYTES) {
15
20
  await source.body.cancel();
21
+
16
22
  return "failed";
17
23
  }
24
+
18
25
  const form = new FormData();
19
- form.append("files", new Blob([await source.arrayBuffer()]), `document.${extension}`);
20
- const response = await send(new Request("http://container/forms/libreoffice/convert", {
21
- method: "POST",
22
- body: form,
23
- signal: AbortSignal.timeout(120_000),
24
- }));
26
+ form.append(
27
+ "files",
28
+ new Blob([await source.arrayBuffer()]),
29
+ `document.${extension}`
30
+ );
31
+
32
+ const response = await send(
33
+ new Request("http://container/forms/libreoffice/convert", {
34
+ method: "POST",
35
+ body: form,
36
+ signal: AbortSignal.timeout(120_000),
37
+ })
38
+ );
39
+
25
40
  if (!response.ok) {
26
41
  await response.body?.cancel();
42
+
27
43
  if ([400, 403, 415, 422].includes(response.status)) return "failed";
28
44
  throw new Error(`Office conversion failed with status ${response.status}`);
29
45
  }
30
- if (!response.body || response.headers.get("content-type")?.split(";", 1)[0] !== "application/pdf") {
46
+
47
+ if (
48
+ !response.body ||
49
+ response.headers.get("content-type")?.split(";", 1)[0] !== "application/pdf"
50
+ ) {
31
51
  await response.body?.cancel();
32
52
  throw new Error("Office converter did not return a PDF");
33
53
  }
54
+
34
55
  await bucket.put(officePreviewKey(sourceKey), response.body, {
35
56
  httpMetadata: { contentType: "application/pdf" },
36
57
  });
58
+
37
59
  return "ready";
38
60
  }
@@ -1,16 +1,26 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
- import { officePreviewExtension, officePreviewKey } from "../../shared/office-preview";
3
- import { convertOfficeDocument, type OfficeConversionResult } from "./office-conversion";
2
+
3
+ import {
4
+ officePreviewExtension,
5
+ officePreviewKey,
6
+ } from "../../shared/office-preview";
7
+ import { convertOfficeDocument } from "./office-conversion";
8
+ import type { OfficeConversionResult } from "./office-conversion";
9
+ import { repeatUntil } from "./repeat";
4
10
 
5
11
  export class OfficePreviewContainer extends DurableObject<Env> {
6
12
  private conversion: Promise<OfficeConversionResult> | null = null;
7
13
 
8
14
  async convert(sourceKey: string, extension: string) {
9
- if (officePreviewExtension(`document.${extension}`) !== extension) return "failed" as const;
15
+ if (officePreviewExtension(`document.${extension}`) !== extension) {
16
+ return "failed" as const;
17
+ }
18
+
10
19
  // Queue redelivery can overlap. Each attachment uses its own Durable Object,
11
20
  // so duplicate requests share one conversion and cannot stop each other's container.
12
21
  if (this.conversion) return this.conversion;
13
22
  this.conversion = this.runConversion(sourceKey, extension);
23
+
14
24
  try {
15
25
  return await this.conversion;
16
26
  } finally {
@@ -18,20 +28,31 @@ export class OfficePreviewContainer extends DurableObject<Env> {
18
28
  }
19
29
  }
20
30
 
21
- private async runConversion(sourceKey: string, extension: string): Promise<OfficeConversionResult> {
22
- if (await this.env.MAIL_STORAGE.head(officePreviewKey(sourceKey))) return "ready";
23
- const container = this.ctx.container;
24
- if (!container) throw new Error("Office preview container is not configured");
31
+ private async runConversion(
32
+ sourceKey: string,
33
+ extension: string
34
+ ): Promise<OfficeConversionResult> {
35
+ if (await this.env.MAIL_STORAGE.head(officePreviewKey(sourceKey))) {
36
+ return "ready";
37
+ }
38
+
39
+ const { container } = this.ctx;
40
+
41
+ if (!container) {
42
+ throw new Error("Office preview container is not configured");
43
+ }
44
+
25
45
  try {
26
46
  if (!container.running) container.start({ enableInternet: false });
27
47
  await container.setInactivityTimeout(10_000);
28
48
  const port = container.getTcpPort(3000);
29
49
  await waitForConverter(port);
50
+
30
51
  return await convertOfficeDocument(
31
52
  this.env.MAIL_STORAGE,
32
53
  (request) => port.fetch(request),
33
54
  sourceKey,
34
- extension,
55
+ extension
35
56
  );
36
57
  } finally {
37
58
  // R2 has consumed the PDF before this runs; no container is kept warm.
@@ -41,17 +62,23 @@ export class OfficePreviewContainer extends DurableObject<Env> {
41
62
  }
42
63
 
43
64
  async function waitForConverter(port: Fetcher) {
44
- for (let attempt = 0; attempt < 120; attempt += 1) {
65
+ const ready = await repeatUntil(120, async () => {
45
66
  try {
46
67
  const response = await port.fetch("http://container/health", {
47
- signal: AbortSignal.timeout(1_000),
68
+ signal: AbortSignal.timeout(1000),
48
69
  });
70
+
49
71
  await response.body?.cancel();
50
- if (response.ok) return;
72
+
73
+ if (response.ok) return true;
51
74
  } catch {
52
75
  // The container process starts before its HTTP port is ready.
53
76
  }
77
+
54
78
  await scheduler.wait(500);
55
- }
56
- throw new Error("Office preview container did not become ready");
79
+
80
+ return undefined;
81
+ });
82
+
83
+ if (!ready) throw new Error("Office preview container did not become ready");
57
84
  }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+
2
3
  import { officePreviewExtension } from "../../shared/office-preview";
3
4
  import { mailboxStub } from "../mailbox";
4
5
 
@@ -9,41 +10,84 @@ const jobSchema = z.object({
9
10
  sourceKey: z.string().min(1),
10
11
  });
11
12
 
12
- export async function consumeOfficePreviews(batch: MessageBatch<unknown>, env: Env) {
13
- for (const message of batch.messages) {
14
- const parsed = jobSchema.safeParse(message.body);
15
- if (!parsed.success) {
13
+ export async function consumeOfficePreviews(
14
+ batch: MessageBatch<unknown>,
15
+ env: Env
16
+ ) {
17
+ // Each job converts its own attachment, in its own container.
18
+ await Promise.all(
19
+ batch.messages.map((message) => processOfficePreview(message, env))
20
+ );
21
+ }
22
+
23
+ async function processOfficePreview(message: Message<unknown>, env: Env) {
24
+ const parsed = jobSchema.safeParse(message.body);
25
+
26
+ if (!parsed.success) {
27
+ message.ack();
28
+
29
+ return;
30
+ }
31
+
32
+ const job = parsed.data;
33
+ const mailbox = mailboxStub(env, job.mailboxId);
34
+
35
+ try {
36
+ const file = await mailbox.getAttachment(job.messageId, job.attachmentId);
37
+
38
+ if (!file || file.r2Key !== job.sourceKey) {
39
+ // A previous attempt may have produced a PDF after the email was deleted.
40
+ await mailbox.completeOfficePreview(
41
+ job.messageId,
42
+ job.attachmentId,
43
+ job.sourceKey,
44
+ "failed"
45
+ );
16
46
  message.ack();
17
- continue;
47
+
48
+ return;
18
49
  }
19
- const job = parsed.data;
20
- const mailbox = mailboxStub(env, job.mailboxId);
21
- try {
22
- const file = await mailbox.getAttachment(job.messageId, job.attachmentId);
23
- if (!file || file.r2Key !== job.sourceKey) {
24
- // A previous attempt may have produced a PDF after the email was deleted.
25
- await mailbox.completeOfficePreview(job.messageId, job.attachmentId, job.sourceKey, "failed");
26
- message.ack();
27
- continue;
28
- }
29
- if (file.pdfPreviewStatus !== "pending") {
30
- message.ack();
31
- continue;
32
- }
33
- const extension = officePreviewExtension(file.filename);
34
- const status = extension
35
- ? await env.OFFICE_PREVIEW_CONTAINER.getByName(job.sourceKey).convert(job.sourceKey, extension)
36
- : "failed";
37
- await mailbox.completeOfficePreview(job.messageId, job.attachmentId, job.sourceKey, status);
38
- message.ack();
39
- } catch (error) {
40
- console.error("Could not generate Office preview", { messageId: job.messageId, error });
41
- if (message.attempts < 3) {
42
- message.retry({ delaySeconds: 30 * message.attempts });
43
- continue;
44
- }
45
- await mailbox.completeOfficePreview(job.messageId, job.attachmentId, job.sourceKey, "failed");
50
+
51
+ if (file.pdfPreviewStatus !== "pending") {
46
52
  message.ack();
53
+
54
+ return;
55
+ }
56
+
57
+ const extension = officePreviewExtension(file.filename);
58
+
59
+ const status = extension
60
+ ? await env.OFFICE_PREVIEW_CONTAINER.getByName(job.sourceKey).convert(
61
+ job.sourceKey,
62
+ extension
63
+ )
64
+ : "failed";
65
+
66
+ await mailbox.completeOfficePreview(
67
+ job.messageId,
68
+ job.attachmentId,
69
+ job.sourceKey,
70
+ status
71
+ );
72
+ message.ack();
73
+ } catch (error) {
74
+ console.error("Could not generate Office preview", {
75
+ messageId: job.messageId,
76
+ error,
77
+ });
78
+
79
+ if (message.attempts < 3) {
80
+ message.retry({ delaySeconds: 30 * message.attempts });
81
+
82
+ return;
47
83
  }
84
+
85
+ await mailbox.completeOfficePreview(
86
+ job.messageId,
87
+ job.attachmentId,
88
+ job.sourceKey,
89
+ "failed"
90
+ );
91
+ message.ack();
48
92
  }
49
93
  }
@@ -1,15 +1,22 @@
1
1
  import { getDomain } from "tldts";
2
+
2
3
  import { addressDomain } from "../../shared/mail-headers";
3
4
 
4
5
  /** Organizational domain (Public Suffix List registrable domain) of a host or address. */
5
6
  export function organizationalDomain(value: string | null | undefined) {
6
7
  const domain = addressDomain(value);
8
+
7
9
  if (!domain) return null;
10
+
8
11
  return getDomain(domain) ?? domain;
9
12
  }
10
13
 
11
14
  /** DMARC relaxed alignment: both sides share one organizational domain. */
12
- export function relaxedAligned(left: string | null | undefined, right: string | null | undefined) {
15
+ export function relaxedAligned(
16
+ left: string | null | undefined,
17
+ right: string | null | undefined
18
+ ) {
13
19
  const a = organizationalDomain(left);
20
+
14
21
  return Boolean(a) && a === organizationalDomain(right);
15
22
  }