@open-workspace/email 0.4.1 → 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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,243 @@
1
+ import { normalizeEmail } from "@open-workspace/core/module";
2
+
3
+ import type { MailboxState } from "../../shared/mail";
4
+ import type { AutoReplySettings, Email } from "../mailbox/schema";
5
+ import { replyThreadHeaders } from "./rfc";
6
+ import { isEmptyRichContent } from "./rich-content";
7
+ import type { RichContentInput } from "./rich-content";
8
+ import { mailboxPrefix } from "./storage-keys";
9
+
10
+ /** Replies a mailbox may send in one hour, whatever else allows them. */
11
+ export const AUTO_REPLY_HOURLY_CAP = 50;
12
+
13
+ /** Only the start of a message is read for its headers; bodies never are. */
14
+ const HEADER_SCAN_BYTES = 64 * 1024;
15
+
16
+ /** Where a mailbox's auto-reply images live; they go with the mailbox's objects. */
17
+ export function autoReplyImagePrefix(mailboxId: string) {
18
+ return `${mailboxPrefix(mailboxId)}auto-reply/`;
19
+ }
20
+
21
+ export function autoReplyStatus(
22
+ settings: Pick<AutoReplySettings, "enabled" | "startsAt" | "endsAt"> | null,
23
+ now: Date
24
+ ) {
25
+ if (!settings?.enabled) return "off";
26
+
27
+ if (settings.startsAt && now < settings.startsAt) return "scheduled";
28
+
29
+ if (settings.endsAt && now >= settings.endsAt) return "ended";
30
+
31
+ return "active";
32
+ }
33
+
34
+ /** A disabled reply can be saved while its messages are still being written. */
35
+ export function autoReplyContentError(
36
+ enabled: boolean,
37
+ messages: Record<
38
+ "inside" | "outside",
39
+ RichContentInput & { enabled: boolean }
40
+ >
41
+ ) {
42
+ if (!enabled) return null;
43
+
44
+ if (!messages.inside.enabled && !messages.outside.enabled) {
45
+ return "Turn on the message for people inside or outside the workspace";
46
+ }
47
+
48
+ for (const who of ["inside", "outside"] as const) {
49
+ if (messages[who].enabled && isEmptyRichContent(messages[who])) {
50
+ return `Write the message for people ${who} the workspace`;
51
+ }
52
+ }
53
+
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * The top-level header block, names lowercased and repeated headers joined
59
+ * with ", ". At most HEADER_SCAN_BYTES are decoded.
60
+ */
61
+ export function parseHeaderBlock(raw: ArrayBuffer) {
62
+ const text = new TextDecoder("latin1").decode(
63
+ raw.slice(0, HEADER_SCAN_BYTES)
64
+ );
65
+
66
+ const end = text.search(/\r?\n\r?\n/u);
67
+
68
+ const block = (end === -1 ? text : text.slice(0, end)).replaceAll(
69
+ /\r?\n[ \t]+/gu,
70
+ " "
71
+ );
72
+
73
+ const headers = new Map<string, string>();
74
+
75
+ for (const line of block.split(/\r?\n/u)) {
76
+ const colon = line.indexOf(":");
77
+
78
+ if (colon <= 0) continue;
79
+ const name = line.slice(0, colon).trim().toLowerCase();
80
+ const value = line.slice(colon + 1).trim();
81
+ const previous = headers.get(name);
82
+
83
+ headers.set(name, previous === undefined ? value : `${previous}, ${value}`);
84
+ }
85
+
86
+ return headers;
87
+ }
88
+
89
+ const SYSTEM_LOCAL_PART =
90
+ /^(?:mailer-daemon|postmaster|no-?reply|do-?not-?reply|bounces?(?:[+._-].*)?)$/iu;
91
+
92
+ /**
93
+ * RFC 3834 and common-practice checks that depend only on the message and
94
+ * how it was delivered: why it gets no reply, or null when it may get one.
95
+ * Mail delivered to the mailbox directly, through an alias or a plus
96
+ * address may be answered. Mail the catch-all took isn't: the reply would
97
+ * come from the mailbox's own address, handing it to whoever guessed at
98
+ * the domain. A copy of a workspace mailing list's post (`listAddress`)
99
+ * never is.
100
+ */
101
+ export function messageSkipReason(input: {
102
+ headers: Map<string, string>;
103
+ envelopeFrom: string;
104
+ /** The address the message was delivered to (the envelope recipient). */
105
+ deliveredTo: string;
106
+ /** The mailbox's address and its aliases, lowercased. */
107
+ ownAddresses: readonly string[];
108
+ listAddress: string | null;
109
+ /** Where its conversation is now. */
110
+ mailboxState: MailboxState | undefined;
111
+ email: Pick<Email, "attachmentsJson">;
112
+ }) {
113
+ const { headers } = input;
114
+
115
+ // Spam, and mail a rule discarded; Archive and folders still get a reply.
116
+ if (input.mailboxState === "spam" || input.mailboxState === "trash") {
117
+ return input.mailboxState;
118
+ }
119
+
120
+ if (input.listAddress) return "mailing list copy";
121
+
122
+ const delivered = input.deliveredTo.trim().toLowerCase();
123
+ const at = delivered.lastIndexOf("@");
124
+ const plus = delivered.indexOf("+");
125
+
126
+ // `sam+shop@` reached `sam@`.
127
+ const base =
128
+ plus > 0 && plus < at
129
+ ? `${delivered.slice(0, plus)}${delivered.slice(at)}`
130
+ : delivered;
131
+
132
+ if (!input.ownAddresses.includes(base)) return "catch-all delivery";
133
+
134
+ const autoSubmitted = headers
135
+ .get("auto-submitted")
136
+ ?.split(";", 1)[0]
137
+ ?.trim()
138
+ .toLowerCase();
139
+
140
+ if (autoSubmitted && autoSubmitted !== "no") return "auto-submitted";
141
+
142
+ const precedence = headers.get("precedence")?.trim().toLowerCase();
143
+
144
+ // `auto_reply` is what older auto-responders send instead of Auto-Submitted.
145
+ if (
146
+ precedence &&
147
+ ["bulk", "list", "junk", "auto_reply"].includes(precedence)
148
+ ) {
149
+ return "precedence";
150
+ }
151
+
152
+ if (headers.has("list-id") || headers.has("list-unsubscribe")) {
153
+ return "mailing list";
154
+ }
155
+
156
+ const suppress = headers.get("x-auto-response-suppress")?.toLowerCase() ?? "";
157
+
158
+ if (/\b(?:oof|all)\b/u.test(suppress)) return "x-auto-response-suppress";
159
+
160
+ const contentType = headers.get("content-type")?.toLowerCase() ?? "";
161
+
162
+ if (contentType.startsWith("multipart/report")) return "delivery report";
163
+
164
+ // Calendar invitations and responses are machine-generated; an .ics part
165
+ // inside multipart mail counts as well.
166
+ if (
167
+ contentType.startsWith("text/calendar") ||
168
+ input.email.attachmentsJson.some(
169
+ (file) =>
170
+ /^(?:text\/calendar|application\/ics)\b/iu.test(file.contentType) ||
171
+ /\.ics$/iu.test(file.filename)
172
+ )
173
+ ) {
174
+ return "calendar message";
175
+ }
176
+
177
+ const sender = input.envelopeFrom.trim().replaceAll(/^<|>$/gu, "");
178
+
179
+ if (!sender) return "empty envelope sender";
180
+
181
+ if (SYSTEM_LOCAL_PART.test(sender.split("@", 1)[0] ?? "")) {
182
+ return "system sender";
183
+ }
184
+
185
+ return input.ownAddresses.includes(sender.toLowerCase())
186
+ ? "own address"
187
+ : null;
188
+ }
189
+
190
+ /** The reply goes to the envelope sender (Return-Path), per RFC 3834. */
191
+ export function autoReplyRecipient(envelopeFrom: string) {
192
+ return normalizeEmail(envelopeFrom.trim().replaceAll(/^<|>$/gu, ""));
193
+ }
194
+
195
+ /** Header values here come from other people's mail; keep each on one line. */
196
+ function oneLine(value: string) {
197
+ return value.replaceAll(/[\r\n]+/gu, " ");
198
+ }
199
+
200
+ /** The message `EMAIL.send` gets: never stored, and marked as automatic. */
201
+ export function buildAutoReply(input: {
202
+ from: { address: string; name: string };
203
+ recipient: string;
204
+ original: Pick<
205
+ Email,
206
+ "subject" | "messageIdHeader" | "inReplyToJson" | "referencesJson"
207
+ >;
208
+ message: { subject: string | null; html: string; text: string };
209
+ /** The images the HTML shows, loaded from R2. */
210
+ images?: {
211
+ contentId: string;
212
+ filename: string;
213
+ type: string;
214
+ content: ArrayBuffer;
215
+ }[];
216
+ }) {
217
+ const thread = replyThreadHeaders(input.original);
218
+
219
+ // Every one of these is on Email Sending's header allowlist.
220
+ const headers = Object.fromEntries(
221
+ [
222
+ ["Auto-Submitted", "auto-replied"],
223
+ ["X-Auto-Response-Suppress", "All"],
224
+ ["In-Reply-To", oneLine(thread.inReplyTo.join(" "))],
225
+ ["References", oneLine(thread.references.join(" "))],
226
+ ].filter(([, value]) => value)
227
+ );
228
+
229
+ return {
230
+ from: { name: oneLine(input.from.name), email: input.from.address },
231
+ to: input.recipient,
232
+ subject: oneLine(
233
+ input.message.subject?.trim() || `Auto: ${input.original.subject}`
234
+ ),
235
+ text: input.message.text,
236
+ html: input.message.html,
237
+ attachments: (input.images ?? []).map((image) => ({
238
+ disposition: "inline" as const,
239
+ ...image,
240
+ })),
241
+ headers,
242
+ };
243
+ }
@@ -1,7 +1,7 @@
1
+ import { readBounded } from "@open-workspace/core/module";
1
2
  import { z } from "zod";
2
3
 
3
4
  import type { BimiResult, BimiStatus } from "../../shared/mail-sender-intel";
4
- import { readCappedBody } from "./capped-body";
5
5
  import { isAbortError } from "./doh";
6
6
  import type { DnsResolver } from "./doh";
7
7
  import { assertProxyableRemoteUrl } from "./remote-proxy";
@@ -61,11 +61,9 @@ const FORBIDDEN_ELEMENTS =
61
61
  * Conservative SVG Tiny PS check. Rejects anything that could run code or load
62
62
  * another resource; returns the trimmed document, or a reason it was refused.
63
63
  */
64
- export function validateBimiSvg(
65
- source: string
66
- ): { svg: string } | { error: string } {
64
+ export function validateBimiSvg(source: string) {
67
65
  if (new TextEncoder().encode(source).byteLength > MAX_BIMI_SVG_BYTES) {
68
- return { error: "The logo is larger than 32 KB" };
66
+ return svgProblem("The logo is larger than 32 KB");
69
67
  }
70
68
 
71
69
  const svg = source.replace(/^/u, "").trim();
@@ -76,51 +74,56 @@ export function validateBimiSvg(
76
74
  .trim();
77
75
 
78
76
  if (/<!DOCTYPE|<!ENTITY|<!\[CDATA\[/iu.test(body)) {
79
- return { error: "The logo declares a DTD, entity or CDATA section" };
77
+ return svgProblem("The logo declares a DTD, entity or CDATA section");
80
78
  }
81
79
 
82
80
  if (!/^<svg[\s>]/iu.test(body) || !/<\/svg>\s*$/iu.test(body)) {
83
- return { error: "The file is not an SVG document" };
81
+ return svgProblem("The file is not an SVG document");
84
82
  }
85
83
 
86
84
  if (!/xmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/u.test(body)) {
87
- return { error: "The SVG namespace is missing" };
85
+ return svgProblem("The SVG namespace is missing");
88
86
  }
89
87
 
90
88
  if (FORBIDDEN_ELEMENTS.test(body)) {
91
- return { error: "The logo contains scripts, links, images or animation" };
89
+ return svgProblem("The logo contains scripts, links, images or animation");
92
90
  }
93
91
 
94
92
  if (/\son[a-z]+\s*=/iu.test(body)) {
95
- return { error: "The logo contains event handlers" };
93
+ return svgProblem("The logo contains event handlers");
96
94
  }
97
95
 
98
96
  if (/javascript:|data:|@import/iu.test(body)) {
99
- return { error: "The logo references executable or embedded content" };
97
+ return svgProblem("The logo references executable or embedded content");
100
98
  }
101
99
 
102
100
  for (const match of body.matchAll(
103
101
  /\b(?:xlink:)?href\s*=\s*["']([^"']*)["']/giu
104
102
  )) {
105
103
  if (!match[1].trim().startsWith("#")) {
106
- return { error: "The logo references an external resource" };
104
+ return svgProblem("The logo references an external resource");
107
105
  }
108
106
  }
109
107
 
110
108
  for (const match of body.matchAll(/url\(\s*['"]?([^'")]*)/giu)) {
111
109
  if (!match[1].trim().startsWith("#")) {
112
- return { error: "The logo references an external resource" };
110
+ return svgProblem("The logo references an external resource");
113
111
  }
114
112
  }
115
113
 
116
114
  return { svg };
117
115
  }
118
116
 
117
+ /** Why an SVG isn't a usable logo, as `validateBimiSvg` gives it. */
118
+ function svgProblem(error: string) {
119
+ return { error };
120
+ }
121
+
119
122
  async function readCapped(response: Response, limit: number) {
120
123
  if (!response.body) return null;
121
- const bytes = await readCappedBody(response.body, limit);
124
+ const { bytes, complete } = await readBounded(response.body, limit);
122
125
 
123
- return bytes && new TextDecoder().decode(bytes);
126
+ return complete ? new TextDecoder().decode(bytes) : null;
124
127
  }
125
128
 
126
129
  type Lookup = { status: BimiStatus; reason: string | null; svg?: string };
@@ -130,24 +133,30 @@ async function lookup(input: {
130
133
  fetch: typeof fetch;
131
134
  domain: string;
132
135
  signal?: AbortSignal;
133
- }): Promise<Lookup> {
136
+ }) {
134
137
  const answer = await input.resolve(`default._bimi.${input.domain}`, "TXT");
135
138
 
136
139
  if (answer.status === "timeout" || answer.status === "error") {
137
140
  return {
138
141
  status: "error",
139
142
  reason: "The BIMI record could not be looked up",
140
- };
143
+ } satisfies Lookup;
141
144
  }
142
145
 
143
146
  const record = answer.records.map(parseBimiRecord).find(Boolean);
144
147
 
145
148
  if (!record) {
146
- return { status: "none", reason: "The domain publishes no BIMI record" };
149
+ return {
150
+ status: "none",
151
+ reason: "The domain publishes no BIMI record",
152
+ } satisfies Lookup;
147
153
  }
148
154
 
149
155
  if (!record.location) {
150
- return { status: "none", reason: "The domain declined to show a logo" };
156
+ return {
157
+ status: "none",
158
+ reason: "The domain declined to show a logo",
159
+ } satisfies Lookup;
151
160
  }
152
161
 
153
162
  let url: URL;
@@ -158,14 +167,14 @@ async function lookup(input: {
158
167
  return {
159
168
  status: "invalid",
160
169
  reason: "The BIMI logo location is not a valid public URL",
161
- };
170
+ } satisfies Lookup;
162
171
  }
163
172
 
164
173
  if (url.protocol !== "https:") {
165
174
  return {
166
175
  status: "invalid",
167
176
  reason: "The BIMI logo is not served over HTTPS",
168
- };
177
+ } satisfies Lookup;
169
178
  }
170
179
 
171
180
  try {
@@ -179,33 +188,41 @@ async function lookup(input: {
179
188
  return {
180
189
  status: "error",
181
190
  reason: `The logo server answered ${response.status}`,
182
- };
191
+ } satisfies Lookup;
183
192
  }
184
193
 
185
194
  const declared = Number(response.headers.get("content-length") ?? 0);
186
195
 
187
196
  if (declared > MAX_BIMI_SVG_BYTES) {
188
- return { status: "invalid", reason: "The logo is larger than 32 KB" };
197
+ return {
198
+ status: "invalid",
199
+ reason: "The logo is larger than 32 KB",
200
+ } satisfies Lookup;
189
201
  }
190
202
 
191
203
  const text = await readCapped(response, MAX_BIMI_SVG_BYTES);
192
204
 
193
205
  if (text === null) {
194
- return { status: "invalid", reason: "The logo is larger than 32 KB" };
206
+ return {
207
+ status: "invalid",
208
+ reason: "The logo is larger than 32 KB",
209
+ } satisfies Lookup;
195
210
  }
196
211
 
197
212
  const checked = validateBimiSvg(text);
198
213
 
199
- if ("error" in checked) return { status: "invalid", reason: checked.error };
214
+ if ("error" in checked) {
215
+ return { status: "invalid", reason: checked.error } satisfies Lookup;
216
+ }
200
217
 
201
- return { status: "ok", reason: null, svg: checked.svg };
218
+ return { status: "ok", reason: null, svg: checked.svg } satisfies Lookup;
202
219
  } catch (error) {
203
220
  return {
204
221
  status: "error",
205
222
  reason: isAbortError(error)
206
223
  ? "The logo download timed out"
207
224
  : "The logo could not be downloaded",
208
- };
225
+ } satisfies Lookup;
209
226
  }
210
227
  }
211
228
 
@@ -229,11 +246,7 @@ type BimiInput = {
229
246
  };
230
247
 
231
248
  /** One domain's logo: the cached outcome while fresh, else a new lookup that is cached. */
232
- async function domainBimi(
233
- input: BimiInput,
234
- domain: string,
235
- now: number
236
- ): Promise<BimiResult> {
249
+ async function domainBimi(input: BimiInput, domain: string, now: number) {
237
250
  const key = bimiObjectKey(domain);
238
251
  const cached = await input.bucket.head(key).catch(() => null);
239
252
  const metadata = CachedBimiMetadata.safeParse(cached?.customMetadata);
@@ -243,7 +256,7 @@ async function domainBimi(
243
256
  const ttl = status === "error" ? BIMI_ERROR_TTL_MS : BIMI_CACHE_TTL_MS;
244
257
 
245
258
  if (now - checkedAt < ttl) {
246
- return { domain, status, reason: reason || null };
259
+ return { domain, status, reason: reason || null } satisfies BimiResult;
247
260
  }
248
261
  }
249
262
 
@@ -265,14 +278,18 @@ async function domainBimi(
265
278
  })
266
279
  .catch(() => undefined);
267
280
 
268
- return { domain, status: result.status, reason: result.reason };
281
+ return {
282
+ domain,
283
+ status: result.status,
284
+ reason: result.reason,
285
+ } satisfies BimiResult;
269
286
  }
270
287
 
271
288
  /**
272
289
  * Per-domain logo, cached in R2 for a day (an hour after a failure). The
273
290
  * From domain's record wins; the organizational domain is the fallback.
274
291
  */
275
- export async function resolveBimi(input: BimiInput): Promise<BimiResult> {
292
+ export async function resolveBimi(input: BimiInput) {
276
293
  const now = input.now ?? Date.now();
277
294
 
278
295
  const [first, fallback] = [
@@ -288,7 +305,7 @@ export async function resolveBimi(input: BimiInput): Promise<BimiResult> {
288
305
  domain: input.fromDomain,
289
306
  status: "none",
290
307
  reason: "The domain publishes no BIMI record",
291
- };
308
+ } satisfies BimiResult;
292
309
  }
293
310
 
294
311
  const primary = await domainBimi(input, first, now);
@@ -3,11 +3,13 @@ import { timed } from "@open-workspace/core/module";
3
3
  import type { Context } from "hono";
4
4
  import { z } from "zod";
5
5
 
6
+ import { DRAFTS_FOLDER_ID } from "../../shared/folder-order";
6
7
  import { CONVERSATION_PAGE_SIZE } from "../../shared/mail";
7
8
  import { parseMailPath } from "../../shared/mail-path";
8
9
  import { mailboxStub } from "../mailbox";
9
10
  import { mailboxListRowSchema, sessionMailboxListQuery } from "./access";
10
11
  import type { MailboxListRow } from "./access";
12
+ import { mailboxDraftSenders } from "./draft-sender";
11
13
  import {
12
14
  conversationPageView,
13
15
  folderListView,
@@ -47,18 +49,24 @@ async function loadMailBootstrap(
47
49
  const { mailboxId, folder } = startupLocation(input.pathname, rows);
48
50
  const access = rows.find((row) => row.id === mailboxId);
49
51
 
50
- if (!access) return { ...mailboxListView(rows), mailbox: null };
52
+ if (!access) return { ...mailboxListView(c, rows), mailbox: null };
53
+
54
+ const senders =
55
+ folder === DRAFTS_FOLDER_ID
56
+ ? await mailboxDraftSenders(c.env.DB, access)
57
+ : undefined;
51
58
 
52
59
  const view = await timed(c, "do", "startup", () =>
53
60
  mailboxStub(c.env, access.id).startupView(
54
61
  c.get("user").id,
55
62
  folder,
56
- CONVERSATION_PAGE_SIZE
63
+ CONVERSATION_PAGE_SIZE,
64
+ senders
57
65
  )
58
66
  );
59
67
 
60
68
  return {
61
- ...mailboxListView(rows),
69
+ ...mailboxListView(c, rows),
62
70
  mailbox: {
63
71
  id: access.id,
64
72
  folder,
@@ -0,0 +1,69 @@
1
+ import {
2
+ apiError,
3
+ can,
4
+ createDb,
5
+ mayManageAddress,
6
+ } from "@open-workspace/core/module";
7
+ import type { AppEnv } from "@open-workspace/core/module";
8
+ import type { Context } from "hono";
9
+
10
+ import { accessibleMailbox } from "./access";
11
+
12
+ /**
13
+ * Who may do what with a mailbox, in one place, so every route (and JMAP)
14
+ * answers the same and the app can hide what the Worker would refuse.
15
+ *
16
+ * - Read: anyone `accessibleMailbox` lets in.
17
+ * - Send, and delete for good: send access.
18
+ * - Organize the mailbox itself (folders, rules, AI sorting, blocked and
19
+ * trusted senders): its owner for
20
+ * a person's own mailbox; for a shared inbox, which these act on for
21
+ * everyone, people who manage teams.
22
+ * - Configure the address (auto-reply, forwards): its owner for their own
23
+ * mailbox, and whoever may manage the address in core (mayManageAddress).
24
+ */
25
+
26
+ /** Whether `mailbox` (as accessibleMailbox returns it) may be organized by this request. */
27
+ export function mayOrganizeMailbox(
28
+ c: Context<AppEnv>,
29
+ mailbox: { ownerUserId: string | null }
30
+ ) {
31
+ return mailbox.ownerUserId !== null || can(c, "manage_teams");
32
+ }
33
+
34
+ /**
35
+ * The refusal for changing how a mailbox is organized (its folders, rules,
36
+ * AI sorting, and the senders it blocks or trusts) without the right, or
37
+ * null.
38
+ */
39
+ export async function organizeRefusal(c: Context<AppEnv>, mailboxId: string) {
40
+ const access = await accessibleMailbox(c, mailboxId, "read");
41
+
42
+ if (!access) {
43
+ return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
44
+ }
45
+
46
+ return mayOrganizeMailbox(c, access)
47
+ ? null
48
+ : apiError(
49
+ c,
50
+ 403,
51
+ "FORBIDDEN",
52
+ "Only people who manage teams can change a shared inbox's folders, rules, AI sorting and blocked or trusted senders"
53
+ );
54
+ }
55
+
56
+ /** Whether this request may change what is set on an address (auto-reply, forwards). */
57
+ export function mayConfigureAddress(
58
+ c: Context<AppEnv>,
59
+ address: { ownerUserId: string | null }
60
+ ) {
61
+ if (
62
+ address.ownerUserId !== null &&
63
+ address.ownerUserId === c.get("user").id
64
+ ) {
65
+ return Promise.resolve(true);
66
+ }
67
+
68
+ return mayManageAddress(c, createDb(c.env.DB), address);
69
+ }
@@ -63,7 +63,7 @@ export function classificationSignals(input: {
63
63
  feedback?: ClassificationSignals["userFeedback"];
64
64
  workspaceFeedback?: ClassificationSignals["workspaceFeedback"];
65
65
  delivery?: DeliveryFacts | null;
66
- }): ClassificationSignals {
66
+ }) {
67
67
  const auth = input.authentication;
68
68
  const { intel } = input;
69
69