@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
@@ -0,0 +1,313 @@
1
+ import {
2
+ oauthScopeAnyOf,
3
+ requireAuth,
4
+ requestPermissions,
5
+ createDb,
6
+ mailboxAddressSql,
7
+ mailboxKind,
8
+ mailboxKindOrderSql,
9
+ mailboxAccess,
10
+ mailboxes,
11
+ apiError,
12
+ zValidator,
13
+ } from "@open-workspace/core/module";
14
+ import type { Database, AppEnv } from "@open-workspace/core/module";
15
+ import { eq } from "drizzle-orm";
16
+ import { Hono } from "hono";
17
+ import type { Context } from "hono";
18
+ import { z } from "zod";
19
+
20
+ import {
21
+ importPlacements,
22
+ MAX_IMPORT_KEY_LENGTH,
23
+ MAX_IMPORT_MESSAGE_BYTES,
24
+ } from "../../shared/mail-import";
25
+ import {
26
+ IMPORT_MAIL,
27
+ IMPORT_MAIL_SCOPE,
28
+ MAIL_ORGANIZE_SCOPE,
29
+ } from "../../shared/permissions";
30
+ import { mailboxStub } from "../mailbox";
31
+ import { readCappedBody } from "./capped-body";
32
+ import { rawMessageId } from "./inbound";
33
+
34
+ /**
35
+ * Importing existing mail (the `open-workspace import` CLI).
36
+ *
37
+ * Who may import where:
38
+ * - A person holding the "Import mail" permission (`import_mail`; every
39
+ * administrator) may import into any mailbox, personal or team. An app
40
+ * needs the `admin.import_mail` scope for that.
41
+ * - Anyone else may import only into their own personal mailboxes (those
42
+ * they own, primary or not), not into team mailboxes they share: imported
43
+ * mail is shown as received, so only its owner may add to it. An app
44
+ * needs `mail.organize` for that.
45
+ */
46
+
47
+ const importQuerySchema = z.object({
48
+ /** The message's id at its source; importing the same id again does nothing. */
49
+ sourceId: z.string().min(1).max(MAX_IMPORT_KEY_LENGTH),
50
+ placement: z.enum(importPlacements).default("inbox"),
51
+ /** A custom folder for a message in the Inbox, created when missing. */
52
+ folder: z.string().trim().min(1).max(80).optional(),
53
+ /** "1" when the message was read (for everyone who can open the mailbox). */
54
+ seen: z.enum(["0", "1"]).default("0"),
55
+ /** The source's thread id: messages with the same key are one conversation. */
56
+ thread: z.string().min(1).max(MAX_IMPORT_KEY_LENGTH).optional(),
57
+ /** When the message was received: epoch ms or an ISO date; else its Date header. */
58
+ receivedAt: z
59
+ .string()
60
+ .max(40)
61
+ .optional()
62
+ .transform((value, context) => {
63
+ if (value === undefined) return null;
64
+ const time = /^\d+$/u.test(value) ? Number(value) : Date.parse(value);
65
+
66
+ if (!Number.isFinite(time)) {
67
+ context.addIssue({
68
+ code: "custom",
69
+ message: "receivedAt must be epoch milliseconds or an ISO date",
70
+ });
71
+
72
+ return z.NEVER;
73
+ }
74
+
75
+ return time;
76
+ }),
77
+ /** Without it, mail from the mailbox's own address counts as sent. */
78
+ direction: z.enum(["incoming", "outgoing"]).optional(),
79
+ });
80
+
81
+ async function sha256Hex(value: string) {
82
+ const digest = await crypto.subtle.digest(
83
+ "SHA-256",
84
+ new TextEncoder().encode(value)
85
+ );
86
+
87
+ return [...new Uint8Array(digest)]
88
+ .map((byte) => byte.toString(16).padStart(2, "0"))
89
+ .join("");
90
+ }
91
+
92
+ /** A mailbox's import target: where it is and who can open it. */
93
+ async function importMailbox(db: Database, mailboxId: string) {
94
+ const [mailbox] = await db
95
+ .select({
96
+ id: mailboxes.id,
97
+ address: mailboxAddressSql,
98
+ ownerUserId: mailboxes.ownerUserId,
99
+ })
100
+ .from(mailboxes)
101
+ .where(eq(mailboxes.id, mailboxId))
102
+ .limit(1);
103
+
104
+ return mailbox ?? null;
105
+ }
106
+
107
+ /**
108
+ * Whether this request may import into any mailbox, not just the person's
109
+ * own: the person holds the permission and, for an app, so does its token.
110
+ */
111
+ function importsAnywhere(c: Context<AppEnv>) {
112
+ return requestPermissions(c).includes(IMPORT_MAIL);
113
+ }
114
+
115
+ /** Whether an app's token may import into its person's own mailboxes. */
116
+ function organizes(c: Context<AppEnv>) {
117
+ return (
118
+ c.get("authKind") !== "oauth" ||
119
+ c.get("oauthScopes").includes(MAIL_ORGANIZE_SCOPE)
120
+ );
121
+ }
122
+
123
+ /** The mailbox if this request may import into it, else the refusal. */
124
+ async function authorizedMailbox(c: Context<AppEnv>, mailboxId: string) {
125
+ const mailbox = await importMailbox(createDb(c.env.DB), mailboxId);
126
+
127
+ if (
128
+ mailbox &&
129
+ (importsAnywhere(c) ||
130
+ (mailbox.ownerUserId === c.get("user").id && organizes(c)))
131
+ ) {
132
+ return mailbox;
133
+ }
134
+
135
+ return apiError(
136
+ c,
137
+ 403,
138
+ "FORBIDDEN",
139
+ "You may not import mail into this mailbox"
140
+ );
141
+ }
142
+
143
+ class TooLargeError extends Error {}
144
+
145
+ /** The request body, refusing one larger than `limit` without reading it all. */
146
+ async function boundedBody(request: Request, limit: number) {
147
+ const declared = Number(request.headers.get("content-length") ?? Number.NaN);
148
+
149
+ if (declared > limit) throw new TooLargeError();
150
+
151
+ if (!request.body) return new Uint8Array();
152
+ const body = await readCappedBody(request.body, limit);
153
+
154
+ if (!body) throw new TooLargeError();
155
+
156
+ return body;
157
+ }
158
+
159
+ export const mailImportRoutes = new Hono<AppEnv>()
160
+ .use("*", requireAuth)
161
+ .use("*", oauthScopeAnyOf(MAIL_ORGANIZE_SCOPE, IMPORT_MAIL_SCOPE))
162
+ /** The mailboxes this request may import into, for mapping source accounts to them. */
163
+ .get("/mailboxes", async (c) => {
164
+ const db = createDb(c.env.DB);
165
+ const anywhere = importsAnywhere(c);
166
+
167
+ if (!anywhere && !organizes(c)) {
168
+ return c.json({ ok: true as const, mailboxes: [] });
169
+ }
170
+
171
+ const rows = await db
172
+ .select({
173
+ id: mailboxes.id,
174
+ address: mailboxAddressSql,
175
+ displayName: mailboxes.displayName,
176
+ ownerUserId: mailboxes.ownerUserId,
177
+ teamId: mailboxes.teamId,
178
+ delivery: mailboxes.delivery,
179
+ })
180
+ .from(mailboxes)
181
+ .where(anywhere ? undefined : eq(mailboxes.ownerUserId, c.get("user").id))
182
+ .orderBy(mailboxKindOrderSql, mailboxAddressSql);
183
+
184
+ return c.json({
185
+ ok: true as const,
186
+ mailboxes: rows
187
+ // A mailing list keeps no mail of its own.
188
+ .filter((row) => row.delivery === "inbox")
189
+ .map((row) => ({
190
+ id: row.id,
191
+ address: row.address,
192
+ displayName: row.displayName,
193
+ kind: mailboxKind(row.ownerUserId),
194
+ ownerUserId: row.ownerUserId,
195
+ teamId: row.teamId,
196
+ })),
197
+ });
198
+ })
199
+ .post(
200
+ "/mailboxes/:id/messages",
201
+ zValidator("query", importQuerySchema),
202
+ async (c) => {
203
+ const target = await authorizedMailbox(c, c.req.param("id"));
204
+
205
+ if (target instanceof Response) return target;
206
+ const input = c.req.valid("query");
207
+ let raw: Uint8Array;
208
+
209
+ try {
210
+ raw = await boundedBody(c.req.raw, MAX_IMPORT_MESSAGE_BYTES);
211
+ } catch (error) {
212
+ if (!(error instanceof TooLargeError)) throw error;
213
+
214
+ return apiError(
215
+ c,
216
+ 413,
217
+ "TOO_LARGE",
218
+ `Messages are limited to ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB, the size Email Routing delivers`
219
+ );
220
+ }
221
+
222
+ if (!raw.byteLength) {
223
+ return apiError(
224
+ c,
225
+ 400,
226
+ "BAD_REQUEST",
227
+ "The body must be the raw message (message/rfc822)"
228
+ );
229
+ }
230
+
231
+ const mailbox = mailboxStub(c.env, target.id);
232
+ const importId = `imp_${(await sha256Hex(input.sourceId)).slice(0, 32)}`;
233
+ const known = await mailbox.findImported(importId, rawMessageId(raw));
234
+
235
+ if (known) {
236
+ return c.json({
237
+ ok: true as const,
238
+ duplicate: true as const,
239
+ ...known,
240
+ });
241
+ }
242
+
243
+ const rawObjectKey = `mailboxes/${target.id}/raw/${importId}.eml`;
244
+ await c.env.MAIL_STORAGE.put(rawObjectKey, raw, {
245
+ httpMetadata: { contentType: "message/rfc822" },
246
+ });
247
+
248
+ const seenBy =
249
+ input.seen === "1"
250
+ ? (
251
+ await createDb(c.env.DB)
252
+ .select({ userId: mailboxAccess.userId })
253
+ .from(mailboxAccess)
254
+ .where(eq(mailboxAccess.mailboxId, target.id))
255
+ ).map((row) => row.userId)
256
+ : [];
257
+
258
+ const result = await mailbox.importMessage({
259
+ importId,
260
+ rawObjectKey,
261
+ mailboxAddress: target.address,
262
+ receivedAt: input.receivedAt,
263
+ placement: input.placement,
264
+ folderName: input.folder ?? null,
265
+ seenBy,
266
+ conversationId: input.thread
267
+ ? `conv_imp_${(await sha256Hex(input.thread)).slice(0, 32)}`
268
+ : null,
269
+ direction: input.direction ?? null,
270
+ });
271
+
272
+ if (result.status === "unprocessable") {
273
+ return apiError(
274
+ c,
275
+ 422,
276
+ "UNPROCESSABLE",
277
+ `The message could not be read: ${result.reason}`
278
+ );
279
+ }
280
+
281
+ if (result.status === "duplicate") {
282
+ return c.json({
283
+ ok: true as const,
284
+ duplicate: true as const,
285
+ id: result.id,
286
+ conversationId: result.conversationId,
287
+ });
288
+ }
289
+
290
+ return c.json(
291
+ {
292
+ ok: true as const,
293
+ duplicate: false as const,
294
+ id: result.id,
295
+ conversationId: result.conversationId,
296
+ folderSkipped: result.folderSkipped,
297
+ },
298
+ 201
299
+ );
300
+ }
301
+ )
302
+ /**
303
+ * Announces what was imported (inbox counts, open apps, JMAP state) once.
304
+ * Imports announce themselves within seconds anyway; this does it now.
305
+ */
306
+ .post("/mailboxes/:id/finish", async (c) => {
307
+ const target = await authorizedMailbox(c, c.req.param("id"));
308
+
309
+ if (target instanceof Response) return target;
310
+ const { version } = await mailboxStub(c.env, target.id).finishImport();
311
+
312
+ return c.json({ ok: true as const, version });
313
+ });
@@ -1,5 +1,8 @@
1
- import { bytesToBase64Url } from "@open-workspace/core/worker/lib/crypto.ts";
2
- import { normalizeEmail, normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
1
+ import {
2
+ bytesToBase64Url,
3
+ normalizeEmail,
4
+ normalizeMailboxAddress,
5
+ } from "@open-workspace/core/module";
3
6
 
4
7
  export async function inboundDeliveryId(input: {
5
8
  mailboxId: string;
@@ -7,16 +10,23 @@ export async function inboundDeliveryId(input: {
7
10
  envelopeTo: string;
8
11
  raw: ArrayBuffer;
9
12
  }) {
10
- const prefix = new TextEncoder().encode([
11
- input.mailboxId,
12
- normalizeEmail(input.envelopeFrom),
13
- normalizeMailboxAddress(input.envelopeTo),
14
- "",
15
- ].join("\0"));
16
- const rawDigest = new Uint8Array(await crypto.subtle.digest("SHA-256", input.raw));
13
+ const prefix = new TextEncoder().encode(
14
+ [
15
+ input.mailboxId,
16
+ normalizeEmail(input.envelopeFrom),
17
+ normalizeMailboxAddress(input.envelopeTo),
18
+ "",
19
+ ].join("\0")
20
+ );
21
+
22
+ const rawDigest = new Uint8Array(
23
+ await crypto.subtle.digest("SHA-256", input.raw)
24
+ );
25
+
17
26
  const digestInput = new Uint8Array(prefix.byteLength + rawDigest.byteLength);
18
27
  digestInput.set(prefix);
19
28
  digestInput.set(rawDigest, prefix.byteLength);
20
29
  const digest = await crypto.subtle.digest("SHA-256", digestInput);
30
+
21
31
  return `in_${bytesToBase64Url(new Uint8Array(digest))}`;
22
32
  }
@@ -1,4 +1,5 @@
1
- import { normalizeEmail } from "@open-workspace/core/worker/lib/ids.ts";
1
+ import { normalizeEmail } from "@open-workspace/core/module";
2
+
2
3
  import type { MailAddress } from "../mailbox/model";
3
4
  import type { Email } from "../mailbox/schema";
4
5
  import { normalizedParticipantSet } from "./participants";
@@ -23,26 +24,35 @@ export function shouldDetachInboundReply(input: {
23
24
  const { parent } = input;
24
25
  const normalizedListId = input.listId?.trim().toLocaleLowerCase() ?? null;
25
26
  const parentListId = parent.listId?.trim().toLocaleLowerCase() ?? null;
27
+
26
28
  if (parent.listId && parentListId !== normalizedListId) return true;
27
29
 
28
30
  const parentParticipants = normalizedParticipantSet(
29
31
  [...parent.fromJson, ...parent.toJson, ...parent.ccJson].map(
30
- (participant) => participant.address,
32
+ (participant) => participant.address
31
33
  ),
32
- input.ownAddress,
34
+ input.ownAddress
33
35
  );
36
+
34
37
  const incomingParticipants = normalizedParticipantSet(
35
38
  [...input.from, ...input.to, ...input.cc].map(
36
- (participant) => participant.address,
39
+ (participant) => participant.address
37
40
  ),
38
- input.ownAddress,
41
+ input.ownAddress
39
42
  );
43
+
40
44
  const parentWasGroup = Boolean(parent.listId) || parentParticipants.size > 1;
41
- const incomingIsDirect = input.listId === null && incomingParticipants.size === 1;
45
+
46
+ const incomingIsDirect =
47
+ input.listId === null && incomingParticipants.size === 1;
48
+
42
49
  if (parentWasGroup && incomingIsDirect) return true;
43
50
 
44
51
  const hiddenRecipients = new Set(
45
- parent.bccJson.map((recipient) => normalizeEmail(recipient.address)),
52
+ parent.bccJson.map((recipient) => normalizeEmail(recipient.address))
53
+ );
54
+
55
+ return input.from.some((sender) =>
56
+ hiddenRecipients.has(normalizeEmail(sender.address))
46
57
  );
47
- return input.from.some((sender) => hiddenRecipients.has(normalizeEmail(sender.address)));
48
58
  }
@@ -1,7 +1,7 @@
1
- import PostalMime, { type Address, type Email as ParsedEmail } from "postal-mime";
2
- import { convert } from "html-to-text";
1
+ import { createId, normalizeMailboxAddress } from "@open-workspace/core/module";
2
+ import type { Address, Email as ParsedEmail } from "postal-mime";
3
+
3
4
  import { headerValues } from "../../shared/mail-headers";
4
- import { createId, normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
5
5
  import type { MailAddress, StoredAttachment } from "../mailbox/model";
6
6
  import type { Email, NewEmail, PendingInbound } from "../mailbox/schema";
7
7
  import { inboundHeaderMetadata } from "./auth-headers";
@@ -22,13 +22,16 @@ function flattenAddresses(values: Address[] | undefined): MailAddress[] {
22
22
  ? value.group.map((mailbox) => address(mailbox.address, mailbox.name))
23
23
  : value.address
24
24
  ? [address(value.address, value.name)]
25
- : [],
25
+ : []
26
26
  );
27
27
  }
28
28
 
29
29
  function attachmentBytes(content: ArrayBuffer | Uint8Array | string) {
30
- if (typeof content === "string") return new TextEncoder().encode(content);
31
- return content instanceof Uint8Array ? content : new Uint8Array(content);
30
+ if (content instanceof Uint8Array) return content;
31
+
32
+ if (content instanceof ArrayBuffer) return new Uint8Array(content);
33
+
34
+ return new TextEncoder().encode(content);
32
35
  }
33
36
 
34
37
  export class UnprocessableInboundEmailError extends Error {
@@ -49,42 +52,56 @@ const MAX_HEADER_SCAN_BYTES = 256 * 1024;
49
52
 
50
53
  /** The header section of a raw message as text; bodies are never needed here. */
51
54
  export function rawHeaderText(rawMime: ArrayBuffer | Uint8Array) {
52
- const bytes = rawMime instanceof Uint8Array ? rawMime : new Uint8Array(rawMime);
55
+ const bytes =
56
+ rawMime instanceof Uint8Array ? rawMime : new Uint8Array(rawMime);
57
+
53
58
  return new TextDecoder().decode(bytes.subarray(0, MAX_HEADER_SCAN_BYTES));
54
59
  }
55
60
 
56
61
  /** The Message-ID of a raw message, read from its headers alone. */
57
62
  export function rawMessageId(rawMime: ArrayBuffer | Uint8Array) {
58
- return messageIds(headerValues(rawHeaderText(rawMime), "message-id")[0])[0] ?? null;
63
+ return (
64
+ messageIds(headerValues(rawHeaderText(rawMime), "message-id")[0])[0] ?? null
65
+ );
59
66
  }
60
67
 
61
68
  /** RFC 2919 list identifier: design@example.com is design.example.com. */
62
- export function listIdFor(address: string) {
63
- return normalizeMailboxAddress(address).replace("@", ".");
69
+ export function listIdFor(listAddress: string) {
70
+ return normalizeMailboxAddress(listAddress).replace("@", ".");
64
71
  }
65
72
 
66
73
  export function inboundMessageId(deliveryId: string) {
67
74
  return `msg_${deliveryId.replaceAll(/[^a-zA-Z0-9_-]/gu, "_")}`;
68
75
  }
69
76
 
77
+ /**
78
+ * MIME parsing and HTML-to-text conversion load with the first delivery a
79
+ * Worker instance processes; the code is large and most requests do not.
80
+ */
81
+ const postalMime = () => import("postal-mime").then((module) => module.default);
82
+
70
83
  async function parseMime(bytes: ArrayBuffer): Promise<ParsedEmail> {
84
+ const PostalMime = await postalMime();
85
+
71
86
  try {
72
87
  return await PostalMime.parse(bytes);
73
88
  } catch (error) {
74
89
  throw new UnprocessableInboundEmailError(
75
90
  "The original message could not be parsed",
76
- { cause: error },
91
+ { cause: error }
77
92
  );
78
93
  }
79
94
  }
80
95
 
81
96
  export async function readInboundRawMime(env: Env, job: PendingInbound) {
82
97
  const raw = await env.MAIL_STORAGE.get(job.rawObjectKey);
98
+
83
99
  if (!raw) {
84
100
  // The durable queue is committed before the R2 upload, so an alarm can
85
101
  // briefly win that race. Missing storage remains retryable.
86
102
  throw new MissingRawMimeError();
87
103
  }
104
+
88
105
  return raw.arrayBuffer();
89
106
  }
90
107
 
@@ -95,6 +112,7 @@ export function prepareUnprocessableInboundEmail(input: {
95
112
  }): NewEmail {
96
113
  const messageId = inboundMessageId(input.job.id);
97
114
  const fromAddress = input.job.envelopeFrom || "unknown@invalid";
115
+
98
116
  return {
99
117
  id: messageId,
100
118
  conversationId: createId("conv"),
@@ -130,10 +148,21 @@ export function prepareUnprocessableInboundEmail(input: {
130
148
  };
131
149
  }
132
150
 
151
+ /** What parsing a delivery reads of it: a queued delivery, or an imported message. */
152
+ export type InboundMessageSource = Pick<
153
+ PendingInbound,
154
+ | "id"
155
+ | "rawObjectKey"
156
+ | "envelopeFrom"
157
+ | "envelopeTo"
158
+ | "listAddress"
159
+ | "receivedAt"
160
+ >;
161
+
133
162
  export async function prepareInboundEmail(input: {
134
163
  env: Env;
135
164
  mailboxId: string;
136
- job: PendingInbound;
165
+ job: InboundMessageSource;
137
166
  rawMime: ArrayBuffer;
138
167
  resolveParent: (inReplyTo: string[], references: string[]) => Email | null;
139
168
  }): Promise<{ email: NewEmail; linkDomains: string[] }> {
@@ -144,18 +173,22 @@ export async function prepareInboundEmail(input: {
144
173
  const parent = input.resolveParent(inReplyTo, references);
145
174
  const recipient = normalizeMailboxAddress(job.envelopeTo);
146
175
  const from = flattenAddresses(parsed.from ? [parsed.from] : []);
176
+
147
177
  if (!from.length) from.push(address(job.envelopeFrom || "unknown@invalid"));
148
178
  const to = flattenAddresses(parsed.to);
149
179
  const cc = flattenAddresses(parsed.cc);
150
180
  const bcc = flattenAddresses(parsed.bcc);
151
181
  const replyTo = flattenAddresses(parsed.replyTo);
182
+
152
183
  // A workspace mailing list is the latest list hop, so it names the list.
153
184
  const parsedListId = job.listAddress
154
185
  ? listIdFor(job.listAddress)
155
186
  : listId(parsed.headers);
156
- const parsedListPost = job.listAddress ?? listPostAddress(
157
- headerValue(parsed.headers, "list-post"),
158
- );
187
+
188
+ const parsedListPost =
189
+ job.listAddress ??
190
+ listPostAddress(headerValue(parsed.headers, "list-post"));
191
+
159
192
  const detached = parent
160
193
  ? shouldDetachInboundReply({
161
194
  ownAddress: recipient,
@@ -166,11 +199,13 @@ export async function prepareInboundEmail(input: {
166
199
  listId: parsedListId,
167
200
  })
168
201
  : false;
202
+
169
203
  const messageId = inboundMessageId(job.id);
204
+
170
205
  const plainBody = parsed.text?.trim()
171
206
  ? parsed.text
172
207
  : parsed.html
173
- ? convert(parsed.html, {
208
+ ? (await import("html-to-text")).convert(parsed.html, {
174
209
  wordwrap: false,
175
210
  selectors: [
176
211
  { selector: "img", format: "skip" },
@@ -178,42 +213,48 @@ export async function prepareInboundEmail(input: {
178
213
  ],
179
214
  })
180
215
  : "";
216
+
181
217
  const replyText = parseReplyText(plainBody);
218
+
182
219
  const bodyHtmlR2Key = parsed.html
183
220
  ? `mailboxes/${input.mailboxId}/messages/${messageId}/body.html`
184
221
  : null;
222
+
185
223
  if (bodyHtmlR2Key && parsed.html) {
186
224
  await input.env.MAIL_STORAGE.put(bodyHtmlR2Key, parsed.html, {
187
225
  httpMetadata: { contentType: "text/html; charset=utf-8" },
188
226
  });
189
227
  }
190
228
 
191
- const attachments: StoredAttachment[] = [];
192
- for (const [index, file] of parsed.attachments.entries()) {
193
- const id = `att_${messageId}_${index}`;
194
- const r2Key =
195
- `mailboxes/${input.mailboxId}/messages/${messageId}/attachments/${id}`;
196
- const bytes = attachmentBytes(file.content);
197
- await input.env.MAIL_STORAGE.put(r2Key, bytes, {
198
- httpMetadata: { contentType: file.mimeType },
199
- });
200
- attachments.push({
201
- id,
202
- r2Key,
203
- filename: file.filename || "attachment",
204
- contentType: file.mimeType,
205
- size: bytes.byteLength,
206
- contentId: file.contentId ?? null,
207
- disposition: file.disposition === "inline" ? "inline" : "attachment",
208
- delivery: "attached",
209
- downloadTokenHash: null,
210
- downloadExpiresAt: null,
211
- });
212
- }
229
+ // Each attachment is its own R2 object, so they are stored concurrently.
230
+ const attachments = await Promise.all(
231
+ parsed.attachments.map(async (file, index): Promise<StoredAttachment> => {
232
+ const id = `att_${messageId}_${index}`;
233
+ const r2Key = `mailboxes/${input.mailboxId}/messages/${messageId}/attachments/${id}`;
234
+ const bytes = attachmentBytes(file.content);
235
+ await input.env.MAIL_STORAGE.put(r2Key, bytes, {
236
+ httpMetadata: { contentType: file.mimeType },
237
+ });
238
+
239
+ return {
240
+ id,
241
+ r2Key,
242
+ filename: file.filename || "attachment",
243
+ contentType: file.mimeType,
244
+ size: bytes.byteLength,
245
+ contentId: file.contentId ?? null,
246
+ disposition: file.disposition === "inline" ? "inline" : "attachment",
247
+ delivery: "attached",
248
+ downloadTokenHash: null,
249
+ downloadExpiresAt: null,
250
+ };
251
+ })
252
+ );
213
253
 
214
254
  const email: NewEmail = {
215
255
  id: messageId,
216
- conversationId: parent && !detached ? parent.conversationId : createId("conv"),
256
+ conversationId:
257
+ parent && !detached ? parent.conversationId : createId("conv"),
217
258
  direction: "incoming",
218
259
  messageIdHeader: messageIds(parsed.messageId)[0] ?? null,
219
260
  inReplyToJson: inReplyTo,
@@ -224,7 +265,7 @@ export async function prepareInboundEmail(input: {
224
265
  ccJson: cc,
225
266
  bccJson: bcc,
226
267
  subject: parsed.subject?.trim() || "(no subject)",
227
- preview: replyText.bodyText.replace(/\s+/gu, " ").trim().slice(0, 220),
268
+ preview: replyText.bodyText.replaceAll(/\s+/gu, " ").trim().slice(0, 220),
228
269
  bodyText: replyText.bodyText,
229
270
  quotedText: replyText.quotedText,
230
271
  bodyHtmlR2Key,
@@ -243,6 +284,7 @@ export async function prepareInboundEmail(input: {
243
284
  transportState: "received",
244
285
  deliveryStatusJson: [],
245
286
  };
287
+
246
288
  return {
247
289
  email,
248
290
  // Over-collect: workspace domains are filtered out once D1 has been read.