@open-workspace/email 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -13,18 +13,20 @@ import {
13
13
  overRateLimit,
14
14
  } from "@open-workspace/core/module";
15
15
  import type { AppEnv } from "@open-workspace/core/module";
16
+ import { waitUntil } from "cloudflare:workers";
16
17
  import { Hono } from "hono";
17
- import type { Context } from "hono";
18
+ import type { Context, ErrorHandler } from "hono";
18
19
  import { z } from "zod";
19
20
 
20
21
  import { attachmentPreview } from "../../shared/attachment-preview";
22
+ import { DRAFTS_FOLDER_ID } from "../../shared/folder-order";
21
23
  import {
22
24
  baseSubject,
25
+ EmailSizeLimitError,
23
26
  isComposerInlineImageContentType,
24
27
  } from "../../shared/mail";
25
28
  import { remoteImageUrls } from "../../shared/mail-remote";
26
29
  import { MAX_TRANSLATION_CHARACTERS } from "../../shared/mail-translation";
27
- import { officePreviewKey } from "../../shared/office-preview";
28
30
  import {
29
31
  MAIL_ORGANIZE_SCOPE,
30
32
  MAIL_READ_SCOPE,
@@ -32,7 +34,9 @@ import {
32
34
  } from "../../shared/permissions";
33
35
  import { mailboxStub } from "../mailbox";
34
36
  import type { MailboxDO } from "../mailbox";
37
+ import { isRetentionFolder } from "../mailbox/retention";
35
38
  import type { Email } from "../mailbox/schema";
39
+ import type { ConversationPage, ListEmail } from "../mailbox/support";
36
40
  import {
37
41
  accessibleMailbox,
38
42
  accessibleMailboxes,
@@ -40,11 +44,15 @@ import {
40
44
  } from "./access";
41
45
  import type { MailboxListRow } from "./access";
42
46
  import { translateEmailSegments } from "./ai-translation";
47
+ import { autoReplyRoutes } from "./auto-reply-routes";
43
48
  import { BIMI_LOGO_HEADERS, bimiLogoPath, bimiObjectKey } from "./bimi";
49
+ import { mayOrganizeMailbox, organizeRefusal } from "./capabilities";
44
50
  import {
45
51
  decodeConversationCursor,
46
52
  encodeConversationCursor,
47
53
  } from "./conversation-cursor";
54
+ import { draftView, mailDraftRoutes } from "./draft-routes";
55
+ import { mailboxDraftSenders } from "./draft-sender";
48
56
  import { readStoredBody } from "./edge-cache";
49
57
  import {
50
58
  headerAuthentication,
@@ -59,20 +67,22 @@ import {
59
67
  ComposerAttachmentLimitError,
60
68
  preflightOutgoingAttachments,
61
69
  } from "./outbound";
70
+ import { separateHtmlQuote } from "./outbound-content";
62
71
  import {
63
72
  deferEmailSentWebhook,
64
73
  OutgoingRequestConflictError,
65
- submitOutgoing,
66
74
  } from "./outbound-service";
67
75
  import {
68
76
  OutgoingContextError,
69
77
  resolveForwardContext,
78
+ mailboxAliases,
70
79
  resolveReplyContext,
71
80
  } from "./outgoing-context";
72
81
  import { participantLabels } from "./participants";
73
82
  import { signR2GetUrl } from "./r2-presigned-urls";
74
83
  import { signRemoteToken } from "./remote-token";
75
84
  import { buildReplyPlan } from "./reply-plan";
85
+ import { ruleInputSchema, ruleTestSchema } from "./rules";
76
86
  import { mailSafetyRoutes } from "./safety-routes";
77
87
  import {
78
88
  attachmentPreflightSchema,
@@ -90,19 +100,28 @@ import {
90
100
  recipientSuggestionQuerySchema,
91
101
  renameFolderSchema,
92
102
  reorderFoldersSchema,
103
+ retentionFolderSchema,
93
104
  replySchema,
94
105
  uploadIdSchema,
95
106
  } from "./schemas";
96
107
  import { cachedWorkspaceIdentity, spamhausDqsKey } from "./security-settings";
97
108
  import type { WorkspaceIdentity } from "./security-settings";
109
+ import { sendMessage } from "./send-message";
110
+ import type { SendRequest } from "./send-message";
98
111
  import { storedSenderIntel } from "./sender-intel";
112
+ import { signatureRoutes } from "./signature-routes";
113
+ import { withSignature } from "./signatures";
114
+ import { officePreviewKey } from "./storage-keys";
99
115
  import {
100
116
  createComposerUploadIntent,
101
117
  discardComposerUploads,
102
118
  finalizeComposerUpload,
103
119
  UploadValidationError,
104
120
  } from "./uploads";
105
- import { cachedWorkspaceBlockPatterns } from "./workspace-safety";
121
+ import {
122
+ cachedWorkspaceBlockPatterns,
123
+ shareSpamVerdicts,
124
+ } from "./workspace-safety";
106
125
 
107
126
  function mediaType(contentType: string) {
108
127
  return contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
@@ -180,7 +199,7 @@ function getStoredObject(
180
199
  }
181
200
 
182
201
  /** Our own route for a BIMI logo, when DMARC allowed one for this message. */
183
- function senderLogoUrl(email: Email) {
202
+ function senderLogoUrl(email: ListEmail) {
184
203
  const bimi =
185
204
  email.direction === "incoming"
186
205
  ? storedSenderIntel(email.senderIntelJson)?.bimi
@@ -189,21 +208,27 @@ function senderLogoUrl(email: Email) {
189
208
  return bimi?.status === "ok" ? bimiLogoPath(bimi.domain) : null;
190
209
  }
191
210
 
192
- function toMessageSummary(email: Email) {
211
+ function messagePreview(email: ListEmail) {
193
212
  const from = email.fromJson[0] ?? { address: "unknown@invalid", name: null };
194
213
 
195
214
  return {
196
215
  id: email.id,
197
216
  conversationId: email.conversationId,
198
- direction: email.direction,
199
217
  fromAddress: from.address,
200
218
  fromName: from.name,
219
+ subject: email.subject,
220
+ preview: email.preview,
221
+ };
222
+ }
223
+
224
+ function toMessageSummary(email: ListEmail) {
225
+ return {
226
+ ...messagePreview(email),
227
+ direction: email.direction,
201
228
  toAddresses: email.toJson.map((item) => item.address),
202
229
  ccAddresses: email.ccJson.map((item) => item.address),
203
230
  bccAddresses: email.bccJson.map((item) => item.address),
204
231
  replyToAddresses: email.replyToJson.map((item) => item.address),
205
- subject: email.subject,
206
- preview: email.preview,
207
232
  transportState: email.transportState,
208
233
  transportError: email.transportError,
209
234
  deliveryStatuses: email.deliveryStatusJson,
@@ -224,7 +249,7 @@ function workspaceListAddress(email: Email) {
224
249
 
225
250
  function toMessageDetail(
226
251
  email: Email,
227
- ownAddress: string,
252
+ ownAddresses: readonly string[],
228
253
  identity: WorkspaceIdentity,
229
254
  history: Record<string, SenderHistory>,
230
255
  safety: MessageSafetyContext,
@@ -242,6 +267,7 @@ function toMessageDetail(
242
267
  ...toMessageSummary(email),
243
268
  bodyText: email.bodyText,
244
269
  quotedText: email.quotedText,
270
+ hasSeparateHtmlQuote: Boolean(separateHtmlQuote(email)),
245
271
  bodyHtml,
246
272
  aiClassification: email.aiClassificationJson,
247
273
  security: emailSecurity(email, identity, history, safety),
@@ -255,7 +281,8 @@ function toMessageDetail(
255
281
  email.direction === "incoming"
256
282
  ? storedSenderIntel(email.senderIntelJson)
257
283
  : null,
258
- hasOriginal: Boolean(email.rawMimeR2Key),
284
+ // "Show original" explains how received mail got here.
285
+ hasOriginal: email.direction === "incoming" && Boolean(email.rawMimeR2Key),
259
286
  attachments: email.attachmentsJson.map((file) => ({
260
287
  id: file.id,
261
288
  filename: file.filename,
@@ -265,14 +292,31 @@ function toMessageDetail(
265
292
  disposition: file.disposition,
266
293
  pdfPreviewStatus: file.pdfPreviewStatus ?? null,
267
294
  })),
268
- replyPlan: buildReplyPlan(ownAddress, email),
295
+ replyPlan: buildReplyPlan(ownAddresses, email),
269
296
  ...readReceipt,
270
297
  };
271
298
  }
272
299
 
273
- function conversationLabel(ownAddress: string, latest: Email) {
300
+ /**
301
+ * Who a row is with, by the latest message's people; those it names by
302
+ * address only take the names their own mail in the thread gave
303
+ * (`senderNames`).
304
+ */
305
+ function conversationLabel(
306
+ ownAddress: string,
307
+ latest: ListEmail,
308
+ senderNames: Record<string, string>
309
+ ) {
274
310
  const labels = participantLabels(
275
- [...latest.fromJson, ...latest.toJson, ...latest.ccJson],
311
+ [...latest.fromJson, ...latest.toJson, ...latest.ccJson].map(
312
+ (participant) => ({
313
+ address: participant.address,
314
+ name:
315
+ participant.name?.trim() ||
316
+ senderNames[participant.address.toLowerCase()] ||
317
+ null,
318
+ })
319
+ ),
276
320
  ownAddress
277
321
  );
278
322
 
@@ -301,17 +345,21 @@ function outboundTransportState(email: Email) {
301
345
  return email.transportState;
302
346
  }
303
347
 
348
+ /** Where permanently deleted conversations are: nowhere. */
349
+ function deletedPlaces(conversationIds: readonly string[]) {
350
+ return conversationIds.map((id) => ({
351
+ from: id,
352
+ conversationId: id,
353
+ folder: null,
354
+ left: true,
355
+ }));
356
+ }
357
+
304
358
  /** Keeps `work` running after the response; failures are only logged. */
305
- function runInBackground(c: Context<AppEnv>, work: Promise<unknown>) {
306
- const guarded = work.catch((error) =>
307
- console.error("Background work failed", error)
359
+ function runInBackground(work: Promise<unknown>) {
360
+ waitUntil(
361
+ work.catch((error) => console.error("Background work failed", error))
308
362
  );
309
-
310
- try {
311
- c.executionCtx.waitUntil(guarded);
312
- } catch {
313
- // No execution context (in-process calls): the promise still runs.
314
- }
315
363
  }
316
364
 
317
365
  function outgoingResponse(email: Email, detached: boolean) {
@@ -328,36 +376,90 @@ function outgoingResponse(email: Email, detached: boolean) {
328
376
  };
329
377
  }
330
378
 
331
- function outgoingFailure(c: Parameters<typeof apiError>[0], cause: unknown) {
379
+ /** The mail routes' `onError`: what sending and uploading refuse, else thrown on. */
380
+ const outgoingError: ErrorHandler<AppEnv> = (error, c) => {
381
+ if (error instanceof EmailSizeLimitError) {
382
+ return apiError(c, 413, "TOO_LARGE", error.message);
383
+ }
384
+
332
385
  if (
333
- cause instanceof ComposerAttachmentLimitError ||
334
- cause instanceof UploadValidationError
386
+ error instanceof ComposerAttachmentLimitError ||
387
+ error instanceof UploadValidationError
335
388
  ) {
336
- return apiError(c, 400, "BAD_REQUEST", cause.message);
389
+ return apiError(c, 400, "BAD_REQUEST", error.message);
337
390
  }
338
391
 
339
- if (cause instanceof OutgoingRequestConflictError) {
340
- return apiError(c, 409, "CONFLICT", cause.message);
392
+ if (error instanceof OutgoingRequestConflictError) {
393
+ return apiError(c, 409, "CONFLICT", error.message);
341
394
  }
342
395
 
343
- if (cause instanceof OutgoingContextError) {
344
- return apiError(c, cause.status, cause.code, cause.message);
396
+ if (error instanceof OutgoingContextError) {
397
+ return apiError(c, error.status, error.code, error.message);
345
398
  }
346
399
 
347
- throw cause;
400
+ throw error;
401
+ };
402
+
403
+ /** Sends what the request asks from its mailbox (`sendMessage`), answering as the send routes do. */
404
+ async function sendRoute(c: Context<AppEnv>, request: SendRequest) {
405
+ const access = await accessibleMailbox(c, request.message.mailboxId, "send");
406
+
407
+ if (!access) {
408
+ return apiError(c, 403, "FORBIDDEN", "Send access is required");
409
+ }
410
+
411
+ const sent = await sendMessage({
412
+ env: c.env,
413
+ requestUrl: c.req.url,
414
+ sender: c.get("user"),
415
+ mailbox: access,
416
+ request,
417
+ });
418
+
419
+ return c.json(
420
+ outgoingResponse(sent.email, sent.detached),
421
+ sent.inserted ? 201 : 200
422
+ );
348
423
  }
349
424
 
350
425
  /**
351
426
  * GET /mailboxes without `ok`. Each mailbox's `version` is the change
352
- * counter its `unreadCount` reflects; see `update:<version>`.
427
+ * counter its `unreadCount` reflects; see `update:<version>`. Whether this
428
+ * request may organize each one (capabilities.ts) is its `canOrganize`, so
429
+ * the app hides what the Worker would refuse.
353
430
  */
354
- export function mailboxListView(rows: MailboxListRow[]) {
431
+ export function mailboxListView(c: Context<AppEnv>, rows: MailboxListRow[]) {
355
432
  return {
356
433
  mailboxes: rows.map(
357
- ({ ownerUserId, isPrimary: _isPrimary, ...mailbox }) => ({
358
- ...mailbox,
359
- kind: mailboxKind(ownerUserId),
360
- })
434
+ ({
435
+ ownerUserId,
436
+ isPrimary: _isPrimary,
437
+ signatureUserId,
438
+ signatureMailboxId,
439
+ signatureHtml,
440
+ signatureUseOnNew,
441
+ signatureUseOnReply,
442
+ ...mailbox
443
+ }) => {
444
+ const signatureOwnerId = signatureUserId ?? signatureMailboxId;
445
+
446
+ return {
447
+ ...mailbox,
448
+ kind: mailboxKind(ownerUserId),
449
+ /** Its folders, rules and AI sorting (capabilities.ts). */
450
+ canOrganize: mayOrganizeMailbox(c, { ownerUserId }),
451
+ /** The signature sending from here adds (signatures.ts), if any. */
452
+ signature:
453
+ signatureOwnerId && signatureHtml !== null
454
+ ? {
455
+ ownerId: signatureOwnerId,
456
+ html: signatureHtml,
457
+ useOnNew: signatureUseOnNew ?? true,
458
+ useOnReply: signatureUseOnReply ?? true,
459
+ }
460
+ : null,
461
+ };
462
+ }
361
463
  ),
362
464
  };
363
465
  }
@@ -375,10 +477,69 @@ export function folderListView(view: ReturnType<MailboxDO["folderView"]>) {
375
477
  sortOrder: folder.sortOrder,
376
478
  totalCount: folder.totalCount,
377
479
  unreadCount: folder.unreadCount,
480
+ /** Days mail stays in Trash or Spam before it is deleted; null keeps it. */
481
+ retentionDays: isRetentionFolder(folder.systemType)
482
+ ? view.retention[folder.systemType]
483
+ : null,
378
484
  })),
379
485
  };
380
486
  }
381
487
 
488
+ const NO_DELIVERY_STATUSES: Email["deliveryStatusJson"] = [];
489
+
490
+ /**
491
+ * A Drafts folder row, in a conversation row's shape. A reply draft stands
492
+ * for its conversation, which the row opens; a new message or forward is its
493
+ * own row (`conversationId` is the draft's id) and opens the composer.
494
+ */
495
+ function draftRowView(
496
+ draft: ConversationPage["drafts"][number],
497
+ mailboxAddress: string
498
+ ) {
499
+ const conversationId =
500
+ draft.kind === "reply" && draft.conversationId
501
+ ? draft.conversationId
502
+ : draft.id;
503
+
504
+ const recipients =
505
+ draft.to.length || draft.cc.length ? [...draft.to, ...draft.cc] : draft.bcc;
506
+
507
+ const labels = participantLabels(
508
+ recipients.map((address) => ({ address, name: null })),
509
+ mailboxAddress
510
+ );
511
+
512
+ return {
513
+ id: draft.id,
514
+ conversationId,
515
+ direction: "outgoing" as const,
516
+ fromAddress: draft.sender?.address ?? mailboxAddress,
517
+ fromName: draft.sender?.displayName ?? null,
518
+ toAddresses: draft.to,
519
+ ccAddresses: draft.cc,
520
+ bccAddresses: draft.bcc,
521
+ replyToAddresses: draft.replyTo ? [draft.replyTo] : [],
522
+ subject: conversationSubject(draft.subject),
523
+ preview: draft.preview,
524
+ searchMatch: null,
525
+ transportState: null,
526
+ transportError: null,
527
+ deliveryStatuses: NO_DELIVERY_STATUSES,
528
+ timelineAt: draft.updatedAt,
529
+ senderLogoUrl: null,
530
+ conversationLabel: labels.length
531
+ ? labels.slice(0, 3).join(", ")
532
+ : (recipients[0] ?? "(no recipients)"),
533
+ messageCount: 1,
534
+ unreadCount: 0,
535
+ isUnread: false,
536
+ hasIncoming: false,
537
+ draft: true,
538
+ draftId: draft.id,
539
+ draftVersion: draft.version,
540
+ };
541
+ }
542
+
382
543
  /** GET /conversations without `ok`. */
383
544
  export function conversationPageView(
384
545
  page: NonNullable<ReturnType<MailboxDO["listConversations"]>>,
@@ -386,15 +547,31 @@ export function conversationPageView(
386
547
  ) {
387
548
  return {
388
549
  version: page.version,
389
- conversations: page.items.map((item) => ({
390
- ...toMessageSummary(item.email),
391
- subject: conversationSubject(item.email.subject),
392
- conversationLabel: conversationLabel(mailboxAddress, item.email),
393
- messageCount: item.messageCount,
394
- unreadCount: item.unreadCount,
395
- isUnread: item.unreadCount > 0,
396
- hasIncoming: item.hasIncoming,
397
- })),
550
+ conversations: [
551
+ ...page.items.map((item) => ({
552
+ ...toMessageSummary(item.email),
553
+ searchMatch: item.searchMatch,
554
+ subject: conversationSubject(item.email.subject),
555
+ conversationLabel: conversationLabel(
556
+ mailboxAddress,
557
+ item.email,
558
+ item.senderNames
559
+ ),
560
+ messageCount: item.messageCount,
561
+ unreadCount: item.unreadCount,
562
+ isUnread: item.unreadCount > 0,
563
+ hasIncoming: item.hasIncoming,
564
+ hasOutgoing: item.hasOutgoing,
565
+ mailboxState: item.mailboxState,
566
+ folderId: item.folderId,
567
+ /** The caller has a reply draft here; shown as "Draft". */
568
+ draft: item.hasDraft,
569
+ /** Set on Drafts folder rows only: the draft the row is. */
570
+ draftId: null,
571
+ draftVersion: null,
572
+ })),
573
+ ...page.drafts.map((draft) => draftRowView(draft, mailboxAddress)),
574
+ ],
398
575
  nextCursor: page.next ? encodeConversationCursor(page.next) : null,
399
576
  };
400
577
  }
@@ -404,7 +581,10 @@ export const mailRoutes = new Hono<AppEnv>()
404
581
  .get("/mailboxes", oauthScope(MAIL_READ_SCOPE), async (c) => {
405
582
  const rows = await accessibleMailboxes(c);
406
583
 
407
- return c.json({ ok: true as const, ...mailboxListView(rows) });
584
+ return c.json({
585
+ ok: true as const,
586
+ ...mailboxListView(c, rows),
587
+ });
408
588
  })
409
589
  .get("/mailboxes/:id/realtime", oauthScope(MAIL_READ_SCOPE), async (c) => {
410
590
  if (c.get("authKind") !== "session") {
@@ -475,20 +655,16 @@ export const mailRoutes = new Hono<AppEnv>()
475
655
  return apiError(c, 429, "RATE_LIMITED", "Too many attachment uploads");
476
656
  }
477
657
 
478
- try {
479
- const upload = await createComposerUploadIntent({
480
- env: c.env,
481
- mailboxId,
482
- userId: user.id,
483
- filename: body.filename,
484
- contentType: body.contentType,
485
- size: body.size,
486
- });
658
+ const upload = await createComposerUploadIntent({
659
+ env: c.env,
660
+ mailboxId,
661
+ userId: user.id,
662
+ filename: body.filename,
663
+ contentType: body.contentType,
664
+ size: body.size,
665
+ });
487
666
 
488
- return c.json({ ok: true as const, upload }, 201);
489
- } catch (error) {
490
- return outgoingFailure(c, error);
491
- }
667
+ return c.json({ ok: true as const, upload }, 201);
492
668
  }
493
669
  )
494
670
  .post(
@@ -506,19 +682,14 @@ export const mailRoutes = new Hono<AppEnv>()
506
682
  return apiError(c, 403, "FORBIDDEN", "Send access is required");
507
683
  }
508
684
 
509
- try {
510
- const upload = await finalizeComposerUpload({
511
- env: c.env,
512
- mailboxId,
513
- userId: user.id,
514
- uploadId,
515
- defer: (task) => c.executionCtx.waitUntil(task),
516
- });
685
+ const upload = await finalizeComposerUpload({
686
+ env: c.env,
687
+ mailboxId,
688
+ userId: user.id,
689
+ uploadId,
690
+ });
517
691
 
518
- return c.json({ ok: true as const, upload });
519
- } catch (error) {
520
- return outgoingFailure(c, error);
521
- }
692
+ return c.json({ ok: true as const, upload });
522
693
  }
523
694
  )
524
695
  .delete(
@@ -603,9 +774,9 @@ export const mailRoutes = new Hono<AppEnv>()
603
774
  async (c) => {
604
775
  const mailboxId = c.req.param("id");
605
776
 
606
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
607
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
608
- }
777
+ const refused = await organizeRefusal(c, mailboxId);
778
+
779
+ if (refused) return refused;
609
780
 
610
781
  return c.json({
611
782
  ok: true as const,
@@ -615,10 +786,58 @@ export const mailRoutes = new Hono<AppEnv>()
615
786
  });
616
787
  }
617
788
  )
789
+ // Rules are mailbox organization, like folders and AI sorting.
790
+ .get("/mailboxes/:id/rules", oauthScope(MAIL_READ_SCOPE), async (c) => {
791
+ const mailboxId = c.req.param("id");
792
+
793
+ const access = await accessibleMailbox(c, mailboxId, "read");
794
+
795
+ if (!access) {
796
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
797
+ }
798
+
799
+ return c.json({
800
+ ok: true as const,
801
+ /** Whether the signed-in person may change them (capabilities.ts). */
802
+ canEdit: mayOrganizeMailbox(c, access),
803
+ rules: await mailboxStub(c.env, mailboxId).listRules(),
804
+ });
805
+ })
618
806
  .post(
619
- "/mailboxes/:id/folders",
807
+ "/mailboxes/:id/rules",
620
808
  oauthScope(MAIL_ORGANIZE_SCOPE),
621
- zValidator("json", createFolderSchema),
809
+ zValidator("json", ruleInputSchema),
810
+ async (c) => {
811
+ const mailboxId = c.req.param("id");
812
+
813
+ const refused = await organizeRefusal(c, mailboxId);
814
+
815
+ if (refused) return refused;
816
+
817
+ const result = await mailboxStub(c.env, mailboxId).createRule(
818
+ c.req.valid("json")
819
+ );
820
+
821
+ if (result.status === "invalid") {
822
+ return apiError(c, 400, "BAD_REQUEST", result.error);
823
+ }
824
+
825
+ if (result.status === "limit") {
826
+ return apiError(
827
+ c,
828
+ 409,
829
+ "CONFLICT",
830
+ "A mailbox can have at most 100 rules"
831
+ );
832
+ }
833
+
834
+ return c.json({ ok: true as const, rule: result.rule }, 201);
835
+ }
836
+ )
837
+ .post(
838
+ "/mailboxes/:id/rules/test",
839
+ oauthScope(MAIL_READ_SCOPE),
840
+ zValidator("json", ruleTestSchema),
622
841
  async (c) => {
623
842
  const mailboxId = c.req.param("id");
624
843
 
@@ -626,6 +845,151 @@ export const mailRoutes = new Hono<AppEnv>()
626
845
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
627
846
  }
628
847
 
848
+ return c.json({
849
+ ok: true as const,
850
+ ...(await mailboxStub(c.env, mailboxId).testRule(c.req.valid("json"))),
851
+ });
852
+ }
853
+ )
854
+ .put(
855
+ "/mailboxes/:id/rules/order",
856
+ oauthScope(MAIL_ORGANIZE_SCOPE),
857
+ zValidator(
858
+ "json",
859
+ z.object({ ruleIds: z.array(z.string().min(1).max(80)).max(100) })
860
+ ),
861
+ async (c) => {
862
+ const mailboxId = c.req.param("id");
863
+
864
+ const refused = await organizeRefusal(c, mailboxId);
865
+
866
+ if (refused) return refused;
867
+
868
+ if (
869
+ !(await mailboxStub(c.env, mailboxId).reorderRules(
870
+ c.req.valid("json").ruleIds
871
+ ))
872
+ ) {
873
+ return apiError(
874
+ c,
875
+ 409,
876
+ "CONFLICT",
877
+ "Rules changed; refresh and try again"
878
+ );
879
+ }
880
+
881
+ return c.json({ ok: true as const });
882
+ }
883
+ )
884
+ .patch(
885
+ "/mailboxes/:id/rules/:ruleId",
886
+ oauthScope(MAIL_ORGANIZE_SCOPE),
887
+ zValidator("json", z.object({ enabled: z.boolean() })),
888
+ async (c) => {
889
+ const mailboxId = c.req.param("id");
890
+ const refused = await organizeRefusal(c, mailboxId);
891
+
892
+ if (refused) return refused;
893
+
894
+ const updated = await mailboxStub(c.env, mailboxId).setRuleEnabled(
895
+ c.req.param("ruleId"),
896
+ c.req.valid("json").enabled
897
+ );
898
+
899
+ if (!updated) return apiError(c, 404, "NOT_FOUND", "Rule not found");
900
+
901
+ return c.json({ ok: true as const });
902
+ }
903
+ )
904
+ .put(
905
+ "/mailboxes/:id/rules/:ruleId",
906
+ oauthScope(MAIL_ORGANIZE_SCOPE),
907
+ zValidator("json", ruleInputSchema.omit({ enabled: true }).strict()),
908
+ async (c) => {
909
+ const mailboxId = c.req.param("id");
910
+
911
+ const refused = await organizeRefusal(c, mailboxId);
912
+
913
+ if (refused) return refused;
914
+
915
+ const result = await mailboxStub(c.env, mailboxId).updateRule(
916
+ c.req.param("ruleId"),
917
+ c.req.valid("json")
918
+ );
919
+
920
+ if (result.status === "invalid") {
921
+ return apiError(c, 400, "BAD_REQUEST", result.error);
922
+ }
923
+
924
+ if (result.status === "not_found") {
925
+ return apiError(c, 404, "NOT_FOUND", "Rule not found");
926
+ }
927
+
928
+ return c.json({ ok: true as const, rule: result.rule });
929
+ }
930
+ )
931
+ .delete(
932
+ "/mailboxes/:id/rules/:ruleId",
933
+ oauthScope(MAIL_ORGANIZE_SCOPE),
934
+ async (c) => {
935
+ const mailboxId = c.req.param("id");
936
+
937
+ const refused = await organizeRefusal(c, mailboxId);
938
+
939
+ if (refused) return refused;
940
+
941
+ if (
942
+ !(await mailboxStub(c.env, mailboxId).deleteRule(c.req.param("ruleId")))
943
+ ) {
944
+ return apiError(c, 404, "NOT_FOUND", "Rule not found");
945
+ }
946
+
947
+ return c.json({ ok: true as const });
948
+ }
949
+ )
950
+ .post(
951
+ "/mailboxes/:id/folders/:folder/empty",
952
+ oauthScope(MAIL_ORGANIZE_SCOPE),
953
+ zValidator(
954
+ "param",
955
+ z.object({ id: z.string(), folder: retentionFolderSchema })
956
+ ),
957
+ async (c) => {
958
+ const { id: mailboxId, folder } = c.req.valid("param");
959
+
960
+ if (!(await accessibleMailbox(c, mailboxId, "send"))) {
961
+ return apiError(
962
+ c,
963
+ 403,
964
+ "FORBIDDEN",
965
+ "Send access is required to delete conversations permanently"
966
+ );
967
+ }
968
+
969
+ const { deletedIds, remaining } = await mailboxStub(
970
+ c.env,
971
+ mailboxId
972
+ ).emptyFolder(folder);
973
+
974
+ return c.json({
975
+ ok: true as const,
976
+ deleted: deletedIds.length,
977
+ remaining,
978
+ places: deletedPlaces(deletedIds),
979
+ });
980
+ }
981
+ )
982
+ .post(
983
+ "/mailboxes/:id/folders",
984
+ oauthScope(MAIL_ORGANIZE_SCOPE),
985
+ zValidator("json", createFolderSchema),
986
+ async (c) => {
987
+ const mailboxId = c.req.param("id");
988
+
989
+ const refused = await organizeRefusal(c, mailboxId);
990
+
991
+ if (refused) return refused;
992
+
629
993
  const result = await mailboxStub(c.env, mailboxId).createFolder(
630
994
  createId("fld"),
631
995
  c.req.valid("json").name
@@ -653,9 +1017,9 @@ export const mailRoutes = new Hono<AppEnv>()
653
1017
  async (c) => {
654
1018
  const mailboxId = c.req.param("id");
655
1019
 
656
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
657
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
658
- }
1020
+ const refused = await organizeRefusal(c, mailboxId);
1021
+
1022
+ if (refused) return refused;
659
1023
 
660
1024
  const result = await mailboxStub(c.env, mailboxId).reorderFolders(
661
1025
  c.req.valid("json").folderIds
@@ -680,9 +1044,9 @@ export const mailRoutes = new Hono<AppEnv>()
680
1044
  async (c) => {
681
1045
  const mailboxId = c.req.param("id");
682
1046
 
683
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
684
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
685
- }
1047
+ const refused = await organizeRefusal(c, mailboxId);
1048
+
1049
+ if (refused) return refused;
686
1050
 
687
1051
  const result = await mailboxStub(c.env, mailboxId).renameFolder(
688
1052
  c.req.param("folderId"),
@@ -710,9 +1074,9 @@ export const mailRoutes = new Hono<AppEnv>()
710
1074
  async (c) => {
711
1075
  const mailboxId = c.req.param("id");
712
1076
 
713
- if (!(await accessibleMailbox(c, mailboxId, "read"))) {
714
- return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
715
- }
1077
+ const refused = await organizeRefusal(c, mailboxId);
1078
+
1079
+ if (refused) return refused;
716
1080
 
717
1081
  const result = await mailboxStub(c.env, mailboxId).deleteFolder(
718
1082
  c.req.param("folderId")
@@ -750,6 +1114,11 @@ export const mailRoutes = new Hono<AppEnv>()
750
1114
  );
751
1115
  }
752
1116
 
1117
+ const senders =
1118
+ query.folder === DRAFTS_FOLDER_ID
1119
+ ? await mailboxDraftSenders(c.env.DB, access)
1120
+ : undefined;
1121
+
753
1122
  const page = await timed(c, "do", "conversations", () =>
754
1123
  mailboxStub(c.env, query.mailboxId).listConversations(
755
1124
  c.get("user").id,
@@ -757,7 +1126,8 @@ export const mailRoutes = new Hono<AppEnv>()
757
1126
  query.limit,
758
1127
  cursor,
759
1128
  query.search,
760
- query.unreadOnly === "true"
1129
+ query.unreadOnly === "true",
1130
+ senders
761
1131
  )
762
1132
  );
763
1133
 
@@ -769,6 +1139,38 @@ export const mailRoutes = new Hono<AppEnv>()
769
1139
  });
770
1140
  }
771
1141
  )
1142
+ .post(
1143
+ "/conversations/undo-spam",
1144
+ oauthScope(MAIL_ORGANIZE_SCOPE),
1145
+ zValidator("query", mailboxQuerySchema),
1146
+ zValidator(
1147
+ "json",
1148
+ z.object({ undoId: z.string().regex(/^undo_[\da-f]{32}$/u) })
1149
+ ),
1150
+ async (c) => {
1151
+ const { mailboxId } = c.req.valid("query");
1152
+
1153
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) {
1154
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1155
+ }
1156
+
1157
+ const restored = await mailboxStub(c.env, mailboxId).undoSpamDecision(
1158
+ c.get("user").id,
1159
+ c.req.valid("json").undoId
1160
+ );
1161
+
1162
+ if (!restored) {
1163
+ return apiError(
1164
+ c,
1165
+ 409,
1166
+ "CONFLICT",
1167
+ "Could not undo this spam decision. The mail or sender changed, or Undo expired."
1168
+ );
1169
+ }
1170
+
1171
+ return c.json({ ok: true as const });
1172
+ }
1173
+ )
772
1174
  .patch(
773
1175
  "/conversations/bulk",
774
1176
  oauthScope(MAIL_ORGANIZE_SCOPE),
@@ -793,17 +1195,28 @@ export const mailRoutes = new Hono<AppEnv>()
793
1195
  input.isRead
794
1196
  );
795
1197
 
796
- return c.json({ ok: true as const, updatedCount });
1198
+ // Marked read or unread, they stay where they are.
1199
+ return c.json({ ok: true as const, updatedCount, places: [] });
797
1200
  }
798
1201
 
799
1202
  if (input.type === "update") {
800
- const updatedCount = await stub.bulkUpdateConversations(
1203
+ const placed = await stub.bulkUpdateConversations(
801
1204
  input.conversationIds,
802
1205
  input.sourceFolderId,
803
- input.update
1206
+ input.update,
1207
+ // Out of Spam it is a verdict for anyone who reads the mailbox;
1208
+ // trusting its senders, only for those who may organize it. An
1209
+ // Undo only puts them back: no verdict, nobody trusted.
1210
+ input.undo
1211
+ ? { userId: null, trustSenders: false, undo: true }
1212
+ : {
1213
+ userId: user.id,
1214
+ trustSenders: mayOrganizeMailbox(c, access),
1215
+ offerUndo: input.offerUndo,
1216
+ }
804
1217
  );
805
1218
 
806
- if (updatedCount === null) {
1219
+ if (placed === null) {
807
1220
  return apiError(
808
1221
  c,
809
1222
  404,
@@ -812,7 +1225,17 @@ export const mailRoutes = new Hono<AppEnv>()
812
1225
  );
813
1226
  }
814
1227
 
815
- return c.json({ ok: true as const, updatedCount });
1228
+ if (!placed.undoId) {
1229
+ await shareSpamVerdicts(c.env.DB, mailboxId, placed.verdicts);
1230
+ }
1231
+
1232
+ return c.json({
1233
+ ok: true as const,
1234
+ updatedCount: placed.moved.length,
1235
+ undoId: placed.undoId ?? undefined,
1236
+ /** Where each conversation is now, and whether it left where it was. */
1237
+ places: placed.places,
1238
+ });
816
1239
  }
817
1240
 
818
1241
  if (!access.canSend) {
@@ -824,26 +1247,15 @@ export const mailRoutes = new Hono<AppEnv>()
824
1247
  );
825
1248
  }
826
1249
 
1250
+ // Those still in Trash go; the person hears how many.
827
1251
  const result = await stub.permanentlyDeleteConversations(
828
1252
  input.conversationIds
829
1253
  );
830
1254
 
831
- if (result.outcome === "not_found") {
832
- return apiError(c, 404, "NOT_FOUND", "Conversations not found");
833
- }
834
-
835
- if (result.outcome === "not_in_trash") {
836
- return apiError(
837
- c,
838
- 409,
839
- "CONFLICT",
840
- "Only conversations in Trash can be deleted permanently"
841
- );
842
- }
843
-
844
1255
  return c.json({
845
1256
  ok: true as const,
846
- updatedCount: result.deletedCount,
1257
+ updatedCount: result.deletedIds.length,
1258
+ places: deletedPlaces(result.deletedIds),
847
1259
  });
848
1260
  }
849
1261
  )
@@ -887,7 +1299,9 @@ export const mailRoutes = new Hono<AppEnv>()
887
1299
  c.req.param("id"),
888
1300
  currentUserId,
889
1301
  query.limit,
890
- cursor
1302
+ cursor,
1303
+ c.get("authKind") === "session" && access.canSend,
1304
+ query.match
891
1305
  )
892
1306
  );
893
1307
 
@@ -898,21 +1312,23 @@ export const mailRoutes = new Hono<AppEnv>()
898
1312
  ...new Set(view.readStates.map((readState) => readState.userId)),
899
1313
  ].filter((userId) => userId !== currentUserId);
900
1314
 
901
- const [readers, [identity, workspaceBlocks], bodies] = await Promise.all([
902
- otherReaderIds.length
903
- ? timed(c, "d1", "readers", () =>
904
- listMailboxUsersByIds(c.env.DB, mailboxId, otherReaderIds)
1315
+ const [readers, [identity, workspaceBlocks], bodies, aliases] =
1316
+ await Promise.all([
1317
+ otherReaderIds.length
1318
+ ? timed(c, "d1", "readers", () =>
1319
+ listMailboxUsersByIds(c.env.DB, mailboxId, otherReaderIds)
1320
+ )
1321
+ : [],
1322
+ workspace,
1323
+ Promise.all(
1324
+ view.messages.map((stored) =>
1325
+ stored.bodyHtmlR2Key
1326
+ ? readStoredBody(c, stored.bodyHtmlR2Key)
1327
+ : null
905
1328
  )
906
- : [],
907
- workspace,
908
- Promise.all(
909
- view.messages.map((stored) =>
910
- stored.bodyHtmlR2Key
911
- ? readStoredBody(c, stored.bodyHtmlR2Key)
912
- : null
913
- )
914
- ),
915
- ]);
1329
+ ),
1330
+ timed(c, "d1", "aliases", () => mailboxAliases(c.env.DB, mailboxId)),
1331
+ ]);
916
1332
 
917
1333
  /** One proxy token per remote image URL in the HTML (remote-token.ts). */
918
1334
  const remoteTokens = async (bodyHtml: string) =>
@@ -960,6 +1376,11 @@ export const mailRoutes = new Hono<AppEnv>()
960
1376
  const inline = c.get("authKind") !== "session";
961
1377
  const now = Date.now();
962
1378
 
1379
+ const ownAddresses = [
1380
+ access.address,
1381
+ ...aliases.map((alias) => alias.address),
1382
+ ];
1383
+
963
1384
  const messages = await Promise.all(
964
1385
  view.messages.map(async (stored, index) => {
965
1386
  const bodyHtml = bodies[index] ?? null;
@@ -974,7 +1395,6 @@ export const mailRoutes = new Hono<AppEnv>()
974
1395
  } else {
975
1396
  intelPending = true;
976
1397
  runInBackground(
977
- c,
978
1398
  withSenderIntel(c.env, mailbox, stored, intelContext(bodyHtml))
979
1399
  );
980
1400
  }
@@ -985,15 +1405,18 @@ export const mailRoutes = new Hono<AppEnv>()
985
1405
  return {
986
1406
  ...toMessageDetail(
987
1407
  email,
988
- access.address,
1408
+ ownAddresses,
989
1409
  identity,
990
1410
  view.history,
991
1411
  safety,
992
1412
  bodyHtml,
993
1413
  {
994
- isRead: readStates.some(
995
- (readState) => readState.userId === currentUserId
996
- ),
1414
+ isRead:
1415
+ (email.direction === "outgoing" &&
1416
+ access.kind === "personal") ||
1417
+ readStates.some(
1418
+ (readState) => readState.userId === currentUserId
1419
+ ),
997
1420
  viewedBy: readStates.flatMap((readState) => {
998
1421
  const reader = readerById.get(readState.userId);
999
1422
 
@@ -1024,13 +1447,25 @@ export const mailRoutes = new Hono<AppEnv>()
1024
1447
  })
1025
1448
  );
1026
1449
 
1450
+ const source = view.replyDraftSource;
1451
+
1452
+ const replyDraftSource = source && {
1453
+ ...messagePreview(source),
1454
+ security: emailSecurity(source, identity, view.history, safety),
1455
+ replyPlan: buildReplyPlan(ownAddresses, source),
1456
+ };
1457
+
1027
1458
  return c.json({
1028
1459
  ok: true as const,
1029
1460
  version: view.version,
1461
+ replyDraftSource,
1462
+ pinnedMessageId: view.pinnedMessageId,
1463
+ replyDraft: view.replyDraft ? draftView(view.replyDraft) : null,
1030
1464
  mailboxState: view.mailboxState,
1031
1465
  folderId: view.folderId,
1032
1466
  hasIncoming: view.hasIncoming,
1033
1467
  hasOutgoing: view.hasOutgoing,
1468
+ translationEnabled: aiFeatureEnabled("translation"),
1034
1469
  messageCount: view.messageCount,
1035
1470
  unreadCount: view.unreadCount,
1036
1471
  nextCursor: view.next ? encodeConversationCursor(view.next) : null,
@@ -1038,6 +1473,49 @@ export const mailRoutes = new Hono<AppEnv>()
1038
1473
  });
1039
1474
  }
1040
1475
  )
1476
+ .get(
1477
+ "/messages/:id/forward-source",
1478
+ oauthScope(MAIL_READ_SCOPE),
1479
+ zValidator("query", mailboxQuerySchema),
1480
+ async (c) => {
1481
+ const { mailboxId } = c.req.valid("query");
1482
+
1483
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) {
1484
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1485
+ }
1486
+
1487
+ const view = await mailboxStub(c.env, mailboxId).getMessageSenderView(
1488
+ c.req.param("id")
1489
+ );
1490
+
1491
+ if (!view) {
1492
+ return apiError(c, 404, "NOT_FOUND", "Forwarded message not found");
1493
+ }
1494
+
1495
+ const { email } = view;
1496
+
1497
+ const [identity, workspaceBlocks] = await Promise.all([
1498
+ cachedWorkspaceIdentity(c.env.DB),
1499
+ cachedWorkspaceBlockPatterns(c.env.DB),
1500
+ ]);
1501
+
1502
+ return c.json({
1503
+ ok: true as const,
1504
+ message: {
1505
+ ...messagePreview(email),
1506
+ attachments: email.attachmentsJson.map(({ id, filename, size }) => ({
1507
+ id,
1508
+ filename,
1509
+ size,
1510
+ })),
1511
+ security: emailSecurity(email, identity, view.history, {
1512
+ ...view.safety,
1513
+ workspaceBlocks,
1514
+ }),
1515
+ },
1516
+ });
1517
+ }
1518
+ )
1041
1519
  .get(
1042
1520
  "/messages/:id/sender-intel",
1043
1521
  oauthScope(MAIL_READ_SCOPE),
@@ -1111,21 +1589,27 @@ export const mailRoutes = new Hono<AppEnv>()
1111
1589
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1112
1590
  }
1113
1591
 
1114
- const version = await timed(c, "do", "read", async () => {
1115
- const updated = await mailboxStub(c.env, mailboxId).setMessageRead(
1592
+ const updated = await timed(c, "do", "read", async () => {
1593
+ const result = await mailboxStub(c.env, mailboxId).setMessageRead(
1116
1594
  user.id,
1117
1595
  c.req.param("id"),
1118
1596
  c.req.valid("json").isRead
1119
1597
  );
1120
1598
 
1121
- return updated ? updated.version : null;
1599
+ return result
1600
+ ? { previousVersion: result.previousVersion, version: result.version }
1601
+ : null;
1122
1602
  });
1123
1603
 
1124
- if (version === null) {
1604
+ if (!updated) {
1125
1605
  return apiError(c, 404, "NOT_FOUND", "Message not found");
1126
1606
  }
1127
1607
 
1128
- return c.json({ ok: true as const, version });
1608
+ return c.json({
1609
+ ok: true as const,
1610
+ previousVersion: updated.previousVersion,
1611
+ version: updated.version,
1612
+ });
1129
1613
  }
1130
1614
  )
1131
1615
  .post(
@@ -1282,11 +1766,10 @@ export const mailRoutes = new Hono<AppEnv>()
1282
1766
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
1283
1767
  }
1284
1768
 
1285
- const message = await mailboxStub(c.env, mailboxId).getEmail(
1286
- c.req.param("messageId")
1287
- );
1769
+ const messageId = c.req.param("messageId");
1770
+ const key = await mailboxStub(c.env, mailboxId).getRawMimeKey(messageId);
1288
1771
 
1289
- if (!message?.rawMimeR2Key) {
1772
+ if (!key) {
1290
1773
  return apiError(c, 404, "NOT_FOUND", "Original message not found");
1291
1774
  }
1292
1775
 
@@ -1294,7 +1777,7 @@ export const mailRoutes = new Hono<AppEnv>()
1294
1777
 
1295
1778
  const object = await getStoredObject(
1296
1779
  c.env.MAIL_STORAGE,
1297
- message.rawMimeR2Key,
1780
+ key,
1298
1781
  requestedRange
1299
1782
  );
1300
1783
 
@@ -1304,7 +1787,7 @@ export const mailRoutes = new Hono<AppEnv>()
1304
1787
 
1305
1788
  return storedObjectResponse({
1306
1789
  object,
1307
- contentDisposition: `inline; filename*=UTF-8''${encodeURIComponent(`${message.id}.eml`)}`,
1790
+ contentDisposition: `inline; filename*=UTF-8''${encodeURIComponent(`${messageId}.eml`)}`,
1308
1791
  contentType: "text/plain; charset=utf-8",
1309
1792
  totalBytes: object.size,
1310
1793
  rangeRequested: Boolean(requestedRange),
@@ -1519,7 +2002,7 @@ export const mailRoutes = new Hono<AppEnv>()
1519
2002
  return apiError(c, 404, "NOT_FOUND", "Outgoing message not found");
1520
2003
  }
1521
2004
 
1522
- const resent = await stub.resendOutgoing(message.id);
2005
+ const resent = await stub.resendOutgoing(message.id, c.req.url);
1523
2006
 
1524
2007
  if (!resent) {
1525
2008
  return apiError(
@@ -1534,7 +2017,6 @@ export const mailRoutes = new Hono<AppEnv>()
1534
2017
  env: c.env,
1535
2018
  mailboxId,
1536
2019
  email: resent,
1537
- defer: (task) => c.executionCtx.waitUntil(task),
1538
2020
  });
1539
2021
 
1540
2022
  return c.json({
@@ -1569,195 +2051,105 @@ export const mailRoutes = new Hono<AppEnv>()
1569
2051
  return apiError(c, 429, "RATE_LIMITED", "Too many attachment checks");
1570
2052
  }
1571
2053
 
1572
- try {
1573
- let subject = input.kind === "compose" ? input.subject : "";
1574
- let related: Email | null = null;
1575
- let forwarded: Email | null = null;
1576
- let includeRelatedContext = false;
1577
-
1578
- if (input.kind === "forward") {
1579
- const context = await resolveForwardContext({
1580
- env: c.env,
1581
- mailboxId: input.mailboxId,
1582
- sourceEmailId: input.sourceEmailId,
1583
- });
1584
-
1585
- forwarded = context.source;
1586
- subject = context.subject;
1587
- } else if (input.kind === "reply") {
1588
- const context = await resolveReplyContext({
1589
- env: c.env,
1590
- mailboxId: input.mailboxId,
1591
- ownAddress: access.address,
1592
- sourceEmailId: input.sourceEmailId,
1593
- mode: input.mode,
1594
- cc: input.cc,
1595
- bcc: input.bcc,
1596
- });
1597
-
1598
- related = context.source;
1599
- subject = context.subject;
1600
- includeRelatedContext = context.includeRelatedContext;
1601
- }
2054
+ let subject = input.kind === "compose" ? input.subject : "";
2055
+ let related: Email | null = null;
2056
+ let forwarded: Email | null = null;
2057
+ let includeRelatedContext = false;
1602
2058
 
1603
- const result = await preflightOutgoingAttachments({
2059
+ if (input.kind === "forward") {
2060
+ const context = await resolveForwardContext({
1604
2061
  env: c.env,
1605
- compose: {
1606
- mailboxId: input.mailboxId,
1607
- userId: user.id,
1608
- subject,
1609
- bodyText: input.bodyText,
1610
- bodyHtml: input.bodyHtml,
1611
- attachments: input.attachments,
1612
- },
1613
- related,
1614
- forwarded,
1615
- includeRelatedContext,
2062
+ mailboxId: input.mailboxId,
2063
+ sourceEmailId: input.sourceEmailId,
2064
+ });
2065
+
2066
+ forwarded = context.source;
2067
+ subject = context.subject;
2068
+ } else if (input.kind === "reply") {
2069
+ const context = await resolveReplyContext({
2070
+ env: c.env,
2071
+ mailboxId: input.mailboxId,
2072
+ ownAddress: access.address,
2073
+ sourceEmailId: input.sourceEmailId,
2074
+ mode: input.mode,
2075
+ cc: input.cc,
2076
+ bcc: input.bcc,
1616
2077
  });
1617
2078
 
1618
- return c.json({ ok: true as const, ...result });
1619
- } catch (error) {
1620
- return outgoingFailure(c, error);
2079
+ related = context.source;
2080
+ subject = context.subject;
2081
+ includeRelatedContext = context.includeRelatedContext;
1621
2082
  }
2083
+
2084
+ const message = await withSignature({
2085
+ env: c.env,
2086
+ sender: user,
2087
+ mailbox: access,
2088
+ kind: input.kind === "compose" ? "new" : "reply",
2089
+ message: input,
2090
+ });
2091
+
2092
+ const result = await preflightOutgoingAttachments({
2093
+ env: c.env,
2094
+ compose: {
2095
+ mailboxId: input.mailboxId,
2096
+ userId: user.id,
2097
+ subject,
2098
+ bodyText: message.bodyText,
2099
+ bodyHtml: message.bodyHtml,
2100
+ inlineImages: message.inlineImages,
2101
+ attachments: message.attachments,
2102
+ forwardedAttachmentIds:
2103
+ input.kind === "forward" ? input.forwardedAttachmentIds : undefined,
2104
+ },
2105
+ related,
2106
+ forwarded,
2107
+ includeRelatedContext,
2108
+ });
2109
+
2110
+ return c.json({ ok: true as const, ...result });
1622
2111
  }
1623
2112
  )
1624
2113
  .post(
1625
2114
  "/messages",
1626
2115
  oauthScope(MAIL_SEND_SCOPE),
1627
2116
  zValidator("json", composeSchema),
1628
- async (c) => {
1629
- const input = c.req.valid("json");
1630
- const access = await accessibleMailbox(c, input.mailboxId, "send");
1631
-
1632
- if (!access) {
1633
- return apiError(c, 403, "FORBIDDEN", "Send access is required");
1634
- }
1635
-
1636
- try {
1637
- const submission = await submitOutgoing({
1638
- env: c.env,
1639
- requestUrl: c.req.url,
1640
- compose: {
1641
- ...input,
1642
- userId: c.get("user").id,
1643
- },
1644
- conversationId: createId("conv"),
1645
- related: null,
1646
- forwarded: null,
1647
- includeRelatedContext: false,
1648
- fromAddress: access.address,
1649
- fromName: access.displayName,
1650
- defer: (task) => c.executionCtx.waitUntil(task),
1651
- });
2117
+ (c) => {
2118
+ const message = c.req.valid("json");
1652
2119
 
1653
- return c.json(
1654
- outgoingResponse(submission.email, false),
1655
- submission.inserted ? 201 : 200
1656
- );
1657
- } catch (error) {
1658
- return outgoingFailure(c, error);
1659
- }
2120
+ return sendRoute(c, { kind: "new", message });
1660
2121
  }
1661
2122
  )
1662
2123
  .post(
1663
2124
  "/messages/:id/replies",
1664
2125
  oauthScope(MAIL_SEND_SCOPE),
1665
2126
  zValidator("json", replySchema),
1666
- async (c) => {
1667
- const input = c.req.valid("json");
1668
- const access = await accessibleMailbox(c, input.mailboxId, "send");
1669
-
1670
- if (!access) {
1671
- return apiError(c, 403, "FORBIDDEN", "Send access is required");
1672
- }
1673
-
1674
- try {
1675
- const context = await resolveReplyContext({
1676
- env: c.env,
1677
- mailboxId: input.mailboxId,
1678
- ownAddress: access.address,
1679
- sourceEmailId: c.req.param("id"),
1680
- mode: input.mode,
1681
- cc: input.cc,
1682
- bcc: input.bcc,
1683
- });
1684
-
1685
- const submission = await submitOutgoing({
1686
- env: c.env,
1687
- requestUrl: c.req.url,
1688
- compose: {
1689
- requestId: input.requestId,
1690
- mailboxId: input.mailboxId,
1691
- userId: c.get("user").id,
1692
- ...context.recipients,
1693
- subject: context.subject,
1694
- bodyText: input.bodyText,
1695
- bodyHtml: input.bodyHtml,
1696
- attachments: input.attachments,
1697
- },
1698
- conversationId: context.detached
1699
- ? createId("conv")
1700
- : context.source.conversationId,
1701
- related: context.source,
1702
- forwarded: null,
1703
- includeRelatedContext: context.includeRelatedContext,
1704
- fromAddress: access.address,
1705
- fromName: access.displayName,
1706
- defer: (task) => c.executionCtx.waitUntil(task),
1707
- });
2127
+ (c) => {
2128
+ const message = c.req.valid("json");
1708
2129
 
1709
- return c.json(
1710
- outgoingResponse(submission.email, context.detached),
1711
- submission.inserted ? 201 : 200
1712
- );
1713
- } catch (error) {
1714
- return outgoingFailure(c, error);
1715
- }
2130
+ return sendRoute(c, {
2131
+ kind: "reply",
2132
+ sourceEmailId: c.req.param("id"),
2133
+ message,
2134
+ });
1716
2135
  }
1717
2136
  )
1718
2137
  .post(
1719
2138
  "/messages/:id/forward",
1720
2139
  oauthScope(MAIL_SEND_SCOPE),
1721
2140
  zValidator("json", forwardSchema),
1722
- async (c) => {
1723
- const input = c.req.valid("json");
1724
- const access = await accessibleMailbox(c, input.mailboxId, "send");
1725
-
1726
- if (!access) {
1727
- return apiError(c, 403, "FORBIDDEN", "Send access is required");
1728
- }
2141
+ (c) => {
2142
+ const message = c.req.valid("json");
1729
2143
 
1730
- try {
1731
- const context = await resolveForwardContext({
1732
- env: c.env,
1733
- mailboxId: input.mailboxId,
1734
- sourceEmailId: c.req.param("id"),
1735
- });
1736
-
1737
- const submission = await submitOutgoing({
1738
- env: c.env,
1739
- requestUrl: c.req.url,
1740
- compose: {
1741
- ...input,
1742
- userId: c.get("user").id,
1743
- subject: context.subject,
1744
- },
1745
- conversationId: createId("conv"),
1746
- related: null,
1747
- forwarded: context.source,
1748
- includeRelatedContext: false,
1749
- fromAddress: access.address,
1750
- fromName: access.displayName,
1751
- defer: (task) => c.executionCtx.waitUntil(task),
1752
- });
1753
-
1754
- return c.json(
1755
- outgoingResponse(submission.email, false),
1756
- submission.inserted ? 201 : 200
1757
- );
1758
- } catch (error) {
1759
- return outgoingFailure(c, error);
1760
- }
2144
+ return sendRoute(c, {
2145
+ kind: "forward",
2146
+ sourceEmailId: c.req.param("id"),
2147
+ message,
2148
+ });
1761
2149
  }
1762
2150
  )
1763
- .route("/", mailSafetyRoutes);
2151
+ .route("/drafts", mailDraftRoutes)
2152
+ .route("/", mailSafetyRoutes)
2153
+ .route("/", signatureRoutes)
2154
+ .route("/", autoReplyRoutes)
2155
+ .onError(outgoingError);