@open-workspace/email 0.2.0 → 0.4.0

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