@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -1,134 +1,162 @@
1
+ import {
2
+ aiObjectRunner,
3
+ aiFeatureEnabled,
4
+ aiModel,
5
+ createId,
6
+ normalizeMailboxAddress,
7
+ deferWebhookTask,
8
+ queueWebhookEvent,
9
+ } from "@open-workspace/core/module";
10
+ import type { AiModel } from "@open-workspace/core/module";
11
+ import { required } from "@open-workspace/core/shared";
1
12
  import { DurableObject } from "cloudflare:workers";
2
- import { and, asc, desc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
3
- import { drizzle, type DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
4
- import { migrate } from "drizzle-orm/durable-sqlite/migrator";
5
- import migrations from "./migrations";
6
13
  import {
7
- bumpJmapState,
8
- emailPlacement as jmapEmailPlacement,
9
- jmapState,
10
- mailboxes as jmapMailboxRows,
11
- moveEmails as jmapMoveEmails,
12
- queryEmails as queryJmapEmails,
13
- threadEmails as jmapThreadEmails,
14
- } from "./jmap-store";
15
- import { officePreviewExtension, officePreviewKey } from "../../shared/office-preview";
14
+ and,
15
+ asc,
16
+ desc,
17
+ eq,
18
+ inArray,
19
+ isNull,
20
+ lt,
21
+ lte,
22
+ or,
23
+ sql,
24
+ } from "drizzle-orm";
25
+ import { drizzle } from "drizzle-orm/durable-sqlite";
26
+ import type { DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
27
+ import { migrate } from "drizzle-orm/durable-sqlite/migrator";
28
+ import { z } from "zod";
29
+
30
+ import migrations from "../../drizzle/mailbox/migrations.js";
16
31
  import {
17
- dispatchOfficePreviewJobs,
18
- hasPendingOfficePreviews,
19
- insertOfficePreviewJobs,
20
- nextOfficePreviewAttempt,
21
- prepareOfficePreviews,
22
- } from "./office-preview-jobs";
32
+ FOLDER_ORDER_STEP,
33
+ folderOrderPositions,
34
+ isCompleteFolderOrder,
35
+ sortFolders,
36
+ } from "../../shared/folder-order";
23
37
  import {
24
38
  MAX_CUSTOM_FOLDER_COUNT,
25
- MAILBOX_REALTIME_UPDATE,
26
- type MailboxPushJob,
27
- type MailboxRealtimeClientMessage,
39
+ mailboxRealtimeUpdate,
28
40
  } from "../../shared/mail";
41
+ import type {
42
+ MailboxPushJob,
43
+ MailboxRealtimeClientMessage,
44
+ } from "../../shared/mail";
45
+ import { blockPatternsFor } from "../../shared/mail-feedback";
46
+ import type {
47
+ FeedbackLabel,
48
+ SenderBlock,
49
+ Unsubscription,
50
+ } from "../../shared/mail-feedback";
51
+ import { headerValues } from "../../shared/mail-headers";
52
+ import { MAX_IMPORTED_TEXT_CHARACTERS } from "../../shared/mail-import";
53
+ import type { ImportPlacement } from "../../shared/mail-import";
54
+ import {
55
+ officePreviewExtension,
56
+ officePreviewKey,
57
+ } from "../../shared/office-preview";
58
+ import {
59
+ EMAIL_RECEIVED_EVENT,
60
+ EMAIL_WEBHOOK_SOURCE,
61
+ emailWebhookEventId,
62
+ } from "../../shared/webhooks";
29
63
  import {
30
64
  classifyInboundEmail,
31
65
  EmailAiClassificationError,
32
66
  MAILBOX_AI_MAX_ATTEMPTS,
33
67
  } from "../mail/ai-classification";
34
- import { aiObjectRunner } from "@open-workspace/core/worker/ai/generate.ts";
35
- import type { MailSafetyBindings } from "@open-workspace/core/worker/env.ts";
36
- import { aiFeatureEnabled, aiModel, type AiModel } from "@open-workspace/core/worker/ai/models.ts";
68
+ import { classificationSignals } from "../mail/classification-signals";
69
+ import type { ClassificationSignals } from "../mail/classification-signals";
70
+ import { deliveryFacts } from "../mail/delivery-facts";
37
71
  import {
38
72
  inboundMessageId,
39
73
  MissingRawMimeError,
40
74
  prepareInboundEmail,
41
75
  prepareUnprocessableInboundEmail,
76
+ rawHeaderText,
42
77
  rawMessageId,
43
78
  readInboundRawMime,
44
79
  UnprocessableInboundEmailError,
45
80
  } from "../mail/inbound";
46
- import { prepareOutboundDelivery } from "../mail/outbound-delivery";
47
- import {
48
- blockFromPattern,
49
- listBlockedSenders,
50
- recordCorrespondents,
51
- recordSenderFeedback,
52
- senderFeedbackSummary,
53
- senderHistory,
54
- senderStatuses,
55
- setSenderBlocked,
56
- setSenderTrusted,
57
- workspaceBlockFor,
58
- } from "./senders";
59
- import {
60
- deleteMailRule,
61
- emailRuleSubject,
62
- insertMailRule,
63
- listMailRules,
64
- reorderMailRules,
65
- updateMailRule,
66
- type MailRuleInput,
67
- } from "./rules";
68
- import { evaluateRules, ruleDestination, ruleMatches, type RuleOutcome } from "../../shared/mail-rules";
69
- import {
70
- blockPatternsFor,
71
- type FeedbackLabel,
72
- type ReportKind,
73
- type SenderBlock,
74
- type SenderStatus,
75
- type Unsubscription,
76
- } from "../../shared/mail-feedback";
77
- import { workspaceBlockPatterns, workspaceFeedbackSummary } from "../mail/workspace-safety";
78
- import { deliveryFacts } from "../mail/delivery-facts";
79
- import { createId } from "@open-workspace/core/worker/lib/ids.ts";
80
- import { classificationSignals, type ClassificationSignals } from "../mail/classification-signals";
81
- import { messageSecurity } from "../mail/message-security";
82
- import { collectSenderIntel } from "../mail/sender-intel";
83
- import {
84
- spamhausDqsKey,
85
- workspaceIdentity,
86
- type WorkspaceIdentity,
87
- } from "../mail/security-settings";
88
- import {
89
- suggestParticipants,
90
- type ParticipantSource,
91
- } from "../mail/participants";
92
81
  import { listActiveMailboxSessions } from "../mail/mailbox-directory";
82
+ import { messageSecurity } from "../mail/message-security";
83
+ import { emailListKey } from "../mail/message-view";
84
+ import { prepareOutboundDelivery } from "../mail/outbound-delivery";
85
+ import { suggestParticipants } from "../mail/participants";
86
+ import type { ParticipantSource } from "../mail/participants";
93
87
  import { buildEmailSearchQuery } from "../mail/search";
88
+ import { spamhausDqsKey, workspaceIdentity } from "../mail/security-settings";
89
+ import type { WorkspaceIdentity } from "../mail/security-settings";
90
+ import { collectSenderIntel } from "../mail/sender-intel";
94
91
  import {
95
- deferWebhookTask,
96
- emailWebhookEventId,
97
- queueWebhookEvent,
98
- } from "@open-workspace/core/worker/webhooks/service.ts";
92
+ workspaceBlockPatterns,
93
+ workspaceFeedbackSummary,
94
+ } from "../mail/workspace-safety";
95
+ import { indexInsertedEmail } from "./email-index";
99
96
  import {
100
97
  customFolderPredicate,
101
98
  folderAggregateJoinPredicate,
102
99
  systemFolderDefinitions,
103
100
  systemFolderPredicate,
104
- type MailboxState,
105
- type SystemFolderType,
106
101
  } from "./folder-model";
102
+ import type { MailboxState, SystemFolderType } from "./folder-model";
103
+ import { mergedPlacement, requestedPlacement } from "./import-placement";
104
+ import { readInboxCounts, writeInboxCounts } from "./inbox-counts";
105
+ import type { InboxCounts } from "./inbox-counts";
106
+ import {
107
+ bumpJmapState,
108
+ emailPlacement as jmapEmailPlacement,
109
+ jmapState,
110
+ mailboxes as jmapMailboxRows,
111
+ moveEmails as jmapMoveEmails,
112
+ queryEmails as queryJmapEmails,
113
+ threadEmails as jmapThreadEmails,
114
+ } from "./jmap-store";
115
+ import type {
116
+ EmailAiClassification,
117
+ EmailScreening,
118
+ MailboxAiConfiguration,
119
+ RecipientDeliveryStatus,
120
+ SenderIntel,
121
+ } from "./model";
122
+ import {
123
+ dispatchOfficePreviewJobs,
124
+ hasPendingOfficePreviews,
125
+ insertOfficePreviewJobs,
126
+ nextOfficePreviewAttempt,
127
+ prepareOfficePreviews,
128
+ } from "./office-preview-jobs";
107
129
  import {
108
130
  conversations,
109
131
  emailReadStates,
110
132
  emails,
111
133
  folders,
134
+ systemFolderOrder,
112
135
  mailboxAiConfiguration,
113
136
  pendingInbound,
114
137
  pendingObjectDeletions,
115
138
  senders,
116
139
  unsubscriptions,
117
- type Email,
118
- type FolderRecord,
119
- type NewEmail,
120
- type NewFolder,
121
- type PendingInbound,
122
140
  } from "./schema";
123
141
  import type {
124
- EmailAiClassification,
125
- EmailScreening,
126
- InboundAuthentication,
127
- ListUnsubscribe,
128
- MailboxAiConfiguration,
129
- RecipientDeliveryStatus,
130
- SenderIntel,
131
- } from "./model";
142
+ Email,
143
+ FolderRecord,
144
+ NewEmail,
145
+ NewFolder,
146
+ PendingInbound,
147
+ } from "./schema";
148
+ import {
149
+ blockFromPattern,
150
+ listBlockedSenders,
151
+ recordCorrespondents,
152
+ recordSenderFeedback,
153
+ senderFeedbackSummary,
154
+ senderHistory,
155
+ senderStatuses,
156
+ setSenderBlocked,
157
+ setSenderTrusted,
158
+ workspaceBlockFor,
159
+ } from "./senders";
132
160
 
