@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
@@ -16,8 +16,8 @@ import {
16
16
  MAIL_SEND_SCOPE,
17
17
  } from "../../shared/permissions";
18
18
  import { mailboxStub } from "../mailbox";
19
- import type { Email } from "../mailbox/schema";
20
19
  import { accessibleMailbox } from "./access";
20
+ import { mayOrganizeMailbox, organizeRefusal } from "./capabilities";
21
21
  import { oneClickFetcher } from "./demo-routes";
22
22
  import { emailListKey } from "./message-view";
23
23
  import { submitOutgoing } from "./outbound-service";
@@ -30,12 +30,14 @@ import {
30
30
  unsubscribeSchema,
31
31
  } from "./schemas";
32
32
  import {
33
+ mailtoUnsubscribeAddress,
33
34
  oneClickHost,
34
- parseMailtoUnsubscribe,
35
35
  postOneClick,
36
36
  } from "./unsubscribe";
37
37
  import {
38
- recordWorkspaceFeedback,
38
+ blocksOwnMailDomain,
39
+ mailboxBlockRefused,
40
+ shareSpamVerdicts,
39
41
  workspaceBlockPatterns,
40
42
  } from "./workspace-safety";
41
43
 
@@ -43,33 +45,21 @@ function forbidden(c: Context<AppEnv>) {
43
45
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
44
46
  }
45
47
 
