@open-workspace/email 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -1,9 +1,11 @@
1
1
  import type { AppEnv } from "@open-workspace/core/module";
2
2
  import { createId } from "@open-workspace/core/module";
3
+ import { waitUntil } from "cloudflare:workers";
3
4
  import { z } from "zod";
4
5
 
5
6
  import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
6
7
  import { signR2PutUrl } from "./r2-presigned-urls";
8
+ import { mailboxPrefix } from "./storage-keys";
7
9
 
8
10
  type Bindings = AppEnv["Bindings"];
9
11
 
@@ -76,6 +78,76 @@ export function composerUploadMetaKey(
76
78
  return `${composerUploadPrefix(mailboxId, userId, uploadId)}/metadata.json`;
77
79
  }
78
80
 
81
+ /**
82
+ * Where a draft keeps an upload's bytes: under the mailbox's own prefix (so
83
+ * deleting the mailbox deletes it), outside `composer-uploads/` and its 7-day
84
+ * expiry. Keyed by the upload's id so the composer gets the same upload back.
85
+ */
86
+ export function draftFileKey(
87
+ mailboxId: string,
88
+ userId: string,
89
+ uploadId: string
90
+ ) {
91
+ return `${mailboxPrefix(mailboxId)}drafts/${userId}/${uploadId}`;
92
+ }
93
+
94
+ const draftFileMetaSchema = z.object({
95
+ filename: z.string().min(1).max(255),
96
+ contentType: z.string().min(1).max(255),
97
+ });
98
+
99
+ /** The upload as its draft holds it, or null if no draft holds it. */
100
+ async function loadDraftFile(input: {
101
+ env: Bindings;
102
+ mailboxId: string;
103
+ userId: string;
104
+ uploadId: string;
105
+ }) {
106
+ const r2Key = draftFileKey(input.mailboxId, input.userId, input.uploadId);
107
+ const object = await input.env.MAIL_STORAGE.head(r2Key);
108
+ const meta = draftFileMetaSchema.safeParse(object?.customMetadata);
109
+
110
+ if (!object || !meta.success) return null;
111
+
112
+ return {
113
+ id: input.uploadId,
114
+ r2Key,
115
+ filename: meta.data.filename,
116
+ contentType: meta.data.contentType,
117
+ size: object.size,
118
+ };
119
+ }
120
+
121
+ /** Copies an object to a draft file key, with what loading it back needs. */
122
+ export async function copyDraftFile(
123
+ env: Bindings,
124
+ sourceKey: string,
125
+ file: { r2Key: string; filename: string; contentType: string }
126
+ ) {
127
+ const source = await env.MAIL_STORAGE.get(sourceKey);
128
+
129
+ if (!source) {
130
+ throw new UploadValidationError("Attachment upload was not found");
131
+ }
132
+
133
+ await env.MAIL_STORAGE.put(file.r2Key, source.body, {
134
+ httpMetadata: { contentType: file.contentType },
135
+ customMetadata: { filename: file.filename, contentType: file.contentType },
136
+ });
137
+ }
138
+
139
+ /** Reads a file a draft holds, for showing its inline image in the composer. */
140
+ export function readDraftFile(input: {
141
+ env: Bindings;
142
+ mailboxId: string;
143
+ userId: string;
144
+ uploadId: string;
145
+ }) {
146
+ return input.env.MAIL_STORAGE.get(
147
+ draftFileKey(input.mailboxId, input.userId, input.uploadId)
148
+ );
149
+ }
150
+
79
151
  function composerUploadKeys(
80
152
  mailboxId: string,
81
153
  userId: string,
@@ -114,6 +186,50 @@ async function readUploadMeta(env: Bindings, metadataKey: string) {
114
186
  }
115
187
  }
116
188
 
