@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,123 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Email Routing's destination addresses: where a `forward` address may send
5
+ * mail. Cloudflare emails each new destination a link, and forwards to it
6
+ * only once that link was followed.
7
+ *
8
+ * The Worker calls the API with the token `Email()` mints (alchemy/index.ts).
9
+ * `alchemy dev` binds none, so locally `emailRoutingApi` is null: no
10
+ * destination is created and none counts as confirmed. The stack tests bind
11
+ * placeholders and answer these requests like any outgoing request
12
+ * (test/stack/fake-email-routing.ts).
13
+ */
14
+ const API_BASE = "https://api.cloudflare.com/client/v4";
15
+
16
+ /** Pages of destinations read at most; an account rarely has more than a few. */
17
+ const MAX_PAGES = 20;
18
+
19
+ const PER_PAGE = 50;
20
+
21
+ const destinationsPage = z.object({
22
+ success: z.boolean(),
23
+ result: z
24
+ .array(
25
+ z.object({
26
+ email: z.string(),
27
+ // When the destination followed its confirmation link; null until then.
28
+ verified: z.string().nullish(),
29
+ })
30
+ )
31
+ .nullish(),
32
+ });
33
+
34
+ export type DestinationStatus = "confirmed" | "waiting";
35
+
36
+ function emailRoutingApi(env: Env) {
37
+ const accountId = env.EMAIL_ROUTING_ACCOUNT_ID;
38
+ const token = env.EMAIL_ROUTING_API_TOKEN;
39
+
40
+ if (!accountId || !token) return null;
41
+
42
+ return {
43
+ url: `${API_BASE}/accounts/${encodeURIComponent(accountId)}/email/routing/addresses`,
44
+ headers: { authorization: `Bearer ${token}` },
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Every destination address of the account, by lowercase address; null when
50
+ * Email Routing isn't connected (local development).
51
+ */
52
+ export async function destinationStatuses(env: Env) {
53
+ const api = emailRoutingApi(env);
54
+
55
+ if (!api) return null;
56
+ const statuses = new Map<string, DestinationStatus>();
57
+
58
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
59
+ // oxlint-disable-next-line eslint/no-await-in-loop -- each page says whether there is another
60
+ const response = await fetch(
61
+ `${api.url}?page=${page}&per_page=${PER_PAGE}`,
62
+ { headers: api.headers }
63
+ );
64
+
65
+ if (!response.ok) {
66
+ throw new Error(
67
+ `Email Routing answered ${response.status} listing destinations`
68
+ );
69
+ }
70
+
71
+ // oxlint-disable-next-line eslint/no-await-in-loop -- each page says whether there is another
72
+ const body = destinationsPage.parse(await response.json());
73
+ const rows = body.result ?? [];
74
+
75
+ for (const row of rows) {
76
+ statuses.set(
77
+ row.email.toLowerCase(),
78
+ row.verified ? "confirmed" : "waiting"
79
+ );
80
+ }
81
+
82
+ if (rows.length < PER_PAGE) break;
83
+ }
84
+
85
+ return statuses;
86
+ }
87
+
88
+ /**
89
+ * Adds the addresses Email Routing doesn't have yet as destinations, so
90
+ * Cloudflare emails each one its confirmation link. Throws if one fails.
91
+ */
92
+ export async function createDestinations(env: Env, addresses: string[]) {
93
+ const api = emailRoutingApi(env);
94
+ const known = await destinationStatuses(env);
95
+
96
+ if (!api || !known) return;
97
+
98
+ const results = await Promise.allSettled(
99
+ addresses
100
+ .flatMap((email) => (known.has(email.toLowerCase()) ? [] : [email]))
101
+ .map(async (email) => {
102
+ const response = await fetch(api.url, {
103
+ method: "POST",
104
+ headers: { ...api.headers, "content-type": "application/json" },
105
+ body: JSON.stringify({ email }),
106
+ });
107
+
108
+ if (!response.ok) {
109
+ throw new Error(
110
+ `Email Routing answered ${response.status} adding ${email}`
111
+ );
112
+ }
113
+ })
114
+ );
115
+
116
+ const failed = results.flatMap((result) =>
117
+ result.status === "rejected" ? [result.reason] : []
118
+ );
119
+
120
+ if (failed.length) {
121
+ throw new AggregateError(failed, "Some forward destinations weren't added");
122
+ }
123
+ }
@@ -0,0 +1,114 @@
1
+ import {
2
+ apiError,
3
+ mayManageAddress,
4
+ createDb,
5
+ requireAuth,
6
+ } from "@open-workspace/core/module";
7
+ import type { AppEnv } from "@open-workspace/core/module";
8
+ import { mailboxes } from "@open-workspace/core/schema";
9
+ import { eq } from "drizzle-orm";
10
+ import { Hono } from "hono";
11
+ import type { Context } from "hono";
12
+
13
+ import { createDestinations, destinationStatuses } from "./email-routing";
14
+
15
+ async function forwardAddress(db: D1Database, mailboxId: string) {
16
+ const [row] = await createDb(db)
17
+ .select({
18
+ ownerUserId: mailboxes.ownerUserId,
19
+ delivery: mailboxes.delivery,
20
+ forwardTo: mailboxes.forwardTo,
21
+ })
22
+ .from(mailboxes)
23
+ .where(eq(mailboxes.id, mailboxId))
24
+ .limit(1);
25
+
26
+ return row ?? null;
27
+ }
28
+
29
+ /**
30
+ * Core's `mailboxSaved` hook: a forward's destinations that Email Routing
31
+ * doesn't know yet are added, and Cloudflare emails each its confirmation.
32
+ */
33
+ export async function addForwardDestinations(env: Env, mailboxId: string) {
34
+ const address = await forwardAddress(env.DB, mailboxId);
35
+
36
+ if (address?.delivery === "forward" && address.forwardTo?.length) {
37
+ await createDestinations(env, address.forwardTo);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * A forward's saved destinations, if the signed-in person manages the
43
+ * address: null when it doesn't exist, false when they may not manage it.
44
+ */
45
+ async function managedForward(c: Context<AppEnv>, mailboxId: string) {
46
+ const address = await forwardAddress(c.env.DB, mailboxId);
47
+
48
+ if (!address) return null;
49
+
50
+ // Managed like the address itself, never by its owner alone: a person's
51
+ // forwards are set under People.
52
+ if (!(await mayManageAddress(c, createDb(c.env.DB), address))) {
53
+ return false;
54
+ }
55
+
56
+ return address.delivery === "forward" ? (address.forwardTo ?? []) : [];
57
+ }
58
+
59
+ const notFound = "Address not found";
60
+ const forbidden = "You do not have permission to manage this address";
61
+
62
+ /**
63
+ * A forward's saved destinations for the address editor under People or
64
+ * Teams, which only people who manage that address see: whether each
65
+ * confirmed Cloudflare's email, or is missing from Email Routing because
66
+ * adding it failed. Saving the address in the editor adds missing ones
67
+ * again (POST), so a failure shows there instead of only in the logs.
68
+ */
69
+ export const forwardDestinationRoutes = new Hono<AppEnv>()
70
+ .use("*", requireAuth)
71
+ .get("/:mailboxId", async (c) => {
72
+ const forwardTo = await managedForward(c, c.req.param("mailboxId"));
73
+
74
+ if (forwardTo === null) return apiError(c, 404, "NOT_FOUND", notFound);
75
+
76
+ if (forwardTo === false) return apiError(c, 403, "FORBIDDEN", forbidden);
77
+
78
+ const statuses = forwardTo.length ? await destinationStatuses(c.env) : null;
79
+
80
+ return c.json({
81
+ ok: true as const,
82
+ /** False in local development, where there is no Email Routing. */
83
+ connected: statuses !== null || !forwardTo.length,
84
+ destinations: forwardTo.map((email) => ({
85
+ email,
86
+ /** Null when Email Routing isn't connected. */
87
+ status: statuses
88
+ ? (statuses.get(email.toLowerCase()) ?? ("missing" as const))
89
+ : null,
90
+ })),
91
+ });
92
+ })
93
+ .post("/:mailboxId", async (c) => {
94
+ const forwardTo = await managedForward(c, c.req.param("mailboxId"));
95
+
96
+ if (forwardTo === null) return apiError(c, 404, "NOT_FOUND", notFound);
97
+
98
+ if (forwardTo === false) return apiError(c, 403, "FORBIDDEN", forbidden);
99
+
100
+ try {
101
+ await createDestinations(c.env, forwardTo);
102
+ } catch (error) {
103
+ console.error("Could not add forward destinations", error);
104
+
105
+ return apiError(
106
+ c,
107
+ 502,
108
+ "BAD_GATEWAY",
109
+ "Cloudflare didn't add the forward destinations; save again to retry"
110
+ );
111
+ }
112
+
113
+ return c.json({ ok: true as const });
114
+ });
@@ -0,0 +1,115 @@
1
+ import { linkedAttachmentTextToken } from "../../shared/mail";
2
+ import type { StoredAttachment } from "../mailbox/model";
3
+ import { storedDownloadUrls } from "./download-links";
4
+
5
+ type Reference = { placeholder: string | null; filename: string };
6
+
7
+ /** The quoted copy of a Workspace download must follow the file selection and the new message's expiry. */
8
+ export async function forwardDownloads(
9
+ sourceText: string,
10
+ sourceHtml: string,
11
+ source: readonly StoredAttachment[],
12
+ selected: ReadonlyMap<string, string>
13
+ ) {
14
+ let text = sourceText;
15
+ let html = sourceHtml;
16
+
17
+ const owned = new Map(
18
+ source.flatMap((file) =>
19
+ file.downloadTokenHash ? [[file.downloadTokenHash, file] as const] : []
20
+ )
21
+ );
22
+
23
+ if (!owned.size) return { text, html };
24
+ const references = new Map<string, Reference>();
25
+
26
+ for (const { url, hash } of await storedDownloadUrls(text, html)) {
27
+ const file = owned.get(hash);
28
+
29
+ if (file) {
30
+ references.set(url, {
31
+ placeholder: selected.get(file.id) ?? null,
32
+ filename: file.filename,
33
+ });
34
+ }
35
+ }
36
+
37
+ if (!references.size) return { text, html };
38
+
39
+ const textMarker = (ref: Reference) =>
40
+ ref.placeholder ? linkedAttachmentTextToken(ref.placeholder) : "";
41
+
42
+ const htmlMarker = (ref: Reference) =>
43
+ ref.placeholder
44
+ ? `<span data-linked-attachment="${ref.placeholder}"></span>`
45
+ : "";
46
+
47
+ // Replace generated footers as a block so their old expiry and removed
48
+ // filenames disappear. Footers belonging to other messages stay intact.
49
+ const footer = (
50
+ urls: string[],
51
+ original: string,
52
+ marker: (ref: Reference) => string
53
+ ) => {
54
+ const refs = urls.map((url) => references.get(url));
55
+
56
+ if (!refs.length || refs.some((ref) => !ref)) return original;
57
+
58
+ return refs
59
+ .flatMap((ref) => (ref ? [marker(ref)] : []))
60
+ .filter(Boolean)
61
+ .join("\n");
62
+ };
63
+
64
+ text = text.replaceAll(
65
+ /Attachments \(download links expire [\d-]+\):(?:\r?\n- [^\n]*)+/gu,
66
+ (block) =>
67
+ footer(
68
+ block
69
+ .split(/\r?\n/u)
70
+ .slice(1)
71
+ .map((line) => line.slice(line.lastIndexOf(": ") + 2)),
72
+ block,
73
+ textMarker
74
+ )
75
+ );
76
+ html = html.replaceAll(
77
+ /<p>Attachments \(download links expire [\d-]+\):<\/p>\s*<ul>.*?<\/ul>/gsu,
78
+ (block) =>
79
+ footer(
80
+ [...block.matchAll(/href="([^"]+)"/gu)].map((match) => match[1]),
81
+ block,
82
+ htmlMarker
83
+ )
84
+ );
85
+
86
+ // forwardHtmlContent has sanitized these anchors. Replace the full card, including
87
+ // its old caption, before resolving the forward's links alongside new uploads.
88
+ html = html.replaceAll(
89
+ /<a href="([^"]+)">[\s\S]*?<\/a>/gu,
90
+ (anchor, url: string) => {
91
+ const ref = references.get(url);
92
+
93
+ if (!ref) return anchor;
94
+
95
+ return htmlMarker(ref);
96
+ }
97
+ );
98
+
99
+ for (const [url, ref] of references) {
100
+ const marker = textMarker(ref);
101
+ text = text
102
+ .replaceAll(`${ref.filename}: ${url}`, () => marker)
103
+ .replaceAll(url, () => marker);
104
+ // HTML-only mail can also display a URL as plain text.
105
+ html = html.replaceAll(
106
+ /(^|>)([^<]+)/gu,
107
+ (node, start: string, content: string) =>
108
+ content.includes(url)
109
+ ? start + content.replaceAll(url, () => htmlMarker(ref))
110
+ : node
111
+ );
112
+ }
113
+
114
+ return { text: text.trimEnd(), html };
115
+ }
@@ -0,0 +1,85 @@
1
+ import sanitizeHtml from "sanitize-html";
2
+
3
+ import { escapeHtml, safeLink } from "../../shared/mail-html";
4
+
5
+ /** Preserve safe text formatting in the quoted HTML and link destinations in the plain alternative. */
6
+ export function forwardHtmlContent(sourceHtml: string, sourceText: string) {
7
+ const links = new Map<string, string>();
8
+
9
+ // Only the text layout and clickable links go into the forward. Original
10
+ // inline images already travel as attachments, and remote resources stay out.
11
+ const html = sanitizeHtml(sourceHtml, {
12
+ allowedTags: [
13
+ "a",
14
+ "b",
15
+ "blockquote",
16
+ "br",
17
+ "code",
18
+ "div",
19
+ "em",
20
+ "h1",
21
+ "h2",
22
+ "h3",
23
+ "h4",
24
+ "h5",
25
+ "h6",
26
+ "i",
27
+ "li",
28
+ "ol",
29
+ "p",
30
+ "pre",
31
+ "s",
32
+ "strong",
33
+ "table",
34
+ "tbody",
35
+ "td",
36
+ "tfoot",
37
+ "th",
38
+ "thead",
39
+ "tr",
40
+ "u",
41
+ "ul",
42
+ ],
43
+ allowedAttributes: {
44
+ a: ["href"],
45
+ td: ["rowspan", "colspan"],
46
+ th: ["rowspan", "colspan"],
47
+ },
48
+ nonTextTags: ["head", "script", "style", "textarea", "option", "noscript"],
49
+ exclusiveFilter(frame) {
50
+ if (frame.tag !== "a") return false;
51
+ const href = frame.attribs.href?.trim();
52
+
53
+ if (!href || !safeLink(href)) return "excludeTag";
54
+ const label = frame.text.trim();
55
+
56
+ if (label || !links.has(href)) links.set(href, label);
57
+
58
+ // A linked image may be the entire button. Its destination still needs visible text.
59
+ return !label;
60
+ },
61
+ });
62
+
63
+ if (!links.size && !html.replaceAll(/<[^>]*>/gu, "").trim()) return null;
64
+ const mentioned = new Set(sourceText.split(/\s+/u));
65
+
66
+ const missing = [...links].flatMap(([href, label]) =>
67
+ mentioned.has(href) ||
68
+ mentioned.has(`[${href}]`) ||
69
+ mentioned.has(`<${href}>`)
70
+ ? []
71
+ : [label && label !== href ? `${label}: ${href}` : href]
72
+ );
73
+
74
+ const imageLinks = [...links].flatMap(([href, label]) => {
75
+ if (label) return [];
76
+ const url = escapeHtml(href);
77
+
78
+ return [`<div><a href="${url}">${url}</a></div>`];
79
+ });
80
+
81
+ return {
82
+ html: html + imageLinks.join(""),
83
+ text: [sourceText, ...missing].join("\n"),
84
+ };
85
+ }
@@ -1,4 +1,3 @@
1
- import type { InboundAuthentication } from "../../shared/mail-authentication";
2
1
  import type { SenderIntel } from "../../shared/mail-sender-intel";
3
2
  import type { mailboxStub } from "../mailbox";
4
3
  import type { Email } from "../mailbox/schema";
@@ -9,9 +8,7 @@ import {
9
8
  storedSenderIntel,
10
9
  } from "./sender-intel";
11
10
 
12
- export function headerAuthentication(
13
- email: Email
14
- ): InboundAuthentication | null {
11
+ export function headerAuthentication(email: Email) {
15
12
  const stored = email.authenticationResultsJson;
16
13
 
17
14
  return stored?.version === 1 ? stored : null;
@@ -66,7 +63,7 @@ export async function withSenderIntel(
66
63
  mailbox: ReturnType<typeof mailboxStub>,
67
64
  email: Email,
68
65
  context: SenderIntelContext
69
- ): Promise<Email> {
66
+ ) {
70
67
  if (!senderIntelPending(email)) return email;
71
68
  const key = `${mailbox.id.toString()}:${email.id}`;
72
69
  let work = inFlight.get(key);