133
161
  const schema = {
134
162
  conversations,
@@ -141,52 +169,65 @@ const schema = {
141
169
  senders,
142
170
  unsubscriptions,
143
171
  };
172
+
144
173
  type MailboxDatabase = DrizzleSqliteDODatabase<typeof schema>;
174
+
175
+ /** The change counter whose inbox counts D1 has (see `syncInboxCounts`). */
176
+ const COUNTS_VERSION_KEY = "inboxCountsVersion";
145
177
  const INBOUND_ALARM_BATCH_SIZE = 1;
146
178
  const OBJECT_DELETION_ALARM_BATCH_SIZE = 100;
147
179
  const MAX_RETRY_DELAY_MS = 60 * 60 * 1000;
148
180
  const MAX_INBOUND_RETRY_AGE_MS = 24 * 60 * 60 * 1000;
149
- const ALARM_WAKE_DELAY_MS = 1_000;
181
+ const ALARM_WAKE_DELAY_MS = 1000;
150
182
  const PRESENCE_TTL_MS = 60_000;
151
183
  const AI_CONFIGURATION_ID = "default";
152
184
 
185
+ /** Set while imported mail has not been announced (counts, realtime, JMAP state). */
186
+ const IMPORT_PENDING_KEY = "import:pending";
187
+
188
+ /** How long imported mail may wait to be announced when the importer does not finish. */
189
+ const IMPORT_ANNOUNCE_DELAY_MS = 15_000;
190
+
153
191
  /** Browser sessions, authorized against their session on every update. */
154
192
  const SESSION_SOCKET_TAG = "session";
193
+
155
194
  /** JMAP EventSource streams held by the Worker; they receive the new state. */
156
195
  const JMAP_SOCKET_TAG = "jmap";
157
196
 
158
- type MailboxSocketAttachment = {
159
- userId: string;
160
- sessionId: string;
161
- sessionTokenHash: string;
162
- visibility: "visible" | "hidden";
163
- presenceUpdatedAt: number;
164
- };
197
+ /** What a browser session sends: whether its tab is visible. */
198
+ const visibilitySchema = z.enum([
199
+ "visible",
200
+ "hidden",
201
+ ]) satisfies z.ZodType<MailboxRealtimeClientMessage>;
202
+
203
+ /** Who a session socket belongs to; it survives hibernation with the socket. */
204
+ const socketAttachmentSchema = z.object({
205
+ userId: z.string(),
206
+ sessionId: z.string(),
207
+ sessionTokenHash: z.string(),
208
+ visibility: visibilitySchema,
209
+ presenceUpdatedAt: z.number(),
210
+ });
165
211
 
212
+ type MailboxSocketAttachment = z.output<typeof socketAttachmentSchema>;
213
+
214
+ /** A session socket's attachment; null for other sockets (JMAP streams carry none). */
166
215
  function socketAttachment(socket: WebSocket): MailboxSocketAttachment | null {
167
- const value = socket.deserializeAttachment();
168
- if (!value || typeof value !== "object") return null;
169
- const attachment = value as Partial<MailboxSocketAttachment>;
170
- if (
171
- typeof attachment.userId !== "string"
172
- || typeof attachment.sessionId !== "string"
173
- || typeof attachment.sessionTokenHash !== "string"
174
- || !["visible", "hidden"].includes(attachment.visibility ?? "")
175
- || typeof attachment.presenceUpdatedAt !== "number"
176
- ) {
177
- return null;
178
- }
179
- return attachment as MailboxSocketAttachment;
216
+ const attachment = socketAttachmentSchema.safeParse(
217
+ socket.deserializeAttachment()
218
+ );
219
+
220
+ return attachment.success ? attachment.data : null;
180
221
  }
181
222
 
182
- function errorMessage(error: unknown) {
183
- return error instanceof Error ? error.message : String(error);
223
+ function errorMessage(cause: unknown) {
224
+ return cause instanceof Error ? cause.message : String(cause);
184
225
  }
185
226
 
186
227
  function retryDelay(attempts: number) {
187
228
  return Math.min(
188
229
  MAX_RETRY_DELAY_MS,
189
- 5_000 * 2 ** Math.min(Math.max(attempts - 1, 0), 10),
230
+ 5000 * 2 ** Math.min(Math.max(attempts - 1, 0), 10)
190
231
  );
191
232
  }
192
233
 
@@ -227,6 +268,51 @@ export type InboundDeliveryInput = {
227
268
  receivedAt: number;
228
269
  };
229
270
 
271
+ export type ImportMessageInput = {
272
+ /** The import's delivery id: the message is stored as `inboundMessageId(importId)`. */
273
+ importId: string;
274
+ /** Where the route stored the raw message. */
275
+ rawObjectKey: string;
276
+ /** The mailbox's own address, which tells sent mail from received. */
277
+ mailboxAddress: string;
278
+ /** When the message was received; the Date header (then now) without one. */
279
+ receivedAt: number | null;
280
+ placement: ImportPlacement;
281
+ /** A custom folder (by name, created when missing) for a message in the Inbox. */
282
+ folderName: string | null;
283
+ /** The people a received message is read for. */
284
+ seenBy: string[];
285
+ /** The conversation the importer's thread key names; null threads by Message-ID headers. */
286
+ conversationId: string | null;
287
+ /** Null decides by the From address. */
288
+ direction: "incoming" | "outgoing" | null;
289
+ };
290
+
291
+ export type ImportMessageResult =
292
+ | {
293
+ status: "imported";
294
+ id: string;
295
+ conversationId: string;
296
+ /** Why the requested folder was not used, if it was not. */
297
+ folderSkipped: "limit" | "invalid" | null;
298
+ }
299
+ | { status: "duplicate"; id: string; conversationId: string }
300
+ | { status: "unprocessable"; reason: string };
301
+
302
+ function clampText(value: string | null | undefined) {
303
+ return value && value.length > MAX_IMPORTED_TEXT_CHARACTERS
304
+ ? value.slice(0, MAX_IMPORTED_TEXT_CHARACTERS)
305
+ : (value ?? null);
306
+ }
307
+
308
+ /** The Date header of a raw message, in ms, if it parses. */
309
+ function headerDate(rawMime: ArrayBuffer) {
310
+ const value = headerValues(rawHeaderText(rawMime), "date")[0];
311
+ const time = value ? Date.parse(value) : Number.NaN;
312
+
313
+ return Number.isFinite(time) ? time : null;
314
+ }
315
+
230
316
  export type FolderListItem = {
231
317
  id: string;
232
318
  name: string;
@@ -290,16 +376,16 @@ function folderMembership(folder: MailFolder) {
290
376
  bindings: [folder.id],
291
377
  };
292
378
  }
379
+
293
380
  return {
294
381
  predicate: systemFolderPredicate(folder.systemType, "c"),
295
382
  bindings: [],
296
383
  };
297
384
  }
298
385
 
299
- const SYSTEM_FOLDER_DEFINITIONS_JSON = JSON.stringify(systemFolderDefinitions);
300
386
  const FOLDER_AGGREGATE_JOIN_PREDICATE = folderAggregateJoinPredicate(
301
387
  "folder",
302
- "conversation",
388
+ "conversation"
303
389
  );
304
390
 
305
391
  export type TransportUpdate = {
@@ -310,26 +396,26 @@ export type TransportUpdate = {
310
396
 
311
397
  /** Where an incoming message lands, decided before it is stored. */
312
398
  type InboundPlacement = {
313
- state: "spam" | "archive" | null;
399
+ state: "spam" | null;
314
400
  folderId: string | null;
315
- /** Rule folders apply even when the conversation already has one; AI folders do not. */
316
- overrideFolder: boolean;
317
- markReadUserIds: string[];
318
401
  };
319
402
 
320
403
  type InboundScreening = {
321
404
  block: SenderBlock | null;
322
405
  trusted: boolean;
323
- rules: RuleOutcome;
324
- markReadUserIds: string[];
325
406
  };
326
407
 
327
- const LIKE_ESCAPE = (value: string) => value.replace(/[\\%_]/gu, (char) => `\\${char}`);
408
+ const LIKE_ESCAPE = (value: string) =>
409
+ value.replaceAll(/[\\%_]/gu, (char) => `\\${char}`);
328
410
 
329
411
  /** SQL predicate on a lowercased address expression for a block pattern. */
330
412
  function blockPatternPredicate(expression: string, pattern: string) {
331
- if (!pattern.startsWith("@")) return { sql: `${expression} = ?`, bindings: [pattern] };
413
+ if (!pattern.startsWith("@")) {
414
+ return { sql: `${expression} = ?`, bindings: [pattern] };
415
+ }
416
+
332
417
  const domain = LIKE_ESCAPE(pattern.slice(1));
418
+
333
419
  return {
334
420
  sql: `(${expression} like ? escape '\\' or ${expression} like ? escape '\\')`,
335
421
  bindings: [`%@${domain}`, `%.${domain}`],
@@ -341,6 +427,13 @@ export class MailboxDO extends DurableObject<Env> {
341
427
  private readonly state: DurableObjectState;
342
428
  private readonly bindings: Env;
343
429
  private recentParticipantSources: ParticipantSource[] | null = null;
430
+ /** The running D1 write of the inbox counts; see `syncInboxCounts`. */
431
+ private countsWrite: Promise<void> | null = null;
432
+ private countsDirty = false;
433
+ /** What the last successful write stored, so the next writes only what changed. */
434
+ private writtenCounts: InboxCounts | null = null;
435
+ /** The D1 bookmark after that write; realtime messages pass it on. */
436
+ private countsBookmark: string | null = null;
344
437
 
345
438
  constructor(ctx: DurableObjectState, env: Env) {
346
439
  super(ctx, env);
@@ -349,6 +442,12 @@ export class MailboxDO extends DurableObject<Env> {
349
442
  this.db = drizzle(ctx.storage, { schema });
350
443
  ctx.blockConcurrencyWhile(async () => {
351
444
  await migrate(this.db, migrations);
445
+
446
+ // D1 lacks this mailbox's latest counts: a write failed, or had not
447
+ // finished, before the object stopped.
448
+ if (ctx.storage.kv.get<number>(COUNTS_VERSION_KEY) !== this.version()) {
449
+ void this.syncInboxCounts();
450
+ }
352
451
  });
353
452
  }
354
453
 
@@ -356,19 +455,30 @@ export class MailboxDO extends DurableObject<Env> {
356
455
  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
357
456
  return new Response("WebSocket upgrade required", { status: 426 });
358
457
  }
458
+
359
459
  // JMAP EventSource streams; the Worker holding one checks its token.
360
460
  if (request.headers.get("x-openworkspace-jmap") === "1") {
361
461
  const pair = new WebSocketPair();
362
462
  this.state.acceptWebSocket(pair[1], [JMAP_SOCKET_TAG]);
463
+
363
464
  return new Response(null, { status: 101, webSocket: pair[0] });
364
465
  }
466
+
365
467
  const userId = request.headers.get("x-openworkspace-user-id");
366
468
  const sessionId = request.headers.get("x-openworkspace-session-id");
367
- const sessionTokenHash = request.headers.get("x-openworkspace-session-token-hash");
469
+
470
+ const sessionTokenHash = request.headers.get(
471
+ "x-openworkspace-session-token-hash"
472
+ );
473
+
368
474
  if (!userId || !sessionId || !sessionTokenHash) {
369
475
  return new Response("Authentication required", { status: 401 });
370
476
  }
371
- const requestedVisibility = request.headers.get("x-openworkspace-visibility");
477
+
478
+ const requestedVisibility = request.headers.get(
479
+ "x-openworkspace-visibility"
480
+ );
481
+
372
482
  const visibility = requestedVisibility === "hidden" ? "hidden" : "visible";
373
483
  const pair = new WebSocketPair();
374
484
  const client = pair[0];
@@ -381,14 +491,20 @@ export class MailboxDO extends DurableObject<Env> {
381
491
  presenceUpdatedAt: Date.now(),
382
492
  } satisfies MailboxSocketAttachment);
383
493
  this.state.acceptWebSocket(server, [SESSION_SOCKET_TAG]);
494
+ // The client compares this with the versions of the data it already
495
+ // has, and refetches only what is older.
496
+ server.send(mailboxRealtimeUpdate(this.version(), this.countsBookmark));
497
+
384
498
  return new Response(null, { status: 101, webSocket: client });
385
499
  }
386
500
 
387
501
  webSocketMessage(socket: WebSocket, message: string | ArrayBuffer) {
388
- if (typeof message !== "string") return;
389
- if (message !== "visible" && message !== "hidden") return;
390
- const visibility: MailboxRealtimeClientMessage = message;
502
+ const parsed = visibilitySchema.safeParse(message);
503
+
504
+ if (!parsed.success) return;
505
+ const visibility = parsed.data;
391
506
  const attachment = socketAttachment(socket);
507
+
392
508
  if (!attachment) return;
393
509
  socket.serializeAttachment({
394
510
  ...attachment,
@@ -409,7 +525,9 @@ export class MailboxDO extends DurableObject<Env> {
409
525
  for (const socket of this.state.getWebSockets()) {
410
526
  socket.close(1001, "Mailbox deleted");
411
527
  }
528
+
412
529
  this.recentParticipantSources = null;
530
+ this.writtenCounts = null;
413
531
  await this.state.storage.deleteAll();
414
532
  }
415
533
 
@@ -424,13 +542,15 @@ export class MailboxDO extends DurableObject<Env> {
424
542
  emailReadStates,
425
543
  and(
426
544
  eq(emailReadStates.emailId, emails.id),
427
- eq(emailReadStates.userId, userId),
428
- ),
545
+ eq(emailReadStates.userId, userId)
546
+ )
429
547
  )
430
548
  .where(eq(emails.id, messageId))
431
549
  .get();
550
+
432
551
  if (!messageState || messageState.readByUserId) return true;
433
552
  const visibleAfter = Date.now() - PRESENCE_TTL_MS;
553
+
434
554
  return (await this.authorizedSockets({ userId, visibleAfter })).length > 0;
435
555
  }
436
556
 
@@ -438,58 +558,80 @@ export class MailboxDO extends DurableObject<Env> {
438
558
  userId: string;
439
559
  visibleAfter: number;
440
560
  }) {
441
- const sockets = this.state.getWebSockets(SESSION_SOCKET_TAG).flatMap((socket) => {
442
- const attachment = socketAttachment(socket);
443
- if (attachment) {
444
- if (
445
- filter
446
- && (
447
- attachment.userId !== filter.userId
448
- || attachment.visibility !== "visible"
449
- || attachment.presenceUpdatedAt < filter.visibleAfter
450
- )
451
- ) {
452
- return [];
561
+ const sockets = this.state
562
+ .getWebSockets(SESSION_SOCKET_TAG)
563
+ .flatMap((socket) => {
564
+ const attachment = socketAttachment(socket);
565
+
566
+ if (attachment) {
567
+ if (
568
+ filter &&
569
+ (attachment.userId !== filter.userId ||
570
+ attachment.visibility !== "visible" ||
571
+ attachment.presenceUpdatedAt < filter.visibleAfter)
572
+ ) {
573
+ return [];
574
+ }
575
+
576
+ return [{ socket, attachment }];
453
577
  }
454
- return [{ socket, attachment }];
455
- }
456
- socket.close(1008, "Realtime authorization expired");
457
- return [];
458
- });
578
+
579
+ socket.close(1008, "Realtime authorization expired");
580
+
581
+ return [];
582
+ });
583
+
459
584
  if (!sockets.length) return sockets;
460
585
 
461
586
  const mailboxId = this.state.id.name;
587
+
462
588
  if (!mailboxId) {
463
- for (const { socket } of sockets) socket.close(1008, "Mailbox identity is unavailable");
589
+ for (const { socket } of sockets) {
590
+ socket.close(1008, "Mailbox identity is unavailable");
591
+ }
592
+
464
593
  return [];
465
594
  }
466
- const sessionIds = [...new Set(
467
- sockets.map(({ attachment }) => attachment.sessionId),
468
- )];
595
+
596
+ const sessionIds = [
597
+ ...new Set(sockets.map(({ attachment }) => attachment.sessionId)),
598
+ ];
599
+
469
600
  const validSessions = await listActiveMailboxSessions(
470
601
  this.bindings.DB,
471
602
  mailboxId,
472
603
  sessionIds,
473
- Date.now(),
604
+ Date.now()
474
605
  );
606
+
475
607
  const validSessionsById = new Map(
476
- validSessions.map((session) => [session.id, session]),
608
+ validSessions.map((session) => [session.id, session])
477
609
  );
610
+
478
611
  return sockets.flatMap(({ socket, attachment }) => {
479
612
  const session = validSessionsById.get(attachment.sessionId);
613
+
480
614
  if (
481
- session?.userId === attachment.userId
482
- && session.tokenHash === attachment.sessionTokenHash
615
+ session?.userId === attachment.userId &&
616
+ session.tokenHash === attachment.sessionTokenHash
483
617
  ) {
484
618
  return [{ socket, attachment }];
485
619
  }
620
+
486
621
  socket.close(1008, "Realtime authorization expired");
622
+
487
623
  return [];
488
624
  });
489
625
  }
490
626
 
491
- private async broadcastUpdate() {
627
+ /**
628
+ * Announces the current version to the mailbox's sockets once
629
+ * `countsWritten` (the inbox counts write the change started, in parallel
630
+ * with authorizing the sockets) settled, with that write's bookmark.
631
+ */
632
+ private async broadcastUpdate(countsWritten: Promise<void>) {
492
633
  let sockets: Awaited<ReturnType<MailboxDO["authorizedSockets"]>>;
634
+
493
635
  try {
494
636
  sockets = await this.authorizedSockets();
495
637
  } catch {
@@ -499,33 +641,103 @@ export class MailboxDO extends DurableObject<Env> {
499
641
  // Closing forces clients to reconnect and refresh instead of silently
500
642
  // losing the only invalidation now that there is no polling fallback.
501
643
  for (const socket of this.state.getWebSockets(SESSION_SOCKET_TAG)) {
502
- socket.close(1011, "Realtime authorization is temporarily unavailable");
644
+ socket.close(
645
+ 1011,
646
+ "Realtime authorization is temporarily unavailable"
647
+ );
503
648
  }
649
+
504
650
  throw error;
505
651
  }
506
652
  }
653
+
654
+ if (!sockets.length) return;
655
+ await countsWritten;
656
+
507
657
  for (const { socket } of sockets) {
508
658
  try {
509
- socket.send(MAILBOX_REALTIME_UPDATE);
659
+ socket.send(mailboxRealtimeUpdate(this.version(), this.countsBookmark));
510
660
  } catch {
511
661
  socket.close(1011, "Could not deliver realtime event");
512
662
  }
513
663
  }
514
664
  }
515
665
 
666
+ /**
667
+ * The change counter that realtime updates carry (`update:<version>`).
668
+ * Reads return it so clients can tell whether their data already has a
669
+ * change they are told about.
670
+ */
671
+ private version() {
672
+ return Number(jmapState(this.state.storage));
673
+ }
674
+
675
+ /**
676
+ * Copies the inbox counts to D1 (`mailbox_counts`), where mailbox lists
677
+ * read them without waking this object. Writes run one at a time in the
678
+ * background; changes made during one are written by the next, so D1 ends
679
+ * at the latest counts. Settles once D1 has them (failures are logged and
680
+ * retried by the next change or start).
681
+ */
682
+ private syncInboxCounts(): Promise<void> {
683
+ this.countsDirty = true;
684
+
685
+ if (!this.countsWrite) {
686
+ // Started after the assignment, so its `finally` clears this one.
687
+ this.countsWrite = Promise.resolve().then(() => this.writeInboxCounts());
688
+ this.state.waitUntil(this.countsWrite);
689
+ }
690
+
691
+ return this.countsWrite;
692
+ }
693
+
694
+ private async writeInboxCounts() {
695
+ const mailboxId = this.state.id.name;
696
+
697
+ try {
698
+ // countsDirty is set again by writes while the await below is pending.
699
+ // oxlint-disable-next-line no-unmodified-loop-condition
700
+ while (mailboxId && this.countsDirty) {
701
+ this.countsDirty = false;
702
+ const version = this.version();
703
+ const counts = readInboxCounts(this.state.storage.sql);
704
+ // oxlint-disable-next-line eslint/no-await-in-loop -- writes the counts again until no write raced this one; each write needs the previous counts
705
+ this.countsBookmark = await writeInboxCounts(this.bindings.DB, {
706
+ mailboxId,
707
+ version,
708
+ counts,
709
+ previous: this.writtenCounts,
710
+ });
711
+ this.writtenCounts = counts;
712
+ this.state.storage.kv.put(COUNTS_VERSION_KEY, version);
713
+ }
714
+ } catch (error) {
715
+ // The stored version stays behind, so the next start writes them again.
716
+ this.writtenCounts = null;
717
+ console.error("Could not write mailbox counts to D1", error);
718
+ } finally {
719
+ this.countsWrite = null;
720
+ }
721
+ }
722
+
516
723
  private publishUpdate() {
517
724
  bumpJmapState(this.state.storage);
518
- this.state.waitUntil(this.broadcastUpdate().catch((error) => {
519
- console.error("Could not authorize realtime delivery", error);
520
- }));
725
+ const countsWritten = this.syncInboxCounts();
726
+ this.state.waitUntil(
727
+ this.broadcastUpdate(countsWritten).catch((error) => {
728
+ console.error("Could not authorize realtime delivery", error);
729
+ })
730
+ );
521
731
  this.announceJmapState();
522
732
  }
523
733
 
524
- /** Tells JMAP EventSource streams and push subscribers the new state. */
525
- private announceJmapState() {
734
+ /** Tells JMAP EventSource streams and (unless `push` is false) push subscribers the new state. */
735
+ private announceJmapState(push = true) {
526
736
  const mailboxId = this.state.id.name;
737
+
527
738
  if (!mailboxId) return;
528
739
  const state = jmapState(this.state.storage);
740
+
529
741
  for (const socket of this.state.getWebSockets(JMAP_SOCKET_TAG)) {
530
742
  try {
531
743
  socket.send(state);
@@ -533,15 +745,27 @@ export class MailboxDO extends DurableObject<Env> {
533
745
  socket.close(1011, "Could not deliver realtime event");
534
746
  }
535
747
  }
536
- const job: MailboxPushJob = { type: "jmap-state", mailboxId, state, occurredAt: Date.now() };
537
- this.state.waitUntil(this.bindings.PUSH_NOTIFICATIONS.send(job).catch((error) => {
538
- console.error("Could not queue JMAP push", error);
539
- }));
748
+
749
+ if (!push) return;
750
+
751
+ const job: MailboxPushJob = {
752
+ type: "jmap-state",
753
+ mailboxId,
754
+ state,
755
+ occurredAt: Date.now(),
756
+ };
757
+
758
+ this.state.waitUntil(
759
+ this.bindings.PUSH_NOTIFICATIONS.send(job).catch((error) => {
760
+ console.error("Could not queue JMAP push", error);
761
+ })
762
+ );
540
763
  }
541
764
 
542
765
  private queueIncomingNotification(email: Email) {
543
766
  if (email.direction !== "incoming") return;
544
767
  const sender = email.fromJson[0];
768
+
545
769
  const job: MailboxPushJob = {
546
770
  type: "dispatch",
547
771
  mailboxId: this.state.id.name ?? "unknown-mailbox",
@@ -551,19 +775,25 @@ export class MailboxDO extends DurableObject<Env> {
551
775
  sender: sender?.name || sender?.address || "Unknown sender",
552
776
  subject: email.subject,
553
777
  };
778
+
554
779
  return this.bindings.PUSH_NOTIFICATIONS.send(job);
555
780
  }
556
781
 
557
782
  private retryStoredInboundNotification(
558
783
  job: PendingInbound,
559
784
  now: number,
560
- error: unknown,
785
+ cause: unknown
561
786
  ) {
562
787
  if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
563
788
  this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
564
- console.error(`Stopped retrying notification for inbound delivery ${job.id}`, error);
789
+ console.error(
790
+ `Stopped retrying notification for inbound delivery ${job.id}`,
791
+ cause
792
+ );
793
+
565
794
  return;
566
795
  }
796
+
567
797
  const attempts = job.attempts + 1;
568
798
  this.db
569
799
  .update(pendingInbound)
@@ -573,35 +803,51 @@ export class MailboxDO extends DurableObject<Env> {
573
803
  })
574
804
  .where(eq(pendingInbound.id, job.id))
575
805
  .run();
576
- console.error(`Could not queue notification for inbound delivery ${job.id}`, error);
806
+ console.error(
807
+ `Could not queue notification for inbound delivery ${job.id}`,
808
+ cause
809
+ );
577
810
  }
578
811
 
579
812
  private async finishStoredInbound(
580
813
  job: PendingInbound,
581
814
  email: Email,
582
815
  now: number,
583
- announce: boolean,
816
+ announce: boolean
584
817
  ) {
585
818
  try {
586
819
  const mailboxId = this.state.id.name ?? "unknown-mailbox";
587
820
  deferWebhookTask(
588
821
  (task) => this.state.waitUntil(task),
589
- () => queueWebhookEvent(this.bindings, {
590
- eventId: emailWebhookEventId("email.received", mailboxId, email.id),
591
- eventType: "email.received",
592
- occurredAt: email.timelineAt.getTime(),
593
- source: { kind: "email", mailboxId, messageId: email.id },
594
- }),
822
+ () =>
823
+ queueWebhookEvent(this.bindings, {
824
+ eventId: emailWebhookEventId(
825
+ EMAIL_RECEIVED_EVENT,
826
+ mailboxId,
827
+ email.id
828
+ ),
829
+ eventType: EMAIL_RECEIVED_EVENT,
830
+ occurredAt: email.timelineAt.getTime(),
831
+ source: {
832
+ kind: EMAIL_WEBHOOK_SOURCE,
833
+ mailboxId,
834
+ messageId: email.id,
835
+ },
836
+ })
595
837
  );
838
+
596
839
  if (announce) this.publishUpdate();
840
+
597
841
  const conversation = this.db
598
842
  .select({ mailboxState: conversations.mailboxState })
599
843
  .from(conversations)
600
844
  .where(eq(conversations.id, email.conversationId))
601
845
  .all()[0];
846
+
602
847
  if (conversation?.mailboxState !== "spam") {
603
848
  await this.queueIncomingNotification(email);
604
849
  }
850
+
605
851
  this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
606
852
  } catch (error) {
607
853
  this.retryStoredInboundNotification(job, now, error);
@@ -614,16 +860,21 @@ export class MailboxDO extends DurableObject<Env> {
614
860
  limit: number,
615
861
  cursor: ConversationCursorPosition | null,
616
862
  search: string | undefined,
617
- unreadOnly = false,
863
+ unreadOnly = false
618
864
  ) {
619
865
  const folder = this.getFolder(folderId);
866
+
620
867
  if (!folder) return null;
621
868
  const membership = folderMembership(folder);
622
869
  const searchQuery = search ? buildEmailSearchQuery(search) : undefined;
623
- if (search && !searchQuery) return { items: [], next: null };
870
+
871
+ if (search && !searchQuery) {
872
+ return { items: [], next: null, version: this.version() };
873
+ }
624
874
 
625
875
  const predicates = [membership.predicate];
626
- const bindings: Array<string | number> = [...membership.bindings];
876
+ const bindings: (string | number)[] = [...membership.bindings];
877
+
627
878
  if (unreadOnly) {
628
879
  predicates.push(`exists (
629
880
  select 1
@@ -639,6 +890,7 @@ export class MailboxDO extends DurableObject<Env> {
639
890
  )`);
640
891
  bindings.push(userId);
641
892
  }
893
+
642
894
  if (searchQuery) {
643
895
  // Folder membership belongs to the conversation, while a match can be in
644
896
  // any message in that conversation.
@@ -649,15 +901,19 @@ export class MailboxDO extends DurableObject<Env> {
649
901
  )`);
650
902
  bindings.push(searchQuery);
651
903
  }
904
+
652
905
  if (cursor) {
653
906
  predicates.push(
654
- "(c.timeline_at < ? or (c.timeline_at = ? and c.latest_email_id < ?))",
907
+ "(c.timeline_at < ? or (c.timeline_at = ? and c.latest_email_id < ?))"
655
908
  );
656
909
  bindings.push(cursor.timelineAt, cursor.timelineAt, cursor.emailId);
657
910
  }
911
+
658
912
  bindings.push(limit + 1);
659
913
 
660
- const rows = this.state.storage.sql.exec<ConversationRow>(`
914
+ const rows = this.state.storage.sql
915
+ .exec<ConversationRow>(
916
+ `
661
917
  select
662
918
  c.latest_email_id as email_id,
663
919
  c.timeline_at,
@@ -683,116 +939,174 @@ export class MailboxDO extends DurableObject<Env> {
683
939
  where ${predicates.join(" and ")}
684
940
  order by c.timeline_at desc, c.latest_email_id desc
685
941
  limit ?
686
- `, userId, ...bindings).toArray();
942
+ `,
943
+ userId,
944
+ ...bindings
945
+ )
946
+ .toArray();
687
947
 
688
948
  const pageRows = rows.slice(0, limit);
689
949
  const emailIds = pageRows.map((row) => row.email_id);
950
+
690
951
  const emailRows = emailIds.length
691
952
  ? this.db.select().from(emails).where(inArray(emails.id, emailIds)).all()
692
953
  : [];
954
+
693
955
  const emailsById = new Map(emailRows.map((email) => [email.id, email]));
956
+
694
957
  const items = pageRows.flatMap((row): ConversationListItem[] => {
695
958
  const email = emailsById.get(row.email_id);
959
+
696
960
  return email
697
- ? [{
698
- email,
699
- messageCount: Number(row.message_count),
700
- unreadCount: Number(row.unread_count),
701
- hasIncoming: Boolean(row.has_incoming),
702
- }]
961
+ ? [
962
+ {
963
+ email,
964
+ messageCount: Number(row.message_count),
965
+ unreadCount: Number(row.unread_count),
966
+ hasIncoming: Boolean(row.has_incoming),
967
+ },
968
+ ]
703
969
  : [];
704
970
  });
971
+
705
972
  const last = pageRows.at(-1);
973
+
706
974
  return {
707
975
  items,
708
- next: rows.length > limit && last
709
- ? { timelineAt: Number(last.timeline_at), emailId: last.email_id }
710
- : null,
976
+ next:
977
+ rows.length > limit && last
978
+ ? { timelineAt: Number(last.timeline_at), emailId: last.email_id }
979
+ : null,
980
+ version: this.version(),
711
981
  };
712
982
  }
713
983
 
984
+ /** The system folders at their places in the mailbox's folder order. */
985
+ private systemFolders() {
986
+ const stored = new Map(
987
+ this.db
988
+ .select()
989
+ .from(systemFolderOrder)
990
+ .all()
991
+ .map((row) => [row.folderId, row.sortOrder])
992
+ );
993
+
994
+ return systemFolderDefinitions.map((folder) => ({
995
+ ...folder,
996
+ sortOrder:
997
+ folder.id === "inbox" ? 0 : (stored.get(folder.id) ?? folder.sortOrder),
998
+ }));
999
+ }
1000
+
714
1001
  getFolder(id: string): MailFolder | null {
715
- const system = systemFolderDefinitions.find((folder) => folder.id === id);
1002
+ const system = this.systemFolders().find((folder) => folder.id === id);
1003
+
716
1004
  if (system) {
717
1005
  return {
718
1006
  ...system,
719
1007
  kind: "system",
720
1008
  };
721
1009
  }
1010
+
722
1011
  const custom = this.db
723
1012
  .select()
724
1013
  .from(folders)
725
1014
  .where(eq(folders.id, id))
726
1015
  .all()[0];
1016
+
727
1017
  return custom ? { ...custom, kind: "custom", systemType: null } : null;
728
1018
  }
729
1019
 
730
1020
  private folderNameTaken(name: string, excludingId?: string) {
731
1021
  const normalized = name.toLocaleLowerCase("en-US");
732
- return systemFolderDefinitions.some(
733
- (folder) => folder.name.toLocaleLowerCase("en-US") === normalized,
734
- ) || this.db
735
- .select({ id: folders.id, name: folders.name })
736
- .from(folders)
737
- .all()
738
- .some((folder) =>
739
- folder.id !== excludingId
740
- && folder.name.toLocaleLowerCase("en-US") === normalized
741
- );
1022
+
1023
+ return (
1024
+ systemFolderDefinitions.some(
1025
+ (folder) => folder.name.toLocaleLowerCase("en-US") === normalized
1026
+ ) ||
1027
+ this.db
1028
+ .select({ id: folders.id, name: folders.name })
1029
+ .from(folders)
1030
+ .all()
1031
+ .some(
1032
+ (folder) =>
1033
+ folder.id !== excludingId &&
1034
+ folder.name.toLocaleLowerCase("en-US") === normalized
1035
+ )
1036
+ );
742
1037
  }
743
1038
 
744
1039
  createFolder(id: string, name: string) {
1040
+ const result = this.insertFolder(id, name);
1041
+
1042
+ if (result.status === "ok") this.publishUpdate();
1043
+
1044
+ return result;
1045
+ }
1046
+
1047
+ private insertFolder(id: string, name: string) {
745
1048
  const normalizedName = name.trim();
1049
+
746
1050
  if (!normalizedName || normalizedName.length > 80) {
747
1051
  return { status: "invalid" as const };
748
1052
  }
1053
+
749
1054
  const existing = this.db
750
1055
  .select({ id: folders.id, sortOrder: folders.sortOrder })
751
1056
  .from(folders)
752
- .orderBy(asc(folders.sortOrder), asc(folders.name))
753
1057
  .all();
1058
+
754
1059
  if (existing.length >= MAX_CUSTOM_FOLDER_COUNT) {
755
1060
  return { status: "limit" as const };
756
1061
  }
1062
+
757
1063
  if (this.folderNameTaken(normalizedName)) {
758
1064
  return { status: "conflict" as const };
759
1065
  }
760
- const folder = this.db.transaction((tx) => {
761
- const inserted = tx
762
- .insert(folders)
763
- .values({ id, name: normalizedName, sortOrder: 100 + existing.length })
764
- .returning()
765
- .all()[0]!;
766
- [...existing.map((item) => item.id), id].forEach((folderId, index) => {
767
- tx.update(folders)
768
- .set({ sortOrder: 100 + index })
769
- .where(eq(folders.id, folderId))
770
- .run();
771
- });
772
- return inserted;
773
- });
774
- this.publishUpdate();
1066
+
1067
+ // A new folder goes to the end of the whole order, system folders included.
1068
+ const last = Math.max(
1069
+ ...existing.map((item) => item.sortOrder),
1070
+ ...this.systemFolders().map((item) => item.sortOrder)
1071
+ );
1072
+
1073
+ const folder = this.db
1074
+ .insert(folders)
1075
+ .values({ id, name: normalizedName, sortOrder: last + FOLDER_ORDER_STEP })
1076
+ .returning()
1077
+ .get();
1078
+
775
1079
  return { status: "ok" as const, folder };
776
1080
  }
777
1081
 
778
1082
  renameFolder(id: string, name: string) {
779
1083
  const normalizedName = name.trim();
1084
+
780
1085
  if (!normalizedName || normalizedName.length > 80) {
781
1086
  return { status: "invalid" as const };
782
1087
  }
783
- if (!this.getFolder(id) || systemFolderDefinitions.some((item) => item.id === id)) {
1088
+
1089
+ if (
1090
+ !this.getFolder(id) ||
1091
+ systemFolderDefinitions.some((item) => item.id === id)
1092
+ ) {
784
1093
  return { status: "not_found" as const };
785
1094
  }
1095
+
786
1096
  if (this.folderNameTaken(normalizedName, id)) {
787
1097
  return { status: "conflict" as const };
788
1098
  }
789
- const folder = this.db
1099
+
1100
+ const [folder] = this.db
790
1101
  .update(folders)
791
1102
  .set({ name: normalizedName })
792
1103
  .where(eq(folders.id, id))
793
1104
  .returning()
794
- .all()[0]!;
1105
+ .all();
1106
+
1107
+ if (!folder) return { status: "not_found" as const };
795
1108
  this.publishUpdate();
1109
+
796
1110
  return { status: "ok" as const, folder };
797
1111
  }
798
1112
 
@@ -802,38 +1116,46 @@ export class MailboxDO extends DurableObject<Env> {
802
1116
  .where(eq(folders.id, id))
803
1117
  .returning({ id: folders.id })
804
1118
  .all()[0];
1119
+
805
1120
  if (!deleted) return { status: "not_found" as const };
806
- // Rules that filed into this folder keep their other actions.
807
- this.state.storage.sql.exec(
808
- "update mail_rules set actions_json = json_remove(actions_json, '$.folderId') where json_extract(actions_json, '$.folderId') = ?",
809
- id,
810
- );
811
1121
  this.publishUpdate();
1122
+
812
1123
  return { status: "ok" as const };
813
1124
  }
814
1125
 
1126
+ /**
1127
+ * Sets the one order of every folder but Inbox: each system folder and
1128
+ * custom folder exactly once, so system folders can sit among custom ones.
1129
+ */
815
1130
  reorderFolders(folderIds: string[]) {
816
- const existingIds = this.db
1131
+ const customIds = this.db
817
1132
  .select({ id: folders.id })
818
1133
  .from(folders)
819
1134
  .all()
820
1135
  .map((folder) => folder.id);
821
- if (
822
- folderIds.length !== existingIds.length
823
- || new Set(folderIds).size !== folderIds.length
824
- || existingIds.some((id) => !folderIds.includes(id))
825
- ) {
1136
+
1137
+ if (!isCompleteFolderOrder(folderIds, customIds)) {
826
1138
  return { status: "conflict" as const };
827
1139
  }
1140
+
1141
+ const custom = new Set(customIds);
828
1142
  this.db.transaction((tx) => {
829
- folderIds.forEach((id, index) => {
830
- tx.update(folders)
831
- .set({ sortOrder: 100 + index })
832
- .where(eq(folders.id, id))
833
- .run();
834
- });
1143
+ for (const { id, sortOrder } of folderOrderPositions(folderIds)) {
1144
+ if (custom.has(id)) {
1145
+ tx.update(folders).set({ sortOrder }).where(eq(folders.id, id)).run();
1146
+ } else {
1147
+ tx.insert(systemFolderOrder)
1148
+ .values({ folderId: id, sortOrder })
1149
+ .onConflictDoUpdate({
1150
+ target: systemFolderOrder.folderId,
1151
+ set: { sortOrder },
1152
+ })
1153
+ .run();
1154
+ }
1155
+ }
835
1156
  });
836
1157
  this.publishUpdate();
1158
+
837
1159
  return { status: "ok" as const };
838
1160
  }
839
1161
 
@@ -843,6 +1165,7 @@ export class MailboxDO extends DurableObject<Env> {
843
1165
  .from(mailboxAiConfiguration)
844
1166
  .where(eq(mailboxAiConfiguration.id, AI_CONFIGURATION_ID))
845
1167
  .all()[0];
1168
+
846
1169
  return stored
847
1170
  ? {
848
1171
  instructions: stored.instructions,
@@ -854,21 +1177,22 @@ export class MailboxDO extends DurableObject<Env> {
854
1177
  };
855
1178
  }
856
1179
 
857
- async getMailboxAiSettings() {
1180
+ getMailboxAiSettings() {
858
1181
  return {
859
1182
  configuration: this.aiConfiguration(),
860
1183
  globalEnabled: aiFeatureEnabled("classification"),
861
1184
  };
862
1185
  }
863
1186
 
864
- async setMailboxAiConfiguration(configuration: MailboxAiConfiguration) {
1187
+ setMailboxAiConfiguration(configuration: MailboxAiConfiguration) {
865
1188
  if (
866
- configuration.confidenceThreshold < 50
867
- || configuration.confidenceThreshold > 100
868
- || configuration.instructions.length > 4_000
1189
+ configuration.confidenceThreshold < 50 ||
1190
+ configuration.confidenceThreshold > 100 ||
1191
+ configuration.instructions.length > 4000
869
1192
  ) {
870
1193
  throw new Error("Invalid mailbox AI configuration");
871
1194
  }
1195
+
872
1196
  this.db
873
1197
  .insert(mailboxAiConfiguration)
874
1198
  .values({
@@ -886,6 +1210,7 @@ export class MailboxDO extends DurableObject<Env> {
886
1210
  },
887
1211
  })
888
1212
  .run();
1213
+
889
1214
  return this.getMailboxAiSettings();
890
1215
  }
891
1216
 
@@ -894,47 +1219,66 @@ export class MailboxDO extends DurableObject<Env> {
894
1219
  }
895
1220
 
896
1221
  jmapMailboxes(userId: string) {
897
- return { state: jmapState(this.state.storage), mailboxes: jmapMailboxRows(this.state.storage.sql, userId) };
1222
+ return {
1223
+ state: jmapState(this.state.storage),
1224
+ mailboxes: jmapMailboxRows(this.state.storage.sql, userId),
1225
+ };
898
1226
  }
899
1227
 
900
1228
  jmapQueryEmails(input: Parameters<typeof queryJmapEmails>[1]) {
901
- return { state: jmapState(this.state.storage), ...queryJmapEmails(this.state.storage.sql, input) };
1229
+ return {
1230
+ state: jmapState(this.state.storage),
1231
+ ...queryJmapEmails(this.state.storage.sql, input),
1232
+ };
902
1233
  }
903
1234
 
904
1235
  /** Emails with their JMAP Mailbox and this user's $seen keyword; unknown ids are left out. */
905
1236
  jmapEmails(userId: string, ids: string[]) {
906
1237
  const placement = jmapEmailPlacement(this.state.storage.sql, userId, ids);
1238
+
907
1239
  return {
908
1240
  state: jmapState(this.state.storage),
909
1241
  emails: ids.flatMap((id) => {
910
1242
  const email = this.getEmail(id);
911
1243
  const place = placement.get(id);
1244
+
912
1245
  return email && place ? [{ email, ...place }] : [];
913
1246
  }),
914
1247
  };
915
1248
  }
916
1249
 
917
1250
  jmapThreads(ids: string[]) {
918
- return { state: jmapState(this.state.storage), threads: [...jmapThreadEmails(this.state.storage.sql, ids)] };
1251
+ return {
1252
+ state: jmapState(this.state.storage),
1253
+ threads: [...jmapThreadEmails(this.state.storage.sql, ids)].map(
1254
+ ([id, emailIds]) => ({ id, emailIds })
1255
+ ),
1256
+ };
919
1257
  }
920
1258
 
921
1259
  jmapMoveEmails(emailIds: string[], target: string) {
922
1260
  const moved = jmapMoveEmails(this.state.storage.sql, emailIds, target);
1261
+
923
1262
  if (moved) this.publishUpdate();
1263
+
924
1264
  return moved;
925
1265
  }
926
1266
 
927
1267
  getEmail(id: string) {
928
- return this.db.select().from(emails).where(eq(emails.id, id)).all()[0] ?? null;
1268
+ return (
1269
+ this.db.select().from(emails).where(eq(emails.id, id)).all()[0] ?? null
1270
+ );
929
1271
  }
930
1272
 
931
1273
  getEmailByMessageId(messageIdHeader: string) {
932
- return this.db
933
- .select()
934
- .from(emails)
935
- .where(eq(emails.messageIdHeader, messageIdHeader))
936
- .orderBy(desc(emails.timelineAt))
937
- .all()[0] ?? null;
1274
+ return (
1275
+ this.db
1276
+ .select()
1277
+ .from(emails)
1278
+ .where(eq(emails.messageIdHeader, messageIdHeader))
1279
+ .orderBy(desc(emails.timelineAt))
1280
+ .all()[0] ?? null
1281
+ );
938
1282
  }
939
1283
 
940
1284
  getConversation(conversationId: string) {
@@ -955,7 +1299,9 @@ export class MailboxDO extends DurableObject<Env> {
955
1299
  .from(conversations)
956
1300
  .where(eq(conversations.id, conversationId))
957
1301
  .all()[0];
1302
+
958
1303
  if (!conversation) return null;
1304
+
959
1305
  return {
960
1306
  mailboxState: conversation.mailboxState,
961
1307
  folderId: conversation.folderId,
@@ -978,33 +1324,38 @@ export class MailboxDO extends DurableObject<Env> {
978
1324
  conversationId: string,
979
1325
  userId: string,
980
1326
  limit: number,
981
- cursor: ConversationCursorPosition | null,
1327
+ cursor: ConversationCursorPosition | null
982
1328
  ) {
983
1329
  const conversation = this.db
984
1330
  .select({
985
1331
  mailboxState: conversations.mailboxState,
986
1332
  folderId: conversations.folderId,
987
1333
  hasIncoming: conversations.hasIncoming,
1334
+ hasOutgoing: conversations.hasOutgoing,
988
1335
  })
989
1336
  .from(conversations)
990
1337
  .where(eq(conversations.id, conversationId))
991
1338
  .all()[0];
1339
+
992
1340
  if (!conversation) return null;
993
1341
 
994
1342
  const pageLimit = Math.max(1, Math.min(limit, 25));
995
1343
  const cursorDate = cursor ? new Date(cursor.timelineAt) : null;
996
- const predicate = cursor && cursorDate
997
- ? and(
998
- eq(emails.conversationId, conversationId),
999
- or(
1000
- lt(emails.timelineAt, cursorDate),
1001
- and(
1002
- eq(emails.timelineAt, cursorDate),
1003
- lt(emails.id, cursor.emailId),
1004
- ),
1005
- ),
1006
- )
1007
- : eq(emails.conversationId, conversationId);
1344
+
1345
+ const predicate =
1346
+ cursor && cursorDate
1347
+ ? and(
1348
+ eq(emails.conversationId, conversationId),
1349
+ or(
1350
+ lt(emails.timelineAt, cursorDate),
1351
+ and(
1352
+ eq(emails.timelineAt, cursorDate),
1353
+ lt(emails.id, cursor.emailId)
1354
+ )
1355
+ )
1356
+ )
1357
+ : eq(emails.conversationId, conversationId);
1358
+
1008
1359
  const descending = this.db
1009
1360
  .select()
1010
1361
  .from(emails)
@@ -1012,10 +1363,14 @@ export class MailboxDO extends DurableObject<Env> {
1012
1363
  .orderBy(desc(emails.timelineAt), desc(emails.id))
1013
1364
  .limit(pageLimit + 1)
1014
1365
  .all();
1366
+
1015
1367
  const page = descending.slice(0, pageLimit);
1016
1368
  const oldest = page.at(-1);
1017
1369
  const messageIds = page.map((email) => email.id);
1018
- const counts = this.state.storage.sql.exec<ConversationSnapshotCountRow>(`
1370
+
1371
+ const counts = this.state.storage.sql
1372
+ .exec<ConversationSnapshotCountRow>(
1373
+ `
1019
1374
  select
1020
1375
  count(*) as message_count,
1021
1376
  coalesce(sum(
@@ -1031,57 +1386,152 @@ export class MailboxDO extends DurableObject<Env> {
1031
1386
  ), 0) as unread_count
1032
1387
  from emails message
1033
1388
  where message.conversation_id = ?
1034
- `, userId, conversationId).one();
1389
+ `,
1390
+ userId,
1391
+ conversationId
1392
+ )
1393
+ .one();
1394
+
1035
1395
  return {
1036
1396
  mailboxState: conversation.mailboxState,
1037
1397
  folderId: conversation.folderId,
1038
1398
  hasIncoming: conversation.hasIncoming,
1399
+ hasOutgoing: conversation.hasOutgoing,
1039
1400
  messageCount: Number(counts.message_count),
1040
1401
  unreadCount: Number(counts.unread_count),
1041
1402
  messages: page.reverse(),
1042
- next: descending.length > pageLimit && oldest
1043
- ? { timelineAt: oldest.timelineAt.getTime(), emailId: oldest.id }
1044
- : null,
1403
+ next:
1404
+ descending.length > pageLimit && oldest
1405
+ ? { timelineAt: oldest.timelineAt.getTime(), emailId: oldest.id }
1406
+ : null,
1045
1407
  readStates: messageIds.length
1046
1408
  ? this.db
1047
- .select({
1048
- emailId: emailReadStates.emailId,
1049
- userId: emailReadStates.userId,
1050
- readAt: emailReadStates.readAt,
1051
- })
1052
- .from(emailReadStates)
1053
- .where(inArray(emailReadStates.emailId, messageIds))
1054
- .orderBy(asc(emailReadStates.readAt))
1055
- .all()
1409
+ .select({
1410
+ emailId: emailReadStates.emailId,
1411
+ userId: emailReadStates.userId,
1412
+ readAt: emailReadStates.readAt,
1413
+ })
1414
+ .from(emailReadStates)
1415
+ .where(inArray(emailReadStates.emailId, messageIds))
1416
+ .orderBy(asc(emailReadStates.readAt))
1417
+ .all()
1056
1418
  : [],
1057
1419
  };
1058
1420
  }
1059
1421
 
1422
+ /**
1423
+ * Everything the reader needs from this mailbox in one call: a page of the
1424
+ * conversation with read states, plus sender history and block, trust and
1425
+ * unsubscribe state for its incoming senders.
1426
+ */
1427
+ getConversationView(
1428
+ conversationId: string,
1429
+ userId: string,
1430
+ limit: number,
1431
+ cursor: ConversationCursorPosition | null
1432
+ ) {
1433
+ const snapshot = this.getConversationPageSnapshot(
1434
+ conversationId,
1435
+ userId,
1436
+ limit,
1437
+ cursor
1438
+ );
1439
+
1440
+ if (!snapshot) return null;
1441
+
1442
+ const incoming = snapshot.messages.filter(
1443
+ (message) => message.direction === "incoming"
1444
+ );
1445
+
1446
+ const senderAddresses = incoming.flatMap((message) =>
1447
+ message.fromJson[0] ? [message.fromJson[0].address] : []
1448
+ );
1449
+
1450
+ return {
1451
+ ...snapshot,
1452
+ history: this.getSenderHistory(senderAddresses),
1453
+ safety: this.getMessageSafetyContext(
1454
+ senderAddresses,
1455
+ incoming.flatMap((message) => emailListKey(message) ?? [])
1456
+ ),
1457
+ version: this.version(),
1458
+ };
1459
+ }
1460
+
1461
+ /** One message with its sender's history and safety state, for re-deriving its security summary. */
1462
+ getMessageSenderView(emailId: string) {
1463
+ const email = this.getEmail(emailId);
1464
+
1465
+ if (!email) return null;
1466
+
1467
+ const sender =
1468
+ email.direction === "incoming" ? email.fromJson[0]?.address : undefined;
1469
+
1470
+ const senderAddresses = sender ? [sender] : [];
1471
+ const listKey = emailListKey(email);
1472
+
1473
+ return {
1474
+ email,
1475
+ history: this.getSenderHistory(senderAddresses),
1476
+ safety: this.getMessageSafetyContext(
1477
+ senderAddresses,
1478
+ listKey ? [listKey] : []
1479
+ ),
1480
+ };
1481
+ }
1482
+
1060
1483
  getAttachment(emailId: string, attachmentId: string) {
1061
1484
  const email = this.getEmail(emailId);
1062
- return email?.attachmentsJson.find((file) => file.id === attachmentId) ?? null;
1485
+
1486
+ return (
1487
+ email?.attachmentsJson.find((file) => file.id === attachmentId) ?? null
1488
+ );
1063
1489
  }
1064
1490
 
1065
- async completeOfficePreview(emailId: string, attachmentId: string, sourceKey: string, status: "ready" | "failed") {
1491
+ async completeOfficePreview(
1492
+ emailId: string,
1493
+ attachmentId: string,
1494
+ sourceKey: string,
1495
+ status: "ready" | "failed"
1496
+ ) {
1066
1497
  const email = this.getEmail(emailId);
1067
- const file = email?.attachmentsJson.find((file) => file.id === attachmentId && file.r2Key === sourceKey);
1498
+
1499
+ const file = email?.attachmentsJson.find(
1500
+ (attachment) =>
1501
+ attachment.id === attachmentId && attachment.r2Key === sourceKey
1502
+ );
1503
+
1068
1504
  if (!email || !file) {
1069
1505
  // Conversion may finish after permanent deletion already removed its objects.
1070
1506
  // Persist cleanup before the queue acknowledges, so an R2 outage cannot orphan the PDF.
1071
1507
  const cleanupAt = new Date();
1072
1508
  await this.scheduleAlarm(cleanupAt.getTime() + ALARM_WAKE_DELAY_MS);
1073
- this.db.insert(pendingObjectDeletions).values({
1074
- objectKey: officePreviewKey(sourceKey), nextAttemptAt: cleanupAt,
1075
- }).onConflictDoNothing().run();
1509
+ this.db
1510
+ .insert(pendingObjectDeletions)
1511
+ .values({
1512
+ objectKey: officePreviewKey(sourceKey),
1513
+ nextAttemptAt: cleanupAt,
1514
+ })
1515
+ .onConflictDoNothing()
1516
+ .run();
1517
+
1076
1518
  return false;
1077
1519
  }
1520
+
1078
1521
  if (file.pdfPreviewStatus !== "pending") return true;
1079
- this.db.update(emails).set({
1080
- attachmentsJson: email.attachmentsJson.map((attachment) =>
1081
- attachment.id === attachmentId ? { ...attachment, pdfPreviewStatus: status } : attachment
1082
- ),
1083
- }).where(eq(emails.id, emailId)).run();
1522
+ this.db
1523
+ .update(emails)
1524
+ .set({
1525
+ attachmentsJson: email.attachmentsJson.map((attachment) =>
1526
+ attachment.id === attachmentId
1527
+ ? { ...attachment, pdfPreviewStatus: status }
1528
+ : attachment
1529
+ ),
1530
+ })
1531
+ .where(eq(emails.id, emailId))
1532
+ .run();
1084
1533
  this.publishUpdate();
1534
+
1085
1535
  return true;
1086
1536
  }
1087
1537
 
@@ -1097,21 +1547,30 @@ export class MailboxDO extends DurableObject<Env> {
1097
1547
  .orderBy(desc(emails.timelineAt), desc(emails.id))
1098
1548
  .limit(500)
1099
1549
  .all();
1100
- const flagged = this.state.storage.sql.exec<{ address: string }>(
1101
- "select address from senders where blocked_at is not null or reported_at is not null",
1102
- ).toArray().map((row) => row.address);
1550
+
1551
+ const flagged = this.state.storage.sql
1552
+ .exec<{ address: string }>(
1553
+ "select address from senders where blocked_at is not null or reported_at is not null"
1554
+ )
1555
+ .toArray()
1556
+ .map((row) => row.address);
1557
+
1103
1558
  const excluded = new Set(flagged);
1559
+
1104
1560
  return suggestParticipants(
1105
1561
  this.recentParticipantSources,
1106
1562
  ownAddress,
1107
1563
  query,
1108
1564
  limit,
1109
- (address) => blockPatternsFor(address).some((pattern) => excluded.has(pattern)),
1565
+ (address) =>
1566
+ blockPatternsFor(address).some((pattern) => excluded.has(pattern))
1110
1567
  );
1111
1568
  }
1112
1569
 
1113
1570
  listFolders(userId: string): FolderListItem[] {
1114
- const rows = this.state.storage.sql.exec<FolderListRow>(`
1571
+ const rows = this.state.storage.sql
1572
+ .exec<FolderListRow>(
1573
+ `
1115
1574
  with folder_rows(id, name, kind, system_type, sort_order) as (
1116
1575
  select
1117
1576
  json_extract(value, '$.id'),
@@ -1166,30 +1625,59 @@ export class MailboxDO extends DurableObject<Env> {
1166
1625
  folder.kind,
1167
1626
  folder.system_type,
1168
1627
  folder.sort_order
1169
- `, SYSTEM_FOLDER_DEFINITIONS_JSON, userId).toArray();
1170
-
1171
- return rows.map((row): FolderListItem => ({
1172
- id: row.id,
1173
- name: row.name,
1174
- kind: row.kind,
1175
- systemType: row.system_type,
1176
- sortOrder: Number(row.sort_order),
1177
- totalCount: Number(row.total_count),
1178
- unreadCount: Number(row.unread_count),
1179
- })).sort(
1180
- (left, right) =>
1181
- left.sortOrder - right.sortOrder || left.name.localeCompare(right.name),
1628
+ `,
1629
+ JSON.stringify(this.systemFolders()),
1630
+ userId
1631
+ )
1632
+ .toArray();
1633
+
1634
+ return sortFolders(
1635
+ rows.map((row): FolderListItem => ({
1636
+ id: row.id,
1637
+ name: row.name,
1638
+ kind: row.kind,
1639
+ systemType: row.system_type,
1640
+ sortOrder: Number(row.sort_order),
1641
+ totalCount: Number(row.total_count),
1642
+ unreadCount: Number(row.unread_count),
1643
+ }))
1182
1644
  );
1183
1645
  }
1184
1646
 
1647
+ /**
1648
+ * What the mail screen shows first, in one call: the folders and the first
1649
+ * page of `folderId` (null for no such folder).
1650
+ */
1651
+ startupView(userId: string, folderId: string, limit: number) {
1652
+ return {
1653
+ folders: this.folderView(userId),
1654
+ conversations: this.listConversations(
1655
+ userId,
1656
+ folderId,
1657
+ limit,
1658
+ null,
1659
+ undefined
1660
+ ),
1661
+ };
1662
+ }
1663
+
1664
+ /** `listFolders` with the change counter it reflects. */
1665
+ folderView(userId: string) {
1666
+ return { folders: this.listFolders(userId), version: this.version() };
1667
+ }
1668
+
1185
1669
  getFolderCounts(userId: string, folderId: string): FolderCounts | null {
1186
1670
  const folder = this.getFolder(folderId);
1671
+
1187
1672
  return folder ? this.countFolder(userId, folder) : null;
1188
1673
  }
1189
1674
 
1190
1675
  private countFolder(userId: string, folder: MailFolder): FolderCounts {
1191
1676
  const membership = folderMembership(folder);
1192
- const counts = this.state.storage.sql.exec<FolderCountRow>(`
1677
+
1678
+ const counts = this.state.storage.sql
1679
+ .exec<FolderCountRow>(
1680
+ `
1193
1681
  select
1194
1682
  count(*) as total_count,
1195
1683
  coalesce(sum((
@@ -1206,16 +1694,24 @@ export class MailboxDO extends DurableObject<Env> {
1206
1694
  )), 0) as unread_count
1207
1695
  from conversations c
1208
1696
  where ${membership.predicate}
1209
- `, userId, ...membership.bindings).one();
1697
+ `,
1698
+ userId,
1699
+ ...membership.bindings
1700
+ )
1701
+ .one();
1702
+
1210
1703
  return {
1211
1704
  totalCount: Number(counts.total_count),
1212
1705
  unreadCount: Number(counts.unread_count),
1213
1706
  };
1214
1707
  }
1215
1708
 
1709
+ /** Sets one person's read state; the change counter after it, or false for no such message. */
1216
1710
  setMessageRead(userId: string, emailId: string, isRead: boolean) {
1217
1711
  const email = this.getEmail(emailId);
1712
+
1218
1713
  if (!email) return false;
1714
+
1219
1715
  if (isRead) {
1220
1716
  const readAt = new Date();
1221
1717
  this.db
@@ -1229,35 +1725,44 @@ export class MailboxDO extends DurableObject<Env> {
1229
1725
  } else {
1230
1726
  this.db
1231
1727
  .delete(emailReadStates)
1232
- .where(and(
1233
- eq(emailReadStates.userId, userId),
1234
- eq(emailReadStates.emailId, emailId),
1235
- ))
1728
+ .where(
1729
+ and(
1730
+ eq(emailReadStates.userId, userId),
1731
+ eq(emailReadStates.emailId, emailId)
1732
+ )
1733
+ )
1236
1734
  .run();
1237
1735
  }
1736
+
1238
1737
  this.publishUpdate();
1239
- return true;
1738
+
1739
+ return { version: this.version() };
1240
1740
  }
1241
1741
 
1242
1742
  bulkSetConversationRead(
1243
1743
  userId: string,
1244
1744
  conversationIds: string[],
1245
- isRead: boolean,
1745
+ isRead: boolean
1246
1746
  ) {
1247
1747
  const candidates = [...new Set(conversationIds)];
1748
+
1248
1749
  if (!candidates.length) return 0;
1249
1750
  const candidatesJson = stringListJson(candidates);
1751
+
1250
1752
  const existingIds = this.db
1251
1753
  .select({ id: conversations.id })
1252
1754
  .from(conversations)
1253
- .where(and(
1254
- sql`${conversations.id} in (
1755
+ .where(
1756
+ and(
1757
+ sql`${conversations.id} in (
1255
1758
  select cast(value as text) from json_each(${candidatesJson})
1256
1759
  )`,
1257
- eq(conversations.hasIncoming, true),
1258
- ))
1760
+ eq(conversations.hasIncoming, true)
1761
+ )
1762
+ )
1259
1763
  .all()
1260
1764
  .map((conversation) => conversation.id);
1765
+
1261
1766
  if (!existingIds.length) return 0;
1262
1767
  const existingIdsJson = stringListJson(existingIds);
1263
1768
 
@@ -1298,15 +1803,19 @@ export class MailboxDO extends DurableObject<Env> {
1298
1803
  )
1299
1804
  `);
1300
1805
  }
1806
+
1301
1807
  this.publishUpdate();
1808
+
1302
1809
  return existingIds.length;
1303
1810
  }
1304
1811
 
1305
1812
  async enqueueInbound(input: InboundDeliveryInput) {
1306
1813
  const receivedAt = new Date(input.receivedAt);
1814
+
1307
1815
  if (Number.isNaN(receivedAt.getTime())) {
1308
1816
  throw new Error("Inbound delivery has an invalid receipt time");
1309
1817
  }
1818
+
1310
1819
  if (this.state.id.name && this.state.id.name !== input.mailboxId) {
1311
1820
  throw new Error("Inbound delivery targeted the wrong mailbox object");
1312
1821
  }
@@ -1317,12 +1826,14 @@ export class MailboxDO extends DurableObject<Env> {
1317
1826
  const alarmAt = queuedAt.getTime() + ALARM_WAKE_DELAY_MS;
1318
1827
  await this.scheduleAlarm(alarmAt);
1319
1828
  const messageId = inboundMessageId(input.id);
1829
+
1320
1830
  const queued = this.db.transaction((tx) => {
1321
1831
  const existing = tx
1322
1832
  .select({ id: emails.id })
1323
1833
  .from(emails)
1324
1834
  .where(eq(emails.id, messageId))
1325
1835
  .all()[0];
1836
+
1326
1837
  if (existing) return false;
1327
1838
 
1328
1839
  const result = tx
@@ -1339,25 +1850,279 @@ export class MailboxDO extends DurableObject<Env> {
1339
1850
  .onConflictDoNothing()
1340
1851
  .returning({ id: pendingInbound.id })
1341
1852
  .all();
1853
+
1342
1854
  return result.length > 0;
1343
1855
  });
1856
+
1344
1857
  return { messageId, queued };
1345
1858
  }
1346
1859
 
1347
- async insertEmail(email: NewEmail) {
1348
- email = prepareOfficePreviews(email);
1349
- if (hasPendingOfficePreviews(email)) await this.scheduleAlarm(Date.now() + ALARM_WAKE_DELAY_MS);
1860
+ async insertEmail(input: NewEmail) {
1861
+ const email = prepareOfficePreviews(input);
1862
+
1863
+ if (hasPendingOfficePreviews(email)) {
1864
+ await this.scheduleAlarm(Date.now() + ALARM_WAKE_DELAY_MS);
1865
+ }
1866
+
1350
1867
  this.db.transaction((tx) => {
1351
- const inserted = tx.insert(emails).values(email).onConflictDoNothing().returning({ id: emails.id }).all();
1868
+ const inserted = tx
1869
+ .insert(emails)
1870
+ .values(email)
1871
+ .onConflictDoNothing()
1872
+ .returning({ id: emails.id })
1873
+ .all();
1874
+
1352
1875
  if (inserted.length) {
1876
+ indexInsertedEmail(this.state.storage.sql, email.id);
1353
1877
  insertOfficePreviewJobs(this.state.storage.sql, email);
1354
1878
  recordCorrespondents(this.state.storage.sql, email);
1355
1879
  }
1356
1880
  });
1357
1881
  this.recentParticipantSources = null;
1882
+ void this.syncInboxCounts();
1883
+
1358
1884
  return this.getEmail(email.id);
1359
1885
  }
1360
1886
 
1887
+ /**
1888
+ * The message an import already stored: the one `importId` made, or one
1889
+ * with the same Message-ID (from another source, or delivered here).
1890
+ */
1891
+ findImported(importId: string, messageIdHeader: string | null) {
1892
+ const existing =
1893
+ this.getEmail(inboundMessageId(importId)) ??
1894
+ (messageIdHeader ? this.getEmailByMessageId(messageIdHeader) : null);
1895
+
1896
+ return existing
1897
+ ? { id: existing.id, conversationId: existing.conversationId }
1898
+ : null;
1899
+ }
1900
+
1901
+ /**
1902
+ * Stores one existing message (raw MIME already in R2) as delivery would,
1903
+ * with its place, read state, date and thread given by the importer. No
1904
+ * AI, sender checks, webhooks or push: imported mail is history. The
1905
+ * conversation and search index are kept as for any message; counts,
1906
+ * realtime and JMAP state are announced once for the batch
1907
+ * (`finishImport`, or the alarm when the importer never says it finished).
1908
+ * Idempotent by `importId` and by Message-ID.
1909
+ */
1910
+ async importMessage(input: ImportMessageInput): Promise<ImportMessageResult> {
1911
+ const id = inboundMessageId(input.importId);
1912
+ const known = this.getEmail(id);
1913
+
1914
+ if (known) {
1915
+ return { status: "duplicate", id, conversationId: known.conversationId };
1916
+ }
1917
+
1918
+ const object = await this.bindings.MAIL_STORAGE.get(input.rawObjectKey);
1919
+
1920
+ if (!object) throw new MissingRawMimeError();
1921
+ const rawMime = await object.arrayBuffer();
1922
+ const messageIdHeader = rawMessageId(rawMime);
1923
+
1924
+ const copy = messageIdHeader
1925
+ ? this.getEmailByMessageId(messageIdHeader)
1926
+ : null;
1927
+
1928
+ if (copy) {
1929
+ // Nothing will point at this upload.
1930
+ await this.bindings.MAIL_STORAGE.delete(input.rawObjectKey);
1931
+
1932
+ return {
1933
+ status: "duplicate",
1934
+ id: copy.id,
1935
+ conversationId: copy.conversationId,
1936
+ };
1937
+ }
1938
+
1939
+ const receivedAt = new Date(
1940
+ input.receivedAt ?? headerDate(rawMime) ?? Date.now()
1941
+ );
1942
+
1943
+ let parsed: NewEmail;
1944
+
1945
+ try {
1946
+ parsed = (
1947
+ await prepareInboundEmail({
1948
+ env: this.bindings,
1949
+ mailboxId: this.state.id.name ?? "unknown-mailbox",
1950
+ job: {
1951
+ id: input.importId,
1952
+ rawObjectKey: input.rawObjectKey,
1953
+ envelopeFrom: "",
1954
+ envelopeTo: input.mailboxAddress,
1955
+ listAddress: null,
1956
+ receivedAt,
1957
+ },
1958
+ rawMime,
1959
+ resolveParent: (inReplyTo, references) =>
1960
+ this.resolveParent(inReplyTo, references),
1961
+ })
1962
+ ).email;
1963
+ } catch (error) {
1964
+ if (!(error instanceof UnprocessableInboundEmailError)) throw error;
1965
+ await this.bindings.MAIL_STORAGE.delete(input.rawObjectKey);
1966
+
1967
+ return { status: "unprocessable", reason: error.message };
1968
+ }
1969
+
1970
+ const own = normalizeMailboxAddress(input.mailboxAddress);
1971
+
1972
+ const direction =
1973
+ input.direction ??
1974
+ (parsed.fromJson[0] &&
1975
+ normalizeMailboxAddress(parsed.fromJson[0].address) === own
1976
+ ? "outgoing"
1977
+ : "incoming");
1978
+
1979
+ const imported: NewEmail = {
1980
+ ...parsed,
1981
+ conversationId: input.conversationId ?? parsed.conversationId,
1982
+ direction,
1983
+ bodyText: clampText(parsed.bodyText),
1984
+ quotedText: clampText(parsed.quotedText),
1985
+ // Not an SMTP delivery to this workspace.
1986
+ envelopeFrom: null,
1987
+ envelopeTo: null,
1988
+ };
1989
+
1990
+ // Mail this mailbox sent went out already, unauthenticated by anyone here.
1991
+ if (direction === "outgoing") {
1992
+ imported.transportState = "submitted";
1993
+ imported.authenticationResultsJson = null;
1994
+ imported.listUnsubscribeJson = null;
1995
+ }
1996
+
1997
+ const email = prepareOfficePreviews(imported);
1998
+
1999
+ const stored = this.db.transaction((tx) => {
2000
+ const before =
2001
+ tx
2002
+ .select({
2003
+ mailboxState: conversations.mailboxState,
2004
+ folderId: conversations.folderId,
2005
+ })
2006
+ .from(conversations)
2007
+ .where(eq(conversations.id, email.conversationId))
2008
+ .all()[0] ?? null;
2009
+
2010
+ let folderId: string | null = null;
2011
+ let folderSkipped: "limit" | "invalid" | null = null;
2012
+
2013
+ if (input.placement === "inbox" && input.folderName) {
2014
+ const folder = this.importFolder(input.folderName);
2015
+
2016
+ if ("id" in folder) folderId = folder.id;
2017
+ else folderSkipped = folder.skipped;
2018
+ }
2019
+
2020
+ const inserted = tx
2021
+ .insert(emails)
2022
+ .values(email)
2023
+ .onConflictDoNothing()
2024
+ .returning({ id: emails.id })
2025
+ .all();
2026
+
2027
+ if (!inserted.length) return null;
2028
+ indexInsertedEmail(this.state.storage.sql, email.id);
2029
+ insertOfficePreviewJobs(this.state.storage.sql, email);
2030
+ recordCorrespondents(this.state.storage.sql, email);
2031
+
2032
+ const placement = mergedPlacement(
2033
+ before,
2034
+ requestedPlacement(input.placement, folderId)
2035
+ );
2036
+
2037
+ if (placement) {
2038
+ tx.update(conversations)
2039
+ .set(placement)
2040
+ .where(eq(conversations.id, email.conversationId))
2041
+ .run();
2042
+ }
2043
+
2044
+ if (direction === "incoming") {
2045
+ for (const userId of new Set(input.seenBy)) {
2046
+ tx.insert(emailReadStates)
2047
+ .values({ userId, emailId: email.id, readAt: receivedAt })
2048
+ .onConflictDoNothing()
2049
+ .run();
2050
+ }
2051
+ }
2052
+
2053
+ return { folderSkipped };
2054
+ });
2055
+
2056
+ if (!stored) {
2057
+ const existing = this.getEmail(id);
2058
+
2059
+ return {
2060
+ status: "duplicate",
2061
+ id,
2062
+ conversationId: existing?.conversationId ?? email.conversationId,
2063
+ };
2064
+ }
2065
+
2066
+ this.recentParticipantSources = null;
2067
+ this.state.storage.kv.put(IMPORT_PENDING_KEY, true);
2068
+ await this.scheduleAlarm(
2069
+ Date.now() +
2070
+ (hasPendingOfficePreviews(email)
2071
+ ? ALARM_WAKE_DELAY_MS
2072
+ : IMPORT_ANNOUNCE_DELAY_MS)
2073
+ );
2074
+
2075
+ return {
2076
+ status: "imported",
2077
+ id,
2078
+ conversationId: email.conversationId,
2079
+ folderSkipped: stored.folderSkipped,
2080
+ };
2081
+ }
2082
+
2083
+ /** The custom folder with this name (any case), created when missing; why not, when it cannot be. */
2084
+ private importFolder(
2085
+ name: string
2086
+ ): { id: string } | { skipped: "limit" | "invalid" } {
2087
+ const normalized = name.trim().toLocaleLowerCase("en-US");
2088
+
2089
+ const existing = this.db
2090
+ .select({ id: folders.id, name: folders.name })
2091
+ .from(folders)
2092
+ .all()
2093
+ .find((folder) => folder.name.toLocaleLowerCase("en-US") === normalized);
2094
+
2095
+ if (existing) return { id: existing.id };
2096
+ const created = this.insertFolder(createId("fld"), name);
2097
+
2098
+ if (created.status === "ok") return { id: created.folder.id };
2099
+
2100
+ // A system folder's name ("Sent", "Archive") is no custom folder.
2101
+ return { skipped: created.status === "limit" ? "limit" : "invalid" };
2102
+ }
2103
+
2104
+ /**
2105
+ * Announces what imports stored since the last time: writes the inbox
2106
+ * counts to D1 once, bumps the JMAP state, and tells open apps to refresh.
2107
+ * Push subscribers are not told; imported mail is not new mail.
2108
+ */
2109
+ async finishImport() {
2110
+ if (this.state.storage.kv.get<boolean>(IMPORT_PENDING_KEY)) {
2111
+ this.state.storage.kv.delete(IMPORT_PENDING_KEY);
2112
+ bumpJmapState(this.state.storage);
2113
+ const countsWritten = this.syncInboxCounts();
2114
+ this.state.waitUntil(
2115
+ this.broadcastUpdate(countsWritten).catch((error) => {
2116
+ console.error("Could not authorize realtime delivery", error);
2117
+ })
2118
+ );
2119
+ this.announceJmapState(false);
2120
+ await countsWritten;
2121
+ }
2122
+
2123
+ return { version: this.version() };
2124
+ }
2125
+
1361
2126
  /**
1362
2127
  * DNS intelligence and receiver signals for a parsed delivery, gathered
1363
2128
  * before AI classification so the model can use them. Fails open.
@@ -1366,24 +2131,37 @@ export class MailboxDO extends DurableObject<Env> {
1366
2131
  let identity: WorkspaceIdentity = { domains: [], names: new Map() };
1367
2132
  let dqsKey: string | null = null;
1368
2133
  let workspaceBlocks = new Map<string, number>();
2134
+
1369
2135
  try {
1370
2136
  [identity, dqsKey, workspaceBlocks] = await Promise.all([
1371
2137
  workspaceIdentity(this.bindings.DB),
1372
- spamhausDqsKey(this.bindings as Env & MailSafetyBindings),
2138
+ spamhausDqsKey(this.bindings),
1373
2139
  workspaceBlockPatterns(this.bindings.DB),
1374
2140
  ]);
1375
2141
  } catch (error) {
1376
- console.error("Could not read workspace identity for sender checks", error);
2142
+ console.error(
2143
+ "Could not read workspace identity for sender checks",
2144
+ error
2145
+ );
1377
2146
  }
2147
+
1378
2148
  const stored = email.authenticationResultsJson;
1379
2149
  const authentication = stored ?? null;
1380
2150
  const from = email.fromJson[0] ?? { address: "", name: null };
1381
- const sql = this.state.storage.sql;
1382
- const status = from.address ? senderStatuses(sql, [from.address]).get(from.address.toLocaleLowerCase()) : undefined;
1383
- const block = workspaceBlockFor(from.address, workspaceBlocks) ?? status?.block ?? null;
2151
+ const storage = this.state.storage.sql;
2152
+
2153
+ const status = from.address
2154
+ ? senderStatuses(storage, [from.address]).get(
2155
+ from.address.toLocaleLowerCase()
2156
+ )
2157
+ : undefined;
2158
+
2159
+ const block =
2160
+ workspaceBlockFor(from.address, workspaceBlocks) ?? status?.block ?? null;
2161
+
1384
2162
  const trusted = Boolean(status?.trustedAt) && !block;
1385
- const rules = evaluateRules(listMailRules(sql), emailRuleSubject(email));
1386
2163
  let intel: SenderIntel | null = null;
2164
+
1387
2165
  try {
1388
2166
  intel = await collectSenderIntel({
1389
2167
  authentication,
@@ -1394,9 +2172,16 @@ export class MailboxDO extends DurableObject<Env> {
1394
2172
  bucket: this.bindings.MAIL_STORAGE,
1395
2173
  });
1396
2174
  } catch (error) {
1397
- console.error(`Could not collect sender intelligence for ${email.id}`, error);
2175
+ console.error(
2176
+ `Could not collect sender intelligence for ${email.id}`,
2177
+ error
2178
+ );
1398
2179
  }
1399
- const history = senderHistory(sql, [from.address]).get(from.address.toLocaleLowerCase());
2180
+
2181
+ const history = senderHistory(storage, [from.address]).get(
2182
+ from.address.toLocaleLowerCase()
2183
+ );
2184
+
1400
2185
  const delivery = deliveryFacts({
1401
2186
  authentication,
1402
2187
  deliveredTo: email.envelopeTo ?? null,
@@ -1406,6 +2191,7 @@ export class MailboxDO extends DurableObject<Env> {
1406
2191
  workspaceDomains: identity.domains,
1407
2192
  isKnownAddressee: (address) => this.isKnownAddressee(address),
1408
2193
  });
2194
+
1409
2195
  const security = messageSecurity({
1410
2196
  fromAddress: from.address,
1411
2197
  fromName: from.name,
@@ -1415,30 +2201,39 @@ export class MailboxDO extends DurableObject<Env> {
1415
2201
  internalNames: identity.names,
1416
2202
  intel,
1417
2203
  // Counted as if this message were already stored.
1418
- history: { inboundCount: (history?.inboundCount ?? 0) + 1, outboundCount: history?.outboundCount ?? 0 },
2204
+ history: {
2205
+ inboundCount: (history?.inboundCount ?? 0) + 1,
2206
+ outboundCount: history?.outboundCount ?? 0,
2207
+ },
1419
2208
  replyTo: (email.replyToJson ?? []).map((item) => item.address),
1420
2209
  listId: email.listId ?? null,
1421
2210
  delivery,
1422
2211
  trusted,
1423
2212
  });
1424
- let markReadUserIds: string[] = [];
1425
- if (rules.markRead && !block) {
1426
- try {
1427
- markReadUserIds = await this.mailboxMemberIds();
1428
- } catch (error) {
1429
- console.error(`Could not read mailbox members to mark ${email.id} read`, error);
1430
- }
1431
- }
1432
- const screening: InboundScreening = { block, trusted, rules, markReadUserIds };
1433
- let workspaceFeedback: Awaited<ReturnType<typeof workspaceFeedbackSummary>> | null = null;
2213
+
2214
+ const screening: InboundScreening = { block, trusted };
2215
+
2216
+ let workspaceFeedback: Awaited<
2217
+ ReturnType<typeof workspaceFeedbackSummary>
2218
+ > | null = null;
2219
+
1434
2220
  const mailboxId = this.state.id.name;
1435
- if (from.address && mailboxId && !block && !rules.destination) {
2221
+
2222
+ if (from.address && mailboxId && !block) {
1436
2223
  try {
1437
- workspaceFeedback = await workspaceFeedbackSummary(this.bindings.DB, mailboxId, from.address);
2224
+ workspaceFeedback = await workspaceFeedbackSummary(
2225
+ this.bindings.DB,
2226
+ mailboxId,
2227
+ from.address
2228
+ );
1438
2229
  } catch (error) {
1439
- console.error(`Could not read workspace feedback for ${email.id}`, error);
2230
+ console.error(
2231
+ `Could not read workspace feedback for ${email.id}`,
2232
+ error
2233
+ );
1440
2234
  }
1441
2235
  }
2236
+
1442
2237
  return {
1443
2238
  intel,
1444
2239
  delivery,
@@ -1448,7 +2243,9 @@ export class MailboxDO extends DurableObject<Env> {
1448
2243
  intel,
1449
2244
  firstTimeSender: security.firstTimeSender,
1450
2245
  warnings: security.warnings,
1451
- feedback: from.address ? senderFeedbackSummary(sql, from.address) : null,
2246
+ feedback: from.address
2247
+ ? senderFeedbackSummary(storage, from.address)
2248
+ : null,
1452
2249
  workspaceFeedback,
1453
2250
  delivery,
1454
2251
  }),
@@ -1457,7 +2254,9 @@ export class MailboxDO extends DurableObject<Env> {
1457
2254
 
1458
2255
  /** Mail written to this address already reached the mailbox from at least two senders. */
1459
2256
  private isKnownAddressee(address: string) {
1460
- const [row] = this.state.storage.sql.exec<{ senders: number }>(`
2257
+ const [row] = this.state.storage.sql
2258
+ .exec<{ senders: number }>(
2259
+ `
1461
2260
  select count(distinct lower(json_extract(message.from_json, '$[0].address'))) as senders
1462
2261
  from emails message
1463
2262
  where message.direction = 'incoming'
@@ -1468,59 +2267,57 @@ export class MailboxDO extends DurableObject<Env> {
1468
2267
  select 1 from json_each(message.cc_json) recipient
1469
2268
  where lower(json_extract(recipient.value, '$.address')) = ?1
1470
2269
  )
1471
- `, address.toLocaleLowerCase()).toArray();
1472
- return Number(row?.senders ?? 0) >= 2;
1473
- }
2270
+ `,
2271
+ address.toLocaleLowerCase()
2272
+ )
2273
+ .toArray();
1474
2274
 
1475
- private async mailboxMemberIds() {
1476
- const mailboxId = this.state.id.name;
1477
- if (!mailboxId) return [];
1478
- const result = await this.bindings.DB
1479
- .prepare("select user_id from mailbox_access where mailbox_id = ?")
1480
- .bind(mailboxId)
1481
- .all<{ user_id: string }>();
1482
- return result.results.map((row) => row.user_id);
2275
+ return Number(row?.senders ?? 0) >= 2;
1483
2276
  }
1484
2277
 
1485
- /** Blocks win over rules, rules over AI; trusted senders and "never spam" rules override an AI spam verdict. */
2278
+ /** Blocks win over AI; trusted senders override an AI spam verdict. */
1486
2279
  private inboundPlacement(
1487
2280
  screening: InboundScreening,
1488
- classification: EmailAiClassification | null,
2281
+ classification: EmailAiClassification | null
1489
2282
  ): InboundPlacement {
1490
- const markReadUserIds = screening.markReadUserIds;
1491
- if (screening.block) return { state: "spam", folderId: null, overrideFolder: false, markReadUserIds: [] };
1492
- const destination = screening.rules.destination;
1493
- if (destination?.kind === "spam") return { state: "spam", folderId: null, overrideFolder: false, markReadUserIds };
1494
- if (destination?.kind === "archive") return { state: "archive", folderId: null, overrideFolder: false, markReadUserIds };
1495
- if (destination?.kind === "folder") {
1496
- return { state: null, folderId: destination.folderId, overrideFolder: true, markReadUserIds };
1497
- }
1498
- const spamAllowed = !screening.trusted && !screening.rules.neverSpam;
1499
- if (classification?.spam && spamAllowed) {
1500
- return { state: "spam", folderId: null, overrideFolder: false, markReadUserIds };
2283
+ if (screening.block) return { state: "spam", folderId: null };
2284
+
2285
+ if (classification?.spam && !screening.trusted) {
2286
+ return { state: "spam", folderId: null };
1501
2287
  }
1502
- return { state: null, folderId: classification?.folderId ?? null, overrideFolder: false, markReadUserIds };
2288
+
2289
+ return { state: null, folderId: classification?.folderId ?? null };
1503
2290
  }
1504
2291
 
1505
2292
  /** The model from openworkspace.json; tests substitute one on the instance. */
1506
- protected classificationModel(): AiModel | null {
2293
+ protected classificationModel(): Promise<AiModel | null> {
1507
2294
  return aiModel(this.bindings, "classification");
1508
2295
  }
1509
2296
 
1510
- private async classifyInbound(rawMime: ArrayBuffer, signals: ClassificationSignals | null) {
2297
+ private async classifyInbound(
2298
+ rawMime: ArrayBuffer,
2299
+ signals: ClassificationSignals | null
2300
+ ) {
1511
2301
  let ai: AiModel | null;
2302
+
1512
2303
  try {
1513
- ai = this.classificationModel();
2304
+ ai = await this.classificationModel();
1514
2305
  } catch (error) {
1515
- throw new EmailAiClassificationError("The classification model is misconfigured", { cause: error });
2306
+ throw new EmailAiClassificationError(
2307
+ "The classification model is misconfigured",
2308
+ { cause: error }
2309
+ );
1516
2310
  }
2311
+
1517
2312
  if (!ai) return null;
1518
2313
  const configuration = this.aiConfiguration();
2314
+
1519
2315
  const customFolders = this.db
1520
2316
  .select({ id: folders.id, name: folders.name })
1521
2317
  .from(folders)
1522
2318
  .orderBy(asc(folders.sortOrder), asc(folders.name))
1523
2319
  .all();
2320
+
1524
2321
  return classifyInboundEmail({
1525
2322
  rawMime,
1526
2323
  folders: customFolders,
@@ -1532,11 +2329,12 @@ export class MailboxDO extends DurableObject<Env> {
1532
2329
  }
1533
2330
 
1534
2331
  private insertClassifiedInboundEmail(
1535
- email: NewEmail,
2332
+ input: NewEmail,
1536
2333
  classification: EmailAiClassification | null,
1537
- placement: InboundPlacement,
2334
+ placement: InboundPlacement
1538
2335
  ) {
1539
- email = prepareOfficePreviews(email);
2336
+ const email = prepareOfficePreviews(input);
2337
+
1540
2338
  const stored = this.db.transaction((tx) => {
1541
2339
  const trustedFolder = placement.folderId
1542
2340
  ? tx
@@ -1545,10 +2343,17 @@ export class MailboxDO extends DurableObject<Env> {
1545
2343
  .where(eq(folders.id, placement.folderId))
1546
2344
  .all()[0]
1547
2345
  : null;
1548
- const normalizedClassification = classification?.folderId
1549
- && !tx.select({ id: folders.id }).from(folders).where(eq(folders.id, classification.folderId)).all()[0]
1550
- ? { ...classification, folderId: null }
1551
- : classification;
2346
+
2347
+ const normalizedClassification =
2348
+ classification?.folderId &&
2349
+ !tx
2350
+ .select({ id: folders.id })
2351
+ .from(folders)
2352
+ .where(eq(folders.id, classification.folderId))
2353
+ .all()[0]
2354
+ ? { ...classification, folderId: null }
2355
+ : classification;
2356
+
1552
2357
  const inserted = tx
1553
2358
  .insert(emails)
1554
2359
  .values({
@@ -1558,14 +2363,17 @@ export class MailboxDO extends DurableObject<Env> {
1558
2363
  .onConflictDoNothing()
1559
2364
  .returning()
1560
2365
  .all()[0];
2366
+
1561
2367
  if (!inserted) return null;
2368
+ indexInsertedEmail(this.state.storage.sql, inserted.id);
1562
2369
  insertOfficePreviewJobs(this.state.storage.sql, email);
1563
2370
  recordCorrespondents(this.state.storage.sql, email);
1564
2371
 
1565
2372
  const activeConversation = and(
1566
2373
  eq(conversations.id, email.conversationId),
1567
- eq(conversations.mailboxState, "active"),
2374
+ eq(conversations.mailboxState, "active")
1568
2375
  );
2376
+
1569
2377
  if (placement.state) {
1570
2378
  tx.update(conversations)
1571
2379
  .set({ mailboxState: placement.state, folderId: null })
@@ -1574,31 +2382,45 @@ export class MailboxDO extends DurableObject<Env> {
1574
2382
  } else if (trustedFolder) {
1575
2383
  tx.update(conversations)
1576
2384
  .set({ folderId: trustedFolder.id })
1577
- .where(placement.overrideFolder ? activeConversation : and(activeConversation, isNull(conversations.folderId)))
2385
+ .where(and(activeConversation, isNull(conversations.folderId)))
1578
2386
  .run();
1579
2387
  }
1580
- const readAt = new Date();
1581
- for (const userId of placement.markReadUserIds) {
1582
- tx.insert(emailReadStates).values({ userId, emailId: inserted.id, readAt }).onConflictDoNothing().run();
1583
- }
1584
- return tx
1585
- .select()
1586
- .from(emails)
1587
- .where(eq(emails.id, inserted.id))
1588
- .all()[0] ?? null;
2388
+
2389
+ return (
2390
+ tx.select().from(emails).where(eq(emails.id, inserted.id)).all()[0] ??
2391
+ null
2392
+ );
1589
2393
  });
2394
+
1590
2395
  this.recentParticipantSources = null;
2396
+
1591
2397
  return stored;
1592
2398
  }
1593
2399
 
1594
- /** Lazy fill for messages stored before sender intelligence existed. */
1595
- setEmailSenderIntel(emailId: string, intel: SenderIntel) {
1596
- return this.db
1597
- .update(emails)
1598
- .set({ senderIntelJson: intel })
1599
- .where(and(eq(emails.id, emailId), eq(emails.direction, "incoming"), isNull(emails.senderIntelJson)))
1600
- .returning({ id: emails.id })
1601
- .all().length > 0;
2400
+ /**
2401
+ * Fills sender intelligence in on view: for a message without any, or
2402
+ * replacing the failed result checked at `replacesCheckedAt`.
2403
+ */
2404
+ setEmailSenderIntel(
2405
+ emailId: string,
2406
+ intel: SenderIntel,
2407
+ replacesCheckedAt: number | null = null
2408
+ ) {
2409
+ const current =
2410
+ replacesCheckedAt === null
2411
+ ? isNull(emails.senderIntelJson)
2412
+ : sql`json_extract(${emails.senderIntelJson}, '$.checkedAt') = ${replacesCheckedAt}`;
2413
+
2414
+ return (
2415
+ this.db
2416
+ .update(emails)
2417
+ .set({ senderIntelJson: intel })
2418
+ .where(
2419
+ and(eq(emails.id, emailId), eq(emails.direction, "incoming"), current)
2420
+ )
2421
+ .returning({ id: emails.id })
2422
+ .all().length > 0
2423
+ );
1602
2424
  }
1603
2425
 
1604
2426
  /** Inbound/outbound counters for the given addresses (lowercased keys). */
@@ -1609,18 +2431,31 @@ export class MailboxDO extends DurableObject<Env> {
1609
2431
  /** Block, trust and report state for senders, and unsubscribe records for lists. */
1610
2432
  getMessageSafetyContext(addresses: string[], listKeys: string[]) {
1611
2433
  const keys = [...new Set(listKeys)].slice(0, 100);
2434
+
1612
2435
  const rows = keys.length
1613
- ? this.db.select().from(unsubscriptions).where(inArray(unsubscriptions.listKey, keys)).all()
2436
+ ? this.db
2437
+ .select()
2438
+ .from(unsubscriptions)
2439
+ .where(inArray(unsubscriptions.listKey, keys))
2440
+ .all()
1614
2441
  : [];
2442
+
1615
2443
  return {
1616
- senders: Object.fromEntries(senderStatuses(this.state.storage.sql, addresses)) as Record<string, SenderStatus>,
1617
- unsubscriptions: Object.fromEntries(rows.map((row): [string, Unsubscription] => [row.listKey, {
1618
- listKey: row.listKey,
1619
- method: row.method,
1620
- status: row.status,
1621
- target: row.target,
1622
- at: row.createdAt.getTime(),
1623
- }])),
2444
+ senders: Object.fromEntries(
2445
+ senderStatuses(this.state.storage.sql, addresses)
2446
+ ),
2447
+ unsubscriptions: Object.fromEntries(
2448
+ rows.map((row): [string, Unsubscription] => [
2449
+ row.listKey,
2450
+ {
2451
+ listKey: row.listKey,
2452
+ method: row.method,
2453
+ status: row.status,
2454
+ target: row.target,
2455
+ at: row.createdAt.getTime(),
2456
+ },
2457
+ ])
2458
+ ),
1624
2459
  };
1625
2460
  }
1626
2461
 
@@ -1635,10 +2470,13 @@ export class MailboxDO extends DurableObject<Env> {
1635
2470
  }): Unsubscription {
1636
2471
  const createdAt = new Date();
1637
2472
  const values = { ...input, createdAt };
1638
- this.db.insert(unsubscriptions).values(values)
2473
+ this.db
2474
+ .insert(unsubscriptions)
2475
+ .values(values)
1639
2476
  .onConflictDoUpdate({ target: unsubscriptions.listKey, set: values })
1640
2477
  .run();
1641
2478
  this.publishUpdate();
2479
+
1642
2480
  return {
1643
2481
  listKey: input.listKey,
1644
2482
  method: input.method,
@@ -1650,8 +2488,14 @@ export class MailboxDO extends DurableObject<Env> {
1650
2488
 
1651
2489
  /** Moves every Inbox or Archive conversation with mail from the pattern to Spam. */
1652
2490
  private moveSenderConversationsToSpam(pattern: string) {
1653
- const predicate = blockPatternPredicate("lower(json_extract(message.from_json, '$[0].address'))", pattern);
1654
- return this.state.storage.sql.exec<{ id: string }>(`
2491
+ const predicate = blockPatternPredicate(
2492
+ "lower(json_extract(message.from_json, '$[0].address'))",
2493
+ pattern
2494
+ );
2495
+
2496
+ return this.state.storage.sql
2497
+ .exec<{ id: string }>(
2498
+ `
1655
2499
  update conversations
1656
2500
  set mailbox_state = 'spam', folder_id = null
1657
2501
  where mailbox_state in ('active', 'archive')
@@ -1660,36 +2504,50 @@ export class MailboxDO extends DurableObject<Env> {
1660
2504
  where message.direction = 'incoming' and ${predicate.sql}
1661
2505
  )
1662
2506
  returning id
1663
- `, ...predicate.bindings).toArray().length;
2507
+ `,
2508
+ ...predicate.bindings
2509
+ )
2510
+ .toArray().length;
1664
2511
  }
1665
2512
 
1666
2513
  blockSender(pattern: string, moveExisting: boolean) {
1667
2514
  const moved = this.db.transaction(() => {
1668
2515
  setSenderBlocked(this.state.storage.sql, pattern, true, Date.now());
2516
+
1669
2517
  return moveExisting ? this.moveSenderConversationsToSpam(pattern) : 0;
1670
2518
  });
2519
+
1671
2520
  this.recentParticipantSources = null;
1672
2521
  this.publishUpdate();
2522
+
1673
2523
  return { block: blockFromPattern(pattern, Date.now(), false), moved };
1674
2524
  }
1675
2525
 
1676
2526
  /** For a workspace-wide block: existing mail goes to Spam; the block itself lives in D1. */
1677
2527
  moveSenderToSpam(pattern: string) {
1678
2528
  const moved = this.moveSenderConversationsToSpam(pattern);
2529
+
1679
2530
  if (moved) {
1680
2531
  this.recentParticipantSources = null;
1681
2532
  this.publishUpdate();
1682
2533
  }
2534
+
1683
2535
  return moved;
1684
2536
  }
1685
2537
 
1686
2538
  unblockSender(pattern: string) {
1687
- const existed = this.state.storage.sql
1688
- .exec("select 1 from senders where address = ? and blocked_at is not null", pattern)
1689
- .toArray().length > 0;
2539
+ const existed =
2540
+ this.state.storage.sql
2541
+ .exec(
2542
+ "select 1 from senders where address = ? and blocked_at is not null",
2543
+ pattern
2544
+ )
2545
+ .toArray().length > 0;
2546
+
1690
2547
  setSenderBlocked(this.state.storage.sql, pattern, false, Date.now());
1691
2548
  this.recentParticipantSources = null;
1692
2549
  this.publishUpdate();
2550
+
1693
2551
  return existed;
1694
2552
  }
1695
2553
 
@@ -1700,66 +2558,101 @@ export class MailboxDO extends DurableObject<Env> {
1700
2558
  setSenderTrusted(address: string, trusted: boolean) {
1701
2559
  setSenderTrusted(this.state.storage.sql, address, trusted, Date.now());
1702
2560
  this.publishUpdate();
2561
+
1703
2562
  return true;
1704
2563
  }
1705
2564
 
1706
2565
  /** The newest incoming message of each conversation, for actions that need a sender. */
1707
2566
  latestIncomingEmails(conversationIds: string[]) {
1708
2567
  const ids = [...new Set(conversationIds)].slice(0, 100);
2568
+
1709
2569
  if (!ids.length) return [];
1710
- const rows = this.state.storage.sql.exec<{ id: string }>(`
2570
+
2571
+ const rows = this.state.storage.sql
2572
+ .exec<{ id: string }>(
2573
+ `
1711
2574
  select (
1712
2575
  select message.id from emails message
1713
2576
  where message.conversation_id = requested.value and message.direction = 'incoming'
1714
2577
  order by message.timeline_at desc, message.id desc limit 1
1715
2578
  ) as id
1716
2579
  from json_each(?) requested
1717
- `, stringListJson(ids)).toArray().flatMap((row) => row.id ? [row.id] : []);
1718
- return rows.length ? this.db.select().from(emails).where(inArray(emails.id, rows)).all() : [];
2580
+ `,
2581
+ stringListJson(ids)
2582
+ )
2583
+ .toArray()
2584
+ .flatMap((row) => (row.id ? [row.id] : []));
2585
+
2586
+ return rows.length
2587
+ ? this.db.select().from(emails).where(inArray(emails.id, rows)).all()
2588
+ : [];
1719
2589
  }
1720
2590
 
1721
2591
  /**
1722
- * Report spam or phishing: labels the message, records feedback for the
1723
- * classifier, and moves its conversation to Spam. Never contacts the sender.
2592
+ * Report spam: labels the message, records feedback for the classifier,
2593
+ * and moves its conversation to Spam. Never contacts the sender.
1724
2594
  */
1725
- reportMessage(input: { emailId: string; kind: ReportKind; userId: string }) {
2595
+ reportMessage(input: { emailId: string; userId: string }) {
1726
2596
  const email = this.getEmail(input.emailId);
2597
+
1727
2598
  if (!email || email.direction !== "incoming") return null;
1728
2599
  const address = email.fromJson[0]?.address ?? "";
2600
+
1729
2601
  const moved = this.db.transaction((tx) => {
1730
- tx.update(emails).set({ reportLabel: input.kind }).where(eq(emails.id, email.id)).run();
2602
+ tx.update(emails)
2603
+ .set({ reportLabel: "spam" })
2604
+ .where(eq(emails.id, email.id))
2605
+ .run();
2606
+
1731
2607
  if (address.includes("@")) {
1732
2608
  recordSenderFeedback(this.state.storage.sql, {
1733
2609
  id: createId("fbk"),
1734
2610
  address,
1735
2611
  emailId: email.id,
1736
- label: input.kind,
2612
+ label: "spam",
1737
2613
  userId: input.userId,
1738
2614
  now: Date.now(),
1739
2615
  });
1740
2616
  }
1741
- return tx.update(conversations)
1742
- .set({ mailboxState: "spam", folderId: null })
1743
- .where(and(
1744
- eq(conversations.id, email.conversationId),
1745
- inArray(conversations.mailboxState, ["active", "archive"]),
1746
- ))
1747
- .returning({ id: conversations.id })
1748
- .all().length > 0;
2617
+
2618
+ return (
2619
+ tx
2620
+ .update(conversations)
2621
+ .set({ mailboxState: "spam", folderId: null })
2622
+ .where(
2623
+ and(
2624
+ eq(conversations.id, email.conversationId),
2625
+ inArray(conversations.mailboxState, ["active", "archive"])
2626
+ )
2627
+ )
2628
+ .returning({ id: conversations.id })
2629
+ .all().length > 0
2630
+ );
1749
2631
  });
2632
+
1750
2633
  this.recentParticipantSources = null;
1751
2634
  this.publishUpdate();
1752
- return { email: this.getEmail(email.id)!, moved };
2635
+
2636
+ return {
2637
+ email: required(this.getEmail(email.id), "The reported email exists"),
2638
+ moved,
2639
+ };
1753
2640
  }
1754
2641
 
1755
2642
  /** "Not spam": back to Inbox, the sender becomes trusted, and the feedback is recorded. */
1756
2643
  markNotSpam(input: { emailId: string; userId: string }) {
1757
2644
  const email = this.getEmail(input.emailId);
2645
+
1758
2646
  if (!email || email.direction !== "incoming") return null;
1759
2647
  const address = email.fromJson[0]?.address ?? "";
1760
2648
  const label: FeedbackLabel = "not_spam";
2649
+
1761
2650
  const restored = this.db.transaction((tx) => {
1762
- tx.update(emails).set({ reportLabel: null }).where(eq(emails.conversationId, email.conversationId)).run();
2651
+ tx.update(emails)
2652
+ .set({ reportLabel: null })
2653
+ .where(eq(emails.conversationId, email.conversationId))
2654
+ .run();
2655
+
1763
2656
  if (address.includes("@")) {
1764
2657
  recordSenderFeedback(this.state.storage.sql, {
1765
2658
  id: createId("fbk"),
@@ -1771,121 +2664,59 @@ export class MailboxDO extends DurableObject<Env> {
1771
2664
  });
1772
2665
  setSenderTrusted(this.state.storage.sql, address, true, Date.now());
1773
2666
  }
1774
- return tx.update(conversations)
1775
- .set({ mailboxState: "active" })
1776
- .where(and(eq(conversations.id, email.conversationId), eq(conversations.mailboxState, "spam")))
1777
- .returning({ id: conversations.id })
1778
- .all().length > 0;
1779
- });
1780
- this.recentParticipantSources = null;
1781
- this.publishUpdate();
1782
- return { restored, address: address.includes("@") ? address : null };
1783
- }
1784
2667
 
1785
- listRules() {
1786
- return listMailRules(this.state.storage.sql);
1787
- }
2668
+ return (
2669
+ tx
2670
+ .update(conversations)
2671
+ .set({ mailboxState: "active" })
2672
+ .where(
2673
+ and(
2674
+ eq(conversations.id, email.conversationId),
2675
+ eq(conversations.mailboxState, "spam")
2676
+ )
2677
+ )
2678
+ .returning({ id: conversations.id })
2679
+ .all().length > 0
2680
+ );
2681
+ });
1788
2682
 
1789
- createRule(input: MailRuleInput) {
1790
- const id = createId("rul");
1791
- insertMailRule(this.state.storage.sql, id, input, Date.now());
2683
+ this.recentParticipantSources = null;
1792
2684
  this.publishUpdate();
1793
- return this.listRules().find((rule) => rule.id === id)!;
1794
- }
1795
-
1796
- updateRule(id: string, input: MailRuleInput) {
1797
- const updated = updateMailRule(this.state.storage.sql, id, input, Date.now());
1798
- if (updated) this.publishUpdate();
1799
- return updated ? this.listRules().find((rule) => rule.id === id)! : null;
1800
- }
1801
2685
 
1802
- deleteRule(id: string) {
1803
- const deleted = deleteMailRule(this.state.storage.sql, id);
1804
- if (deleted) this.publishUpdate();
1805
- return deleted;
1806
- }
1807
-
1808
- reorderRules(ids: string[]) {
1809
- const reordered = reorderMailRules(this.state.storage.sql, ids);
1810
- if (reordered) this.publishUpdate();
1811
- return reordered;
1812
- }
1813
-
1814
- /**
1815
- * Applies one rule to mail already in the mailbox (newest 5,000 incoming
1816
- * messages). Only Inbox conversations move, except Spam, which also takes
1817
- * archived ones; "mark read" applies for the person who asked.
1818
- */
1819
- applyRuleToExisting(ruleId: string, userId: string) {
1820
- const rule = this.listRules().find((candidate) => candidate.id === ruleId);
1821
- if (!rule) return null;
1822
- const rows = this.db
1823
- .select({
1824
- id: emails.id,
1825
- conversationId: emails.conversationId,
1826
- fromJson: emails.fromJson,
1827
- toJson: emails.toJson,
1828
- ccJson: emails.ccJson,
1829
- subject: emails.subject,
1830
- listId: emails.listId,
1831
- attachmentsJson: emails.attachmentsJson,
1832
- })
1833
- .from(emails)
1834
- .where(eq(emails.direction, "incoming"))
1835
- .orderBy(desc(emails.timelineAt))
1836
- .limit(5_000)
1837
- .all();
1838
- const matched = rows.filter((row) => ruleMatches(rule.conditions, emailRuleSubject(row)));
1839
- const conversationIds = stringListJson([...new Set(matched.map((row) => row.conversationId))]);
1840
- const destination = ruleDestination(rule.actions);
1841
- const sql = this.state.storage.sql;
1842
- const updated = this.db.transaction(() => {
1843
- let count = 0;
1844
- if (destination?.kind === "spam" && !rule.actions.neverSpam) {
1845
- count = sql.exec(`update conversations set mailbox_state = 'spam', folder_id = null
1846
- where id in (select value from json_each(?)) and mailbox_state in ('active', 'archive') returning id`,
1847
- conversationIds).toArray().length;
1848
- } else if (destination?.kind === "archive") {
1849
- count = sql.exec(`update conversations set mailbox_state = 'archive', folder_id = null
1850
- where id in (select value from json_each(?)) and mailbox_state = 'active' returning id`,
1851
- conversationIds).toArray().length;
1852
- } else if (destination?.kind === "folder" && this.getFolder(destination.folderId)?.kind === "custom") {
1853
- count = sql.exec(`update conversations set folder_id = ?
1854
- where id in (select value from json_each(?)) and mailbox_state = 'active' and has_incoming = 1
1855
- and (folder_id is null or folder_id <> ?) returning id`,
1856
- destination.folderId, conversationIds, destination.folderId).toArray().length;
1857
- }
1858
- if (rule.actions.markRead) {
1859
- const readAt = Date.now();
1860
- for (const row of matched) {
1861
- sql.exec("insert into email_read_states (user_id, email_id, read_at) values (?, ?, ?) on conflict do nothing", userId, row.id, readAt);
1862
- }
1863
- }
1864
- return count;
1865
- });
1866
- this.publishUpdate();
1867
- return { matched: matched.length, updated };
2686
+ return { restored, address: address.includes("@") ? address : null };
1868
2687
  }
1869
2688
 
1870
- async submitOutgoing(email: NewEmail) {
2689
+ submitOutgoing(input: NewEmail) {
1871
2690
  return this.state.blockConcurrencyWhile(async () => {
1872
- if (email.direction !== "outgoing" || email.transportState !== "unconfirmed") {
2691
+ if (
2692
+ input.direction !== "outgoing" ||
2693
+ input.transportState !== "unconfirmed"
2694
+ ) {
1873
2695
  throw new Error("Only unconfirmed outgoing messages can be submitted");
1874
2696
  }
1875
- if (!email.requestFingerprint) {
2697
+
2698
+ if (!input.requestFingerprint) {
1876
2699
  throw new Error("An outgoing request fingerprint is required");
1877
2700
  }
1878
- email = prepareOfficePreviews(email);
1879
- if (hasPendingOfficePreviews(email)) await this.scheduleAlarm(Date.now() + ALARM_WAKE_DELAY_MS);
2701
+
2702
+ const email = prepareOfficePreviews(input);
2703
+
2704
+ if (hasPendingOfficePreviews(email)) {
2705
+ await this.scheduleAlarm(Date.now() + ALARM_WAKE_DELAY_MS);
2706
+ }
2707
+
1880
2708
  const submission = this.db.transaction((tx): SubmitOutgoingResult => {
1881
2709
  const existing = tx
1882
2710
  .select()
1883
2711
  .from(emails)
1884
2712
  .where(eq(emails.id, email.id))
1885
2713
  .all()[0];
2714
+
1886
2715
  if (existing) {
1887
- const sameRequest = existing.direction === "outgoing"
1888
- && existing.requestFingerprint === email.requestFingerprint;
2716
+ const sameRequest =
2717
+ existing.direction === "outgoing" &&
2718
+ existing.requestFingerprint === email.requestFingerprint;
2719
+
1889
2720
  return {
1890
2721
  outcome: sameRequest ? "existing" : "conflict",
1891
2722
  email: existing,
@@ -1893,28 +2724,36 @@ export class MailboxDO extends DurableObject<Env> {
1893
2724
  }
1894
2725
 
1895
2726
  tx.insert(emails).values(email).run();
2727
+ indexInsertedEmail(this.state.storage.sql, email.id);
1896
2728
  insertOfficePreviewJobs(this.state.storage.sql, email);
1897
2729
  recordCorrespondents(this.state.storage.sql, email);
2730
+
1898
2731
  const inserted = tx
1899
2732
  .select()
1900
2733
  .from(emails)
1901
2734
  .where(eq(emails.id, email.id))
1902
2735
  .all()[0];
2736
+
1903
2737
  if (!inserted) throw new Error("Outgoing message was not persisted");
2738
+
1904
2739
  return { outcome: "inserted", email: inserted };
1905
2740
  });
2741
+
1906
2742
  if (submission.outcome !== "inserted") return submission;
1907
2743
  this.recentParticipantSources = null;
2744
+
1908
2745
  const result = {
1909
2746
  ...submission,
1910
2747
  email: await this.deliverOutgoing(submission.email.id),
1911
2748
  };
2749
+
1912
2750
  this.publishUpdate();
2751
+
1913
2752
  return result;
1914
2753
  });
1915
2754
  }
1916
2755
 
1917
- async resendOutgoing(id: string) {
2756
+ resendOutgoing(id: string) {
1918
2757
  return this.state.blockConcurrencyWhile(async () => {
1919
2758
  const result = this.db
1920
2759
  .update(emails)
@@ -1924,47 +2763,67 @@ export class MailboxDO extends DurableObject<Env> {
1924
2763
  transportError: null,
1925
2764
  deliveryStatusJson: [],
1926
2765
  })
1927
- .where(and(
1928
- eq(emails.id, id),
1929
- eq(emails.direction, "outgoing"),
1930
- inArray(emails.transportState, ["failed", "unconfirmed"]),
1931
- ))
2766
+ .where(
2767
+ and(
2768
+ eq(emails.id, id),
2769
+ eq(emails.direction, "outgoing"),
2770
+ inArray(emails.transportState, ["failed", "unconfirmed"])
2771
+ )
2772
+ )
1932
2773
  .returning({ id: emails.id })
1933
2774
  .all();
2775
+
1934
2776
  if (!result.length) return null;
1935
2777
  const email = await this.deliverOutgoing(id);
1936
2778
  this.publishUpdate();
2779
+
1937
2780
  return email;
1938
2781
  });
1939
2782
  }
1940
2783
 
1941
- seedMailbox(
2784
+ async seedMailbox(
1942
2785
  folderValues: NewFolder[],
1943
2786
  emailValues: NewEmail[],
1944
- conversationValues: Array<{
2787
+ conversationValues: {
1945
2788
  id: string;
1946
2789
  mailboxState?: MailboxState;
1947
2790
  folderId?: string | null;
1948
- }> = [],
1949
- senderValues: Array<typeof senders.$inferInsert> = [],
1950
- ruleValues: Array<MailRuleInput & { id: string }> = [],
2791
+ }[] = [],
2792
+ senderValues: (typeof senders.$inferInsert)[] = []
1951
2793
  ) {
1952
2794
  this.db.transaction((tx) => {
1953
- for (const rule of ruleValues) {
1954
- const exists = this.state.storage.sql.exec("select 1 from mail_rules where id = ?", rule.id).toArray().length;
1955
- if (!exists) insertMailRule(this.state.storage.sql, rule.id, rule, Date.now());
1956
- }
1957
2795
  // Prior history first: seeded messages then add to it exactly once.
1958
2796
  for (const sender of senderValues) {
1959
2797
  tx.insert(senders).values(sender).onConflictDoNothing().run();
1960
2798
  }
2799
+
2800
+ // Seeding sets the folder order afresh: seeded folders at their places,
2801
+ // system folders at their defaults (so a demo login undoes a reorder).
2802
+ tx.delete(systemFolderOrder).run();
2803
+
1961
2804
  for (const folder of folderValues) {
1962
- tx.insert(folders).values(folder).onConflictDoNothing().run();
2805
+ tx.insert(folders)
2806
+ .values(folder)
2807
+ .onConflictDoUpdate({
2808
+ target: folders.id,
2809
+ set: { sortOrder: folder.sortOrder },
2810
+ })
2811
+ .run();
1963
2812
  }
2813
+
1964
2814
  for (const email of emailValues) {
1965
- const inserted = tx.insert(emails).values(email).onConflictDoNothing().returning({ id: emails.id }).all();
1966
- if (inserted.length) recordCorrespondents(this.state.storage.sql, email);
2815
+ const inserted = tx
2816
+ .insert(emails)
2817
+ .values(email)
2818
+ .onConflictDoNothing()
2819
+ .returning({ id: emails.id })
2820
+ .all();
2821
+
2822
+ if (!inserted.length) continue;
2823
+ indexInsertedEmail(this.state.storage.sql, email.id);
2824
+ recordCorrespondents(this.state.storage.sql, email);
1967
2825
  }
2826
+
1968
2827
  for (const conversation of conversationValues) {
1969
2828
  tx.update(conversations)
1970
2829
  .set({
@@ -1976,30 +2835,34 @@ export class MailboxDO extends DurableObject<Env> {
1976
2835
  }
1977
2836
  });
1978
2837
  this.recentParticipantSources = null;
2838
+ await this.syncInboxCounts();
2839
+
1979
2840
  return { folders: folderValues.length, emails: emailValues.length };
1980
2841
  }
1981
2842
 
1982
2843
  /**
1983
2844
  * Demo logins start from the same safety state every time: no reports,
1984
- * unsubscribes, trust or extra rules, and only the seeded blocks.
2845
+ * unsubscribes or trust, and only the seeded blocks.
1985
2846
  */
1986
2847
  resetDemoSafetyState(input: {
1987
2848
  emailIds: string[];
1988
- reportLabels: Record<string, "spam" | "phishing">;
1989
- blockedPatterns: Array<{ pattern: string; at: number }>;
1990
- ruleIds: string[];
2849
+ blockedPatterns: { pattern: string; at: number }[];
1991
2850
  }) {
1992
- const sql = this.state.storage.sql;
2851
+ const storage = this.state.storage.sql;
1993
2852
  this.db.transaction(() => {
1994
- sql.exec("update emails set report_label = null where id in (select value from json_each(?))", stringListJson(input.emailIds));
1995
- for (const [emailId, label] of Object.entries(input.reportLabels)) {
1996
- sql.exec("update emails set report_label = ? where id = ?", label, emailId);
2853
+ storage.exec(
2854
+ "update emails set report_label = null where id in (select value from json_each(?))",
2855
+ stringListJson(input.emailIds)
2856
+ );
2857
+ storage.exec("delete from unsubscriptions");
2858
+ storage.exec("delete from sender_feedback");
2859
+ storage.exec(
2860
+ "update senders set trusted_at = null, reported_at = null, blocked_at = null"
2861
+ );
2862
+
2863
+ for (const block of input.blockedPatterns) {
2864
+ setSenderBlocked(storage, block.pattern, true, block.at);
1997
2865
  }
1998
- sql.exec("delete from unsubscriptions");
1999
- sql.exec("delete from sender_feedback");
2000
- sql.exec("update senders set trusted_at = null, reported_at = null, blocked_at = null");
2001
- for (const block of input.blockedPatterns) setSenderBlocked(sql, block.pattern, true, block.at);
2002
- sql.exec("delete from mail_rules where id not in (select value from json_each(?))", stringListJson(input.ruleIds));
2003
2866
  });
2004
2867
  this.recentParticipantSources = null;
2005
2868
  }
@@ -2007,43 +2870,54 @@ export class MailboxDO extends DurableObject<Env> {
2007
2870
  bulkUpdateConversations(
2008
2871
  conversationIds: string[],
2009
2872
  sourceFolderId: string,
2010
- update: ConversationUpdate,
2873
+ update: ConversationUpdate
2011
2874
  ) {
2012
2875
  const sourceFolder = this.getFolder(sourceFolderId);
2876
+
2013
2877
  if (!sourceFolder) return null;
2878
+
2014
2879
  if (update.folderId) {
2015
2880
  const targetFolder = this.getFolder(update.folderId);
2881
+
2016
2882
  if (!targetFolder || targetFolder.kind !== "custom") return null;
2017
2883
  }
2884
+
2018
2885
  const candidates = [...new Set(conversationIds)];
2886
+
2019
2887
  if (!candidates.length) return 0;
2020
2888
  const assignments: string[] = [];
2021
- const values: Array<string | null> = [];
2889
+ const values: (string | null)[] = [];
2890
+
2022
2891
  // A custom folder is a classification inside the active Inbox
2023
2892
  // distribution, so assigning one also restores the conversation.
2024
2893
  const mailboxState = update.folderId
2025
- ? "active" as const
2894
+ ? ("active" as const)
2026
2895
  : update.mailboxState;
2896
+
2027
2897
  if (mailboxState !== undefined) {
2028
2898
  assignments.push("mailbox_state = ?");
2029
2899
  values.push(mailboxState);
2030
2900
  }
2901
+
2031
2902
  if (update.folderId !== undefined) {
2032
2903
  assignments.push("folder_id = ?");
2033
2904
  values.push(update.folderId);
2034
2905
  }
2906
+
2035
2907
  if (!assignments.length) return 0;
2036
2908
  const membership = folderMembership(sourceFolder);
2037
2909
  const candidatesJson = stringListJson(candidates);
2910
+
2038
2911
  // Setting folderId means placing the conversation in the Inbox
2039
2912
  // distribution. Outgoing-only conversations must stay in Sent.
2040
- const targetPredicate = update.folderId !== undefined
2041
- ? "and c.has_incoming = 1"
2042
- : "";
2913
+ const targetPredicate =
2914
+ update.folderId === undefined ? "" : "and c.has_incoming = 1";
2043
2915
 
2044
2916
  // Keep the source-folder guard in the update itself so a stale shared
2045
2917
  // selection cannot overwrite a teammate's newer move.
2046
- const result = this.state.storage.sql.exec<{ id: string }>(`
2918
+ const result = this.state.storage.sql
2919
+ .exec<{ id: string }>(
2920
+ `
2047
2921
  update conversations as c
2048
2922
  set ${assignments.join(", ")}
2049
2923
  where c.id in (
@@ -2052,28 +2926,47 @@ export class MailboxDO extends DurableObject<Env> {
2052
2926
  and ${membership.predicate}
2053
2927
  ${targetPredicate}
2054
2928
  returning id
2055
- `, ...values, candidatesJson, ...membership.bindings).toArray();
2929
+ `,
2930
+ ...values,
2931
+ candidatesJson,
2932
+ ...membership.bindings
2933
+ )
2934
+ .toArray();
2935
+
2056
2936
  if (result.length) this.publishUpdate();
2937
+
2057
2938
  return result.length;
2058
2939
  }
2059
2940
 
2060
2941
  async permanentlyDeleteConversations(conversationIds: string[]) {
2061
2942
  const candidates = [...new Set(conversationIds)];
2943
+
2062
2944
  if (!candidates.length) {
2063
2945
  return { outcome: "not_found" as const, deletedCount: 0 };
2064
2946
  }
2947
+
2065
2948
  const candidatesJson = stringListJson(candidates);
2949
+
2066
2950
  const storedConversations = this.db
2067
- .select({ id: conversations.id, mailboxState: conversations.mailboxState })
2951
+ .select({
2952
+ id: conversations.id,
2953
+ mailboxState: conversations.mailboxState,
2954
+ })
2068
2955
  .from(conversations)
2069
2956
  .where(sql`${conversations.id} in (
2070
2957
  select cast(value as text) from json_each(${candidatesJson})
2071
2958
  )`)
2072
2959
  .all();
2960
+
2073
2961
  if (storedConversations.length !== candidates.length) {
2074
2962
  return { outcome: "not_found" as const, deletedCount: 0 };
2075
2963
  }
2076
- if (storedConversations.some((conversation) => conversation.mailboxState !== "trash")) {
2964
+
2965
+ if (
2966
+ storedConversations.some(
2967
+ (conversation) => conversation.mailboxState !== "trash"
2968
+ )
2969
+ ) {
2077
2970
  return { outcome: "not_in_trash" as const, deletedCount: 0 };
2078
2971
  }
2079
2972
 
@@ -2090,45 +2983,59 @@ export class MailboxDO extends DurableObject<Env> {
2090
2983
  select cast(value as text) from json_each(${candidatesJson})
2091
2984
  )`)
2092
2985
  .all();
2986
+
2093
2987
  const incomingEmailIds = new Set(
2094
2988
  storedEmails.flatMap((email) =>
2095
2989
  email.direction === "incoming" ? [email.id] : []
2096
- ),
2990
+ )
2097
2991
  );
2992
+
2098
2993
  const pendingInboundIds = incomingEmailIds.size
2099
2994
  ? this.db
2100
- .select({ id: pendingInbound.id })
2101
- .from(pendingInbound)
2102
- .all()
2103
- .flatMap((job) =>
2104
- incomingEmailIds.has(inboundMessageId(job.id)) ? [job.id] : []
2105
- )
2995
+ .select({ id: pendingInbound.id })
2996
+ .from(pendingInbound)
2997
+ .all()
2998
+ .flatMap((job) =>
2999
+ incomingEmailIds.has(inboundMessageId(job.id)) ? [job.id] : []
3000
+ )
2106
3001
  : [];
3002
+
2107
3003
  const pendingInboundIdsJson = stringListJson(pendingInboundIds);
2108
- const objectKeys = [...new Set(storedEmails.flatMap((email) => [
2109
- ...(email.bodyHtmlR2Key ? [email.bodyHtmlR2Key] : []),
2110
- ...(email.rawMimeR2Key ? [email.rawMimeR2Key] : []),
2111
- ...email.attachmentsJson.flatMap((attachment) => [
2112
- attachment.r2Key,
2113
- ...(officePreviewExtension(attachment.filename) ? [officePreviewKey(attachment.r2Key)] : []),
2114
- ]),
2115
- ]))];
3004
+
3005
+ const objectKeys = [
3006
+ ...new Set(
3007
+ storedEmails.flatMap((email) => [
3008
+ ...(email.bodyHtmlR2Key ? [email.bodyHtmlR2Key] : []),
3009
+ ...(email.rawMimeR2Key ? [email.rawMimeR2Key] : []),
3010
+ ...email.attachmentsJson.flatMap((attachment) => [
3011
+ attachment.r2Key,
3012
+ ...(officePreviewExtension(attachment.filename)
3013
+ ? [officePreviewKey(attachment.r2Key)]
3014
+ : []),
3015
+ ]),
3016
+ ])
3017
+ ),
3018
+ ];
2116
3019
 
2117
3020
  const referencedObjectKeys = this.referencedObjectKeys(
2118
3021
  objectKeys,
2119
- candidates,
3022
+ candidates
2120
3023
  );
3024
+
2121
3025
  const ownedObjectKeys = objectKeys.filter(
2122
- (objectKey) => !referencedObjectKeys.has(objectKey),
3026
+ (objectKey) => !referencedObjectKeys.has(objectKey)
2123
3027
  );
3028
+
2124
3029
  const cleanupAt = new Date();
2125
3030
  // Schedule first so the cleanup rows committed below can never be left
2126
3031
  // without a retry after an interruption. The short delay prevents the
2127
3032
  // alarm from waking on setAlarm's await before the rows are inserted.
2128
3033
  const cleanupAlarmAt = cleanupAt.getTime() + ALARM_WAKE_DELAY_MS;
3034
+
2129
3035
  if (ownedObjectKeys.length) {
2130
3036
  await this.scheduleAlarm(cleanupAlarmAt);
2131
3037
  }
3038
+
2132
3039
  this.db.transaction((tx) => {
2133
3040
  tx.run(sql`
2134
3041
  delete from pending_office_previews where email_id in (
@@ -2137,12 +3044,14 @@ export class MailboxDO extends DurableObject<Env> {
2137
3044
  )
2138
3045
  )
2139
3046
  `);
3047
+
2140
3048
  for (const objectKey of ownedObjectKeys) {
2141
3049
  tx.insert(pendingObjectDeletions)
2142
3050
  .values({ objectKey, nextAttemptAt: cleanupAt })
2143
3051
  .onConflictDoNothing()
2144
3052
  .run();
2145
3053
  }
3054
+
2146
3055
  if (pendingInboundIds.length) {
2147
3056
  tx.delete(pendingInbound)
2148
3057
  .where(sql`${pendingInbound.id} in (
@@ -2150,6 +3059,7 @@ export class MailboxDO extends DurableObject<Env> {
2150
3059
  )`)
2151
3060
  .run();
2152
3061
  }
3062
+
2153
3063
  tx.run(sql`
2154
3064
  delete from email_search where conversation_id in (
2155
3065
  select cast(value as text) from json_each(${candidatesJson})
@@ -2176,6 +3086,7 @@ export class MailboxDO extends DurableObject<Env> {
2176
3086
  });
2177
3087
  this.recentParticipantSources = null;
2178
3088
  this.publishUpdate();
3089
+
2179
3090
  return {
2180
3091
  outcome: "deleted" as const,
2181
3092
  deletedCount: storedConversations.length,
@@ -2184,10 +3095,13 @@ export class MailboxDO extends DurableObject<Env> {
2184
3095
 
2185
3096
  private referencedObjectKeys(
2186
3097
  objectKeys: string[],
2187
- excludedConversationIds: string[],
3098
+ excludedConversationIds: string[]
2188
3099
  ) {
2189
3100
  if (!objectKeys.length) return new Set<string>();
2190
- const rows = this.state.storage.sql.exec<{ object_key: string }>(`
3101
+
3102
+ const rows = this.state.storage.sql
3103
+ .exec<{ object_key: string }>(
3104
+ `
2191
3105
  with
2192
3106
  candidate_keys(object_key) as (
2193
3107
  select cast(value as text) from json_each(?)
@@ -2214,7 +3128,12 @@ export class MailboxDO extends DurableObject<Env> {
2214
3128
  )
2215
3129
  )
2216
3130
  )
2217
- `, stringListJson(objectKeys), stringListJson(excludedConversationIds)).toArray();
3131
+ `,
3132
+ stringListJson(objectKeys),
3133
+ stringListJson(excludedConversationIds)
3134
+ )
3135
+ .toArray();
3136
+
2218
3137
  return new Set(rows.map((row) => row.object_key));
2219
3138
  }
2220
3139
 
@@ -2229,40 +3148,52 @@ export class MailboxDO extends DurableObject<Env> {
2229
3148
  .where(and(eq(emails.id, id), eq(emails.direction, "outgoing")))
2230
3149
  .returning({ id: emails.id })
2231
3150
  .all();
3151
+
2232
3152
  return result.length > 0;
2233
3153
  }
2234
3154
 
2235
3155
  recordDeliveryStatus(
2236
3156
  messageIdHeader: string,
2237
- status: RecipientDeliveryStatus,
3157
+ status: RecipientDeliveryStatus
2238
3158
  ) {
2239
3159
  const email = this.getEmailByMessageId(messageIdHeader);
3160
+
2240
3161
  if (!email || email.direction !== "outgoing") return "not_found" as const;
3162
+
2241
3163
  const existing = email.deliveryStatusJson.find(
2242
- (item) => item.recipient === status.recipient,
3164
+ (item) => item.recipient === status.recipient
2243
3165
  );
3166
+
2244
3167
  if (existing?.eventId === status.eventId) return "duplicate" as const;
3168
+
2245
3169
  if (existing && existing.eventAt > status.eventAt) return "stale" as const;
2246
3170
 
2247
3171
  const next = [
2248
3172
  ...email.deliveryStatusJson.filter(
2249
- (item) => item.recipient !== status.recipient,
3173
+ (item) => item.recipient !== status.recipient
2250
3174
  ),
2251
3175
  status,
2252
3176
  ];
3177
+
2253
3178
  this.db
2254
3179
  .update(emails)
2255
3180
  .set({ deliveryStatusJson: next })
2256
3181
  .where(eq(emails.id, email.id))
2257
3182
  .run();
2258
3183
  this.publishUpdate();
3184
+
2259
3185
  return "updated" as const;
2260
3186
  }
2261
3187
 
2262
3188
  async alarm() {
2263
3189
  const now = Date.now();
3190
+ await this.finishImport();
2264
3191
  await this.processInboundJobs(now);
2265
- await dispatchOfficePreviewJobs(this.state.storage.sql, this.bindings, this.state.id.name ?? "unknown-mailbox");
3192
+ await dispatchOfficePreviewJobs(
3193
+ this.state.storage.sql,
3194
+ this.bindings,
3195
+ this.state.id.name ?? "unknown-mailbox"
3196
+ );
2266
3197
  await this.processObjectDeletionJobs(now);
2267
3198
  await this.scheduleRemainingWork();
2268
3199
  }
@@ -2274,9 +3205,12 @@ export class MailboxDO extends DurableObject<Env> {
2274
3205
  */
2275
3206
  private isDuplicateDelivery(job: PendingInbound, rawMime: ArrayBuffer) {
2276
3207
  const messageId = rawMessageId(rawMime);
3208
+
2277
3209
  if (!messageId) return false;
2278
3210
  const existing = this.getEmailByMessageId(messageId);
3211
+
2279
3212
  if (!existing) return false;
3213
+
2280
3214
  return existing.direction === "incoming" || Boolean(job.listAddress);
2281
3215
  }
2282
3216
 
@@ -2285,128 +3219,169 @@ export class MailboxDO extends DurableObject<Env> {
2285
3219
  .select()
2286
3220
  .from(pendingInbound)
2287
3221
  .where(lte(pendingInbound.nextAttemptAt, new Date(now)))
2288
- .orderBy(asc(pendingInbound.nextAttemptAt), asc(pendingInbound.receivedAt))
3222
+ .orderBy(
3223
+ asc(pendingInbound.nextAttemptAt),
3224
+ asc(pendingInbound.receivedAt)
3225
+ )
2289
3226
  // MIME parsing can be memory-heavy; the next due row schedules a quick
2290
3227
  // follow-up, so one delivery per wake keeps peak memory bounded.
2291
3228
  .limit(INBOUND_ALARM_BATCH_SIZE)
2292
3229
  .all();
3230
+
2293
3231
  for (const job of jobs) {
2294
- const messageId = inboundMessageId(job.id);
2295
- const existing = this.getEmail(messageId);
2296
- if (existing) {
2297
- await this.finishStoredInbound(job, existing, now, false);
2298
- continue;
3232
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one delivery at a time keeps MIME parsing's peak memory bounded
3233
+ await this.processInboundJob(job, now);
3234
+ }
3235
+ }
3236
+
3237
+ private async processInboundJob(job: PendingInbound, now: number) {
3238
+ const messageId = inboundMessageId(job.id);
3239
+ const existing = this.getEmail(messageId);
3240
+
3241
+ if (existing) {
3242
+ await this.finishStoredInbound(job, existing, now, false);
3243
+
3244
+ return;
3245
+ }
3246
+
3247
+ try {
3248
+ const rawMime = await readInboundRawMime(this.bindings, job);
3249
+
3250
+ if (this.isDuplicateDelivery(job, rawMime)) {
3251
+ this.db
3252
+ .delete(pendingInbound)
3253
+ .where(eq(pendingInbound.id, job.id))
3254
+ .run();
3255
+
3256
+ return;
2299
3257
  }
2300
3258
 
3259
+ const prepared = await prepareInboundEmail({
3260
+ env: this.bindings,
3261
+ mailboxId: this.state.id.name ?? "unknown-mailbox",
3262
+ job,
3263
+ rawMime,
3264
+ resolveParent: (inReplyTo, references) =>
3265
+ this.resolveParent(inReplyTo, references),
3266
+ });
3267
+
3268
+ const { intel, delivery, signals, screening } =
3269
+ await this.inboundSenderSignals(prepared.email, prepared.linkDomains);
3270
+
3271
+ const screeningJson: EmailScreening | null = screening.block
3272
+ ? { blocked: screening.block.workspace ? "workspace" : "mailbox" }
3273
+ : null;
3274
+
3275
+ const email: NewEmail = {
3276
+ ...prepared.email,
3277
+ senderIntelJson: intel,
3278
+ deliveryJson: delivery,
3279
+ screeningJson,
3280
+ };
3281
+
3282
+ let classification: EmailAiClassification | null = null;
3283
+ // Blocked senders need no model.
3284
+ const skipAi = Boolean(screening.block);
3285
+
2301
3286
  try {
2302
- const rawMime = await readInboundRawMime(this.bindings, job);
2303
- if (this.isDuplicateDelivery(job, rawMime)) {
2304
- this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
2305
- continue;
3287
+ if (!skipAi) {
3288
+ classification = await this.classifyInbound(rawMime, signals);
2306
3289
  }
2307
- const prepared = await prepareInboundEmail({
2308
- env: this.bindings,
2309
- mailboxId: this.state.id.name ?? "unknown-mailbox",
2310
- job,
2311
- rawMime,
2312
- resolveParent: (inReplyTo, references) =>
2313
- this.resolveParent(inReplyTo, references),
2314
- });
2315
- const { intel, delivery, signals, screening } = await this.inboundSenderSignals(prepared.email, prepared.linkDomains);
2316
- const screeningJson: EmailScreening | null = screening.block || screening.rules.ruleIds.length
2317
- ? {
2318
- blocked: screening.block ? (screening.block.workspace ? "workspace" : "mailbox") : null,
2319
- ruleIds: screening.rules.ruleIds,
2320
- ruleDestination: Boolean(screening.rules.destination),
2321
- }
2322
- : null;
2323
- const email: NewEmail = { ...prepared.email, senderIntelJson: intel, deliveryJson: delivery, screeningJson };
2324
- let classification: EmailAiClassification | null = null;
2325
- // Blocked senders and rules that choose a destination need no model.
2326
- const skipAi = Boolean(screening.block || screening.rules.destination);
2327
- try {
2328
- if (!skipAi) classification = await this.classifyInbound(rawMime, signals);
2329
- } catch (error) {
2330
- if (!(error instanceof EmailAiClassificationError)) throw error;
2331
- const aiAttempts = job.aiAttempts + 1;
2332
- if (aiAttempts < MAILBOX_AI_MAX_ATTEMPTS) {
2333
- this.db
2334
- .update(pendingInbound)
2335
- .set({
2336
- aiAttempts,
2337
- nextAttemptAt: new Date(now + retryDelay(aiAttempts)),
2338
- })
2339
- .where(eq(pendingInbound.id, job.id))
2340
- .run();
2341
- console.error(
2342
- `Could not classify inbound delivery ${job.id}; retrying`,
2343
- error,
2344
- );
2345
- continue;
2346
- }
3290
+ } catch (error) {
3291
+ if (!(error instanceof EmailAiClassificationError)) throw error;
3292
+ const aiAttempts = job.aiAttempts + 1;
3293
+
3294
+ if (aiAttempts < MAILBOX_AI_MAX_ATTEMPTS) {
3295
+ this.db
3296
+ .update(pendingInbound)
3297
+ .set({
3298
+ aiAttempts,
3299
+ nextAttemptAt: new Date(now + retryDelay(aiAttempts)),
3300
+ })
3301
+ .where(eq(pendingInbound.id, job.id))
3302
+ .run();
2347
3303
  console.error(
2348
- `Could not classify inbound delivery ${job.id}; delivering to Inbox`,
2349
- error,
3304
+ `Could not classify inbound delivery ${job.id}; retrying`,
3305
+ error
2350
3306
  );
3307
+
3308
+ return;
2351
3309
  }
2352
- const stored = this.insertClassifiedInboundEmail(
2353
- email,
2354
- classification,
2355
- this.inboundPlacement(screening, classification),
3310
+
3311
+ console.error(
3312
+ `Could not classify inbound delivery ${job.id}; delivering to Inbox`,
3313
+ error
2356
3314
  );
3315
+ }
3316
+
3317
+ const stored = this.insertClassifiedInboundEmail(
3318
+ email,
3319
+ classification,
3320
+ this.inboundPlacement(screening, classification)
3321
+ );
3322
+
3323
+ if (!stored) {
3324
+ throw new Error("Parsed inbound email was not persisted");
3325
+ }
3326
+
3327
+ await this.finishStoredInbound(job, stored, now, true);
3328
+ } catch (error) {
3329
+ if (error instanceof UnprocessableInboundEmailError) {
3330
+ const fallback = prepareUnprocessableInboundEmail({
3331
+ job,
3332
+ reason: error.message,
3333
+ rawMimeR2Key: job.rawObjectKey,
3334
+ });
3335
+
3336
+ const stored = await this.insertEmail(fallback);
3337
+
2357
3338
  if (!stored) {
2358
- throw new Error("Parsed inbound email was not persisted");
2359
- }
2360
- await this.finishStoredInbound(job, stored, now, true);
2361
- } catch (error) {
2362
- if (error instanceof UnprocessableInboundEmailError) {
2363
- const fallback = prepareUnprocessableInboundEmail({
2364
- job,
2365
- reason: error.message,
2366
- rawMimeR2Key: job.rawObjectKey,
3339
+ throw new Error("Inbound fallback email was not persisted", {
3340
+ cause: error,
2367
3341
  });
2368
- const stored = await this.insertEmail(fallback);
2369
- if (!stored) {
2370
- throw new Error("Inbound fallback email was not persisted", {
2371
- cause: error,
2372
- });
2373
- }
2374
- await this.finishStoredInbound(job, stored, now, true);
2375
- console.error(`Stored fallback for inbound delivery ${job.id}`, error);
2376
- continue;
2377
3342
  }
2378
- if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
2379
- const fallback = prepareUnprocessableInboundEmail({
2380
- job,
2381
- reason: "Message processing remained unavailable for 24 hours",
2382
- rawMimeR2Key: error instanceof MissingRawMimeError
2383
- ? null
2384
- : job.rawObjectKey,
3343
+
3344
+ await this.finishStoredInbound(job, stored, now, true);
3345
+ console.error(`Stored fallback for inbound delivery ${job.id}`, error);
3346
+
3347
+ return;
3348
+ }
3349
+
3350
+ if (now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS) {
3351
+ const fallback = prepareUnprocessableInboundEmail({
3352
+ job,
3353
+ reason: "Message processing remained unavailable for 24 hours",
3354
+ rawMimeR2Key:
3355
+ error instanceof MissingRawMimeError ? null : job.rawObjectKey,
3356
+ });
3357
+
3358
+ const stored = await this.insertEmail(fallback);
3359
+
3360
+ if (!stored) {
3361
+ throw new Error("Inbound infrastructure fallback was not persisted", {
3362
+ cause: error,
2385
3363
  });
2386
- const stored = await this.insertEmail(fallback);
2387
- if (!stored) {
2388
- throw new Error("Inbound infrastructure fallback was not persisted", {
2389
- cause: error,
2390
- });
2391
- }
2392
- await this.finishStoredInbound(job, stored, now, true);
2393
- console.error(
2394
- `Stored infrastructure fallback for inbound delivery ${job.id}`,
2395
- error,
2396
- );
2397
- continue;
2398
3364
  }
2399
- const attempts = job.attempts + 1;
2400
- this.db
2401
- .update(pendingInbound)
2402
- .set({
2403
- attempts,
2404
- nextAttemptAt: new Date(now + retryDelay(attempts)),
2405
- })
2406
- .where(eq(pendingInbound.id, job.id))
2407
- .run();
2408
- console.error(`Could not ingest inbound delivery ${job.id}`, error);
3365
+
3366
+ await this.finishStoredInbound(job, stored, now, true);
3367
+ console.error(
3368
+ `Stored infrastructure fallback for inbound delivery ${job.id}`,
3369
+ error
3370
+ );
3371
+
3372
+ return;
2409
3373
  }
3374
+
3375
+ const attempts = job.attempts + 1;
3376
+ this.db
3377
+ .update(pendingInbound)
3378
+ .set({
3379
+ attempts,
3380
+ nextAttemptAt: new Date(now + retryDelay(attempts)),
3381
+ })
3382
+ .where(eq(pendingInbound.id, job.id))
3383
+ .run();
3384
+ console.error(`Could not ingest inbound delivery ${job.id}`, error);
2410
3385
  }
2411
3386
  }
2412
3387
 
@@ -2418,21 +3393,29 @@ export class MailboxDO extends DurableObject<Env> {
2418
3393
  .orderBy(asc(pendingObjectDeletions.nextAttemptAt))
2419
3394
  .limit(OBJECT_DELETION_ALARM_BATCH_SIZE)
2420
3395
  .all();
3396
+
2421
3397
  if (!jobs.length) return;
2422
3398
  const objectKeys = jobs.map((job) => job.objectKey);
2423
3399
  const referencedObjectKeys = this.referencedObjectKeys(objectKeys, []);
2424
- const retainedKeys = objectKeys.filter((key) => referencedObjectKeys.has(key));
3400
+
3401
+ const retainedKeys = objectKeys.filter((key) =>
3402
+ referencedObjectKeys.has(key)
3403
+ );
3404
+
2425
3405
  if (retainedKeys.length) {
2426
3406
  this.db
2427
3407
  .delete(pendingObjectDeletions)
2428
3408
  .where(inArray(pendingObjectDeletions.objectKey, retainedKeys))
2429
3409
  .run();
2430
3410
  }
3411
+
2431
3412
  const deletableJobs = jobs.filter(
2432
- (job) => !referencedObjectKeys.has(job.objectKey),
3413
+ (job) => !referencedObjectKeys.has(job.objectKey)
2433
3414
  );
3415
+
2434
3416
  if (!deletableJobs.length) return;
2435
3417
  const deletableKeys = deletableJobs.map((job) => job.objectKey);
3418
+
2436
3419
  try {
2437
3420
  await this.bindings.MAIL_STORAGE.delete(deletableKeys);
2438
3421
  this.db
@@ -2451,6 +3434,7 @@ export class MailboxDO extends DurableObject<Env> {
2451
3434
  .where(eq(pendingObjectDeletions.objectKey, job.objectKey))
2452
3435
  .run();
2453
3436
  }
3437
+
2454
3438
  console.error("Could not delete permanent message objects", error);
2455
3439
  }
2456
3440
  }
@@ -2462,38 +3446,49 @@ export class MailboxDO extends DurableObject<Env> {
2462
3446
  .orderBy(asc(pendingInbound.nextAttemptAt))
2463
3447
  .limit(1)
2464
3448
  .all()[0];
3449
+
2465
3450
  const nextObjectDeletion = this.db
2466
3451
  .select({ nextAttemptAt: pendingObjectDeletions.nextAttemptAt })
2467
3452
  .from(pendingObjectDeletions)
2468
3453
  .orderBy(asc(pendingObjectDeletions.nextAttemptAt))
2469
3454
  .limit(1)
2470
3455
  .all()[0];
2471
- const officePreviewAttempt = nextOfficePreviewAttempt(this.state.storage.sql);
2472
- const nextAttemptAt = [nextInbound, nextObjectDeletion,
2473
- ...(officePreviewAttempt === undefined ? [] : [{ nextAttemptAt: new Date(officePreviewAttempt) }]),
2474
- ]
2475
- .flatMap((job) => job ? [job.nextAttemptAt.getTime()] : [])
2476
- .reduce<number | null>(
2477
- (earliest, value) => earliest === null ? value : Math.min(earliest, value),
2478
- null,
2479
- );
3456
+
3457
+ const officePreviewAttempt = nextOfficePreviewAttempt(
3458
+ this.state.storage.sql
3459
+ );
3460
+
3461
+ const attemptTimes = [
3462
+ nextInbound,
3463
+ nextObjectDeletion,
3464
+ ...(officePreviewAttempt === undefined
3465
+ ? []
3466
+ : [{ nextAttemptAt: new Date(officePreviewAttempt) }]),
3467
+ ].flatMap((job) => (job ? [job.nextAttemptAt.getTime()] : []));
3468
+
3469
+ const nextAttemptAt =
3470
+ attemptTimes.length > 0 ? Math.min(...attemptTimes) : null;
3471
+
2480
3472
  if (nextAttemptAt !== null) {
2481
3473
  await this.scheduleAlarm(
2482
- Math.max(Date.now() + ALARM_WAKE_DELAY_MS, nextAttemptAt),
3474
+ Math.max(Date.now() + ALARM_WAKE_DELAY_MS, nextAttemptAt)
2483
3475
  );
2484
3476
  }
2485
3477
  }
2486
3478
 
2487
3479
  private async deliverOutgoing(id: string) {
2488
3480
  const message = this.getEmail(id);
3481
+
2489
3482
  if (
2490
- !message
2491
- || message.direction !== "outgoing"
2492
- || message.transportState !== "unconfirmed"
3483
+ !message ||
3484
+ message.direction !== "outgoing" ||
3485
+ message.transportState !== "unconfirmed"
2493
3486
  ) {
2494
3487
  throw new Error("Unconfirmed outgoing message was not found");
2495
3488
  }
3489
+
2496
3490
  let delivery: Awaited<ReturnType<typeof prepareOutboundDelivery>>;
3491
+
2497
3492
  try {
2498
3493
  delivery = await prepareOutboundDelivery(this.bindings, message);
2499
3494
  } catch (error) {
@@ -2502,9 +3497,14 @@ export class MailboxDO extends DurableObject<Env> {
2502
3497
  error: errorMessage(error),
2503
3498
  });
2504
3499
  const failed = this.getEmail(id);
2505
- if (!failed) throw new Error("Failed message was not persisted");
3500
+
3501
+ if (!failed) {
3502
+ throw new Error("Failed message was not persisted", { cause: error });
3503
+ }
3504
+
2506
3505
  return failed;
2507
3506
  }
3507
+
2508
3508
  try {
2509
3509
  const result = await this.bindings.EMAIL.send(delivery);
2510
3510
  this.updateTransport(message.id, {
@@ -2518,13 +3518,17 @@ export class MailboxDO extends DurableObject<Env> {
2518
3518
  error: errorMessage(error),
2519
3519
  });
2520
3520
  }
3521
+
2521
3522
  const delivered = this.getEmail(id);
3523
+
2522
3524
  if (!delivered) throw new Error("Submitted message was not persisted");
3525
+
2523
3526
  return delivered;
2524
3527
  }
2525
3528
 
2526
3529
  private async scheduleAlarm(at: number) {
2527
3530
  const current = await this.state.storage.getAlarm();
3531
+
2528
3532
  if (current === null || current > at) await this.state.storage.setAlarm(at);
2529
3533
  }
2530
3534
 
@@ -2534,27 +3538,36 @@ export class MailboxDO extends DurableObject<Env> {
2534
3538
  */
2535
3539
  resolveParent(inReplyTo: string[], references: string[]) {
2536
3540
  const candidates = [...new Set([...inReplyTo, ...references])];
3541
+
2537
3542
  if (!candidates.length) return null;
3543
+
2538
3544
  const rows = this.db
2539
3545
  .select()
2540
3546
  .from(emails)
2541
3547
  .where(inArray(emails.messageIdHeader, candidates))
2542
3548
  .orderBy(desc(emails.timelineAt))
2543
3549
  .all();
3550
+
2544
3551
  const byMessageId = new Map<string, (typeof rows)[number]>();
3552
+
2545
3553
  for (const row of rows) {
2546
3554
  if (row.messageIdHeader && !byMessageId.has(row.messageIdHeader)) {
2547
3555
  byMessageId.set(row.messageIdHeader, row);
2548
3556
  }
2549
3557
  }
3558
+
2550
3559
  for (const messageId of inReplyTo) {
2551
3560
  const row = byMessageId.get(messageId);
3561
+
2552
3562
  if (row) return row;
2553
3563
  }
3564
+
2554
3565
  for (const messageId of references.toReversed()) {
2555
3566
  const row = byMessageId.get(messageId);
3567
+
2556
3568
  if (row) return row;
2557
3569
  }
3570
+
2558
3571
  return null;
2559
3572
  }
2560
3573
  }