46
- /** Report one message as spam: Spam folder, sender feedback here and workspace-wide. */
47
- async function reportOne(input: {
48
- env: Env;
49
- mailboxId: string;
50
- userId: string;
51
- email: Email;
52
- }) {
53
- const result = await mailboxStub(input.env, input.mailboxId).reportMessage({
54
- emailId: input.email.id,
55
- userId: input.userId,
56
- });
48
+ /** Report spam of messages or conversations, and the verdicts shared with the workspace. */
49
+ async function reportSpam(
50
+ env: Env,
51
+ mailboxId: string,
52
+ input: Parameters<ReturnType<typeof mailboxStub>["reportSpam"]>[0]
53
+ ) {
54
+ const result = await mailboxStub(env, mailboxId).reportSpam(input);
57
55
 
58
56
  if (!result) return null;
59
- const sender = result.email.fromJson[0]?.address;
60
-
61
- if (sender) {
62
- await recordWorkspaceFeedback(input.env.DB, {
63
- mailboxId: input.mailboxId,
64
- emailId: result.email.id,
65
- address: sender,
66
- label: "spam",
67
- }).catch((error) =>
68
- console.error(`Could not share the report for ${result.email.id}`, error)
69
- );
57
+
58
+ if (!result.undoId) {
59
+ await shareSpamVerdicts(env.DB, mailboxId, result.verdicts);
70
60
  }
71
61
 
72
- return { moved: result.moved };
62
+ return result;
73
63
  }
74
64
 
75
65
  export const mailSafetyRoutes = new Hono<AppEnv>()
@@ -193,10 +183,21 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
193
183
  detail = result.detail;
194
184
  }
195
185
 
196
- const mailto = methods.mailto
197
- ? parseMailtoUnsubscribe(methods.mailto)
186
+ const listAddress = methods.mailto
187
+ ? mailtoUnsubscribeAddress(methods.mailto)
198
188
  : null;
199
189
 
190
+ // Any incoming mail can name a target: one at the workspace's own
191
+ // domain would be a colleague, written to from this person's address.
192
+ const mailto =
193
+ listAddress && !blocksOwnMailDomain(listAddress.toLowerCase())
194
+ ? listAddress
195
+ : null;
196
+
197
+ if (listAddress && !mailto) {
198
+ detail = `Won't email ${listAddress} to unsubscribe: it is an address of this workspace`;
199
+ }
200
+
200
201
  if (mailto && access.canSend) {
201
202
  const submission = await submitOutgoing({
202
203
  env: c.env,
@@ -205,11 +206,11 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
205
206
  requestId: crypto.randomUUID(),
206
207
  mailboxId,
207
208
  userId: user.id,
208
- to: [mailto.to],
209
+ to: [mailto],
209
210
  cc: [],
210
211
  bcc: [],
211
- subject: mailto.subject,
212
- bodyText: mailto.body,
212
+ subject: "unsubscribe",
213
+ bodyText: "unsubscribe",
213
214
  attachments: [],
214
215
  },
215
216
  conversationId: createId("conv"),
@@ -218,7 +219,6 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
218
219
  includeRelatedContext: false,
219
220
  fromAddress: access.address,
220
221
  fromName: access.displayName,
221
- defer: (task) => c.executionCtx.waitUntil(task),
222
222
  });
223
223
 
224
224
  const failed = submission.email.transportState === "failed";
@@ -226,7 +226,7 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
226
226
  const unsubscription = await record(
227
227
  "mailto",
228
228
  failed ? "failed" : "requested",
229
- mailto.to,
229
+ mailto,
230
230
  failed ? submission.email.transportError : detail
231
231
  );
232
232
 
@@ -291,24 +291,18 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
291
291
 
292
292
  if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
293
293
 
294
- const email = await mailboxStub(c.env, mailboxId).getEmail(
295
- c.req.param("id")
296
- );
297
-
298
- if (!email || email.direction !== "incoming") {
299
- return apiError(c, 404, "NOT_FOUND", "Message not found");
300
- }
301
-
302
- const result = await reportOne({
303
- env: c.env,
304
- mailboxId,
294
+ const result = await reportSpam(c.env, mailboxId, {
295
+ emailId: c.req.param("id"),
305
296
  userId: user.id,
306
- email,
307
297
  });
308
298
 
309
299
  if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
310
300
 
311
- return c.json({ ok: true as const, ...result });
301
+ return c.json({
302
+ ok: true as const,
303
+ places: result.places,
304
+ undoId: result.undoId,
305
+ });
312
306
  }
313
307
  )
314
308
  .post(
@@ -324,20 +318,40 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
324
318
  if (!access) return forbidden(c);
325
319
  const input = c.req.valid("json");
326
320
 
327
- const messages = await mailboxStub(c.env, mailboxId).latestIncomingEmails(
328
- input.conversationIds
329
- );
321
+ // Each conversation's received mail, as moving it into Spam does.
322
+ const result = await reportSpam(c.env, mailboxId, {
323
+ conversationIds: input.conversationIds,
324
+ userId: user.id,
325
+ });
330
326
 
331
- // Each report concerns its own message; the mailbox serializes them.
332
- const results = await Promise.all(
333
- messages.map((email) =>
334
- reportOne({ env: c.env, mailboxId, userId: user.id, email })
335
- )
336
- );
327
+ return c.json({ ok: true as const, places: result?.places ?? [] });
328
+ }
329
+ )
330
+ .post(
331
+ "/conversations/not-spam",
332
+ oauthScope(MAIL_ORGANIZE_SCOPE),
333
+ zValidator("query", mailboxQuerySchema),
334
+ zValidator("json", bulkReportSchema),
335
+ async (c) => {
336
+ const { mailboxId } = c.req.valid("query");
337
+ const user = c.get("user");
338
+ const access = await accessibleMailbox(c, mailboxId, "read");
339
+
340
+ if (!access) return forbidden(c);
341
+ const stub = mailboxStub(c.env, mailboxId);
342
+
343
+ // As Not spam does for each conversation's received mail: feedback,
344
+ // trusted senders (for those who may organize the mailbox), and back
345
+ // into the threads they were kept out of.
346
+ const result = await stub.markNotSpam({
347
+ conversationIds: c.req.valid("json").conversationIds,
348
+ userId: user.id,
349
+ trustSenders: mayOrganizeMailbox(c, access),
350
+ });
337
351
 
338
- const reported = results.filter(Boolean).length;
352
+ await shareSpamVerdicts(c.env.DB, mailboxId, result?.verdicts ?? []);
339
353
 
340
- return c.json({ ok: true as const, reportedCount: reported });
354
+ return c.json({ ok: true as const, places: result?.places ?? [] });
341
355
  }
342
356
  )
