@open-workspace/email 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,336 @@
1
+ /** A mailbox's rules for new mail, and its AI sorting settings. */
2
+ import {
3
+ aiFeatureEnabled,
4
+ createDb,
5
+ createId,
6
+ } from "@open-workspace/core/module";
7
+ import { mailboxAccess } from "@open-workspace/core/schema";
8
+ import { asc, desc, eq } from "drizzle-orm";
9
+
10
+ import { evaluateRules, ruleMatches } from "../mail/rules";
11
+ import type { RuleInput, RuleOutcome } from "../mail/rules";
12
+ import * as mailboxFolders from "./mailbox-folders";
13
+ import type { MailboxAiConfiguration } from "./model";
14
+ import { emails, folders, mailboxAiConfiguration, mailRules } from "./schema";
15
+ import type { MailRule, NewEmail } from "./schema";
16
+ import type { MailboxContext } from "./support";
17
+ import {
18
+ AI_CONFIGURATION_ID,
19
+ MAX_RULES,
20
+ RULE_TEST_SCAN,
21
+ ruleView,
22
+ } from "./support";
23
+
24
+ export function aiConfiguration(m: MailboxContext) {
25
+ const stored = m.db
26
+ .select()
27
+ .from(mailboxAiConfiguration)
28
+ .where(eq(mailboxAiConfiguration.id, AI_CONFIGURATION_ID))
29
+ .all()[0];
30
+
31
+ return stored
32
+ ? {
33
+ instructions: stored.instructions,
34
+ confidenceThreshold: stored.confidenceThreshold,
35
+ }
36
+ : {
37
+ instructions: "",
38
+ confidenceThreshold: 75,
39
+ };
40
+ }
41
+
42
+ function customFolderIds(m: MailboxContext) {
43
+ return new Set(
44
+ m.db
45
+ .select({ id: folders.id })
46
+ .from(folders)
47
+ .all()
48
+ .map((folder) => folder.id)
49
+ );
50
+ }
51
+
52
+ /** `folderDeleted`: a "Move to folder" action whose folder is gone, so it files nothing. */
53
+ export function listRules(m: MailboxContext) {
54
+ const custom = customFolderIds(m);
55
+
56
+ return m.db
57
+ .select()
58
+ .from(mailRules)
59
+ .orderBy(asc(mailRules.position))
60
+ .all()
61
+ .map((rule) => ({
62
+ ...ruleView(rule),
63
+ folderDeleted: rule.actionsJson.some(
64
+ (action) =>
65
+ action.type === "moveToFolder" && !custom.has(action.folderId)
66
+ ),
67
+ }));
68
+ }
69
+
70
+ /**
71
+ * A "Move to folder" action needs a custom folder that exists, unless the
72
+ * rule already had it: a rule whose folder was deleted can still be
73
+ * renamed or switched off.
74
+ */
75
+ export function ruleFolderError(
76
+ m: MailboxContext,
77
+ input: Pick<RuleInput, "actions">,
78
+ kept: readonly string[] = []
79
+ ) {
80
+ return input.actions.some(
81
+ (action) =>
82
+ action.type === "moveToFolder" &&
83
+ !kept.includes(action.folderId) &&
84
+ mailboxFolders.getFolder(m, action.folderId)?.kind !== "custom"
85
+ )
86
+ ? "Move to folder needs an existing custom folder"
87
+ : null;
88
+ }
89
+
90
+ export function createRule(m: MailboxContext, input: RuleInput) {
91
+ const error = ruleFolderError(m, input);
92
+
93
+ if (error) return { status: "invalid" as const, error };
94
+
95
+ const existing = m.db
96
+ .select({ position: mailRules.position })
97
+ .from(mailRules)
98
+ .all();
99
+
100
+ if (existing.length >= MAX_RULES) return { status: "limit" as const };
101
+
102
+ const rule: MailRule = {
103
+ id: createId("rule"),
104
+ position: Math.max(0, ...existing.map((row) => row.position)) + 1,
105
+ name: input.name,
106
+ enabled: input.enabled,
107
+ match: input.match,
108
+ conditionsJson: input.conditions,
109
+ actionsJson: input.actions,
110
+ stopProcessing: input.stopProcessing,
111
+ updatedAt: new Date(),
112
+ };
113
+
114
+ m.db.insert(mailRules).values(rule).run();
115
+
116
+ return { status: "ok" as const, rule: ruleView(rule) };
117
+ }
118
+
119
+ export function updateRule(
120
+ m: MailboxContext,
121
+ id: string,
122
+ input: Omit<RuleInput, "enabled">
123
+ ) {
124
+ const stored = m.db
125
+ .select({ actions: mailRules.actionsJson })
126
+ .from(mailRules)
127
+ .where(eq(mailRules.id, id))
128
+ .all()[0];
129
+
130
+ if (!stored) return { status: "not_found" as const };
131
+
132
+ const error = ruleFolderError(
133
+ m,
134
+ input,
135
+ stored.actions.flatMap((action) =>
136
+ action.type === "moveToFolder" ? [action.folderId] : []
137
+ )
138
+ );
139
+
140
+ if (error) return { status: "invalid" as const, error };
141
+
142
+ const [updated] = m.db
143
+ .update(mailRules)
144
+ .set({
145
+ name: input.name,
146
+ match: input.match,
147
+ conditionsJson: input.conditions,
148
+ actionsJson: input.actions,
149
+ stopProcessing: input.stopProcessing,
150
+ updatedAt: new Date(),
151
+ })
152
+ .where(eq(mailRules.id, id))
153
+ .returning()
154
+ .all();
155
+
156
+ if (!updated) return { status: "not_found" as const };
157
+
158
+ return { status: "ok" as const, rule: ruleView(updated) };
159
+ }
160
+
161
+ export function setRuleEnabled(
162
+ m: MailboxContext,
163
+ id: string,
164
+ enabled: boolean
165
+ ) {
166
+ return (
167
+ m.db
168
+ .update(mailRules)
169
+ .set({ enabled, updatedAt: new Date() })
170
+ .where(eq(mailRules.id, id))
171
+ .returning({ id: mailRules.id })
172
+ .get() !== undefined
173
+ );
174
+ }
175
+
176
+ export function deleteRule(m: MailboxContext, id: string) {
177
+ return (
178
+ m.db
179
+ .delete(mailRules)
180
+ .where(eq(mailRules.id, id))
181
+ .returning({ id: mailRules.id })
182
+ .all().length > 0
183
+ );
184
+ }
185
+
186
+ export function reorderRules(m: MailboxContext, ruleIds: string[]) {
187
+ const current = m.db.select({ id: mailRules.id }).from(mailRules).all();
188
+
189
+ if (
190
+ current.length !== ruleIds.length ||
191
+ new Set(ruleIds).size !== ruleIds.length ||
192
+ !current.every((row) => ruleIds.includes(row.id))
193
+ ) {
194
+ return false;
195
+ }
196
+
197
+ m.db.transaction((tx) => {
198
+ for (const [index, id] of ruleIds.entries()) {
199
+ tx.update(mailRules)
200
+ .set({ position: index + 1 })
201
+ .where(eq(mailRules.id, id))
202
+ .run();
203
+ }
204
+ });
205
+
206
+ return true;
207
+ }
208
+
209
+ /** How many of the latest incoming messages the conditions match; changes nothing. */
210
+ export function testRule(
211
+ m: MailboxContext,
212
+ rule: Pick<RuleInput, "match" | "conditions">
213
+ ) {
214
+ const recent = m.db
215
+ .select({
216
+ id: emails.id,
217
+ conversationId: emails.conversationId,
218
+ timelineAt: emails.timelineAt,
219
+ subject: emails.subject,
220
+ fromJson: emails.fromJson,
221
+ toJson: emails.toJson,
222
+ ccJson: emails.ccJson,
223
+ envelopeTo: emails.envelopeTo,
224
+ listId: emails.listId,
225
+ attachmentsJson: emails.attachmentsJson,
226
+ })
227
+ .from(emails)
228
+ .where(eq(emails.direction, "incoming"))
229
+ .orderBy(desc(emails.timelineAt))
230
+ .limit(RULE_TEST_SCAN)
231
+ .all();
232
+
233
+ const matches = recent.filter((email) => ruleMatches(rule, email));
234
+
235
+ return {
236
+ scanned: recent.length,
237
+ matches: matches.length,
238
+ sample: matches.slice(0, 5).map((email) => ({
239
+ id: email.id,
240
+ conversationId: email.conversationId,
241
+ subject: email.subject,
242
+ from: email.fromJson[0]?.address ?? null,
243
+ timelineAt: email.timelineAt.getTime(),
244
+ })),
245
+ };
246
+ }
247
+
248
+ /** The rules' verdict on a live delivery, or null when none matches. */
249
+ export function inboundRules(
250
+ m: MailboxContext,
251
+ email: NewEmail,
252
+ jobId: string
253
+ ) {
254
+ let outcome: RuleOutcome;
255
+
256
+ try {
257
+ // Only a matching Move action needs the folders, once per delivery.
258
+ let custom: Set<string> | undefined;
259
+ outcome = evaluateRules(
260
+ m.db
261
+ .select()
262
+ .from(mailRules)
263
+ .where(eq(mailRules.enabled, true))
264
+ .orderBy(asc(mailRules.position))
265
+ .all()
266
+ .map(ruleView),
267
+ {
268
+ fromJson: email.fromJson ?? [],
269
+ toJson: email.toJson ?? [],
270
+ ccJson: email.ccJson ?? [],
271
+ envelopeTo: email.envelopeTo ?? null,
272
+ subject: email.subject ?? "",
273
+ listId: email.listId ?? null,
274
+ attachmentsJson: email.attachmentsJson ?? [],
275
+ },
276
+ (id) => (custom ??= customFolderIds(m)).has(id)
277
+ );
278
+ } catch (error) {
279
+ // A broken rule never holds up the delivery.
280
+ console.error(`Rules failed for inbound delivery ${jobId}`, error);
281
+
282
+ return null;
283
+ }
284
+
285
+ return outcome.matchedRuleIds.length ? outcome : null;
286
+ }
287
+
288
+ /** Everyone with access to the mailbox: whom "Mark read" marks mail read for. */
289
+ export async function mailboxReaders(m: MailboxContext) {
290
+ const members = await createDb(m.env.DB)
291
+ .select({ userId: mailboxAccess.userId })
292
+ .from(mailboxAccess)
293
+ .where(eq(mailboxAccess.mailboxId, m.state.id.name ?? ""));
294
+
295
+ return members.map((member) => member.userId);
296
+ }
297
+
298
+ export function getMailboxAiSettings(m: MailboxContext) {
299
+ return {
300
+ configuration: aiConfiguration(m),
301
+ globalEnabled: aiFeatureEnabled("classification"),
302
+ };
303
+ }
304
+
305
+ export function setMailboxAiConfiguration(
306
+ m: MailboxContext,
307
+ configuration: MailboxAiConfiguration
308
+ ) {
309
+ if (
310
+ configuration.confidenceThreshold < 50 ||
311
+ configuration.confidenceThreshold > 100 ||
312
+ configuration.instructions.length > 4000
313
+ ) {
314
+ throw new Error("Invalid mailbox AI configuration");
315
+ }
316
+
317
+ m.db
318
+ .insert(mailboxAiConfiguration)
319
+ .values({
320
+ id: AI_CONFIGURATION_ID,
321
+ instructions: configuration.instructions.trim(),
322
+ confidenceThreshold: configuration.confidenceThreshold,
323
+ updatedAt: new Date(),
324
+ })
325
+ .onConflictDoUpdate({
326
+ target: mailboxAiConfiguration.id,
327
+ set: {
328
+ instructions: configuration.instructions.trim(),
329
+ confidenceThreshold: configuration.confidenceThreshold,
330
+ updatedAt: new Date(),
331
+ },
332
+ })
333
+ .run();
334
+
335
+ return getMailboxAiSettings(m);
336
+ }
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Sender safety: blocks, trust, reports, unsubscribes, and taking mail out
3
+ * of Spam back into its conversation.
4
+ */
5
+ import { inJsonList } from "@open-workspace/core/module";
6
+ import { and, eq, isNotNull, isNull, or, sql } from "drizzle-orm";
7
+
8
+ import type { Unsubscription } from "../../shared/mail-feedback";
9
+ import type { SenderIntel } from "./model";
10
+ import { blocksForLeavingSpam, fileSpam, leaveSpam } from "./placement";
11
+ import { emails, senders, unsubscriptions } from "./schema";
12
+ import {
13
+ blockFromPattern,
14
+ listBlockedSenders as listBlockedSenderRows,
15
+ senderHistory,
16
+ senderStatuses,
17
+ setSenderBlocked,
18
+ setSenderTrusted as storeSenderTrusted,
19
+ } from "./senders";
20
+ import { withSpamUndo } from "./spam-undo";
21
+ import type { MailboxContext } from "./support";
22
+ import { blockPatternPredicate } from "./support";
23
+
24
+ /**
25
+ * Fills sender intelligence in on view: for a message without any, or
26
+ * replacing the failed result checked at `replacesCheckedAt`.
27
+ */
28
+ export function setEmailSenderIntel(
29
+ m: MailboxContext,
30
+ emailId: string,
31
+ intel: SenderIntel,
32
+ replacesCheckedAt: number | null = null
33
+ ) {
34
+ const current =
35
+ replacesCheckedAt === null
36
+ ? isNull(emails.senderIntelJson)
37
+ : sql`json_extract(${emails.senderIntelJson}, '$.checkedAt') = ${replacesCheckedAt}`;
38
+
39
+ return (
40
+ m.db
41
+ .update(emails)
42
+ .set({ senderIntelJson: intel })
43
+ .where(
44
+ and(eq(emails.id, emailId), eq(emails.direction, "incoming"), current)
45
+ )
46
+ .returning({ id: emails.id })
47
+ .all().length > 0
48
+ );
49
+ }
50
+
51
+ /** Inbound/outbound counters for the given addresses (lowercased keys). */
52
+ export function getSenderHistory(m: MailboxContext, addresses: string[]) {
53
+ return Object.fromEntries(senderHistory(m.db, addresses));
54
+ }
55
+
56
+ /** Block, trust and report state for senders, and unsubscribe records for lists. */
57
+ export function getMessageSafetyContext(
58
+ m: MailboxContext,
59
+ addresses: string[],
60
+ listKeys: string[]
61
+ ) {
62
+ const rows = m.db
63
+ .select()
64
+ .from(unsubscriptions)
65
+ .where(inJsonList(unsubscriptions.listKey, listKeys))
66
+ .all();
67
+
68
+ return {
69
+ senders: Object.fromEntries(senderStatuses(m.db, addresses)),
70
+ unsubscriptions: Object.fromEntries(
71
+ rows.map((row) => [
72
+ row.listKey,
73
+ {
74
+ listKey: row.listKey,
75
+ method: row.method,
76
+ status: row.status,
77
+ target: row.target,
78
+ at: row.createdAt.getTime(),
79
+ },
80
+ ])
81
+ ),
82
+ };
83
+ }
84
+
85
+ export function recordUnsubscription(
86
+ m: MailboxContext,
87
+ input: {
88
+ listKey: string;
89
+ emailId: string;
90
+ method: Unsubscription["method"];
91
+ status: Unsubscription["status"];
92
+ target: string | null;
93
+ detail: string | null;
94
+ userId: string;
95
+ }
96
+ ) {
97
+ const createdAt = new Date();
98
+ const values = { ...input, createdAt };
99
+ m.db
100
+ .insert(unsubscriptions)
101
+ .values(values)
102
+ .onConflictDoUpdate({ target: unsubscriptions.listKey, set: values })
103
+ .run();
104
+ void m.announce({ inboxChanged: false });
105
+
106
+ return {
107
+ listKey: input.listKey,
108
+ method: input.method,
109
+ status: input.status,
110
+ target: input.target,
111
+ at: createdAt.getTime(),
112
+ };
113
+ }
114
+
115
+ /**
116
+ * Moves the received mail the pattern blocks (its From or envelope sender,
117
+ * as `senderBlockFor` decides) to Spam, without the rest of its
118
+ * conversations (`fileSpam`). Where it went, for each conversation.
119
+ */
120
+ function moveSenderConversationsToSpam(m: MailboxContext, pattern: string) {
121
+ const from = blockPatternPredicate(
122
+ sql`lower(json_extract(${emails.fromJson}, '$[0].address'))`,
123
+ pattern
124
+ );
125
+
126
+ const envelope = blockPatternPredicate(
127
+ sql`lower(trim(${emails.envelopeFrom}))`,
128
+ pattern
129
+ );
130
+
131
+ const matching = m.db
132
+ .select({ id: emails.id })
133
+ .from(emails)
134
+ .where(and(eq(emails.direction, "incoming"), or(from, envelope)))
135
+ .all()
136
+ .map((row) => row.id);
137
+
138
+ const { places } = fileSpam(m, { emailIds: matching }, null);
139
+
140
+ if (places.length) m.scheduleRetention();
141
+
142
+ return places;
143
+ }
144
+
145
+ export function blockSender(
146
+ m: MailboxContext,
147
+ pattern: string,
148
+ moveExisting: boolean
149
+ ) {
150
+ const places = m.db.transaction(() => {
151
+ setSenderBlocked(m.db, pattern, Date.now());
152
+
153
+ return moveExisting ? moveSenderConversationsToSpam(m, pattern) : [];
154
+ });
155
+
156
+ m.forgetParticipants();
157
+ void m.announce({ inboxChanged: places.length > 0 });
158
+
159
+ return { block: blockFromPattern(pattern, Date.now(), false), places };
160
+ }
161
+
162
+ /** For a workspace-wide block: existing mail goes to Spam; the block itself lives in D1. */
163
+ export function moveSenderToSpam(m: MailboxContext, pattern: string) {
164
+ const moved = moveSenderConversationsToSpam(m, pattern).length;
165
+
166
+ if (moved) {
167
+ m.forgetParticipants();
168
+ void m.announce();
169
+ }
170
+
171
+ return moved;
172
+ }
173
+
174
+ export function unblockSender(m: MailboxContext, pattern: string) {
175
+ const unblocked = m.db
176
+ .update(senders)
177
+ .set({ blockedAt: null })
178
+ .where(and(eq(senders.address, pattern), isNotNull(senders.blockedAt)))
179
+ .returning({ address: senders.address })
180
+ .get();
181
+
182
+ m.forgetParticipants();
183
+ void m.announce({ inboxChanged: false });
184
+
185
+ return Boolean(unblocked);
186
+ }
187
+
188
+ export function listBlockedSenders(m: MailboxContext) {
189
+ return listBlockedSenderRows(m.db);
190
+ }
191
+
192
+ export function setSenderTrusted(
193
+ m: MailboxContext,
194
+ address: string,
195
+ trusted: boolean
196
+ ) {
197
+ storeSenderTrusted(m.db, address, trusted, Date.now());
198
+ void m.announce({ inboxChanged: false });
199
+
200
+ return true;
201
+ }
202
+
203
+ /**
204
+ * Report spam, of messages or of conversations' received mail: labels it,
205
+ * records feedback for the classifier, and moves it to Spam with the
206
+ * senders' other mail in the thread, without the rest of it (`fileSpam`).
207
+ * Null when the requested message is missing or outgoing.
208
+ */
209
+ export async function reportSpam(
210
+ m: MailboxContext,
211
+ input: ({ emailId: string } | { conversationIds: string[] }) & {
212
+ userId: string;
213
+ }
214
+ ) {
215
+ const { userId } = input;
216
+
217
+ let outcome;
218
+
219
+ if ("emailId" in input) {
220
+ const email = m.db
221
+ .select({ conversationId: emails.conversationId })
222
+ .from(emails)
223
+ .where(
224
+ and(eq(emails.id, input.emailId), eq(emails.direction, "incoming"))
225
+ )
226
+ .get();
227
+
228
+ if (!email) return null;
229
+ outcome = await withSpamUndo(m, userId, [email.conversationId], () =>
230
+ fileSpam(m, { emailIds: [input.emailId] }, userId)
231
+ );
232
+ } else {
233
+ outcome = {
234
+ ...m.db.transaction(() => fileSpam(m, input, userId)),
235
+ undoId: null,
236
+ };
237
+ }
238
+
239
+ const { places, verdicts, undoId } = outcome;
240
+
241
+ if (places.length) {
242
+ m.forgetParticipants();
243
+ void m.announce();
244
+ m.scheduleRetention();
245
+ }
246
+
247
+ return { places, verdicts, undoId };
248
+ }
249
+
250
+ /**
251
+ * "Not spam", of messages or of the conversations they are in: those
252
+ * conversations still in Spam go back to the Inbox as `leaveSpam` takes
253
+ * them, each sender trusted unless the mail is blocked. Null when none
254
+ * was in Spam.
255
+ */
256
+ export async function markNotSpam(
257
+ m: MailboxContext,
258
+ input: (
259
+ | { emailIds: readonly string[] }
260
+ | { conversationIds: readonly string[] }
261
+ ) & { userId: string; trustSenders: boolean }
262
+ ) {
263
+ const { userId, trustSenders, ...scope } = input;
264
+
265
+ // Re-read inside the transaction: messages may move while fetching workspace blocks.
266
+ const conversationIds = () =>
267
+ "conversationIds" in scope
268
+ ? scope.conversationIds
269
+ : m.db
270
+ .selectDistinct({ id: emails.conversationId })
271
+ .from(emails)
272
+ .where(inJsonList(emails.id, [...scope.emailIds]))
273
+ .all()
274
+ .map((row) => row.id);
275
+
276
+ const workspaceBlocks = await blocksForLeavingSpam(m, [
277
+ { conversationIds: conversationIds(), mailboxState: "active" },
278
+ ]);
279
+
280
+ const outcome = m.db.transaction(() =>
281
+ leaveSpam(
282
+ m,
283
+ conversationIds(),
284
+ { mailboxState: "active" },
285
+ { userId, trustSenders, workspaceBlocks }
286
+ )
287
+ );
288
+
289
+ if (!outcome.places.length) return null;
290
+ m.forgetParticipants();
291
+ void m.announce();
292
+
293
+ return outcome;
294
+ }