@open-workspace/email 0.4.1 → 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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -8,16 +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,
16
+ } from "@open-workspace/core/module";
17
+ import type {
18
+ BatchStatement,
19
+ Database,
20
+ AppEnv,
18
21
  } from "@open-workspace/core/module";
19
- import type { Database, AppEnv } from "@open-workspace/core/module";
20
- 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";
21
29
  import { Hono } from "hono";
22
30
  import { z } from "zod";
23
31
 
@@ -25,20 +33,21 @@ import type { MailboxPushJob } from "../../shared/mail";
25
33
  import { mailPath } from "../../shared/mail-path";
26
34
  import {
27
35
  mailboxNotificationPreferences,
36
+ jmapPushSubscriptions,
28
37
  pushSubscriptions,
29
38
  } from "../db/schema";
30
39
  import { deliverJmapStateChange } from "../jmap/push";
31
40
  import { mailboxStub } from "../mailbox";
32
41
  import { getMailboxAccess } from "./access";
42
+ import { isPublicPushEndpoint } from "./push-endpoint";
33
43
 
34
44
  const pushSubscriptionSchema = z.object({
45
+ // The Worker POSTs to the endpoint for every new message, so it must be a
46
+ // public HTTPS URL (isPublicPushEndpoint), never a relay into the network.
35
47
  endpoint: z
36
48
  .url()
37
49
  .max(4096)
38
- .refine(
39
- (value) => new URL(value).protocol === "https:",
40
- "Push endpoint must use HTTPS"
41
- ),
50
+ .refine(isPublicPushEndpoint, "Push endpoint must be a public HTTPS URL"),
42
51
  keys: z.object({
43
52
  p256dh: z
44
53
  .string()
@@ -75,7 +84,6 @@ const notificationPreferenceSchema = z.object({ enabled: z.boolean() });
75
84
 
76
85
  const pushJobBaseSchema = z.object({
77
86
  mailboxId: z.string().min(1),
78
- conversationId: z.string().min(1),
79
87
  messageId: z.string().min(1),
80
88
  occurredAt: z.number().int().nonnegative(),
81
89
  sender: z.string().min(1).max(500),
@@ -87,6 +95,7 @@ const pushJobSchema = z.discriminatedUnion("type", [
87
95
  type: z.literal("jmap-state"),
88
96
  mailboxId: z.string().min(1),
89
97
  state: z.string().min(1).max(100),
98
+ delivered: z.boolean().default(false),
90
99
  occurredAt: z.number().int().nonnegative(),
91
100
  }),
92
101
  pushJobBaseSchema.extend({ type: z.literal("dispatch") }),
@@ -98,7 +107,6 @@ const pushJobSchema = z.discriminatedUnion("type", [
98
107
  ]) satisfies z.ZodType<MailboxPushJob>;
99
108
 
100
109
  const MAX_PUSH_JOB_AGE_MS = 15 * 60 * 1000;
101
- const MAX_QUEUE_SEND_BATCH_SIZE = 100;
102
110
 
103
111
  type PushConfiguration = {
104
112
  publicKey: string;
@@ -306,11 +314,16 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
306
314
  async (c) => {
307
315
  const input = c.req.valid("json");
308
316
  const now = new Date();
317
+ // Bound to this session, so revoking or signing out of it ends the
318
+ // device's notifications. The app registers again on every start, so
319
+ // after a new sign-in on the device the row follows the new session.
320
+ const sessionId = c.get("sessionId");
309
321
  await createDb(c.env.DB)
310
322
  .insert(pushSubscriptions)
311
323
  .values({
312
324
  id: createId("push"),
313
325
  userId: c.get("user").id,
326
+ sessionId,
314
327
  endpoint: input.endpoint,
315
328
  p256dh: input.keys.p256dh,
316
329
  auth: input.keys.auth,
@@ -321,6 +334,7 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
321
334
  target: pushSubscriptions.endpoint,
322
335
  set: {
323
336
  userId: c.get("user").id,
337
+ sessionId,
324
338
  p256dh: input.keys.p256dh,
325
339
  auth: input.keys.auth,
326
340
  updatedAt: now,
@@ -347,14 +361,45 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
347
361
  }
348
362
  );
349
363
 
350
- /** A person's sessions were all revoked: no device of theirs gets notifications. */
351
- export async function deleteUserPushSubscriptions(
364
+ /**
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
367
+ * session (registered before they were recorded) stay until the device
368
+ * registers again or every session goes; so do those of expired sessions,
369
+ * whose device moves them when it signs in again.
370
+ */
371
+ export function deleteEndedSessionPushSubscriptions(
352
372
  db: Database,
353
373
  userId: string
354
374
  ) {
355
- await db
356
- .delete(pushSubscriptions)
357
- .where(eq(pushSubscriptions.userId, userId));
375
+ return [
376
+ db
377
+ .delete(pushSubscriptions)
378
+ .where(
379
+ and(
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
+ )
389
+ )
390
+ ),
391
+ ] satisfies BatchStatement[];
392
+ }
393
+
394
+ /** A person's sessions were all revoked: no device of theirs gets notifications. */
395
+ export function deleteUserPushSubscriptions(db: Database, userId: string) {
396
+ return [
397
+ db.delete(pushSubscriptions).where(eq(pushSubscriptions.userId, userId)),
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[];
358
403
  }
359
404
 
360
405
  function subscriptionsForMailbox(env: Env, mailboxId: string) {
@@ -409,30 +454,18 @@ async function dispatchPushJob(
409
454
 
410
455
  if (!mailbox || !subscriptions.length) return;
411
456
 
412
- const requests: MessageSendRequest<MailboxPushJob>[] = subscriptions.map(
413
- (subscription) => ({
414
- body: {
415
- ...job,
416
- type: "deliver",
417
- targetSubscriptionId: subscription.id,
418
- mailboxDisplayName: mailbox.displayName,
419
- },
420
- })
421
- );
422
-
423
- const batches: MessageSendRequest<MailboxPushJob>[][] = [];
424
-
425
- for (
426
- let index = 0;
427
- index < requests.length;
428
- index += MAX_QUEUE_SEND_BATCH_SIZE
429
- ) {
430
- batches.push(requests.slice(index, index + MAX_QUEUE_SEND_BATCH_SIZE));
431
- }
432
-
433
- // Each subscription's delivery is its own job, so the batches are independent.
434
- await Promise.all(
435
- 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
+ )
436
469
  );
437
470
  }
438
471
 
@@ -498,12 +531,19 @@ async function deliverPushJob(
498
531
 
499
532
  if (!subscription) return;
500
533
 
501
- const suppressed = await mailboxStub(env, job.mailboxId).shouldSuppressPush(
534
+ // Registered before endpoints had to be public HTTPS URLs.
535
+ if (!isPublicPushEndpoint(subscription.endpoint)) {
536
+ await removeSubscription(env, subscription.id);
537
+
538
+ return;
539
+ }
540
+
541
+ const destination = await mailboxStub(env, job.mailboxId).pushDestination(
502
542
  job.messageId,
503
543
  subscription.userId
504
544
  );
505
545
 
506
- if (suppressed) return;
546
+ if (!destination) return;
507
547
 
508
548
  try {
509
549
  const delivered = await sendPushNotification(
@@ -514,7 +554,11 @@ async function deliverPushJob(
514
554
  {
515
555
  title: `New email in ${job.mailboxDisplayName}`,
516
556
  body: `${job.sender} · ${job.subject || "(no subject)"}`,
517
- url: mailPath(job.mailboxId, "inbox", job.conversationId),
557
+ url: mailPath(
558
+ job.mailboxId,
559
+ destination.folder,
560
+ destination.conversationId
561
+ ),
518
562
  tag: `message-${job.messageId}`,
519
563
  },
520
564
  configuration,
@@ -3,50 +3,119 @@ export type ParsedReplyText = {
3
3
  quotedText: string | null;
4
4
  };
5
5
 
6
- const ATTRIBUTION_LINE = [
7
- /^on .+wrote:\s*$/iu,
8
- /^am .+schrieb .+:\s*$/iu,
9
- /^le .+a écrit\s*:\s*$/iu,
10
- /^в .+написал(?:а)?:\s*$/iu,
6
+ /**
7
+ * Attribution lines are short; longer lines are never tested, which keeps a
8
+ * crafted single-line body from costing more than a scan.
9
+ */
10
+ const MAX_ATTRIBUTION_LENGTH = 300;
11
+
12
+ /** How many lines after an Outlook `From:` line may hold its other headers. */
13
+ const OUTLOOK_FOLLOWUP_LINES = 4;
14
+
15
+ const OUTLOOK_HEADER = /^from:\s+\S/iu;
16
+ const OUTLOOK_FOLLOWUP = /^(?:sent|date|to|subject):\s+\S/iu;
17
+ const QUOTED_LINE = /^\s*>/u;
18
+
19
+ /** Characters `.` does not match; an attribution line never contains one. */
20
+ const LINE_TERMINATOR = /[\r\u2028\u2029]/u;
21
+
22
+ /**
23
+ * Whether `line` is `<prefix><at least one character><suffix>`, the shape of
24
+ * `^prefix.+suffix$`, tested without a regular expression.
25
+ */
26
+ function wraps(line: string, prefix: string, suffix: string) {
27
+ return (
28
+ line.length > prefix.length + suffix.length &&
29
+ line.startsWith(prefix) &&
30
+ line.endsWith(suffix)
31
+ );
32
+ }
33
+
34
+ /** `Am <date> schrieb <name>:` (German). */
35
+ function isGermanAttribution(line: string) {
36
+ if (!wraps(line, "am ", ":")) return false;
37
+ const marker = line.indexOf("schrieb ", "am ".length + 1);
38
+
39
+ // At least one character between the marker and the closing colon.
40
+ return marker !== -1 && marker + "schrieb ".length < line.length - 1;
41
+ }
42
+
43
+ /** `Le <date>, <name> a écrit :` (French). */
44
+ function isFrenchAttribution(line: string) {
45
+ if (!wraps(line, "le ", ":")) return false;
46
+
47
+ return wraps(line.slice(0, -1).trimEnd(), "le ", "a écrit");
48
+ }
49
+
50
+ const SEPARATORS = [
11
51
  /^-----\s*original message\s*-----$/iu,
12
52
  /^-----\s*исходное сообщение\s*-----$/iu,
13
53
  ];
14
54
 
15
- const OUTLOOK_HEADER = /^from:\s+.+$/iu;
16
- const OUTLOOK_FOLLOWUP = /^(?:sent|date|to|subject):\s+.+$/iu;
55
+ /** Whether a trimmed line is a quote's attribution line in one of the known languages. */
56
+ function isAttributionLine(line: string) {
57
+ if (line.length > MAX_ATTRIBUTION_LENGTH || LINE_TERMINATOR.test(line)) {
58
+ return false;
59
+ }
60
+
61
+ const lower = line.toLowerCase();
62
+
63
+ return (
64
+ wraps(lower, "on ", "wrote:") ||
65
+ isGermanAttribution(lower) ||
66
+ isFrenchAttribution(lower) ||
67
+ wraps(lower, "в ", "написал:") ||
68
+ wraps(lower, "в ", "написала:") ||
69
+ SEPARATORS.some((pattern) => pattern.test(line))
70
+ );
71
+ }
17
72
 
18
- /** Whether `text` starts a quote: an attribution line, or an Outlook header block (with the lines after it). */
19
- function isAttribution(text: string, following: string[]) {
20
- const line = text.trim();
73
+ /** Whether line `index` starts a quote: an attribution line, or an Outlook header block (with the lines after it). */
74
+ function isAttribution(lines: string[], index: number) {
75
+ const line = (lines[index] ?? "").trim();
21
76
 
22
- if (ATTRIBUTION_LINE.some((pattern) => pattern.test(line))) return true;
77
+ if (isAttributionLine(line)) return true;
23
78
 
24
79
  if (!OUTLOOK_HEADER.test(line)) return false;
25
80
 
26
- return following
27
- .slice(0, 4)
81
+ return lines
82
+ .slice(index + 1, index + 1 + OUTLOOK_FOLLOWUP_LINES)
28
83
  .some((candidate) => OUTLOOK_FOLLOWUP.test(candidate.trim()));
29
84
  }
30
85
 
31
86
  function quotedBlockStart(lines: string[]) {
32
- for (const [index, text] of lines.entries()) {
33
- if (isAttribution(text, lines.slice(index + 1))) return index;
34
- }
87
+ let attribution = -1;
88
+ let firstQuoted = -1;
89
+ let answered = false;
90
+
91
+ for (const [index, line] of lines.entries()) {
92
+ if (QUOTED_LINE.test(line)) {
93
+ if (firstQuoted === -1) firstQuoted = index;
94
+ continue;
95
+ }
35
96
 
36
- for (const [index, text] of lines.entries()) {
37
- if (!/^\s*>/u.test(text)) continue;
38
- const remaining = lines.slice(index).filter((line) => line.trim());
39
- const quoted = remaining.filter((line) => /^\s*>/u.test(line)).length;
97
+ if (!line.trim()) continue;
40
98
 
41
- if (remaining.length && quoted / remaining.length >= 0.6) return index;
99
+ // An answer below or between quoted questions belongs in the visible body.
100
+ if (firstQuoted !== -1) return -1;
101
+
102
+ if (attribution !== -1) continue;
103
+
104
+ if (!isAttribution(lines, index)) {
105
+ answered = true;
106
+ continue;
107
+ }
108
+
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;
42
113
  }
43
114
 
44
- return -1;
115
+ return attribution === -1 ? firstQuoted : attribution;
45
116
  }
46
117
 
47
- export function parseReplyText(
48
- value: string | undefined | null
49
- ): ParsedReplyText {
118
+ export function parseReplyText(value: string | undefined | null) {
50
119
  const normalized = (value ?? "").replaceAll("\r\n", "\n").trim();
51
120
 
52
121
  if (!normalized) return { bodyText: "", quotedText: null };
@@ -59,3 +128,16 @@ export function parseReplyText(
59
128
 
60
129
  return { bodyText, quotedText: quotedText || null };
61
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
+ }
@@ -39,10 +39,16 @@ function r2Signer(env: Bindings, r2Key: string) {
39
39
  };
40
40
  }
41
41
 
42
+ /**
43
+ * A PUT URL for exactly `size` bytes of `contentType`: both headers are
44
+ * signed, so R2 refuses any other length (SignatureDoesNotMatch). Clients
45
+ * send Content-Length on their own; browsers don't let a page set it.
46
+ */
42
47
  export async function signR2PutUrl(input: {
43
48
  env: Bindings;
44
49
  r2Key: string;
45
50
  contentType: string;
51
+ size: number;
46
52
  }) {
47
53
  const signer = r2Signer(input.env, input.r2Key);
48
54
 
@@ -50,6 +56,7 @@ export async function signR2PutUrl(input: {
50
56
  method: "PUT",
51
57
  headers: {
52
58
  "content-type": input.contentType,
59
+ "content-length": String(input.size),
53
60
  },
54
61
  aws: {
55
62
  allHeaders: true,
@@ -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);