343
357
  .post(
@@ -348,37 +362,22 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
348
362
  const { mailboxId } = c.req.valid("query");
349
363
  const user = c.get("user");
350
364
 
351
- if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
365
+ const access = await accessibleMailbox(c, mailboxId, "read");
366
+
367
+ if (!access) return forbidden(c);
352
368
  const emailId = c.req.param("id");
353
369
 
370
+ // Its sender is trusted only by those who may organize the mailbox.
354
371
  const result = await mailboxStub(c.env, mailboxId).markNotSpam({
355
- emailId,
372
+ emailIds: [emailId],
356
373
  userId: user.id,
374
+ trustSenders: mayOrganizeMailbox(c, access),
357
375
  });
358
376
 
359
- if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
360
-
361
- if (result.address) {
362
- await recordWorkspaceFeedback(c.env.DB, {
363
- mailboxId,
364
- emailId,
365
- address: result.address,
366
- label: "not_spam",
367
- }).catch((error) =>
368
- console.error(
369
- `Could not share the not-spam verdict for ${emailId}`,
370
- error
371
- )
372
- );
373
- }
377
+ await shareSpamVerdicts(c.env.DB, mailboxId, result?.verdicts ?? []);
374
378
 
375
- return c.json({
376
- ok: true as const,
377
- restored: result.restored,
378
- conversationId: result.conversationId,
379
- rejoined: result.rejoined,
380
- folder: result.folder,
381
- });
379
+ // Where its conversation is now; none when it wasn't in Spam.
380
+ return c.json({ ok: true as const, places: result?.places ?? [] });
382
381
  }
383
382
  )
384
383
  .get(
@@ -410,6 +409,9 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
410
409
  zValidator("json", blockSenderSchema),
411
410
  async (c) => {
412
411
  const mailboxId = c.req.param("id");
412
+ const refused = await organizeRefusal(c, mailboxId);
413
+
414
+ if (refused) return refused;
413
415
  const access = await accessibleMailbox(c, mailboxId, "read");
414
416
 
415
417
  if (!access) return forbidden(c);
@@ -425,9 +427,7 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
425
427
  );
426
428
  }
427
429
 
