@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,240 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+
3
+ import { createId, inJsonList } from "@open-workspace/core/module";
4
+ import { required } from "@open-workspace/core/shared";
5
+ import { and, eq, gte, isNotNull, lte, min, sql } from "drizzle-orm";
6
+
7
+ import {
8
+ shareSpamVerdicts,
9
+ undoWorkspaceFeedback,
10
+ } from "../mail/workspace-safety";
11
+ import type { WorkspaceVerdictUndo } from "../mail/workspace-safety";
12
+ import type { SpamVerdict } from "./placement";
13
+ import {
14
+ emails,
15
+ senderFeedback,
16
+ senders as sendersTable,
17
+ spamUndoReceipts,
18
+ } from "./schema";
19
+ import {
20
+ threads,
21
+ filingMessages,
22
+ canRestoreFiling,
23
+ restoreFiling,
24
+ } from "./spam-undo-filing";
25
+ import type { SpamFiling } from "./spam-undo-filing";
26
+ import type { MailboxContext } from "./support";
27
+
28
+ const LIFETIME_MS = 60_000;
29
+
30
+ export function nextSpamUndoExpiry(m: MailboxContext) {
31
+ const [next] = m.db
32
+ .select({ at: min(spamUndoReceipts.expiresAt) })
33
+ .from(spamUndoReceipts)
34
+ .all();
35
+
36
+ return next?.at?.getTime() ?? null;
37
+ }
38
+
39
+ export function expireSpamUndo(m: MailboxContext, now: number) {
40
+ m.db
41
+ .delete(spamUndoReceipts)
42
+ .where(lte(spamUndoReceipts.expiresAt, new Date(now)))
43
+ .run();
44
+ }
45
+
46
+ function timestamp(at: number | null) {
47
+ return at === null ? null : new Date(at);
48
+ }
49
+
50
+ type Sender = {
51
+ address: string;
52
+ trusted_at: number | null;
53
+ reported_at: number | null;
54
+ blocked_at: number | null;
55
+ feedback: string | null;
56
+ };
57
+
58
+ /**
59
+ * Each address's sender state, a row even for one never seen (raw SQL:
60
+ * `json_each` is the row source the senders table is left-joined to).
61
+ */
62
+ function senders(m: MailboxContext, addresses: string[]) {
63
+ return m.state.storage.sql
64
+ .exec<Sender>(
65
+ `select j.value as address, s.trusted_at, s.reported_at, s.blocked_at,
66
+ (select id from sender_feedback where address = j.value order by created_at desc, rowid desc limit 1) as feedback
67
+ from json_each(?) j left join senders s on s.address = j.value order by j.value`,
68
+ JSON.stringify(addresses)
69
+ )
70
+ .toArray();
71
+ }
72
+
73
+ export type SpamUndoReceipt = SpamFiling & {
74
+ sendersBefore: Sender[];
75
+ sendersAfter: Sender[];
76
+ workspace: WorkspaceVerdictUndo[];
77
+ };
78
+
79
+ /** Capture only filing and feedback, without copying message bodies or unrelated mailbox state. */
80
+ export async function withSpamUndo<
81
+ T extends {
82
+ emailIds?: readonly string[];
83
+ verdicts: SpamVerdict[];
84
+ places: { from: string; conversationId: string }[];
85
+ },
86
+ >(
87
+ m: MailboxContext,
88
+ userId: string,
89
+ ids: string[],
90
+ move: (beforeMerge: (target: string) => void) => T
91
+ ) {
92
+ const capture = m.db.transaction(() => {
93
+ const messages = filingMessages(m, ids);
94
+
95
+ const fromAddress = sql<string>`lower(json_extract(${emails.fromJson}, '$[0].address'))`;
96
+
97
+ const addresses = m.db
98
+ .selectDistinct({ address: fromAddress })
99
+ .from(emails)
100
+ .where(
101
+ and(
102
+ eq(emails.direction, "incoming"),
103
+ inJsonList(emails.conversationId, ids),
104
+ isNotNull(fromAddress)
105
+ )
106
+ )
107
+ .all();
108
+
109
+ const sendersBefore = senders(
110
+ m,
111
+ addresses.map((row) => row.address)
112
+ );
113
+
114
+ const before = new Map(threads(m, ids).map((t) => [t.id, t]));
115
+
116
+ const result = move((target) => {
117
+ if (!before.has(target)) {
118
+ for (const thread of threads(m, [target])) {
119
+ before.set(thread.id, thread);
120
+ }
121
+ }
122
+ });
123
+
124
+ if (!result.places.length) return { result, receipt: null };
125
+
126
+ const threadIds = [
127
+ ...new Set(result.places.flatMap((p) => [p.from, p.conversationId])),
128
+ ];
129
+
130
+ const threadsBefore = threadIds.flatMap((id) => before.get(id) ?? []);
131
+ const sources = new Set(result.places.map((place) => place.from));
132
+ const judged = new Set(result.verdicts.map((v) => v.address.toLowerCase()));
133
+
134
+ // A message-menu report only owns that sender's mail in the thread.
135
+ const selected = result.emailIds ? new Set(result.emailIds) : null;
136
+
137
+ const receipt: SpamUndoReceipt = {
138
+ messages: messages.filter(
139
+ (msg) =>
140
+ sources.has(msg.conversation_id) &&
141
+ (!selected || selected.has(msg.id))
142
+ ),
143
+ threadsBefore,
144
+ threadIds,
145
+ threadsAfter: threads(m, threadIds),
146
+ sendersBefore: sendersBefore.filter((s) => judged.has(s.address)),
147
+ sendersAfter: senders(m, [...judged]),
148
+ workspace: [],
149
+ };
150
+
151
+ return { result, receipt };
152
+ });
153
+
154
+ const { result: placed, receipt: saved } = capture;
155
+
156
+ if (!saved) return { ...placed, undoId: null };
157
+ const id = createId("undo");
158
+ const expiresAt = Date.now() + LIFETIME_MS;
159
+
160
+ saved.workspace = await shareSpamVerdicts(
161
+ m.env.DB,
162
+ required(m.state.id.name, "named mailbox"),
163
+ placed.verdicts,
164
+ true
165
+ );
166
+ m.db
167
+ .insert(spamUndoReceipts)
168
+ .values({ id, userId, receipt: saved, expiresAt: new Date(expiresAt) })
169
+ .run();
170
+ await m.scheduleAlarm(expiresAt);
171
+
172
+ return { ...placed, undoId: id };
173
+ }
174
+
175
+ export async function undoSpam(m: MailboxContext, userId: string, id: string) {
176
+ const [stored] = m.db
177
+ .select({ receipt: spamUndoReceipts.receipt })
178
+ .from(spamUndoReceipts)
179
+ .where(
180
+ and(
181
+ eq(spamUndoReceipts.id, id),
182
+ eq(spamUndoReceipts.userId, userId),
183
+ // The alarm may not have deleted an expired one yet.
184
+ gte(spamUndoReceipts.expiresAt, new Date())
185
+ )
186
+ )
187
+ .all();
188
+
189
+ if (!stored) return false;
190
+ const { receipt } = stored;
191
+
192
+ // A teammate's newer filing, report or trust change takes precedence.
193
+ if (
194
+ !canRestoreFiling(m, receipt) ||
195
+ !isDeepStrictEqual(
196
+ senders(
197
+ m,
198
+ receipt.sendersAfter.map((row) => row.address)
199
+ ),
200
+ receipt.sendersAfter
201
+ )
202
+ ) {
203
+ return false;
204
+ }
205
+
206
+ await undoWorkspaceFeedback(
207
+ m.env.DB,
208
+ required(m.state.id.name, "named mailbox"),
209
+ receipt.workspace
210
+ );
211
+ m.db.transaction(() => {
212
+ restoreFiling(m, receipt);
213
+
214
+ for (const sender of receipt.sendersAfter) {
215
+ if (sender.feedback) {
216
+ m.db
217
+ .delete(senderFeedback)
218
+ .where(eq(senderFeedback.id, sender.feedback))
219
+ .run();
220
+ }
221
+ }
222
+
223
+ for (const sender of receipt.sendersBefore) {
224
+ m.db
225
+ .update(sendersTable)
226
+ .set({
227
+ trustedAt: timestamp(sender.trusted_at),
228
+ reportedAt: timestamp(sender.reported_at),
229
+ })
230
+ .where(eq(sendersTable.address, sender.address))
231
+ .run();
232
+ }
233
+
234
+ m.db.delete(spamUndoReceipts).where(eq(spamUndoReceipts.id, id)).run();
235
+ });
236
+ m.forgetParticipants();
237
+ void m.announce();
238
+
239
+ return true;
240
+ }
@@ -0,0 +1,416 @@
1
+ /** Types, constants and helpers shared by MailboxDO (index.ts) and its modules. */
2
+ import type { AiModel } from "@open-workspace/core/module";
3
+ import { eq, sql } from "drizzle-orm";
4
+ import type { SQL } from "drizzle-orm";
5
+ import type { DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
6
+ import { z } from "zod";
7
+
8
+ import type { DRAFTS_FOLDER_ID } from "../../shared/folder-order";
9
+ import type { MailboxRealtimeClientMessage } from "../../shared/mail";
10
+ import type { SenderBlock } from "../../shared/mail-feedback";
11
+ import { headerValues } from "../../shared/mail-headers";
12
+ import type { ImportPlacement } from "../../shared/mail-import";
13
+ import { rawHeaderText } from "../mail/inbound";
14
+ import { customFolderPredicate, systemFolderPredicate } from "./folder-model";
15
+ import type { MailboxState, SystemFolderType } from "./folder-model";
16
+ import type { MailboxDO } from "./index";
17
+ import type { searchDrafts } from "./mailbox-drafts";
18
+ import type { SpamVerdict } from "./placement";
19
+ import {
20
+ conversations,
21
+ emailReadStates,
22
+ emails,
23
+ folders,
24
+ mailboxAiConfiguration,
25
+ mailRules,
26
+ pendingInbound,
27
+ pendingObjectDeletions,
28
+ senders,
29
+ unsubscriptions,
30
+ } from "./schema";
31
+ import type {
32
+ AutoReplySettings,
33
+ Draft,
34
+ Email,
35
+ FolderRecord,
36
+ MailRule,
37
+ PendingInbound,
38
+ } from "./schema";
39
+
40
+ export const schema = {
41
+ conversations,
42
+ emailReadStates,
43
+ emails,
44
+ folders,
45
+ mailboxAiConfiguration,
46
+ mailRules,
47
+ pendingInbound,
48
+ pendingObjectDeletions,
49
+ senders,
50
+ unsubscriptions,
51
+ };
52
+
53
+ export type MailboxDatabase = DrizzleSqliteDODatabase<typeof schema>;
54
+
55
+ /** The change counter whose inbox counts D1 has (see `syncInboxCounts`). */
56
+ export const COUNTS_VERSION_KEY = "inboxCountsVersion";
57
+
58
+ /** The version web clients were last told (see `announce`). */
59
+ export const WEB_VERSION_KEY = "webVersion";
60
+ export const INBOUND_ALARM_BATCH_SIZE = 1;
61
+ export const OBJECT_DELETION_ALARM_BATCH_SIZE = 100;
62
+ export const MAX_RETRY_DELAY_MS = 60 * 60 * 1000;
63
+
64
+ /** A raw copy not yet in the mail archive waits for the hourly archive retry. */
65
+ export const ARCHIVE_WAIT_MS = 60 * 60 * 1000;
66
+ export const MAX_INBOUND_RETRY_AGE_MS = 24 * 60 * 60 * 1000;
67
+
68
+ /** Attempts a delivery may end without an outcome (alarm killed) before it is stored unparsed. */
69
+ export const MAX_UNFINISHED_INBOUND_ATTEMPTS = 3;
70
+
71
+ export const ALARM_WAKE_DELAY_MS = 1000;
72
+
73
+ export const DAY_MS = 24 * 60 * 60 * 1000;
74
+
75
+ export type AutoReplyInput = Omit<
76
+ AutoReplySettings,
77
+ "id" | "updatedBy" | "updatedAt" | "enabled"
78
+ > & { enabled?: boolean };
79
+
80
+ /** Bounds one emptying or retention pass, so a huge Trash can't hold the object. */
81
+ export const RETENTION_BATCH_SIZE = 100;
82
+
83
+ export const PRESENCE_TTL_MS = 60_000;
84
+ export const AI_CONFIGURATION_ID = "default";
85
+
86
+ /** Per person and mailbox; a runaway client can't fill the mailbox's storage. */
87
+ export const MAX_DRAFTS_PER_USER = 200;
88
+
89
+ /** Set while imported mail has not been announced (counts, realtime, JMAP state). */
90
+ export const IMPORT_PENDING_KEY = "import:pending";
91
+
92
+ /**
93
+ * Custom folders imports created, until a restored settings line or the
94
+ * person orders them.
95
+ */
96
+ export const IMPORTED_FOLDERS_KEY = "imported-folders";
97
+
98
+ /** How long imported mail may wait to be announced when the importer does not finish. */
99
+ export const IMPORT_ANNOUNCE_DELAY_MS = 15_000;
100
+
101
+ /** Browser sessions, authorized against their session on every update. */
102
+ export const SESSION_SOCKET_TAG = "session";
103
+
104
+ /** JMAP EventSource streams held by the Worker; they receive the new state. */
105
+ export const JMAP_SOCKET_TAG = "jmap";
106
+
107
+ /** What a browser session sends: whether its tab is visible. */
108
+ export const visibilitySchema = z.enum([
109
+ "visible",
110
+ "hidden",
111
+ ]) satisfies z.ZodType<MailboxRealtimeClientMessage>;
112
+
113
+ /** Who a session socket belongs to; it survives hibernation with the socket. */
114
+ export const socketAttachmentSchema = z.object({
115
+ userId: z.string(),
116
+ sessionId: z.string(),
117
+ sessionTokenHash: z.string(),
118
+ visibility: visibilitySchema,
119
+ presenceUpdatedAt: z.number(),
120
+ });
121
+
122
+ export type MailboxSocketAttachment = z.output<typeof socketAttachmentSchema>;
123
+
124
+ /** A session socket's attachment; null for other sockets (JMAP streams carry none). */
125
+ export function socketAttachment(socket: WebSocket) {
126
+ const attachment = socketAttachmentSchema.safeParse(
127
+ socket.deserializeAttachment()
128
+ );
129
+
130
+ return attachment.success ? attachment.data : null;
131
+ }
132
+
133
+ export function errorMessage(cause: unknown) {
134
+ return cause instanceof Error ? cause.message : String(cause);
135
+ }
136
+
137
+ export function retryDelay(attempts: number) {
138
+ return Math.min(
139
+ MAX_RETRY_DELAY_MS,
140
+ 5000 * 2 ** Math.min(Math.max(attempts - 1, 0), 10)
141
+ );
142
+ }
143
+
144
+ /** Whether a delivery has been retried for as long as it may be. */
145
+ export function isPastRetryAge(job: PendingInbound, now: number) {
146
+ return now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS;
147
+ }
148
+
149
+ export function stringListJson(values: string[]) {
150
+ return JSON.stringify([...new Set(values)]);
151
+ }
152
+
153
+ /** Only an explicit JMAP follow-up removes a submitted JMAP draft. */
154
+ export type SendingDraft = { id: string; version: number; keep?: boolean };
155
+
156
+ export type DraftInput = Omit<Draft, "userId" | "version" | "updatedAt">;
157
+
158
+ export type MailboxBackupSettings = ReturnType<MailboxDO["backupSettings"]>;
159
+
160
+ export type SaveDraftResult =
161
+ | { status: "saved"; draft: Draft }
162
+ | { status: "conflict"; draft: Draft | null }
163
+ | { status: "limit" };
164
+
165
+ export type ConversationUpdate = {
166
+ mailboxState?: MailboxState;
167
+ folderId?: string | null;
168
+ };
169
+
170
+ export type ConversationCursorPosition = {
171
+ timelineAt: number;
172
+ emailId: string;
173
+ };
174
+
175
+ export const listEmailColumns = {
176
+ id: emails.id,
177
+ conversationId: emails.conversationId,
178
+ direction: emails.direction,
179
+ fromJson: emails.fromJson,
180
+ replyToJson: emails.replyToJson,
181
+ toJson: emails.toJson,
182
+ ccJson: emails.ccJson,
183
+ bccJson: emails.bccJson,
184
+ subject: emails.subject,
185
+ preview: emails.preview,
186
+ transportState: emails.transportState,
187
+ transportError: emails.transportError,
188
+ deliveryStatusJson: emails.deliveryStatusJson,
189
+ timelineAt: emails.timelineAt,
190
+ senderIntelJson: emails.senderIntelJson,
191
+ };
192
+
193
+ export type ListEmail = Pick<Email, keyof typeof listEmailColumns>;
194
+
195
+ export type ConversationListItem = {
196
+ email: ListEmail;
197
+ searchMatch: { id: string; snippet: string; quoted: boolean } | null;
198
+ messageCount: number;
199
+ unreadCount: number;
200
+ hasIncoming: boolean;
201
+ hasOutgoing: boolean;
202
+ mailboxState: MailboxState;
203
+ folderId: string | null;
204
+ /** The person has a reply draft in this conversation. */
205
+ hasDraft: boolean;
206
+ /**
207
+ * The names the conversation's senders gave, by lowercase address: your
208
+ * own reply names them by address only.
209
+ */
210
+ senderNames: Record<string, string>;
211
+ };
212
+
213
+ /** A page of a folder's list: conversations, or in Drafts the person's drafts. */
214
+ export type ConversationPage = {
215
+ items: ConversationListItem[];
216
+ drafts: ReturnType<typeof searchDrafts>["drafts"];
217
+ next: ConversationCursorPosition | null;
218
+ version: number;
219
+ };
220
+
221
+ export type SubmitOutgoingResult = {
222
+ outcome: "inserted" | "existing" | "conflict";
223
+ email: Email;
224
+ /** A reply from Spam says its senders are not spam, as Not spam does. */
225
+ verdicts?: SpamVerdict[];
226
+ };
227
+
228
+ export type InboundDeliveryInput = {
229
+ id: string;
230
+ mailboxId: string;
231
+ rawObjectKey: string;
232
+ envelopeFrom: string;
233
+ envelopeTo: string;
234
+ /** Set when this is a member's copy of mail to a workspace mailing list. */
235
+ listAddress?: string;
236
+ receivedAt: number;
237
+ };
238
+
239
+ /** Original mailbox identifiers and delivery metadata kept in a snapshot. */
240
+ export type ImportOriginal = Pick<
241
+ Email,
242
+ | "envelopeTo"
243
+ | "listId"
244
+ | "listPostAddress"
245
+ | "transportState"
246
+ | "transportError"
247
+ | "deliveryStatusJson"
248
+ > & { emailId: string; conversationId: string };
249
+
250
+ export type ImportMessageInput = {
251
+ linkedFiles?: import("./model").StoredAttachment[];
252
+ /** The import's delivery id: the message is stored as `inboundMessageId(importId)`. */
253
+ importId: string;
254
+ /** Where the route stored the raw message. */
255
+ rawObjectKey: string;
256
+ /** The mailbox's own address, which tells sent mail from received. */
257
+ mailboxAddress: string;
258
+ /** Configured aliases when the source leaves direction unspecified. */
259
+ aliases: string[];
260
+ /** When the message was received; the Date header (then now) without one. */
261
+ receivedAt: number | null;
262
+ placement: ImportPlacement;
263
+ /** A custom folder (by name, created when missing) for a message in the Inbox. */
264
+ folderName: string | null;
265
+ /** The people a received message is read for. */
266
+ seenBy: string[];
267
+ /** The conversation the importer's thread key names; null threads by Message-ID headers. */
268
+ conversationId: string | null;
269
+ /**
270
+ * The ids the message and its conversation had in this mailbox (a
271
+ * backup's): the message still here is a duplicate, and its conversation
272
+ * still here takes it instead of `conversationId`.
273
+ */
274
+ original: ImportOriginal | null;
275
+ /** Null decides by the From address. */
276
+ direction: "incoming" | "outgoing" | null;
277
+ };
278
+
279
+ export type ImportMessageResult =
280
+ | {
281
+ status: "imported";
282
+ id: string;
283
+ conversationId: string;
284
+ /** Why the requested folder was not used, if it was not. */
285
+ folderSkipped: "limit" | "invalid" | null;
286
+ }
287
+ | { status: "duplicate"; id: string; conversationId: string }
288
+ | { status: "unprocessable"; reason: string };
289
+
290
+ /** The Date header of a raw message, in ms, if it parses. */
291
+ export function headerDate(rawMime: ArrayBuffer) {
292
+ const value = headerValues(rawHeaderText(rawMime), "date")[0];
293
+ const time = value ? Date.parse(value) : Number.NaN;
294
+
295
+ return Number.isFinite(time) ? time : null;
296
+ }
297
+
298
+ export type FolderListItem = {
299
+ id: string;
300
+ name: string;
301
+ kind: "system" | "custom";
302
+ systemType: SystemFolderType | typeof DRAFTS_FOLDER_ID | null;
303
+ sortOrder: number;
304
+ totalCount: number;
305
+ unreadCount: number;
306
+ };
307
+
308
+ export type MailFolder =
309
+ | (FolderRecord & { kind: "custom"; systemType: null })
310
+ | {
311
+ id: string;
312
+ name: string;
313
+ kind: "system";
314
+ systemType: SystemFolderType;
315
+ sortOrder: number;
316
+ };
317
+
318
+ export type FolderListRow = {
319
+ id: string;
320
+ name: string;
321
+ kind: "system" | "custom";
322
+ system_type: SystemFolderType | null;
323
+ sort_order: number;
324
+ total_count: number;
325
+ unread_count: number;
326
+ };
327
+
328
+ export type FolderCounts = {
329
+ totalCount: number;
330
+ unreadCount: number;
331
+ };
332
+
333
+ export function folderMembership(folder: MailFolder) {
334
+ return folder.kind === "custom"
335
+ ? sql`${eq(conversations.folderId, folder.id)} and ${sql.raw(customFolderPredicate("conversations"))}`
336
+ : sql.raw(systemFolderPredicate(folder.systemType, "conversations"));
337
+ }
338
+
339
+ export type TransportUpdate = {
340
+ state: Email["transportState"];
341
+ messageIdHeader?: string;
342
+ error?: string | null;
343
+ };
344
+
345
+ export const MAX_RULES = 100;
346
+ export const RULE_TEST_SCAN = 500;
347
+
348
+ export function ruleView(rule: MailRule) {
349
+ return {
350
+ id: rule.id,
351
+ name: rule.name,
352
+ enabled: rule.enabled,
353
+ match: rule.match,
354
+ conditions: rule.conditionsJson,
355
+ actions: rule.actionsJson,
356
+ stopProcessing: rule.stopProcessing,
357
+ updatedAt: rule.updatedAt.getTime(),
358
+ };
359
+ }
360
+
361
+ export type InboundScreening = {
362
+ block: SenderBlock | null;
363
+ trusted: boolean;
364
+ };
365
+
366
+ export const LIKE_ESCAPE = (value: string) =>
367
+ value.replaceAll(/[\\%_]/gu, (char) => `\\${char}`);
368
+
369
+ /** SQL predicate on a lowercased address expression for a block pattern. */
370
+ export function blockPatternPredicate(expression: SQL, pattern: string) {
371
+ if (!pattern.startsWith("@")) return eq(expression, pattern);
372
+ const domain = LIKE_ESCAPE(pattern.slice(1));
373
+
374
+ return sql`(${expression} like ${`%@${domain}`} escape '\\' or ${expression} like ${`%.${domain}`} escape '\\')`;
375
+ }
376
+
377
+ /**
378
+ * What the mailbox's modules work with: its database and storage, its
379
+ * bindings, and the Durable Object's own steps they trigger.
380
+ */
381
+ export type MailboxContext = {
382
+ db: MailboxDatabase;
383
+ state: DurableObjectState;
384
+ env: Env;
385
+ /**
386
+ * The one way a change is announced. It always moves the JMAP state and
387
+ * tells JMAP streams; `web` (default) also moves the version web
388
+ * clients compare their data with, writes the inbox counts to D1 and
389
+ * tells open apps; `push` (default) also tells push subscribers.
390
+ * `delivered` says new mail arrived, which JMAP clients hear of as an
391
+ * EmailDelivery change. Settles once D1 has the counts (at once
392
+ * without `web`).
393
+ */
394
+ announce: (options?: {
395
+ web?: boolean;
396
+ push?: boolean;
397
+ delivered?: boolean;
398
+ /** False when only the D1 version needs advancing. */
399
+ inboxChanged?: boolean;
400
+ }) => Promise<void>;
401
+ scheduleAlarm: (at: number) => Promise<void>;
402
+ scheduleRetention: () => void;
403
+ getEmail: (id: string) => Email | null;
404
+ resolveParent: (inReplyTo: string[], references: string[]) => Email | null;
405
+ /** Participant suggestions are read again after a change. */
406
+ forgetParticipants: () => void;
407
+ getEmailByMessageId: (messageIdHeader: string) => Email | null;
408
+ /** The AI model that classifies incoming mail; tests replace it. */
409
+ classificationModel: () => Promise<AiModel | null>;
410
+ /** When an unfinished delivery is tried again; the alarm keeps it. */
411
+ noteAttemptAlarm: (at: number) => void;
412
+ /** The change counter web clients compare their data with: moved only by an announcement they hear. */
413
+ version: () => number;
414
+ /** Messages being handed to Email Sending now; one send each at a time. */
415
+ sending: Set<string>;
416
+ };