@open-workspace/email 0.4.2 → 0.5.1

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 (268) 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-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -1,7 +1,6 @@
1
1
  import { authResults } from "../../shared/mail-authentication";
2
2
  import type {
3
3
  ArcSealer,
4
- AuthResult,
5
4
  DkimResult,
6
5
  DmarcPolicy,
7
6
  InboundAuthentication,
@@ -66,7 +65,7 @@ export type ParsedAuthenticationResults = {
66
65
 
67
66
  const VALUE = String.raw`"(?:[^"\\]|\\.)*"|[^\s;]+`;
68
67
 
69
- function parseResInfo(segment: string): AuthResInfo | null {
68
+ function parseResInfo(segment: string) {
70
69
  const { text, comments } = scanComments(segment);
71
70
  const method = /^\s*([a-z0-9_-]+)(?:\/\d+)?\s*=\s*([a-z0-9_-]+)/iu.exec(text);
72
71
 
@@ -104,13 +103,11 @@ function parseResInfo(segment: string): AuthResInfo | null {
104
103
  reason,
105
104
  comments,
106
105
  props,
107
- };
106
+ } satisfies AuthResInfo;
108
107
  }
109
108
 
110
109
  /** Parses an Authentication-Results value (RFC 8601 §2.2), comments and all. */
111
- export function parseAuthenticationResults(
112
- value: string
113
- ): ParsedAuthenticationResults | null {
110
+ export function parseAuthenticationResults(value: string) {
114
111
  const segments = splitTopLevel(value, ";");
115
112
 
116
113
  const authservId = scanComments(segments[0] ?? "")
@@ -127,7 +124,7 @@ export function parseAuthenticationResults(
127
124
 
128
125
  return info ? [info] : [];
129
126
  }),
130
- };
127
+ } satisfies ParsedAuthenticationResults;
131
128
  }
132
129
 
133
130
  /** ARC-Authentication-Results carries `i=N;` before the A-R payload. */
@@ -148,7 +145,7 @@ export type ParsedReceivedSpf = {
148
145
  pairs: Record<string, string>;
149
146
  };
150
147
 
151
- export function parseReceivedSpf(value: string): ParsedReceivedSpf | null {
148
+ export function parseReceivedSpf(value: string) {
152
149
  const result = /^\s*([a-z]+)/iu.exec(value);
153
150
 
154
151
  if (!result) return null;
@@ -168,7 +165,7 @@ export function parseReceivedSpf(value: string): ParsedReceivedSpf | null {
168
165
  result: result[1].toLocaleLowerCase(),
169
166
  comment: comments[0] ?? null,
170
167
  pairs,
171
- };
168
+ } satisfies ParsedReceivedSpf;
172
169
  }
173
170
 
174
171
  // --- Tag lists (DKIM-Signature, ARC-Seal) ----------------------------------
@@ -199,7 +196,7 @@ type DkimSignatureTags = {
199
196
  signedHeaders: string[];
200
197
  };
201
198
 
202
- function dkimSignatureTags(fields: HeaderField[]): DkimSignatureTags[] {
199
+ function dkimSignatureTags(fields: HeaderField[]) {
203
200
  return fields.flatMap((field) => {
204
201
  if (field.name !== "dkim-signature") return [];
205
202
  const tags = parseTagList(field.value);
@@ -216,7 +213,7 @@ function dkimSignatureTags(fields: HeaderField[]): DkimSignatureTags[] {
216
213
  .split(":")
217
214
  .map((name) => name.trim().toLocaleLowerCase())
218
215
  .filter(Boolean),
219
- },
216
+ } satisfies DkimSignatureTags,
220
217
  ];
221
218
  });
222
219
  }
@@ -257,13 +254,11 @@ export function trustedHeaderBlock(fields: HeaderField[]) {
257
254
  return { hop, trusted: fields.slice(0, end), below: fields.slice(end) };
258
255
  }
259
256
 