428
- const own = access.address.toLocaleLowerCase();
429
-
430
- if (pattern === own || own.endsWith(pattern)) {
430
+ if (mailboxBlockRefused(access.address, pattern)) {
431
431
  return apiError(
432
432
  c,
433
433
  400,
@@ -450,8 +450,9 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
450
450
  zValidator("query", blockPatternQuerySchema),
451
451
  async (c) => {
452
452
  const mailboxId = c.req.param("id");
453
+ const refused = await organizeRefusal(c, mailboxId);
453
454
 
454
- if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
455
+ if (refused) return refused;
455
456
  const pattern = normalizeBlockPattern(c.req.valid("query").pattern);
456
457
 
457
458
  if (
@@ -470,8 +471,9 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
470
471
  zValidator("json", trustSenderSchema),
471
472
  async (c) => {
472
473
  const mailboxId = c.req.param("id");
474
+ const refused = await organizeRefusal(c, mailboxId);
473
475
 
474
- if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
476
+ if (refused) return refused;
475
477
  const input = c.req.valid("json");
476
478
  await mailboxStub(c.env, mailboxId).setSenderTrusted(
477
479
  input.address,
@@ -7,9 +7,12 @@ import {
7
7
  MAX_BULK_CONVERSATION_COUNT,
8
8
  MAX_COMPOSER_ATTACHMENT_BYTES,
9
9
  MAX_COMPOSER_ATTACHMENT_COUNT,
10
+ MAX_COMPOSER_HTML_LENGTH,
11
+ MAX_COMPOSER_TEXT_LENGTH,
10
12
  MAX_CUSTOM_FOLDER_COUNT,
11
13
  MAX_MAIL_RECIPIENTS,
12
14
  replyActionModes,
15
+ autoReplyAudiences,
13
16
  } from "../../shared/mail";
14
17
  import {
15
18
  MAX_TRANSLATION_CHARACTERS,
@@ -32,6 +35,8 @@ export const mailboxAiConfigurationSchema = z.object({
32
35
  confidenceThreshold: z.number().int().min(50).max(100),
33
36
  });
34
37
 
38
+ export const retentionFolderSchema = z.enum(["trash", "spam"]);
39
+
35
40
  /** Every folder but Inbox, in order: the movable system folders and the custom ones. */
36
41
  export const reorderFoldersSchema = z.object({
37
42
  folderIds: z
@@ -66,6 +71,7 @@ export const conversationListQuerySchema = mailboxQuerySchema.extend({
66
71
  });
67
72
 
68
73
  export const conversationMessagesQuerySchema = mailboxQuerySchema.extend({
74
+ match: z.string().min(1).max(512).optional(),
69
75
  limit: z.coerce.number().int().min(1).max(25).default(25),
70
76
  cursor: z.string().trim().min(1).max(512).optional(),
71
77
  });
@@ -102,17 +108,18 @@ export const uploadIdSchema = z
102
108
  .max(80)
103
109
  .regex(/^upl_[a-f0-9]{32}$/u, "Attachment upload id is invalid");
104
110
 
111
+ const contentIdSchema = z
112
+ .string()
113
+ .trim()
114
+ .min(1)
115
+ .max(255)
116
+ .regex(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+$/u, "Content ID is invalid");
117
+
105
118
  export const outboundAttachmentSchema = z
106
119
  .object({
107
120
  uploadId: uploadIdSchema,
108
121
  disposition: z.enum(["attachment", "inline"]).default("attachment"),
109
- contentId: z
110
- .string()
111
- .trim()
112
- .min(1)
113
- .max(255)
114
- .regex(/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+$/u, "Content ID is invalid")
115
- .optional(),
122
+ contentId: contentIdSchema.optional(),
116
123
  })
117
124
  .superRefine((attachment, context) => {
118
125
  if (attachment.disposition === "inline" && !attachment.contentId) {
@@ -132,8 +139,101 @@ export const outboundAttachmentSchema = z
132
139
  }
133
140
  });
134
141
 
142
+ /** Saved rich content from the composer's editor (rich-content.ts). */
143
+ export const richContentFields = {
144
+ /** Stored as given; no text and no image deletes the content. */
145
+ html: z.string().max(20_000),
146
+ text: z.string().max(10_000),
147
+ /**
148
+ * Its `cid:` images: a new composer upload (`uploadId`), or one it already
149
+ * had, kept under its content id.
150
+ */
151
+ images: z
152
+ .array(
153
+ z.object({
154
+ contentId: contentIdSchema,
155
+ uploadId: uploadIdSchema.optional(),
156
+ })
157
+ )
158
+ .max(10)
159
+ .default([]),
160
+ /** The mailbox new images were uploaded through (uploads are per mailbox). */
161
+ uploadMailboxId: z.string().min(1).max(80).optional(),
162
+ };
163
+
164
+ export const signatureSchema = z.object({
165
+ ...richContentFields,
166
+ useOnNew: z.boolean().default(true),
167
+ useOnReply: z.boolean().default(true),
168
+ });
169
+
170
+ /** Saved images (a signature's) a body shows by `cid:`, by owner and content id. */
171
+ export const storedImageRefSchema = z.object({
172
+ ownerId: z.string().min(1).max(80),
173
+ contentId: contentIdSchema,
174
+ });
175
+
176
+ const storedImagesSchema = z
177
+ .array(storedImageRefSchema)
178
+ .max(MAX_COMPOSER_ATTACHMENT_COUNT)
179
+ .default([]);
180
+
181
+ const timestamp = z.iso
182
+ .datetime({ offset: true })
183
+ .transform((value) => new Date(value));
184
+
185
+ /** One of an auto-reply's two messages; kept when switched off. */
186
+ const autoReplyMessageFields = {
187
+ enabled: z.boolean(),
188
+ subject: z
189
+ .string()
190
+ .trim()
191
+ .max(998)
192
+ .nullable()
193
+ .default(null)
194
+ .transform((value) => value || null),
195
+ ...richContentFields,
196
+ };
197
+
198
+ export const autoReplyFields = {
199
+ enabled: z.boolean().optional(),
200
+ startsAt: timestamp.nullable().default(null),
201
+ endsAt: timestamp.nullable().default(null),
202
+ replyIntervalDays: z.number().int().min(1).max(30).default(4),
203
+ /** For senders in the workspace's mail domains. */
204
+ inside: z.object(autoReplyMessageFields),
205
+ /** For everyone else, or only people the mailbox has written to. */
206
+ outside: z.object({
207
+ ...autoReplyMessageFields,
208
+ audience: z.enum(autoReplyAudiences).default("everyone"),
209
+ }),
210
+ };
211
+
212
+ export const autoReplySchema = z
213
+ .object(autoReplyFields)
214
+ .superRefine((value, context) => {
215
+ if (value.startsAt && value.endsAt && value.endsAt <= value.startsAt) {
216
+ context.addIssue({
217
+ code: "custom",
218
+ path: ["endsAt"],
219
+ message: "The end must be after the start",
220
+ });
221
+ }
222
+ });
223
+
135
224
  export const outboundMessageContentFields = {
136
225
  bodyText: z.string().max(500_000).default(""),
226
+ /**
227
+ * Appends the signature that applies: the team address's, or the sender's
228
+ * own for their own mailbox. For API and MCP callers; the web app puts the
229
+ * signature in its editor instead.
230
+ */
231
+ includeSignature: z.boolean().optional(),
232
+ /**
233
+ * Saved images (a signature's) the body shows by `cid:`, sent inline
234
+ * without uploading them again.
235
+ */
236
+ storedImages: storedImagesSchema,
137
237
  bodyHtml: z.string().max(1_000_000).optional(),
138
238
  attachments: z
139
239
  .array(outboundAttachmentSchema)
@@ -157,12 +257,18 @@ export const outboundMessageContentFields = {
157
257
  ),
158
258
  };
159
259
 
160
- const hasMessageBody = (value: { bodyText: string; bodyHtml?: string }) =>
161
- Boolean(value.bodyText.trim() || value.bodyHtml?.trim());
260
+ const hasMessageContent = (value: {
261
+ bodyText: string;
262
+ bodyHtml?: string;
263
+ attachments: readonly unknown[];
264
+ }) =>
265
+ Boolean(
266
+ value.bodyText.trim() || value.bodyHtml?.trim() || value.attachments.length
267
+ );
162
268
 
163
269
  const missingMessageBody = {
164
270
  path: ["bodyText"],
165
- message: "Add text to the message before sending",
271
+ message: "Add text or a file to the message before sending",
166
272
  };
167
273
 
168
274
  export const outboundContentFields = {
@@ -170,8 +276,15 @@ export const outboundContentFields = {
170
276
  ...outboundMessageContentFields,
171
277
  };
172
278
 
279
+ export const draftIdSchema = z
280
+ .string()
281
+ .regex(/^drf_[A-Za-z0-9-]{8,64}$/u, "Draft id is invalid");
282
+
173
283
  const outboundRequestFields = {
174
284
  requestId: z.uuid(),
285
+ /** The sender's draft of this message, deleted once it is accepted. */
286
+ draftId: draftIdSchema.optional(),
287
+ draftVersion: z.number().int().positive().optional(),
175
288
  ...outboundContentFields,
176
289
  };
177
290
 
@@ -192,7 +305,7 @@ export const composeSchema = z
192
305
  ...value,
193
306
  ...dedupeRecipientFields(value),
194
307
  }))
195
- .refine(hasMessageBody, missingMessageBody)
308
+ .refine(hasMessageContent, missingMessageBody)
196
309
  .refine((value) => recipientCount(value) > 0, {
197
310
  message: "Add at least one recipient in To, Cc, or Bcc",
198
311
  })
@@ -205,12 +318,15 @@ export const replySchema = z
205
318
  ...outboundRequestFields,
206
319
  mode: z.enum(replyActionModes),
207
320
  cc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).optional(),
208
- bcc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).default([]),
321
+ bcc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).optional(),
209
322
  })
210
- .refine(hasMessageBody, missingMessageBody);
323
+ .refine(hasMessageContent, missingMessageBody);
324
+
325
+ export const forwardedAttachmentIdsSchema = z.array(z.string().min(1).max(255));
211
326
 
212
327
  export const forwardSchema = z
213
328
  .object({
329
+ forwardedAttachmentIds: forwardedAttachmentIdsSchema.optional(),
214
330
  ...outboundRequestFields,
215
331
  ...outboundRecipientFields,
216
332
  replyTo: emailSchema.optional(),
@@ -235,6 +351,7 @@ export const attachmentPreflightSchema = z.discriminatedUnion("kind", [
235
351
  z.object({
236
352
  ...outboundContentFields,
237
353
  kind: z.literal("forward"),
354
+ forwardedAttachmentIds: forwardedAttachmentIdsSchema.optional(),
238
355
  sourceEmailId: z.string().trim().min(1).max(255),
239
356
  }),
240
357
  z.object({
@@ -243,7 +360,7 @@ export const attachmentPreflightSchema = z.discriminatedUnion("kind", [
243
360
  sourceEmailId: z.string().trim().min(1).max(255),
244
361
  mode: z.enum(replyActionModes),
245
362
  cc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).optional(),
246
- bcc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).default([]),
363
+ bcc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).optional(),
247
364
  }),
248
365
  ]);
249
366
 
@@ -257,17 +374,6 @@ export const updateConversationSchema = z
257
374
  {
258
375
  message: "No changes supplied",
259
376
  }
260
- )
261
- .refine(
262
- (value) =>
263
- value.folderId === undefined ||
264
- value.folderId === null ||
265
- value.mailboxState === undefined ||
266
- value.mailboxState === "active",
267
- {
268
- path: ["mailboxState"],
269
- message: "Moving to a custom folder requires the active mailbox state",
270
- }
271
377
  );
272
378
 
273
379
  const bulkConversationIdsSchema = z
@@ -282,12 +388,30 @@ export const bulkConversationActionSchema = z.discriminatedUnion("type", [
282
388
  conversationIds: bulkConversationIdsSchema,
283
389
  isRead: z.boolean(),
284
390
  }),
285
- z.object({
286
- type: z.literal("update"),
287
- conversationIds: bulkConversationIdsSchema,
288
- sourceFolderId: z.string().trim().min(1).max(255),
289
- update: updateConversationSchema,
290
- }),
391
+ z
392
+ .object({
393
+ type: z.literal("update"),
394
+ conversationIds: bulkConversationIdsSchema,
395
+ sourceFolderId: z.string().trim().min(1).max(255),
396
+ update: updateConversationSchema,
397
+ /**
398
+ * Puts conversations back as an Undo: into or out of Spam it is no
399
+ * verdict on their senders, and trusts none of them.
400
+ */
401
+ undo: z.boolean().default(false),
402
+ offerUndo: z.boolean().optional(),
403
+ })
404
+ .refine(
405
+ ({ undo, update }) =>
406
+ undo ||
407
+ !update.folderId ||
408
+ !update.mailboxState ||
409
+ update.mailboxState === "active",
410
+ {
411
+ path: ["update", "mailboxState"],
412
+ message: "Moving to a custom folder requires the active mailbox state",
413
+ }
414
+ ),
291
415
  z.object({
292
416
  type: z.literal("delete_permanently"),
293
417
  conversationIds: bulkConversationIdsSchema,
@@ -316,3 +440,70 @@ export const unsubscribeSchema = z.object({
316
440
  export const bulkReportSchema = z.object({
317
441
  conversationIds: z.array(z.string().trim().min(1).max(255)).min(1).max(100),
318
442
  });
443
+
444
+ /** Addresses as typed: a draft may hold ones that aren't valid yet. */
445
+ const draftAddressesSchema = z
446
+ .array(z.string().trim().min(1).max(320))
447
+ .max(MAX_MAIL_RECIPIENTS)
448
+ .default([]);
449
+
450
+ const draftReferenceSchema = z
451
+ .string()
452
+ .min(1)
453
+ .max(200)
454
+ .nullable()
455
+ .default(null);
456
+
457
+ /** A composer file a draft keeps, named by its upload; the server adds the rest. */
458
+ const draftAttachmentsSchema = z
459
+ .array(z.object({ assetId: z.uuid() }).and(outboundAttachmentSchema))
460
+ .max(MAX_COMPOSER_ATTACHMENT_COUNT)
461
+ .default([])
462
+ .refine(
463
+ (attachments) =>
464
+ new Set(attachments.map((file) => file.uploadId)).size ===
465
+ attachments.length,
466
+ { message: "Duplicate attachment uploads are not allowed" }
467
+ );
468
+
469
+ // A draft row stays well under the Durable Object's 2 MB value limit even
470
+ // when every character takes three UTF-8 bytes.
471
+ export const saveDraftSchema = z
472
+ .object({
473
+ /** The version this save is based on; 0 creates the draft. */
474
+ expectedVersion: z.number().int().nonnegative(),
475
+ kind: z.enum(["compose", "reply", "forward"]),
476
+ sourceEmailId: draftReferenceSchema,
477
+ forwardedAttachmentIds: forwardedAttachmentIdsSchema
478
+ .nullable()
479
+ .default(null),
480
+ conversationId: draftReferenceSchema,
481
+ replyMode: z.enum(replyActionModes).nullable().default(null),
482
+ to: draftAddressesSchema,
483
+ cc: draftAddressesSchema,
484
+ bcc: draftAddressesSchema,
485
+ replyTo: z.string().trim().max(320).nullable().default(null),
486
+ subject: z.string().max(998).default(""),
487
+ bodyText: z.string().max(MAX_COMPOSER_TEXT_LENGTH).default(""),
488
+ bodyHtml: z.string().max(MAX_COMPOSER_HTML_LENGTH).nullable().default(null),
489
+ editorHtml: z
490
+ .string()
491
+ .max(MAX_COMPOSER_HTML_LENGTH)
492
+ .nullable()
493
+ .default(null),
494
+ attachments: draftAttachmentsSchema,
495
+ /** Signature images the HTML shows; the draft keeps its own copies. */
496
+ storedImages: storedImagesSchema,
497
+ })
498
+ .refine((value) => value.kind === "compose" || value.sourceEmailId, {
499
+ path: ["sourceEmailId"],
500
+ message: "Replies and forwards name their message",
501
+ })
502
+ .refine((value) => value.kind !== "reply" || value.conversationId, {
503
+ path: ["conversationId"],
504
+ message: "Replies name their conversation",
505
+ })
506
+ .refine((value) => value.kind !== "reply" || value.replyMode, {
507
+ path: ["replyMode"],
508
+ message: "Replies name their reply mode",
509
+ });
@@ -5,11 +5,34 @@ const MAX_SEARCH_TOKENS = 24;
5
5
  * User input never reaches FTS5 query syntax directly. Each Unicode word is
6
6
  * quoted and treated as a prefix, which supports partial names and addresses.
7
7
  */
8
- export function buildEmailSearchQuery(value: string) {
8
+ export function emailSearchTokens(value: string) {
9
9
  const tokens = value.normalize("NFKC").match(SEARCH_TOKEN_PATTERN) ?? [];
10
- const unique = [...new Set(tokens)].slice(0, MAX_SEARCH_TOKENS);
10
+
11
+ return [...new Set(tokens)].slice(0, MAX_SEARCH_TOKENS);
12
+ }
13
+
14
+ export function buildEmailSearchQuery(value: string) {
15
+ const unique = emailSearchTokens(value);
11
16
 
12
17
  return unique.length
13
18
  ? unique.map((token) => `"${token}"*`).join(" AND ")
14
19
  : null;
15
20
  }
21
+
22
+ function foldSearchText(value: string) {
23
+ return value.normalize("NFKD").replaceAll(/\p{M}/gu, "").toLowerCase();
24
+ }
25
+
26
+ /** Drafts have no FTS row. Match the same word prefixes across their searchable fields. */
27
+ export function draftSearchMatcher(value: string) {
28
+ const prefixes = emailSearchTokens(foldSearchText(value));
29
+
30
+ return (text: string) => {
31
+ const words = foldSearchText(text).match(SEARCH_TOKEN_PATTERN) ?? [];
32
+
33
+ return (
34
+ prefixes.length > 0 &&
35
+ prefixes.every((prefix) => words.some((word) => word.startsWith(prefix)))
36
+ );
37
+ };
38
+ }