@open-workspace/email 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -8,20 +8,24 @@ import {
8
8
  zValidator,
9
9
  requireSessionAuth,
10
10
  createDb,
11
- mailboxAccess,
12
- mailboxes,
13
- users,
14
11
  mailboxAddressSql,
15
12
  mailboxKindOrderSql,
16
13
  apiError,
17
14
  createId,
15
+ sendInBatches,
18
16
  } from "@open-workspace/core/module";
19
17
  import type {
20
18
  BatchStatement,
21
19
  Database,
22
20
  AppEnv,
23
21
  } from "@open-workspace/core/module";
24
- import { and, desc, eq, isNull, or } from "drizzle-orm";
22
+ import {
23
+ mailboxAccess,
24
+ mailboxes,
25
+ users,
26
+ sessions,
27
+ } from "@open-workspace/core/schema";
28
+ import { and, desc, eq, isNotNull, isNull, notInArray, or } from "drizzle-orm";
25
29
  import { Hono } from "hono";
26
30
  import { z } from "zod";
27
31
 
@@ -29,26 +33,13 @@ import type { MailboxPushJob } from "../../shared/mail";
29
33
  import { mailPath } from "../../shared/mail-path";
30
34
  import {
31
35
  mailboxNotificationPreferences,
36
+ jmapPushSubscriptions,
32
37
  pushSubscriptions,
33
38
  } from "../db/schema";
34
39
  import { deliverJmapStateChange } from "../jmap/push";
35
40
  import { mailboxStub } from "../mailbox";
36
41
  import { getMailboxAccess } from "./access";
37
- import { assertProxyableRemoteUrl } from "./remote-proxy";
38
-
39
- /**
40
- * Push goes to whatever push service the subscriber's browser uses, so any
41
- * public HTTPS host is accepted (a self-hosted Mozilla autopush included).
42
- * What is refused is what the image proxy refuses: credentials in the URL,
43
- * localhost, private and internal addresses, and internal-only names.
44
- */
45
- function isPublicPushEndpoint(endpoint: string) {
46
- try {
47
- return assertProxyableRemoteUrl(endpoint).protocol === "https:";
48
- } catch {
49
- return false;
50
- }
51
- }
42
+ import { isPublicPushEndpoint } from "./push-endpoint";
52
43
 
