@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -1,50 +1,65 @@
1
+ import {
2
+ createDb,
3
+ mailboxes,
4
+ mailboxAddressPredicate,
5
+ normalizeMailboxAddress,
6
+ } from "@open-workspace/core/module";
1
7
  import { z } from "zod";
2
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
3
- import { domains, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
4
- import { mailboxAddressPredicate } from "@open-workspace/core/worker/db/mailboxes.ts";
5
- import { normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
8
+
6
9
  import { mailboxStub } from "../mailbox";
7
- import {
8
- deliveryStatuses,
9
- type RecipientDeliveryStatus,
10
- } from "../mailbox/model";
11
-
12
- const deliveryEventSchema = z.object({
13
- type: z.string().startsWith("cf.email.sending.message."),
14
- source: z.object({
15
- type: z.literal("email.sending"),
16
- }).passthrough(),
17
- payload: z.object({
18
- eventId: z.string().min(1),
19
- messageId: z.string().min(1),
20
- sender: z.string().min(1),
21
- recipient: z.string().min(1),
22
- delivery: z.object({
23
- status: z.enum(deliveryStatuses),
24
- smtpStatusCode: z.string().optional(),
25
- }).passthrough(),
26
- bounce: z.object({ reason: z.string().optional() }).optional(),
27
- failure: z.object({ reason: z.string().optional() }).optional(),
28
- rejection: z.object({
29
- reason: z.string().optional(),
30
- detail: z.string().optional(),
31
- }).optional(),
32
- complaint: z.object({ type: z.string().optional() }).optional(),
33
- }).passthrough(),
34
- metadata: z.object({
35
- eventTimestamp: z.string().datetime(),
36
- }).passthrough(),
37
- }).passthrough();
10
+ import { deliveryStatuses } from "../mailbox/model";
11
+ import type { RecipientDeliveryStatus } from "../mailbox/model";
12
+
13
+ const deliveryEventSchema = z
14
+ .object({
15
+ type: z.string().startsWith("cf.email.sending.message."),
16
+ source: z
17
+ .object({
18
+ type: z.literal("email.sending"),
19
+ })
20
+ .passthrough(),
21
+ payload: z
22
+ .object({
23
+ eventId: z.string().min(1),
24
+ messageId: z.string().min(1),
25
+ sender: z.string().min(1),
26
+ recipient: z.string().min(1),
27
+ delivery: z
28
+ .object({
29
+ status: z.enum(deliveryStatuses),
30
+ smtpStatusCode: z.string().optional(),
31
+ })
32
+ .passthrough(),
33
+ bounce: z.object({ reason: z.string().optional() }).optional(),
34
+ failure: z.object({ reason: z.string().optional() }).optional(),
35
+ rejection: z
36
+ .object({
37
+ reason: z.string().optional(),
38
+ detail: z.string().optional(),
39
+ })
40
+ .optional(),
41
+ complaint: z.object({ type: z.string().optional() }).optional(),
42
+ })
43
+ .passthrough(),
44
+ metadata: z
45
+ .object({
46
+ eventTimestamp: z.string().datetime(),
47
+ })
48
+ .passthrough(),
49
+ })
50
+ .passthrough();
38
51
 
39
52
  type DeliveryEvent = z.infer<typeof deliveryEventSchema>;
40
53
 
41
54
  function deliveryDetail(event: DeliveryEvent) {
42
- return event.payload.bounce?.reason
43
- ?? event.payload.failure?.reason
44
- ?? event.payload.rejection?.detail
45
- ?? event.payload.rejection?.reason
46
- ?? event.payload.complaint?.type
47
- ?? null;
55
+ return (
56
+ event.payload.bounce?.reason ??
57
+ event.payload.failure?.reason ??
58
+ event.payload.rejection?.detail ??
59
+ event.payload.rejection?.reason ??
60
+ event.payload.complaint?.type ??
61
+ null
62
+ );
48
63
  }
49
64
 
50
65
  function recipientStatus(event: DeliveryEvent): RecipientDeliveryStatus {
@@ -60,40 +75,51 @@ function recipientStatus(event: DeliveryEvent): RecipientDeliveryStatus {
60
75
 
61
76
  async function processDeliveryEvent(env: Env, event: DeliveryEvent) {
62
77
  const sender = normalizeMailboxAddress(event.payload.sender);
78
+
63
79
  const [mailbox] = await createDb(env.DB)
64
80
  .select({ id: mailboxes.id })
65
81
  .from(mailboxes)
66
- .innerJoin(domains, mailboxAddressPredicate(sender))
82
+ .where(mailboxAddressPredicate(sender))
67
83
  .limit(1);
84
+
68
85
  if (!mailbox) return "ignored" as const;
86
+
69
87
  return mailboxStub(env, mailbox.id).recordDeliveryStatus(
70
88
  event.payload.messageId,
71
- recipientStatus(event),
89
+ recipientStatus(event)
72
90
  );
73
91
  }
74
92
 
75
93
  export async function consumeDeliveryEvents(
76
94
  batch: MessageBatch<unknown>,
77
- env: Env,
95
+ env: Env
78
96
  ) {
79
- await Promise.all(batch.messages.map(async (message) => {
80
- const parsed = deliveryEventSchema.safeParse(message.body);
81
- if (!parsed.success) {
82
- console.error("Ignoring invalid Email Service event", parsed.error);
83
- message.ack();
84
- return;
85
- }
86
- try {
87
- const result = await processDeliveryEvent(env, parsed.data);
88
- if (result === "not_found") {
89
- // Delivery events can beat the write that stores EmailSendResult.messageId.
90
- message.retry({ delaySeconds: 10 });
97
+ await Promise.all(
98
+ batch.messages.map(async (message) => {
99
+ const parsed = deliveryEventSchema.safeParse(message.body);
100
+
101
+ if (!parsed.success) {
102
+ console.error("Ignoring invalid Email Service event", parsed.error);
103
+ message.ack();
104
+
91
105
  return;
92
106
  }
93
- message.ack();
94
- } catch (error) {
95
- console.error("Could not persist Email Service event", error);
96
- message.retry({ delaySeconds: 10 });
97
- }
98
- }));
107
+
108
+ try {
109
+ const result = await processDeliveryEvent(env, parsed.data);
110
+
111
+ if (result === "not_found") {
112
+ // Delivery events can beat the write that stores EmailSendResult.messageId.
113
+ message.retry({ delaySeconds: 10 });
114
+
115
+ return;
116
+ }
117
+
118
+ message.ack();
119
+ } catch (error) {
120
+ console.error("Could not persist Email Service event", error);
121
+ message.retry({ delaySeconds: 10 });
122
+ }
123
+ })
124
+ );
99
125
  }
@@ -32,6 +32,7 @@ const ACCOUNT_NOTICE_DOMAINS = new Set([
32
32
 
33
33
  export function isAccountNoticeSender(fromDomain: string | null | undefined) {
34
34
  const org = organizationalDomain(fromDomain);
35
+
35
36
  return Boolean(org && ACCOUNT_NOTICE_DOMAINS.has(org));
36
37
  }
37
38
 
@@ -47,15 +48,24 @@ export function forwardingRelay(auth: InboundAuthentication | null) {
47
48
  const fromOrg = organizationalDomain(auth.fromDomain);
48
49
  const envelope = auth.envelopeFrom?.toLocaleLowerCase() ?? "";
49
50
  const envelopeOrg = organizationalDomain(addressDomain(envelope));
50
- const foreignEnvelope = envelopeOrg && envelopeOrg !== fromOrg ? envelopeOrg : null;
51
- if (/^srs[01][=+-]/u.test(envelope) && foreignEnvelope) return foreignEnvelope;
51
+
52
+ const foreignEnvelope =
53
+ envelopeOrg && envelopeOrg !== fromOrg ? envelopeOrg : null;
54
+
55
+ if (/^srs[01][=+-]/u.test(envelope) && foreignEnvelope) {
56
+ return foreignEnvelope;
57
+ }
58
+
52
59
  if (auth.arc && auth.arc.chainLength > 1) {
53
60
  if (foreignEnvelope) return foreignEnvelope;
61
+
54
62
  const sealer = auth.arc.sealers
55
63
  .map((item) => organizationalDomain(item.domain))
56
64
  .find((domain) => domain && domain !== fromOrg);
65
+
57
66
  if (sealer) return sealer;
58
67
  }
68
+
59
69
  return null;
60
70
  }
61
71
 
@@ -72,12 +82,27 @@ export function addressedElsewhere(input: {
72
82
  workspaceDomains: readonly string[];
73
83
  }) {
74
84
  if (input.listId) return null;
75
- const recipients = [...input.to, ...input.cc].map((address) => address.toLocaleLowerCase()).filter((address) => address.includes("@"));
76
- if (!recipients.length) return null;
85
+
86
+ const recipients = [...input.to, ...input.cc].flatMap((address) =>
87
+ address.includes("@") ? [address.toLocaleLowerCase()] : []
88
+ );
89
+
90
+ const [firstRecipient] = recipients;
91
+
92
+ if (firstRecipient === undefined) return null;
77
93
  const deliveredTo = input.deliveredTo?.toLocaleLowerCase();
94
+
78
95
  if (deliveredTo && recipients.includes(deliveredTo)) return null;
79
- if (recipients.some((address) => isWorkspaceDomain(addressDomain(address), input.workspaceDomains))) return null;
80
- return recipients[0]!;
96
+
97
+ if (
98
+ recipients.some((address) =>
99
+ isWorkspaceDomain(addressDomain(address), input.workspaceDomains)
100
+ )
101
+ ) {
102
+ return null;
103
+ }
104
+
105
+ return firstRecipient;
81
106
  }
82
107
 
83
108
  export function deliveryFacts(input: {
@@ -91,6 +116,7 @@ export function deliveryFacts(input: {
91
116
  isKnownAddressee: (address: string) => boolean;
92
117
  }): DeliveryFacts {
93
118
  const addressedTo = addressedElsewhere(input);
119
+
94
120
  return {
95
121
  deliveredTo: input.deliveredTo?.toLocaleLowerCase() ?? null,
96
122
  addressedTo,
@@ -104,17 +130,27 @@ export function deliveryFacts(input: {
104
130
  * are not forwarded and stay quiet; a provider's account notice is suspicious
105
131
  * even without visible forwarding, because those are never Bcc'd.
106
132
  */
107
- export function addressedElsewhereWarning(delivery: DeliveryFacts | null, fromDomain: string | null) {
133
+ export function addressedElsewhereWarning(
134
+ delivery: DeliveryFacts | null,
135
+ fromDomain: string | null
136
+ ) {
108
137
  if (!delivery?.addressedTo || delivery.knownAddressee) return null;
109
138
  const accountNotice = isAccountNoticeSender(fromDomain);
139
+
110
140
  if (!delivery.forwardedVia && !accountNotice) return null;
141
+
111
142
  // A provider forwarding its own user's mail (Gmail auto-forwarding needs the
112
143
  // target to confirm) is likely the person's own setup.
113
- const ownForwarding = delivery.forwardedVia !== null
114
- && delivery.forwardedVia === organizationalDomain(delivery.addressedTo);
144
+ const ownForwarding =
145
+ delivery.forwardedVia !== null &&
146
+ delivery.forwardedVia === organizationalDomain(delivery.addressedTo);
147
+
115
148
  return {
116
149
  kind: "addressed_elsewhere" as const,
117
- severity: accountNotice && !ownForwarding ? "danger" as const : "caution" as const,
150
+ severity:
151
+ accountNotice && !ownForwarding
152
+ ? ("danger" as const)
153
+ : ("caution" as const),
118
154
  addressedTo: delivery.addressedTo,
119
155
  forwardedVia: delivery.forwardedVia,
120
156
  accountNotice,
@@ -1,6 +1,7 @@
1
+ import type { AppEnv } from "@open-workspace/core/module";
2
+ import { apiError } from "@open-workspace/core/module";
1
3
  import { Hono } from "hono";
2
- import type { AppEnv } from "@open-workspace/core/worker/env.ts";
3
- import { apiError } from "@open-workspace/core/worker/lib/http.ts";
4
+
4
5
  import type { OneClickFetcher } from "./unsubscribe";
5
6
 
6
7
  /**
@@ -10,24 +11,47 @@ import type { OneClickFetcher } from "./unsubscribe";
10
11
  */
11
12
  export const DEMO_UNSUBSCRIBE_HOST = "unsubscribe.openworkspace-demo.invalid";
12
13
 
13
- export const demoRoutes = new Hono<AppEnv>()
14
- .post("/list-unsubscribe/:token", async (c) => {
15
- if (c.env.ALLOW_MOCK_AUTH !== "true") return apiError(c, 404, "NOT_FOUND", "Not found");
14
+ export const demoRoutes = new Hono<AppEnv>().post(
15
+ "/list-unsubscribe/:token",
16
+ async (c) => {
17
+ if (c.env.ALLOW_MOCK_AUTH !== "true") {
18
+ return apiError(c, 404, "NOT_FOUND", "Not found");
19
+ }
20
+
16
21
  const body = new TextDecoder().decode(await c.req.arrayBuffer());
22
+
17
23
  if (body.trim() !== "List-Unsubscribe=One-Click") {
18
- return apiError(c, 400, "BAD_REQUEST", "Expected an RFC 8058 one-click body");
24
+ return apiError(
25
+ c,
26
+ 400,
27
+ "BAD_REQUEST",
28
+ "Expected an RFC 8058 one-click body"
29
+ );
19
30
  }
31
+
20
32
  return c.text("You have been unsubscribed.");
21
- });
33
+ }
34
+ );
22
35
 
23
36
  /** Real endpoints go to the network; the demo host is served by `demoRoutes`. */
24
37
  export function oneClickFetcher(env: Env): OneClickFetcher {
25
38
  return (request) => {
26
39
  const url = new URL(request.url);
27
- if (env.ALLOW_MOCK_AUTH === "true" && url.hostname === DEMO_UNSUBSCRIBE_HOST) {
28
- const local = new URL(`/list-unsubscribe${url.pathname.replace(/^\/[^/]*/u, "")}`, "http://demo.local");
29
- return Promise.resolve(demoRoutes.fetch(new Request(local, request), env));
40
+
41
+ if (
42
+ env.ALLOW_MOCK_AUTH === "true" &&
43
+ url.hostname === DEMO_UNSUBSCRIBE_HOST
44
+ ) {
45
+ const local = new URL(
46
+ `/list-unsubscribe${url.pathname.replace(/^\/[^/]*/u, "")}`,
47
+ "http://demo.local"
48
+ );
49
+
50
+ return Promise.resolve(
51
+ demoRoutes.fetch(new Request(local, request), env)
52
+ );
30
53
  }
54
+
31
55
  return fetch(request);
32
56
  };
33
57
  }
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  import type { LookupStatus } from "../../shared/mail-sender-intel";
2
4
 
3
5
  /**
@@ -10,7 +12,12 @@ export const DOH_ENDPOINT = "https://cloudflare-dns.com/dns-query";
10
12
 
11
13
  export type DnsRecordType = "A" | "AAAA" | "PTR" | "TXT";
12
14
 
13
- const recordTypeCodes: Record<DnsRecordType, number> = { A: 1, AAAA: 28, PTR: 12, TXT: 16 };
15
+ const recordTypeCodes: Record<DnsRecordType, number> = {
16
+ A: 1,
17
+ AAAA: 28,
18
+ PTR: 12,
19
+ TXT: 16,
20
+ };
14
21
 
15
22
  export type DnsAnswer = {
16
23
  status: Exclude<LookupStatus, "skipped">;
@@ -18,57 +25,89 @@ export type DnsAnswer = {
18
25
  records: string[];
19
26
  };
20
27
 
21
- export type DnsResolver = (name: string, type: DnsRecordType) => Promise<DnsAnswer>;
28
+ export type DnsResolver = (
29
+ name: string,
30
+ type: DnsRecordType
31
+ ) => Promise<DnsAnswer>;
22
32
 
23
- type DohJson = {
24
- Status?: number;
25
- Answer?: Array<{ type?: number; data?: string }>;
26
- };
33
+ /** The JSON API's answer; an answer record of an unexpected shape is skipped. */
34
+ const DohJson = z.object({
35
+ Status: z.number().optional(),
36
+ Answer: z
37
+ .array(
38
+ z.object({
39
+ type: z.number().optional().catch(undefined),
40
+ data: z.string().optional().catch(undefined),
41
+ })
42
+ )
43
+ .optional(),
44
+ });
27
45
 
28
46
  /** `"v=BIMI1; " "l=https://…"` → `v=BIMI1; l=https://…` (RFC 7208 §3.3 joining). */
29
47
  export function txtData(value: string) {
30
48
  const chunks = [...value.matchAll(/"((?:[^"\\]|\\.)*)"/gu)].map((match) =>
31
- match[1]!.replace(/\\(.)/gu, "$1")
49
+ match[1].replaceAll(/\\(.)/gu, "$1")
32
50
  );
51
+
33
52
  return chunks.length ? chunks.join("") : value;
34
53
  }
35
54
 
36
- export function isAbortError(error: unknown) {
37
- return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
55
+ export function isAbortError(cause: unknown) {
56
+ return (
57
+ cause instanceof Error &&
58
+ (cause.name === "AbortError" || cause.name === "TimeoutError")
59
+ );
38
60
  }
39
61
 
40
- export function createDohResolver(options: {
41
- fetch?: typeof fetch;
42
- signal?: AbortSignal;
43
- endpoint?: string;
44
- } = {}): DnsResolver {
62
+ export function createDohResolver(
63
+ options: {
64
+ fetch?: typeof fetch;
65
+ signal?: AbortSignal;
66
+ endpoint?: string;
67
+ } = {}
68
+ ): DnsResolver {
45
69
  const fetcher = options.fetch ?? fetch;
46
70
  const endpoint = options.endpoint ?? DOH_ENDPOINT;
71
+
47
72
  return async (name, type) => {
48
73
  if (options.signal?.aborted) return { status: "timeout", records: [] };
49
74
  const url = new URL(endpoint);
50
75
  url.searchParams.set("name", name);
51
76
  url.searchParams.set("type", type);
77
+
52
78
  try {
53
79
  const response = await fetcher(url, {
54
80
  headers: { accept: "application/dns-json" },
55
81
  signal: options.signal,
56
82
  });
83
+
57
84
  if (!response.ok) return { status: "error", records: [] };
58
- const body = await response.json() as DohJson;
85
+ const parsed = DohJson.safeParse(await response.json());
86
+
87
+ if (!parsed.success) return { status: "error", records: [] };
88
+ const body = parsed.data;
89
+
59
90
  if (body.Status === 3) return { status: "nxdomain", records: [] };
91
+
60
92
  if (body.Status !== 0) return { status: "error", records: [] };
61
93
  const code = recordTypeCodes[type];
62
- const records = (body.Answer ?? [])
63
- .filter((answer) => answer.type === code && typeof answer.data === "string")
64
- .map((answer) => {
65
- const data = answer.data!.trim();
66
- if (type === "TXT") return txtData(data);
67
- return data.replace(/\.$/u, "").toLocaleLowerCase();
68
- });
94
+
95
+ const records = (body.Answer ?? []).flatMap((answer) => {
96
+ if (answer.type !== code || answer.data === undefined) return [];
97
+ const data = answer.data.trim();
98
+
99
+ if (type === "TXT") return [txtData(data)];
100
+
101
+ return [data.replace(/\.$/u, "").toLocaleLowerCase()];
102
+ });
103
+
69
104
  return { status: "ok", records };
70
105
  } catch (error) {
71
- return { status: isAbortError(error) || options.signal?.aborted ? "timeout" : "error", records: [] };
106
+ return {
107
+ status:
108
+ isAbortError(error) || options.signal?.aborted ? "timeout" : "error",
109
+ records: [],
110
+ };
72
111
  }
73
112
  };
74
113
  }
@@ -1,47 +1,82 @@
1
+ import {
2
+ createDb,
3
+ mailboxes,
4
+ hashToken,
5
+ apiError,
6
+ } from "@open-workspace/core/module";
7
+ import type { AppEnv } from "@open-workspace/core/module";
1
8
  import { eq } from "drizzle-orm";
2
9
  import { Hono } from "hono";
3
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
4
- import { mailboxes } from "@open-workspace/core/worker/db/schema.ts";
5
- import type { AppEnv } from "@open-workspace/core/worker/env.ts";
6
- import { hashToken } from "@open-workspace/core/worker/lib/crypto.ts";
7
- import { apiError } from "@open-workspace/core/worker/lib/http.ts";
10
+
8
11
  import { mailboxStub } from "../mailbox";
9
12
 
10
- export const mailDownloadRoutes = new Hono<AppEnv>().get("/mail/:token", async (c) => {
11
- const token = c.req.param("token");
12
- const [mailboxId, messageId, attachmentId, secret, ...extra] = token.split(".");
13
- if (!mailboxId || !messageId || !attachmentId || !secret || extra.length) {
14
- return apiError(c, 404, "NOT_FOUND", "Download link is invalid or expired");
15
- }
13
+ export const mailDownloadRoutes = new Hono<AppEnv>().get(
14
+ "/mail/:token",
15
+ async (c) => {
16
+ const token = c.req.param("token");
16
17
 
17
- // Check D1 first so an arbitrary public token cannot instantiate new DOs.
18
- const [mailbox] = await createDb(c.env.DB)
19
- .select({ id: mailboxes.id })
20
- .from(mailboxes)
21
- .where(eq(mailboxes.id, mailboxId))
22
- .limit(1);
23
- if (!mailbox) {
24
- return apiError(c, 404, "NOT_FOUND", "Download link is invalid or expired");
25
- }
18
+ const [mailboxId, messageId, attachmentId, secret, ...extra] =
19
+ token.split(".");
26
20
 
27
- const file = await mailboxStub(c.env, mailboxId).getAttachment(messageId, attachmentId);
28
- const valid = file?.delivery === "download_link"
29
- && file.downloadExpiresAt !== null
30
- && file.downloadExpiresAt > Date.now()
31
- && file.downloadTokenHash !== null
32
- && file.downloadTokenHash === await hashToken(token);
33
- if (!file || !valid) {
34
- return apiError(c, 404, "NOT_FOUND", "Download link is invalid or expired");
35
- }
21
+ if (!mailboxId || !messageId || !attachmentId || !secret || extra.length) {
22
+ return apiError(
23
+ c,
24
+ 404,
25
+ "NOT_FOUND",
26
+ "Download link is invalid or expired"
27
+ );
28
+ }
29
+
30
+ // Check D1 first so an arbitrary public token cannot instantiate new DOs.
31
+ const [mailbox] = await createDb(c.env.DB)
32
+ .select({ id: mailboxes.id })
33
+ .from(mailboxes)
34
+ .where(eq(mailboxes.id, mailboxId))
35
+ .limit(1);
36
+
37
+ if (!mailbox) {
38
+ return apiError(
39
+ c,
40
+ 404,
41
+ "NOT_FOUND",
42
+ "Download link is invalid or expired"
43
+ );
44
+ }
36
45
 
37
- const object = await c.env.MAIL_STORAGE.get(file.r2Key);
38
- if (!object) return apiError(c, 404, "NOT_FOUND", "Attachment data is missing");
39
- return new Response(object.body, {
40
- headers: {
41
- "cache-control": "private, no-store",
42
- "content-type": file.contentType,
43
- "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.filename)}`,
44
- "x-content-type-options": "nosniff",
45
- },
46
- });
47
- });
46
+ const file = await mailboxStub(c.env, mailboxId).getAttachment(
47
+ messageId,
48
+ attachmentId
49
+ );
50
+
51
+ const valid =
52
+ file?.delivery === "download_link" &&
53
+ file.downloadExpiresAt !== null &&
54
+ file.downloadExpiresAt > Date.now() &&
55
+ file.downloadTokenHash !== null &&
56
+ file.downloadTokenHash === (await hashToken(token));
57
+
58
+ if (!file || !valid) {
59
+ return apiError(
60
+ c,
61
+ 404,
62
+ "NOT_FOUND",
63
+ "Download link is invalid or expired"
64
+ );
65
+ }
66
+
67
+ const object = await c.env.MAIL_STORAGE.get(file.r2Key);
68
+
69
+ if (!object) {
70
+ return apiError(c, 404, "NOT_FOUND", "Attachment data is missing");
71
+ }
72
+
73
+ return new Response(object.body, {
74
+ headers: {
75
+ "cache-control": "private, no-store",
76
+ "content-type": file.contentType,
77
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.filename)}`,
78
+ "x-content-type-options": "nosniff",
79
+ },
80
+ });
81
+ }
82
+ );