189
+ /** An attachment already held by this mailbox becomes a private, expiring composer upload. */
190
+ export async function copyAttachmentToUpload(
191
+ input: UploadRef & {
192
+ sourceKey: string;
193
+ filename: string;
194
+ contentType: string;
195
+ size: number;
196
+ }
197
+ ) {
198
+ if (input.size <= 0 || input.size > MAX_COMPOSER_ATTACHMENT_BYTES) {
199
+ throw new UploadValidationError(
200
+ "Attachment size is outside the composer limits"
201
+ );
202
+ }
203
+
204
+ const keys = composerUploadKeys(
205
+ input.mailboxId,
206
+ input.userId,
207
+ input.uploadId
208
+ );
209
+
210
+ const contentType =
211
+ input.contentType.trim().slice(0, 255) || "application/octet-stream";
212
+
213
+ await copyStoredAttachmentToMessage({
214
+ env: input.env,
215
+ sourceKey: input.sourceKey,
216
+ destinationKey: keys.immutable,
217
+ contentType,
218
+ });
219
+ await putUploadMeta({
220
+ env: input.env,
221
+ metadataKey: keys.metadata,
222
+ meta: {
223
+ finalizedAt: Date.now(),
224
+ uploadedBy: input.userId,
225
+ mailboxId: input.mailboxId,
226
+ size: input.size,
227
+ filename: input.filename.trim().slice(0, 255) || "attachment",
228
+ contentType,
229
+ },
230
+ });
231
+ }
232
+
117
233
  export async function createComposerUploadIntent(input: {
118
234
  env: Bindings;
119
235
  mailboxId: string;
@@ -121,7 +237,7 @@ export async function createComposerUploadIntent(input: {
121
237
  filename: string;
122
238
  contentType: string;
123
239
  size: number;
124
- }): Promise<ComposerUploadIntent> {
240
+ }) {
125
241
  if (input.size <= 0) {
126
242
  throw new UploadValidationError("Attachment file is empty");
127
243
  }
@@ -323,40 +439,12 @@ function assertUploadOwner(
323
439
  return meta;
324
440
  }
325
441
 
326
- export async function loadComposerUploadMetadata(input: {
327
- env: Bindings;
328
- mailboxId: string;
329
- userId: string;
330
- uploadId: string;
331
- }): Promise<UploadedAttachment> {
332
- const keys = composerUploadKeys(
333
- input.mailboxId,
334
- input.userId,
335
- input.uploadId
336
- );
337
-
338
- const meta = assertUploadOwner(
339
- await readUploadMeta(input.env, keys.metadata),
340
- input.userId,
341
- input.mailboxId
342
- );
343
-
344
- return {
345
- id: input.uploadId,
346
- r2Key: meta.finalizedAt === null ? keys.staging : keys.immutable,
347
- filename: meta.filename,
348
- contentType: meta.contentType,
349
- size: meta.size,
350
- };
351
- }
352
-
353
442
  export async function finalizeComposerUpload(input: {
354
443
  env: Bindings;
355
444
  mailboxId: string;
356
445
  userId: string;
357
446
  uploadId: string;
358
- defer?: (task: Promise<unknown>) => void;
359
- }): Promise<UploadedAttachment> {
447
+ }) {
360
448
  const keys = composerUploadKeys(
361
449
  input.mailboxId,
362
450
  input.userId,
@@ -371,7 +459,7 @@ export async function finalizeComposerUpload(input: {
371
459
 
372
460
  if (meta.finalizedAt !== null) {
373
461
  const upload = await loadComposerUpload(input);
374
- await cleanupStagingAfterFinalization(input, keys.staging);
462
+ cleanupStagingAfterFinalization(input.env, keys.staging);
375
463
 
376
464
  return upload;
377
465
  }
@@ -426,11 +514,10 @@ async function completeComposerUploadFinalization(
426
514
  mailboxId: string;
427
515
  userId: string;
428
516
  uploadId: string;
429
- defer?: (task: Promise<unknown>) => void;
430
517
  },
431
518
  keys: ReturnType<typeof composerUploadKeys>,
432
519
  meta: UploadMeta
433
- ): Promise<UploadedAttachment> {
520
+ ) {
434
521
  await putUploadMeta({
435
522
  env: input.env,
436
523
  metadataKey: keys.metadata,
@@ -439,7 +526,7 @@ async function completeComposerUploadFinalization(
439
526
  finalizedAt: Date.now(),
440
527
  },
441
528
  });
442
- await cleanupStagingAfterFinalization(input, keys.staging);
529
+ cleanupStagingAfterFinalization(input.env, keys.staging);
443
530
 
444
531
  return {
445
532
  id: input.uploadId,
@@ -450,17 +537,9 @@ async function completeComposerUploadFinalization(
450
537
  };
451
538
  }
452
539
 
453
- function cleanupStagingAfterFinalization(
454
- input: {
455
- env: Bindings;
456
- defer?: (task: Promise<unknown>) => void;
457
- },
458
- key: string
459
- ) {
460
- const cleanup = deleteStagingObject(input.env, key);
461
-
462
- if (input.defer) input.defer(cleanup);
463
- else return cleanup;
540
+ /** The staging copy goes after the response (`waitUntil`). */
541
+ function cleanupStagingAfterFinalization(env: Bindings, key: string) {
542
+ waitUntil(deleteStagingObject(env, key));
464
543
  }
465
544
 
466
545
  async function deleteStagingObject(env: Bindings, key: string) {
@@ -472,72 +551,105 @@ async function deleteStagingObject(env: Bindings, key: string) {
472
551
  }
473
552
  }
474
553
 
475
- export async function loadComposerUpload(input: {
554
+ type UploadRef = {
476
555
  env: Bindings;
477
556
  mailboxId: string;
478
557
  userId: string;
479
558
  uploadId: string;
480
- }): Promise<UploadedAttachment> {
559
+ };
560
+
561
+ /**
562
+ * The one way to find an upload's bytes: the uploaded file, else the copy
563
+ * a draft keeps of it (a reopened or restored draft whose upload expired).
564
+ * Found by the file, not its metadata: metadata outliving its file goes to
565
+ * the draft's copy, and a draft's copy needs no metadata. `meta` is the
566
+ * upload's own metadata when the bytes are the upload's.
567
+ */
568
+ async function locateComposerUpload(
569
+ input: UploadRef,
570
+ options: { unfinished: boolean }
571
+ ) {
481
572
  const keys = composerUploadKeys(
482
573
  input.mailboxId,
483
574
  input.userId,
484
575
  input.uploadId
485
576
  );
486
577
 
487
- const [object, meta] = await Promise.all([
578
+ const [object, stored] = await Promise.all([
488
579
  input.env.MAIL_STORAGE.head(keys.immutable),
489
580
  readUploadMeta(input.env, keys.metadata),
490
581
  ]);
491
582
 
492
- if (!object || !meta || meta.finalizedAt === null) {
493
- throw new UploadValidationError("Attachment upload was not found");
494
- }
583
+ const meta =
584
+ stored?.uploadedBy === input.userId && stored.mailboxId === input.mailboxId
585
+ ? stored
586
+ : null;
587
+
588
+ const own = (found: UploadMeta, r2Key: string, size: number) => ({
589
+ upload: {
590
+ id: input.uploadId,
591
+ r2Key,
592
+ filename: found.filename,
593
+ contentType: found.contentType,
594
+ size,
595
+ },
596
+ meta: found,
597
+ });
495
598
 
496
- if (meta.uploadedBy !== input.userId || meta.mailboxId !== input.mailboxId) {
497
- throw new UploadValidationError("Attachment upload was not found");
498
- }
599
+ if (meta && object && meta.finalizedAt !== null) {
600
+ if (object.size <= 0 || object.size !== meta.size) {
601
+ throw new UploadValidationError("Attachment upload is incomplete");
602
+ }
499
603
 
500
- if (object.size <= 0 || object.size !== meta.size) {
501
- throw new UploadValidationError("Attachment upload is incomplete");
604
+ if (object.size > MAX_COMPOSER_ATTACHMENT_BYTES) {
605
+ throw new UploadValidationError("Attachment upload is invalid");
606
+ }
607
+
608
+ return own(meta, keys.immutable, object.size);
502
609
  }
503
610
 
504
- if (object.size > MAX_COMPOSER_ATTACHMENT_BYTES) {
505
- throw new UploadValidationError("Attachment upload is invalid");
611
+ // Not sealed yet: its metadata says what it will be (preflight).
612
+ if (meta && meta.finalizedAt === null && options.unfinished) {
613
+ return own(meta, keys.staging, meta.size);
506
614
  }
507
615
 
508
- return {
509
- id: input.uploadId,
510
- r2Key: keys.immutable,
511
- filename: meta.filename,
512
- contentType: meta.contentType,
513
- size: object.size,
514
- };
616
+ const held = await loadDraftFile(input);
617
+
618
+ if (held) return { upload: held, meta: null };
619
+ throw new UploadValidationError("Attachment upload was not found");
620
+ }
621
+
622
+ /**
623
+ * A finished upload's bytes (see `locateComposerUpload`); `unfinished` also
624
+ * takes one whose bytes aren't sealed yet, at its staging key.
625
+ */
626
+ export async function loadComposerUpload(
627
+ input: UploadRef,
628
+ options?: { unfinished: boolean }
629
+ ) {
630
+ const unfinished = options?.unfinished ?? false;
631
+
632
+ return (await locateComposerUpload(input, { unfinished })).upload;
515
633
  }
516
634
 
517
635
  /**
518
636
  * Sets the name and type a finished upload is sent with, for clients that
519
- * upload bytes first and describe them when composing (JMAP).
637
+ * upload bytes first and describe them when composing (JMAP). A draft's
638
+ * copy keeps the name it has.
520
639
  */
521
- export async function describeComposerUpload(input: {
522
- env: Bindings;
523
- mailboxId: string;
524
- userId: string;
525
- uploadId: string;
526
- filename: string;
527
- contentType: string;
528
- }) {
640
+ export async function describeComposerUpload(
641
+ input: UploadRef & { filename: string; contentType: string }
642
+ ) {
643
+ const { meta } = await locateComposerUpload(input, { unfinished: false });
644
+
645
+ if (!meta) return;
646
+
529
647
  const keys = composerUploadKeys(
530
648
  input.mailboxId,
531
649
  input.userId,
532
650
  input.uploadId
533
651
  );
534
652
 
535
- const meta = assertUploadOwner(
536
- await readUploadMeta(input.env, keys.metadata),
537
- input.userId,
538
- input.mailboxId
539
- );
540
-
541
653
  await putUploadMeta({
542
654
  env: input.env,
543
655
  metadataKey: keys.metadata,
@@ -2,15 +2,16 @@ import {
2
2
  createDb,
3
3
  mailboxAddressSql,
4
4
  mailboxKind,
5
- mailboxes,
6
5
  } from "@open-workspace/core/module";
7
6
  import type { WorkspaceModule } from "@open-workspace/core/module";
7
+ import { mailboxes } from "@open-workspace/core/schema";
8
8
  import { eq } from "drizzle-orm";
9
9
  import { z } from "zod";
10
10
 
11
11
  import { mailboxStub } from "../mailbox";
12
12
  import type { Email } from "../mailbox/schema";
13
13
  import { headerAuthentication } from "./header-metadata";
14
+ import { messageText } from "./outbound-content";
14
15
 
15
16
  function publicEmail(email: Email, bodyHtml: string | null) {
16
17
  return {
@@ -24,7 +25,7 @@ function publicEmail(email: Email, bodyHtml: string | null) {
24
25
  replyTo: email.replyToJson,
25
26
  subject: email.subject,
26
27
  body: {
27
- text: email.bodyText,
28
+ text: messageText(email),
28
29
  html: bodyHtml,
29
30
  },
30
31
  attachments: email.attachmentsJson.map((attachment) => ({
@@ -1,8 +1,13 @@
1
- import { createDb } from "@open-workspace/core/module";
2
- import { and, desc, eq, ne } from "drizzle-orm";
1
+ import { configuredMailDomains, createDb } from "@open-workspace/core/module";
2
+ import { and, countDistinct, desc, eq, ne, or, sql } from "drizzle-orm";
3
3
 
4
+ import { blockPatternsFor } from "../../shared/mail-feedback";
4
5
  import type { FeedbackLabel } from "../../shared/mail-feedback";
5
6
  import { blockedSenders, senderReports } from "../db/schema";
7
+ import type { SpamVerdict } from "../mailbox/placement";
8
+ import { mailboxBlockFor, senderBlockFor } from "../mailbox/senders";
9
+ import type { MessageSenders } from "../mailbox/senders";
10
+ import type { MailboxDatabase } from "../mailbox/support";
6
11
  import { isolateCache, WORKSPACE_CACHE_TTL_MS } from "./isolate-cache";
7
12
 
8
13
  const MAX_WORKSPACE_BLOCKS = 5000;
@@ -21,6 +26,42 @@ export async function workspaceBlockPatterns(binding: D1Database) {
21
26
  return new Map(rows.map((row) => [row.pattern, row.createdAt.getTime()]));
22
27
  }
23
28
 
29
+ /**
30
+ * The one sender screen for arriving mail: the block holding it back when
31
+ * its From or envelope sender is blocked for the workspace or, given the
32
+ * mailbox's storage, for that mailbox; null when none. The workspace's
33
+ * blocks are read fresh, and when they can't be read this throws: the
34
+ * delivery is tried again later, never delivered unscreened.
35
+ */
36
+ export async function screenSender(
37
+ binding: D1Database,
38
+ sender: MessageSenders,
39
+ mailbox?: MailboxDatabase
40
+ ) {
41
+ if (!sender.from?.includes("@") && !sender.envelopeFrom?.includes("@")) {
42
+ return null;
43
+ }
44
+
45
+ return senderBlockFor(
46
+ sender,
47
+ await workspaceBlockPatterns(binding),
48
+ (address) => (mailbox ? mailboxBlockFor(mailbox, address) : null)
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The workspace's blocks, read fresh, for what moving mail out of Spam
54
+ * says about its senders (`leaveSpam`); null when they can't be read, and
55
+ * then it says nothing rather than fail the move.
56
+ */
57
+ export function workspaceBlocksForVerdicts(binding: D1Database) {
58
+ return workspaceBlockPatterns(binding).catch((error) => {
59
+ console.error("Could not read workspace blocks", error);
60
+
61
+ return null;
62
+ });
63
+ }
64
+
24
65
  const blockPatternCache = isolateCache(
25
66
  WORKSPACE_CACHE_TTL_MS,
26
67
  workspaceBlockPatterns
@@ -36,6 +77,32 @@ export function cachedWorkspaceBlockPatterns(binding: D1Database) {
36
77
  return blockPatternCache.get(binding);
37
78
  }
38
79
 
80
+ /** Whether an address's or block pattern's domain is one of the workspace's own mail domains, or overlaps one. */
81
+ export function blocksOwnMailDomain(pattern: string) {
82
+ const domain = pattern.slice(pattern.lastIndexOf("@") + 1);
83
+
84
+ return configuredMailDomains().some(
85
+ (name) =>
86
+ domain === name ||
87
+ domain.endsWith(`.${name}`) ||
88
+ name.endsWith(`.${domain}`)
89
+ );
90
+ }
91
+
92
+ /**
93
+ * Whether the mailbox at `ownAddress` may not block `pattern`: its own
94
+ * address or a domain over it, or a domain of the workspace (or over one),
95
+ * since the workspace's own mail would go to Spam with it. One colleague's
96
+ * address can still be blocked. The mailbox's screen and its restore both
97
+ * ask this.
98
+ */
99
+ export function mailboxBlockRefused(ownAddress: string, pattern: string) {
100
+ return (
101
+ blockPatternsFor(ownAddress).includes(pattern) ||
102
+ (pattern.startsWith("@") && blocksOwnMailDomain(pattern))
103
+ );
104
+ }
105
+
39
106
  export function forgetWorkspaceBlockPatterns() {
40
107
  blockPatternCache.clear();
41
108
  }
@@ -52,7 +119,8 @@ export async function recordWorkspaceFeedback(
52
119
  emailId: string;
53
120
  address: string;
54
121
  label: FeedbackLabel;
55
- }
122
+ },
123
+ keepPrevious = false
56
124
  ) {
57
125
  const address = input.address.toLocaleLowerCase();
58
126
 
@@ -74,24 +142,106 @@ export async function recordWorkspaceFeedback(
74
142
  ? ne(senderReports.label, "not_spam")
75
143
  : eq(senderReports.label, "not_spam");
76
144
 
77
- await db.batch([
78
- db
79
- .delete(senderReports)
80
- .where(
81
- and(
82
- eq(senderReports.mailboxId, input.mailboxId),
83
- eq(senderReports.address, address),
84
- opposite
85
- )
86
- ),
87
- db
88
- .insert(senderReports)
89
- .values(row)
90
- .onConflictDoUpdate({
91
- target: [senderReports.mailboxId, senderReports.emailId],
92
- set: { label: row.label, createdAt: row.createdAt },
93
- }),
145
+ const displaced = db
146
+ .delete(senderReports)
147
+ .where(
148
+ and(
149
+ eq(senderReports.mailboxId, input.mailboxId),
150
+ eq(senderReports.address, address),
151
+ or(opposite, eq(senderReports.emailId, input.emailId))
152
+ )
153
+ );
154
+
155
+ const insert = db.insert(senderReports).values(row);
156
+
157
+ if (!keepPrevious) {
158
+ await db.batch([displaced, insert]);
159
+
160
+ return;
161
+ }
162
+
163
+ const [previous] = await db.batch([
164
+ displaced.returning({
165
+ emailId: senderReports.emailId,
166
+ label: senderReports.label,
167
+ createdAt: senderReports.createdAt,
168
+ }),
169
+ insert,
94
170
  ]);
171
+
172
+ return {
173
+ address,
174
+ emailId: row.emailId,
175
+ at: row.createdAt.getTime(),
176
+ previous: previous.map(({ emailId, label, createdAt }) => ({
177
+ emailId,
178
+ label,
179
+ at: createdAt.getTime(),
180
+ })),
181
+ };
182
+ }
183
+
184
+ export type WorkspaceVerdictUndo = NonNullable<
185
+ Awaited<ReturnType<typeof recordWorkspaceFeedback>>
186
+ >;
187
+
188
+ /** Replay only rows displaced by this verdict, and only while that verdict is current. */
189
+ export async function undoWorkspaceFeedback(
190
+ binding: D1Database,
191
+ mailboxId: string,
192
+ changes: WorkspaceVerdictUndo[]
193
+ ) {
194
+ if (!changes.length) return;
195
+ await binding.batch(
196
+ changes.flatMap((change) => [
197
+ binding
198
+ .prepare(
199
+ "delete from sender_reports where mailbox_id = ? and email_id = ? and created_at = ?"
200
+ )
201
+ .bind(mailboxId, change.emailId, change.at),
202
+ binding
203
+ .prepare(`insert into sender_reports (mailbox_id, email_id, address, domain, label, created_at)
204
+ select ?, json_extract(value, '$.emailId'), ?, ?, json_extract(value, '$.label'), json_extract(value, '$.at')
205
+ from json_each(?) where changes() > 0 on conflict do nothing`)
206
+ .bind(
207
+ mailboxId,
208
+ change.address,
209
+ addressDomain(change.address),
210
+ JSON.stringify(change.previous)
211
+ ),
212
+ ])
213
+ );
214
+ }
215
+
216
+ /**
217
+ * Shares what a person said about senders in one mailbox (Report spam, Not
218
+ * spam, or a move into or out of Spam) with the workspace. A failure is
219
+ * logged: the mailbox already learned it.
220
+ */
221
+ export async function shareSpamVerdicts(
222
+ binding: D1Database,
223
+ mailboxId: string,
224
+ verdicts: readonly SpamVerdict[],
225
+ keepPrevious = false
226
+ ) {
227
+ const changes = await Promise.all(
228
+ verdicts.map((verdict) =>
229
+ recordWorkspaceFeedback(
230
+ binding,
231
+ { mailboxId, ...verdict },
232
+ keepPrevious
233
+ ).catch((error) => {
234
+ console.error(
235
+ `Could not share the ${verdict.label} verdict for ${verdict.emailId}`,
236
+ error
237
+ );
238
+
239
+ return undefined;
240
+ })
241
+ )
242
+ );
243
+
244
+ return changes.filter((change) => change !== undefined);
95
245
  }
96
246
 
97
247
  /** Verdicts other mailboxes in the workspace gave this sender and its domain. */
@@ -102,48 +252,32 @@ export async function workspaceFeedbackSummary(
102
252
  ) {
103
253
  const value = address.toLocaleLowerCase();
104
254
 
105
- const [groups, reporters] = await binding.batch<
106
- {
107
- label: FeedbackLabel;
108
- same_address: number;
109
- count: number;
110
- } & { mailboxes: number }
111
- >([
112
- binding
113
- .prepare(`
114
- select label, address = ?1 as same_address, count(*) as count
115
- from sender_reports
116
- where domain = ?2 and mailbox_id <> ?3
117
- group by label, address = ?1
118
- `)
119
- .bind(value, addressDomain(value), mailboxId),
120
- binding
121
- .prepare(`
122
- select count(distinct mailbox_id) as mailboxes
123
- from sender_reports
124
- where address = ?1 and label <> 'not_spam' and mailbox_id <> ?2
125
- `)
126
- .bind(value, mailboxId),
127
- ]);
128
-
129
- const rows = groups?.results ?? [];
255
+ const db = createDb(binding);
256
+ const { label, address: sender, mailboxId: reporter } = senderReports;
130
257
 
131
- const count = (labels: FeedbackLabel[], sameAddress: boolean) =>
132
- rows
133
- .filter(
134
- (row) =>
135
- labels.includes(row.label) &&
136
- Boolean(row.same_address) === sameAddress
137
- )
138
- .reduce((total, row) => total + Number(row.count), 0);
258
+ const [[counts], [distinct]] = await db.batch([
259
+ db
260
+ .select({
261
+ spamReports: sql<number>`count(*) filter (where ${label} = 'spam' and ${sender} = ${value})`,
262
+ notSpam: sql<number>`count(*) filter (where ${label} = 'not_spam' and ${sender} = ${value})`,
263
+ domainReports: sql<number>`count(*) filter (where ${label} = 'spam' and ${sender} <> ${value})`,
264
+ })
265
+ .from(senderReports)
266
+ .where(
267
+ and(
268
+ eq(senderReports.domain, addressDomain(value)),
269
+ ne(reporter, mailboxId)
270
+ )
271
+ ),
272
+ db
273
+ .select({ mailboxes: countDistinct(reporter) })
274
+ .from(senderReports)
275
+ .where(
276
+ and(eq(sender, value), ne(label, "not_spam"), ne(reporter, mailboxId))
277
+ ),
278
+ ]);
139
279
 
140
- return {
141
- spamReports: count(["spam"], true),
142
- notSpam: count(["not_spam"], true),
143
- domainReports: count(["spam"], false),
144
- /** How many other mailboxes reported this exact address. */
145
- reportingMailboxes: Number(reporters?.results[0]?.mailboxes ?? 0),
146
- };
280
+ return { ...counts, reportingMailboxes: distinct.mailboxes };
147
281
  }
148
282
 
149
283
  export type WorkspaceFeedbackSummary = Awaited<