53
44
  const pushSubscriptionSchema = z.object({
54
45
  // The Worker POSTs to the endpoint for every new message, so it must be a
@@ -93,7 +84,6 @@ const notificationPreferenceSchema = z.object({ enabled: z.boolean() });
93
84
 
94
85
  const pushJobBaseSchema = z.object({
95
86
  mailboxId: z.string().min(1),
96
- conversationId: z.string().min(1),
97
87
  messageId: z.string().min(1),
98
88
  occurredAt: z.number().int().nonnegative(),
99
89
  sender: z.string().min(1).max(500),
@@ -105,6 +95,7 @@ const pushJobSchema = z.discriminatedUnion("type", [
105
95
  type: z.literal("jmap-state"),
106
96
  mailboxId: z.string().min(1),
107
97
  state: z.string().min(1).max(100),
98
+ delivered: z.boolean().default(false),
108
99
  occurredAt: z.number().int().nonnegative(),
109
100
  }),
110
101
  pushJobBaseSchema.extend({ type: z.literal("dispatch") }),
@@ -116,7 +107,6 @@ const pushJobSchema = z.discriminatedUnion("type", [
116
107
  ]) satisfies z.ZodType<MailboxPushJob>;
117
108
 
118
109
  const MAX_PUSH_JOB_AGE_MS = 15 * 60 * 1000;
119
- const MAX_QUEUE_SEND_BATCH_SIZE = 100;
120
110
 
121
111
  type PushConfiguration = {
122
112
  publicKey: string;
@@ -372,35 +362,44 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
372
362
  );
373
363
 
374
364
  /**
375
- * One session was revoked or signed out: its device stops getting
376
- * notifications, in the batch that deletes the session. Rows without a
365
+ * Some of a person's sessions ended: devices on sessions that are gone stop
366
+ * getting notifications, in the batch that deletes them. Rows without a
377
367
  * session (registered before they were recorded) stay until the device
378
- * registers again or every session goes.
368
+ * registers again or every session goes; so do those of expired sessions,
369
+ * whose device moves them when it signs in again.
379
370
  */
380
- export function deleteSessionPushSubscriptions(
371
+ export function deleteEndedSessionPushSubscriptions(
381
372
  db: Database,
382
- session: { userId: string; sessionId: string }
383
- ): BatchStatement[] {
373
+ userId: string
374
+ ) {
384
375
  return [
385
376
  db
386
377
  .delete(pushSubscriptions)
387
378
  .where(
388
379
  and(
389
- eq(pushSubscriptions.userId, session.userId),
390
- eq(pushSubscriptions.sessionId, session.sessionId)
380
+ eq(pushSubscriptions.userId, userId),
381
+ isNotNull(pushSubscriptions.sessionId),
382
+ notInArray(
383
+ pushSubscriptions.sessionId,
384
+ db
385
+ .select({ id: sessions.id })
386
+ .from(sessions)
387
+ .where(eq(sessions.userId, userId))
388
+ )
391
389
  )
392
390
  ),
393
- ];
391
+ ] satisfies BatchStatement[];
394
392
  }
395
393
 
396
394
  /** A person's sessions were all revoked: no device of theirs gets notifications. */
397
- export function deleteUserPushSubscriptions(
398
- db: Database,
399
- userId: string
400
- ): BatchStatement[] {
395
+ export function deleteUserPushSubscriptions(db: Database, userId: string) {
401
396
  return [
402
397
  db.delete(pushSubscriptions).where(eq(pushSubscriptions.userId, userId)),
403
- ];
398
+ // Mail apps' JMAP subscriptions too: their tokens went with the sessions.
399
+ db
400
+ .delete(jmapPushSubscriptions)
401
+ .where(eq(jmapPushSubscriptions.userId, userId)),
402
+ ] satisfies BatchStatement[];
404
403
  }
405
404
 
406
405
  function subscriptionsForMailbox(env: Env, mailboxId: string) {
@@ -455,30 +454,18 @@ async function dispatchPushJob(
455
454
 
456
455
  if (!mailbox || !subscriptions.length) return;
457
456
 
458
- const requests: MessageSendRequest<MailboxPushJob>[] = subscriptions.map(
459
- (subscription) => ({
460
- body: {
461
- ...job,
462
- type: "deliver",
463
- targetSubscriptionId: subscription.id,
464
- mailboxDisplayName: mailbox.displayName,
465
- },
466
- })
467
- );
468
-
469
- const batches: MessageSendRequest<MailboxPushJob>[][] = [];
470
-
471
- for (
472
- let index = 0;
473
- index < requests.length;
474
- index += MAX_QUEUE_SEND_BATCH_SIZE
475
- ) {
476
- batches.push(requests.slice(index, index + MAX_QUEUE_SEND_BATCH_SIZE));
477
- }
478
-
479
- // Each subscription's delivery is its own job, so the batches are independent.
480
- await Promise.all(
481
- batches.map((batch) => env.PUSH_NOTIFICATIONS.sendBatch(batch))
457
+ // Each subscription's delivery is its own job.
458
+ await sendInBatches(
459
+ env.PUSH_NOTIFICATIONS,
460
+ subscriptions.map(
461
+ (subscription) =>
462
+ ({
463
+ ...job,
464
+ type: "deliver",
465
+ targetSubscriptionId: subscription.id,
466
+ mailboxDisplayName: mailbox.displayName,
467
+ }) satisfies MailboxPushJob
468
+ )
482
469
  );
483
470
  }
484
471
 
@@ -551,12 +538,12 @@ async function deliverPushJob(
551
538
  return;
552
539
  }
553
540
 
554
- const suppressed = await mailboxStub(env, job.mailboxId).shouldSuppressPush(
541
+ const destination = await mailboxStub(env, job.mailboxId).pushDestination(
555
542
  job.messageId,
556
543
  subscription.userId
557
544
  );
558
545
 
559
- if (suppressed) return;
546
+ if (!destination) return;
560
547
 
561
548
  try {
562
549
  const delivered = await sendPushNotification(
@@ -567,7 +554,11 @@ async function deliverPushJob(
567
554
  {
568
555
  title: `New email in ${job.mailboxDisplayName}`,
569
556
  body: `${job.sender} · ${job.subject || "(no subject)"}`,
570
- url: mailPath(job.mailboxId, "inbox", job.conversationId),
557
+ url: mailPath(
558
+ job.mailboxId,
559
+ destination.folder,
560
+ destination.conversationId
561
+ ),
571
562
  tag: `message-${job.messageId}`,
572
563
  },
573
564
  configuration,
@@ -83,40 +83,39 @@ function isAttribution(lines: string[], index: number) {
83
83
  .some((candidate) => OUTLOOK_FOLLOWUP.test(candidate.trim()));
84
84
  }
85
85
 
86
- /**
87
- * The first `>` line from which at least 60% of the non-blank lines are
88
- * quoted. One backward pass counts both for every suffix of the body.
89
- */
90
- function trailingQuoteStart(lines: string[]) {
91
- let nonBlank = 0;
92
- let quoted = 0;
93
- let start = -1;
86
+ function quotedBlockStart(lines: string[]) {
87
+ let attribution = -1;
88
+ let firstQuoted = -1;
89
+ let answered = false;
94
90
 
95
- for (let index = lines.length - 1; index >= 0; index -= 1) {
96
- const line = lines[index] ?? "";
91
+ for (const [index, line] of lines.entries()) {
92
+ if (QUOTED_LINE.test(line)) {
93
+ if (firstQuoted === -1) firstQuoted = index;
94
+ continue;
95
+ }
97
96
 
98
- if (line.trim()) nonBlank += 1;
97
+ if (!line.trim()) continue;
99
98
 
100
- if (!QUOTED_LINE.test(line)) continue;
101
- quoted += 1;
99
+ // An answer below or between quoted questions belongs in the visible body.
100
+ if (firstQuoted !== -1) return -1;
102
101
 
103
- if (quoted / nonBlank >= 0.6) start = index;
104
- }
102
+ if (attribution !== -1) continue;
105
103
 
106
- return start;
107
- }
104
+ if (!isAttribution(lines, index)) {
105
+ answered = true;
106
+ continue;
107
+ }
108
108
 
109
- function quotedBlockStart(lines: string[]) {
110
- for (const index of lines.keys()) {
111
- if (isAttribution(lines, index)) return index;
109
+ // A reply written above the quote: everything below is the quote, lines
110
+ // its client wrapped without a `>` and a list's footer included.
111
+ if (answered) return index;
112
+ attribution = index;
112
113
  }
113
114
 
114
- return trailingQuoteStart(lines);
115
+ return attribution === -1 ? firstQuoted : attribution;
115
116
  }
116
117
 
117
- export function parseReplyText(
118
- value: string | undefined | null
119
- ): ParsedReplyText {
118
+ export function parseReplyText(value: string | undefined | null) {
120
119
  const normalized = (value ?? "").replaceAll("\r\n", "\n").trim();
121
120
 
122
121
  if (!normalized) return { bodyText: "", quotedText: null };
@@ -129,3 +128,16 @@ export function parseReplyText(
129
128
 
130
129
  return { bodyText, quotedText: quotedText || null };
131
130
  }
131
+
132
+ /**
133
+ * A quote as a sent message keeps it: the text it answers, without the
134
+ * level of `>` its quoted lines carry in the message (`messageText` puts
135
+ * that level back). Its other lines, an attribution say, stay as they are,
136
+ * inside the quote as a sent message's own header lines are.
137
+ */
138
+ export function sentQuote(quotedText: string) {
139
+ return quotedText
140
+ .split("\n")
141
+ .map((line) => line.replace(/^\s*> ?/u, ""))
142
+ .join("\n");
143
+ }
@@ -1,31 +1,107 @@
1
- import {
2
- createDb,
3
- mailboxAddressPredicate,
4
- mailboxes,
5
- normalizeMailboxAddress,
6
- } from "@open-workspace/core/module";
1
+ import { normalizeMailboxAddress } from "@open-workspace/core/module";
7
2
 
8
3
  import { mailboxStub } from "../mailbox";
9
- import { inboundDeliveryId } from "./inbound-delivery";
10
- import { deliverToList } from "./mailing-list";
4
+ import { receiveArchived } from "./archive";
5
+ import { inboundDeliveryId, inboundMessageDigest } from "./inbound-delivery";
6
+ import { listRecipients } from "./mailing-list";
7
+ import { forwardInbound, resolveInboundRoute } from "./routing";
8
+ import { rawMessageKey } from "./storage-keys";
11
9
 
12
- /** Stores incoming mail for a workspace address, or fans a list's mail out. */
10
+ type ReceivedMessage = { from: string; to: string };
11
+
12
+ /**
13
+ * Stores a received message in each of `targets`' mailboxes, each with its
14
+ * own original (deleting one copy for good leaves the others theirs), and
15
+ * archives it once as `archiveAs`'s from the first copy. Members of a list
16
+ * get `listAddress`, the list's own address. A target that fails is logged
17
+ * and the others still get it; only when every one fails does this throw,
18
+ * and the sender gets a bounce.
19
+ */
20
+ async function deliverInto(input: {
21
+ env: Env;
22
+ message: ReceivedMessage;
23
+ raw: ArrayBuffer;
24
+ receivedAt: number;
25
+ targets: readonly string[];
26
+ archiveAs: string;
27
+ listAddress?: string;
28
+ }) {
29
+ const { env, message, raw, receivedAt } = input;
30
+ const rawDigest = await inboundMessageDigest(raw);
31
+
32
+ const deliveryOf = async (mailboxId: string) => {
33
+ const id = await inboundDeliveryId({
34
+ mailboxId,
35
+ envelopeFrom: message.from,
36
+ envelopeTo: message.to,
37
+ rawDigest,
38
+ });
39
+
40
+ return { id, mailboxId, rawObjectKey: rawMessageKey(mailboxId, id) };
41
+ };
42
+
43
+ const deliveries = await Promise.all(input.targets.map(deliveryOf));
44
+
45
+ const archived =
46
+ deliveries.find(({ mailboxId }) => mailboxId === input.archiveAs) ??
47
+ (await deliveryOf(input.archiveAs));
48
+
49
+ await receiveArchived(
50
+ env,
51
+ {
52
+ id: archived.id,
53
+ mailboxId: input.archiveAs,
54
+ sourceKey: deliveries[0]?.rawObjectKey ?? null,
55
+ receivedAt,
56
+ },
57
+ raw,
58
+ async () => {
59
+ const results = await Promise.allSettled(
60
+ deliveries.map(async (delivery) => {
61
+ // Stored before it is queued: a failed upload fails this copy
62
+ // instead of leaving a delivery without its original.
63
+ await env.MAIL_STORAGE.put(delivery.rawObjectKey, raw, {
64
+ httpMetadata: { contentType: "message/rfc822" },
65
+ });
66
+ await mailboxStub(env, delivery.mailboxId).enqueueInbound({
67
+ ...delivery,
68
+ envelopeFrom: message.from,
69
+ envelopeTo: message.to,
70
+ listAddress: input.listAddress,
71
+ receivedAt,
72
+ });
73
+ })
74
+ );
75
+
76
+ for (const [index, delivery] of deliveries.entries()) {
77
+ const result = results[index];
78
+
79
+ if (result?.status === "rejected") {
80
+ console.error(
81
+ `Could not deliver mail for ${message.to} into ${delivery.mailboxId}`,
82
+ result.reason
83
+ );
84
+ }
85
+ }
86
+
87
+ if (results.every((result) => result.status === "rejected")) {
88
+ throw new Error(`Delivering mail for ${message.to} failed`);
89
+ }
90
+ }
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Stores incoming mail for a workspace address, fans a list's mail out, or
96
+ * forwards it. An alias, a plus address or the catch-all delivers into its
97
+ * mailbox with the envelope recipient kept as the address it was sent to.
98
+ */
13
99
  export async function receiveEmail(message: ForwardableEmailMessage, env: Env) {
14
100
  const receivedAt = Date.now();
15
101
  const recipient = normalizeMailboxAddress(message.to);
102
+ const route = await resolveInboundRoute(env.DB, recipient);
16
103
 
17
- const [mailbox] = await createDb(env.DB)
18
- .select({
19
- id: mailboxes.id,
20
- teamId: mailboxes.teamId,
21
- delivery: mailboxes.delivery,
22
- listPosting: mailboxes.listPosting,
23
- })
24
- .from(mailboxes)
25
- .where(mailboxAddressPredicate(recipient))
26
- .limit(1);
27
-
28
- if (!mailbox) {
104
+ if (!route) {
29
105
  message.setReject(`Mailbox ${recipient} does not exist`);
30
106
 
31
107
  return;
@@ -33,39 +109,70 @@ export async function receiveEmail(message: ForwardableEmailMessage, env: Env) {
33
109
 
34
110
  const raw = await new Response(message.raw).arrayBuffer();
35
111
 
112
+ if (route.kind === "forward") {
113
+ // Archived as the forward address's only once forwarded: nothing else
114
+ // keeps a copy, and archiving never throws.
115
+ await forwardInbound({
116
+ env,
117
+ message,
118
+ raw,
119
+ forwardTo: route.forwardTo,
120
+ archive: async () =>
121
+ receiveArchived(
122
+ env,
123
+ {
124
+ id: await inboundDeliveryId({
125
+ mailboxId: route.id,
126
+ envelopeFrom: message.from,
127
+ envelopeTo: message.to,
128
+ rawDigest: await inboundMessageDigest(raw),
129
+ }),
130
+ mailboxId: route.id,
131
+ sourceKey: null,
132
+ receivedAt,
133
+ },
134
+ raw
135
+ ),
136
+ });
137
+
138
+ return;
139
+ }
140
+
141
+ const { mailbox } = route;
142
+
36
143
  if (mailbox.delivery === "list" && mailbox.teamId) {
37
- await deliverToList({
144
+ const recipients = await listRecipients({
38
145
  env,
39
146
  list: {
40
147
  id: mailbox.id,
148
+ address: `${mailbox.localPart}@${mailbox.domain}`,
41
149
  teamId: mailbox.teamId,
42
150
  listPosting: mailbox.listPosting,
43
151
  },
44
152
  message,
45
153
  raw,
46
- receivedAt,
47
154
  });
48
155
 
156
+ if (recipients) {
157
+ await deliverInto({
158
+ env,
159
+ message,
160
+ raw,
161
+ receivedAt,
162
+ ...recipients,
163
+ archiveAs: mailbox.id,
164
+ });
165
+ }
166
+
49
167
  return;
50
168
  }
51
169
 
52
- const deliveryId = await inboundDeliveryId({
53
- mailboxId: mailbox.id,
54
- envelopeFrom: message.from,
55
- envelopeTo: message.to,
170
+ await deliverInto({
171
+ env,
172
+ message,
56
173
  raw,
57
- });
58
-
59
- const objectKey = `mailboxes/${mailbox.id}/raw/${deliveryId}.eml`;
60
- await mailboxStub(env, mailbox.id).enqueueInbound({
61
- id: deliveryId,
62
- mailboxId: mailbox.id,
63
- rawObjectKey: objectKey,
64
- envelopeFrom: message.from,
65
- envelopeTo: message.to,
66
174
  receivedAt,
67
- });
68
- await env.MAIL_STORAGE.put(objectKey, raw, {
69
- httpMetadata: { contentType: "message/rfc822" },
175
+ targets: [mailbox.id],
176
+ archiveAs: mailbox.id,
70
177
  });
71
178
  }
@@ -10,7 +10,7 @@ export type RecipientFields = {
10
10
  * A destination can occupy only one visible/hidden role. Precedence follows
11
11
  * what recipients can observe: To, then Cc, then Bcc.
12
12
  */
13
- export function dedupeRecipientFields(input: RecipientFields): RecipientFields {
13
+ export function dedupeRecipientFields(input: RecipientFields) {
14
14
  const seen = new Set<string>();
15
15
 
16
16
  const take = (values: string[]) => {
@@ -80,7 +80,7 @@ type Ipv6Groups = [
80
80
  ];
81
81
 
82
82
  /** The eight 16-bit groups of an IPv6 address (brackets, a zone, an IPv4 tail allowed), or null. */
83
- function ipv6Groups(hostname: string): Ipv6Groups | null {
83
+ function ipv6Groups(hostname: string) {
84
84
  let value = hostname
85
85
  .toLowerCase()
86
86
  .replaceAll(/^\[|\]$/gu, "")
@@ -118,7 +118,7 @@ function ipv6Groups(hostname: string): Ipv6Groups | null {
118
118
 
119
119
  if (groups.length !== 8) return null;
120
120
 
121
- return [g0, g1, g2, g3, g4, g5, g6, g7];
121
+ return [g0, g1, g2, g3, g4, g5, g6, g7] satisfies Ipv6Groups;
122
122
  }
123
123
 
124
124
  /**
@@ -183,7 +183,7 @@ function isBlockedIp(hostname: string) {
183
183
  return !groups || isBlockedIpv6(groups);
184
184
  }
185
185
 
186
- export function assertProxyableRemoteUrl(value: string): URL {
186
+ export function assertProxyableRemoteUrl(value: string) {
187
187
  let url: URL;
188
188
 
189
189
  try {
@@ -7,7 +7,7 @@
7
7
  export async function repeatUntil<T>(
8
8
  limit: number,
9
9
  step: (attempt: number) => Promise<T | undefined>
10
- ): Promise<T | undefined> {
10
+ ) {
11
11
  for (let attempt = 0; attempt < limit; attempt += 1) {
12
12
  // oxlint-disable-next-line eslint/no-await-in-loop -- each attempt depends on the one before (that is this helper's contract)
13
13
  const value = await step(attempt);