260
- function authResult(value: string | null | undefined): AuthResult | null {
257
+ function authResult(value: string | null | undefined) {
261
258
  return authResults.find((result) => result === value) ?? null;
262
259
  }
263
260
 
264
- function claimFrom(
265
- parsed: ParsedAuthenticationResults
266
- ): UpstreamAuthenticationClaim {
261
+ function claimFrom(parsed: ParsedAuthenticationResults) {
267
262
  const first = (method: string) =>
268
263
  authResult(
269
264
  parsed.results.find(
@@ -278,17 +273,20 @@ function claimFrom(
278
273
  spf: first("spf"),
279
274
  dkim: first("dkim"),
280
275
  dmarc: first("dmarc"),
281
- };
276
+ } satisfies UpstreamAuthenticationClaim;
282
277
  }
283
278
 
284
- function dmarcPolicy(value: string | undefined): DmarcPolicy | null {
279
+ function dmarcPolicy(value: string | undefined) {
285
280
  const normalized = value?.toLocaleLowerCase();
286
281
 
287
- return normalized === "none" ||
282
+ const policy: DmarcPolicy | null =
283
+ normalized === "none" ||
288
284
  normalized === "quarantine" ||
289
285
  normalized === "reject"
290
- ? normalized
291
- : null;
286
+ ? normalized
287
+ : null;
288
+
289
+ return policy;
292
290
  }
293
291
 
294
292
  function matchSignature(
@@ -321,16 +319,25 @@ function matchSignature(
321
319
  type Verdict = Pick<InboundAuthentication, "verdict" | "verdictReason">;
322
320
 
323
321
  function verdictFor(
324
- input: Pick<InboundAuthentication, "spf" | "dkim" | "dmarc" | "arc">
325
- ): Verdict {
322
+ input: Pick<InboundAuthentication, "spf" | "dkim" | "dmarc" | "arc">,
323
+ fromDomain: string | null
324
+ ) {
326
325
  const alignedDkimPass = input.dkim.some(
327
326
  (dkim) => dkim.result === "pass" && dkim.aligned
328
327
  );
329
328
 
330
329
  const alignedSpfPass = input.spf?.result === "pass" && input.spf.aligned;
331
330
 
332
- if (input.dmarc?.result === "pass") {
333
- return { verdict: "verified", verdictReason: "dmarc_pass" };
331
+ // DMARC passed for the From the app shows, not another one Cloudflare
332
+ // read (two From headers, or several addresses in one).
333
+ if (
334
+ input.dmarc?.result === "pass" &&
335
+ input.dmarc.headerFrom?.toLowerCase() === fromDomain?.toLowerCase()
336
+ ) {
337
+ return {
338
+ verdict: "verified",
339
+ verdictReason: "dmarc_pass",
340
+ } satisfies Verdict;
334
341
  }
335
342
 
336
343
  const failing =
@@ -350,17 +357,23 @@ function verdictFor(
350
357
  oldestSealer &&
351
358
  TRUSTED_ARC_SEALERS.has(oldestSealer)
352
359
  ) {
353
- return { verdict: "unverified", verdictReason: "forwarded_arc" };
360
+ return {
361
+ verdict: "unverified",
362
+ verdictReason: "forwarded_arc",
363
+ } satisfies Verdict;
354
364
  }
355
365
 
356
- return { verdict: "suspicious", verdictReason: failing };
366
+ return { verdict: "suspicious", verdictReason: failing } satisfies Verdict;
357
367
  }
358
368
 
359
369
  if (alignedDkimPass && (!input.dmarc || input.dmarc.result === "none")) {
360
- return { verdict: "verified", verdictReason: "aligned_dkim" };
370
+ return {
371
+ verdict: "verified",
372
+ verdictReason: "aligned_dkim",
373
+ } satisfies Verdict;
361
374
  }
362
375
 
363
- return { verdict: "unverified", verdictReason: "partial" };
376
+ return { verdict: "unverified", verdictReason: "partial" } satisfies Verdict;
364
377
  }
365
378
 
366
379
  function emptyAuthentication(
@@ -368,7 +381,7 @@ function emptyAuthentication(
368
381
  fromDomain: string | null,
369
382
  reason: "not_cloudflare" | "missing_results",
370
383
  envelopeFrom: string | null
371
- ): InboundAuthentication {
384
+ ) {
372
385
  return {
373
386
  source: "headers",
374
387
  version: 1,
@@ -389,7 +402,7 @@ function emptyAuthentication(
389
402
  upstream: [],
390
403
  ignoredCloudflareClaims: 0,
391
404
  trustedHeader: null,
392
- };
405
+ } satisfies InboundAuthentication;
393
406
  }
394
407
 
395
408
  function claimsCloudflare(field: HeaderField) {
@@ -423,7 +436,7 @@ function arcSummary(
423
436
  trusted: HeaderField[],
424
437
  all: HeaderField[],
425
438
  arcResult: AuthResInfo | undefined
426
- ): InboundAuthentication["arc"] {
439
+ ) {
427
440
  const ownSeal = trusted.find(
428
441
  (field) =>
429
442
  field.name === "arc-seal" &&
@@ -487,7 +500,7 @@ function arcSummary(
487
500
  (left, right) => left.instance - right.instance
488
501
  ),
489
502
  oldest,
490
- };
503
+ } satisfies InboundAuthentication["arc"];
491
504
  }
492
505
 
493
506
  /**
@@ -500,7 +513,7 @@ export function parseInboundAuthentication(input: {
500
513
  fromAddress: string | null;
501
514
  envelopeFrom?: string | null;
502
515
  now?: number;
503
- }): InboundAuthentication {
516
+ }) {
504
517
  const now = input.now ?? Date.now();
505
518
  const fields = headerFields(input.raw);
506
519
  const block = trustedHeaderBlock(fields);
@@ -571,7 +584,7 @@ export function parseInboundAuthentication(input: {
571
584
  spamScore: score,
572
585
  upstream,
573
586
  ignoredCloudflareClaims,
574
- };
587
+ } satisfies InboundAuthentication;
575
588
  }
576
589
 
577
590
  const { results } = authenticationResults.parsed;
@@ -685,14 +698,14 @@ export function parseInboundAuthentication(input: {
685
698
  }
686
699
  : null,
687
700
  spamScore: score,
688
- ...verdictFor(parts),
701
+ ...verdictFor(parts, fromDomain),
689
702
  upstream,
690
703
  ignoredCloudflareClaims,
691
704
  trustedHeader: authenticationResults.field.value.slice(
692
705
  0,
693
706
  MAX_TRUSTED_HEADER_LENGTH
694
707
  ),
695
- };
708
+ } satisfies InboundAuthentication;
696
709
  }
697
710
 
698
711
  // --- List-Unsubscribe (RFC 2369 / RFC 8058) --------------------------------
@@ -737,7 +750,7 @@ function mailtoUnsubscribeUrl(value: string) {
737
750
  export function parseListUnsubscribe(
738
751
  raw: string,
739
752
  authentication: Pick<InboundAuthentication, "dkim">
740
- ): ListUnsubscribe | null {
753
+ ) {
741
754
  const fields = headerFields(raw);
742
755
 
743
756
  const header = fields.find(
@@ -753,12 +766,13 @@ export function parseListUnsubscribe(
753
766
  const httpsUrl = uris.map(httpsUnsubscribeUrl).find(Boolean) ?? null;
754
767
  const mailto = uris.map(mailtoUnsubscribeUrl).find(Boolean) ?? null;
755
768
 
756
- const result = (reason: ListUnsubscribe["reason"]): ListUnsubscribe => ({
757
- httpsUrl,
758
- mailto,
759
- oneClick: reason === null,
760
- reason,
761
- });
769
+ const result = (reason: ListUnsubscribe["reason"]) =>
770
+ ({
771
+ httpsUrl,
772
+ mailto,
773
+ oneClick: reason === null,
774
+ reason,
775
+ }) satisfies ListUnsubscribe;
762
776
 
763
777
  if (!httpsUrl && !mailto) return result("invalid-uri");
764
778
 
@@ -0,0 +1,260 @@
1
+ import {
2
+ apiError,
3
+ createDb,
4
+ mailboxAddressSql,
5
+ oauthScope,
6
+ zValidator,
7
+ } from "@open-workspace/core/module";
8
+ import type { AppEnv } from "@open-workspace/core/module";
9
+ import { mailboxes } from "@open-workspace/core/schema";
10
+ import { and, desc, eq } from "drizzle-orm";
11
+ import { Hono } from "hono";
12
+ import type { Context } from "hono";
13
+ import { z } from "zod";
14
+
15
+ import {
16
+ MAIL_ORGANIZE_SCOPE,
17
+ MAIL_READ_SCOPE,
18
+ MAIL_SEND_SCOPE,
19
+ } from "../../shared/permissions";
20
+ import { mailboxStub } from "../mailbox";
21
+ import type { AutoReplyMessage, AutoReplySettings } from "../mailbox/schema";
22
+ import {
23
+ autoReplyContentError,
24
+ autoReplyImagePrefix,
25
+ autoReplyStatus,
26
+ } from "./auto-reply";
27
+ import { mayConfigureAddress } from "./capabilities";
28
+ import { deleteRichImages, storeRichImages } from "./rich-content";
29
+ import { autoReplySchema } from "./schemas";
30
+ import { UploadValidationError } from "./uploads";
31
+
32
+ /**
33
+ * Who may see and change an address's auto-reply: its owner for their own
34
+ * mailbox (Settings), people who manage people for anyone's (People), and
35
+ * people who manage teams for a team inbox (Teams). Only addresses with a
36
+ * mailbox of their own have one: mail to an alias is answered by its
37
+ * target's, and a mailing list's goes straight to its members.
38
+ */
39
+ async function autoReplyAccess(c: Context<AppEnv>, mailboxId: string) {
40
+ const [mailbox] = await createDb(c.env.DB)
41
+ .select({ ownerUserId: mailboxes.ownerUserId })
42
+ .from(mailboxes)
43
+ .where(and(eq(mailboxes.id, mailboxId), eq(mailboxes.delivery, "inbox")))
44
+ .limit(1);
45
+
46
+ if (!mailbox) return "not found";
47
+
48
+ return (await mayConfigureAddress(c, mailbox)) ? "allowed" : "forbidden";
49
+ }
50
+
51
+ function refusal(c: Context<AppEnv>, access: "not found" | "forbidden") {
52
+ return access === "not found"
53
+ ? apiError(c, 404, "NOT_FOUND", "Mailbox not found")
54
+ : apiError(
55
+ c,
56
+ 403,
57
+ "FORBIDDEN",
58
+ "You can't change this mailbox's auto-reply"
59
+ );
60
+ }
61
+
62
+ function messageView({ text: _text, ...message }: AutoReplyMessage) {
63
+ return message;
64
+ }
65
+
66
+ function autoReplyView(mailboxId: string, settings: AutoReplySettings | null) {
67
+ return {
68
+ ok: true as const,
69
+ /** Saved images are shown from `/auto-reply/images/:contentId` of this mailbox. */
70
+ ownerId: mailboxId,
71
+ status: autoReplyStatus(settings, new Date()),
72
+ settings: settings && {
73
+ enabled: settings.enabled,
74
+ startsAt: settings.startsAt,
75
+ endsAt: settings.endsAt,
76
+ replyIntervalDays: settings.replyIntervalDays,
77
+ inside: messageView(settings.inside),
78
+ outside: {
79
+ ...messageView(settings.outside),
80
+ audience: settings.outside.audience,
81
+ },
82
+ updatedAt: settings.updatedAt,
83
+ },
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Mailboxes' auto-replies (mailbox/index.ts sends them). Mounted under
89
+ * /mail. Messages are rich content (rich-content.ts) whose images live under
90
+ * the mailbox's own objects, so they go when it does.
91
+ */
92
+ export const autoReplyRoutes = new Hono<AppEnv>()
93
+ // Settings → Auto-reply: the signed-in person's own mailboxes.
94
+ .get("/auto-replies", oauthScope(MAIL_READ_SCOPE), async (c) => {
95
+ const rows = await createDb(c.env.DB)
96
+ .select({
97
+ id: mailboxes.id,
98
+ address: mailboxAddressSql,
99
+ displayName: mailboxes.displayName,
100
+ })
101
+ .from(mailboxes)
102
+ .where(
103
+ and(
104
+ eq(mailboxes.ownerUserId, c.get("user").id),
105
+ eq(mailboxes.delivery, "inbox")
106
+ )
107
+ )
108
+ .orderBy(desc(mailboxes.isPrimary), mailboxes.displayName);
109
+
110
+ return c.json({ ok: true as const, mailboxes: rows });
111
+ })
112
+ .get("/mailboxes/:id/auto-reply", oauthScope(MAIL_READ_SCOPE), async (c) => {
113
+ const mailboxId = c.req.param("id");
114
+ const access = await autoReplyAccess(c, mailboxId);
115
+
116
+ if (access !== "allowed") return refusal(c, access);
117
+
118
+ return c.json(
119
+ autoReplyView(
120
+ mailboxId,
121
+ await mailboxStub(c.env, mailboxId).getAutoReply()
122
+ )
123
+ );
124
+ })
125
+ // Its text goes out as the mailbox, so an app sets it only if it may send.
126
+ .put(
127
+ "/mailboxes/:id/auto-reply",
128
+ oauthScope(MAIL_ORGANIZE_SCOPE, MAIL_SEND_SCOPE),
129
+ zValidator("json", autoReplySchema),
130
+ async (c) => {
131
+ const mailboxId = c.req.param("id");
132
+ const access = await autoReplyAccess(c, mailboxId);
133
+
134
+ if (access !== "allowed") return refusal(c, access);
135
+ const input = c.req.valid("json");
136
+
137
+ const stub = mailboxStub(c.env, mailboxId);
138
+ const previous = await stub.getAutoReply();
139
+
140
+ const contentError = autoReplyContentError(
141
+ input.enabled ?? previous?.enabled ?? false,
142
+ input
143
+ );
144
+
145
+ if (contentError) return apiError(c, 400, "BAD_REQUEST", contentError);
146
+ const prefix = autoReplyImagePrefix(mailboxId);
147
+
148
+ // One folder for both messages, so an image can move between them.
149
+ const previousImages = previous
150
+ ? [...previous.inside.images, ...previous.outside.images]
151
+ : [];
152
+
153
+ let images;
154
+
155
+ try {
156
+ images = await Promise.all(
157
+ [input.inside, input.outside].map((content) =>
158
+ storeRichImages({
159
+ env: c.env,
160
+ userId: c.get("user").id,
161
+ prefix,
162
+ previous: previousImages,
163
+ content,
164
+ })
165
+ )
166
+ );
167
+ } catch (error) {
168
+ if (error instanceof UploadValidationError) {
169
+ return apiError(c, 400, "BAD_REQUEST", error.message);
170
+ }
171
+
172
+ throw error;
173
+ }
174
+
175
+ const [insideImages = [], outsideImages = []] = images;
176
+
177
+ const message = (
178
+ content: typeof input.inside,
179
+ stored: typeof insideImages
180
+ ) => ({
181
+ enabled: content.enabled,
182
+ subject: content.subject,
183
+ html: content.html,
184
+ text: content.text,
185
+ images: stored,
186
+ });
187
+
188
+ const saved = await stub.setAutoReply(
189
+ {
190
+ enabled: input.enabled,
191
+ startsAt: input.startsAt,
192
+ endsAt: input.endsAt,
193
+ replyIntervalDays: input.replyIntervalDays,
194
+ inside: message(input.inside, insideImages),
195
+ outside: {
196
+ ...message(input.outside, outsideImages),
197
+ audience: input.outside.audience,
198
+ },
199
+ },
200
+ c.get("user").id
201
+ );
202
+
203
+ if ("error" in saved) return apiError(c, 400, "BAD_REQUEST", saved.error);
204
+
205
+ await deleteRichImages(
206
+ c.env.MAIL_STORAGE,
207
+ prefix,
208
+ new Set(
209
+ [...insideImages, ...outsideImages].map((image) => image.contentId)
210
+ )
211
+ );
212
+
213
+ return c.json(autoReplyView(mailboxId, saved));
214
+ }
215
+ )
216
+ // The banner in Mail turns it off without sending the messages back.
217
+ .patch(
218
+ "/mailboxes/:id/auto-reply",
219
+ oauthScope(MAIL_ORGANIZE_SCOPE),
220
+ zValidator("json", z.object({ enabled: z.literal(false) })),
221
+ async (c) => {
222
+ const mailboxId = c.req.param("id");
223
+ const access = await autoReplyAccess(c, mailboxId);
224
+
225
+ if (access !== "allowed") return refusal(c, access);
226
+
227
+ return c.json(
228
+ autoReplyView(
229
+ mailboxId,
230
+ await mailboxStub(c.env, mailboxId).turnOffAutoReply(c.get("user").id)
231
+ )
232
+ );
233
+ }
234
+ )
235
+ .get(
236
+ "/mailboxes/:id/auto-reply/images/:contentId",
237
+ oauthScope(MAIL_READ_SCOPE),
238
+ async (c) => {
239
+ const { id: mailboxId, contentId } = c.req.param();
240
+ const access = await autoReplyAccess(c, mailboxId);
241
+
242
+ const object =
243
+ access === "allowed"
244
+ ? await c.env.MAIL_STORAGE.get(
245
+ `${autoReplyImagePrefix(mailboxId)}${contentId}`
246
+ )
247
+ : null;
248
+
249
+ if (!object) return apiError(c, 404, "NOT_FOUND", "Image not found");
250
+
251
+ return new Response(object.body, {
252
+ headers: {
253
+ "content-type":
254
+ object.httpMetadata?.contentType ?? "application/octet-stream",
255
+ "cache-control": "private, max-age=300",
256
+ "x-content-type-options": "nosniff",
257
+ },
258
+ });
259
+ }
260
+ );