@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
@@ -0,0 +1,104 @@
1
+ import {
2
+ base64UrlToBytes,
3
+ bytesToBase64Url,
4
+ } from "@open-workspace/core/module";
5
+
6
+ /**
7
+ * Capability tokens for the remote image proxy (GET /api/mail/remote). The
8
+ * conversation response hands the browser one for each remote image URL in
9
+ * a message's HTML (`remoteTokens`), and the sanitized message HTML puts it
10
+ * in that image's proxied URL, so the proxy checks a signature instead of a
11
+ * session and mailbox access in D1, and fetches only URLs a message holds.
12
+ *
13
+ * A token is `<userId>.<expiry>.<HMAC-SHA256>` over the user, the mailbox,
14
+ * the image URL and the expiry. Expiries fall on the end of the window after the current one:
15
+ * every token issued within a window is the same (cached documents and the
16
+ * browser's image cache keep their URLs), and a token is valid for between
17
+ * one and two windows. Losing access to a mailbox, or signing out, stops its
18
+ * images loading at the latest when the token expires.
19
+ */
20
+ export const REMOTE_TOKEN_WINDOW_MS = 6 * 60 * 60 * 1000;
21
+
22
+ const keys = new Map<string, Promise<CryptoKey>>();
23
+
24
+ function hmacKey(secret: string) {
25
+ let key = keys.get(secret);
26
+
27
+ if (!key) {
28
+ key = crypto.subtle.importKey(
29
+ "raw",
30
+ new TextEncoder().encode(secret),
31
+ { name: "HMAC", hash: "SHA-256" },
32
+ false,
33
+ ["sign", "verify"]
34
+ );
35
+ keys.set(secret, key);
36
+ }
37
+
38
+ return key;
39
+ }
40
+
41
+ function signedText(
42
+ userId: string,
43
+ mailboxId: string,
44
+ url: string,
45
+ expiresAt: number
46
+ ) {
47
+ return new TextEncoder().encode(
48
+ `mail-remote\n${userId}\n${mailboxId}\n${expiresAt}\n${url}`
49
+ );
50
+ }
51
+
52
+ /** The token `userId` uses for the remote image at `url` in `mailboxId`'s mail, at `now`. */
53
+ export async function signRemoteToken(
54
+ secret: string,
55
+ userId: string,
56
+ mailboxId: string,
57
+ url: string,
58
+ now = Date.now()
59
+ ) {
60
+ const expiresAt =
61
+ (Math.floor(now / REMOTE_TOKEN_WINDOW_MS) + 2) * REMOTE_TOKEN_WINDOW_MS;
62
+
63
+ const signature = await crypto.subtle.sign(
64
+ "HMAC",
65
+ await hmacKey(secret),
66
+ signedText(userId, mailboxId, url, expiresAt)
67
+ );
68
+
69
+ return `${userId}.${expiresAt.toString(36)}.${bytesToBase64Url(new Uint8Array(signature))}`;
70
+ }
71
+
72
+ /** The user a valid, unexpired token for `url` in `mailboxId` was issued to, else null. */
73
+ export async function verifyRemoteToken(
74
+ secret: string,
75
+ token: string,
76
+ mailboxId: string,
77
+ url: string,
78
+ now = Date.now()
79
+ ) {
80
+ const signatureAt = token.lastIndexOf(".");
81
+ const expiryAt = token.lastIndexOf(".", signatureAt - 1);
82
+
83
+ if (expiryAt <= 0) return null;
84
+ const userId = token.slice(0, expiryAt);
85
+ const expiresAt = Number.parseInt(token.slice(expiryAt + 1, signatureAt), 36);
86
+
87
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= now) return null;
88
+ let signature: Uint8Array<ArrayBuffer>;
89
+
90
+ try {
91
+ signature = new Uint8Array(base64UrlToBytes(token.slice(signatureAt + 1)));
92
+ } catch {
93
+ return null;
94
+ }
95
+
96
+ const valid = await crypto.subtle.verify(
97
+ "HMAC",
98
+ await hmacKey(secret),
99
+ signature,
100
+ signedText(userId, mailboxId, url, expiresAt)
101
+ );
102
+
103
+ return valid ? userId : null;
104
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Runs `step` one attempt after another, each starting once the previous one
3
+ * finished, until it returns a value (anything but undefined) or `limit`
4
+ * attempts have run. For loops that are sequential by nature: polling,
5
+ * following redirects, draining a paginated listing.
6
+ */
7
+ export async function repeatUntil<T>(
8
+ limit: number,
9
+ step: (attempt: number) => Promise<T | undefined>
10
+ ): Promise<T | undefined> {
11
+ for (let attempt = 0; attempt < limit; attempt += 1) {
12
+ // oxlint-disable-next-line eslint/no-await-in-loop -- each attempt depends on the one before (that is this helper's contract)
13
+ const value = await step(attempt);
14
+
15
+ if (value !== undefined) return value;
16
+ }
17
+
18
+ return undefined;
19
+ }
@@ -1,7 +1,11 @@
1
- import { normalizeEmail, normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
1
+ import {
2
+ normalizeEmail,
3
+ normalizeMailboxAddress,
4
+ } from "@open-workspace/core/module";
5
+
6
+ import type { ReplyAction, ReplyPlan } from "../../shared/mail";
2
7
  import type { MailAddress } from "../mailbox/model";
3
8
  import type { Email } from "../mailbox/schema";
4
- import type { ReplyAction, ReplyPlan } from "../../shared/mail";
5
9
  import { uniqueParticipantAddresses } from "./participants";
6
10
 
7
11
  export type {
@@ -16,6 +20,7 @@ function uniqueAddresses(values: MailAddress[], ownAddress: string) {
16
20
 
17
21
  function without(values: string[], excluded: string[]) {
18
22
  const blocked = new Set(excluded.map(normalizeEmail));
23
+
19
24
  return values.filter((value) => !blocked.has(normalizeEmail(value)));
20
25
  }
21
26
 
@@ -32,28 +37,36 @@ type ReplySource = Pick<
32
37
  | "listPostAddress"
33
38
  >;
34
39
 
35
- export function canReplyFrom(email: Pick<ReplySource, "direction" | "messageIdHeader" | "transportState">) {
40
+ export function canReplyFrom(
41
+ email: Pick<ReplySource, "direction" | "messageIdHeader" | "transportState">
42
+ ) {
36
43
  if (email.direction === "incoming") return true;
37
- return Boolean(email.messageIdHeader)
38
- && email.transportState === "submitted";
44
+
45
+ return Boolean(email.messageIdHeader) && email.transportState === "submitted";
39
46
  }
40
47
 
41
- export function buildReplyPlan(ownAddress: string, email: ReplySource): ReplyPlan {
48
+ export function buildReplyPlan(
49
+ ownAddress: string,
50
+ email: ReplySource
51
+ ): ReplyPlan {
42
52
  if (email.direction === "outgoing") {
43
53
  const to = uniqueAddresses(email.toJson, ownAddress);
44
54
  const cc = without(uniqueAddresses(email.ccJson, ownAddress), to);
45
55
  const participants = [...to, ...cc];
56
+
46
57
  return {
47
58
  defaultMode: "continue",
48
59
  isGroup: participants.length > 1,
49
60
  participants,
50
61
  actions: canReplyFrom(email)
51
- ? [{
52
- mode: "continue",
53
- label: "Continue",
54
- to,
55
- cc,
56
- }]
62
+ ? [
63
+ {
64
+ mode: "continue",
65
+ label: "Continue",
66
+ to,
67
+ cc,
68
+ },
69
+ ]
57
70
  : [],
58
71
  };
59
72
  }
@@ -63,46 +76,58 @@ export function buildReplyPlan(ownAddress: string, email: ReplySource): ReplyPla
63
76
  const replyTargets = uniqueAddresses(
64
77
  email.listId
65
78
  ? email.fromJson
66
- : email.replyToJson.length ? email.replyToJson : email.fromJson,
67
- ownAddress,
79
+ : email.replyToJson.length
80
+ ? email.replyToJson
81
+ : email.fromJson,
82
+ ownAddress
68
83
  );
84
+
69
85
  const visibleParticipants = uniqueAddresses(
70
- [
71
- ...email.fromJson,
72
- ...email.toJson,
73
- ...email.ccJson,
74
- ],
75
- ownAddress,
86
+ [...email.fromJson, ...email.toJson, ...email.ccJson],
87
+ ownAddress
76
88
  );
89
+
77
90
  const replyAllParticipants = uniqueAddresses(
78
91
  [
79
92
  ...(email.listId
80
93
  ? email.fromJson
81
- : email.replyToJson.length ? email.replyToJson : email.fromJson),
94
+ : email.replyToJson.length
95
+ ? email.replyToJson
96
+ : email.fromJson),
82
97
  ...email.toJson,
83
98
  ...email.ccJson,
84
99
  ],
85
- ownAddress,
100
+ ownAddress
86
101
  );
87
- const visibleIsGroup = Boolean(email.listId) || replyAllParticipants.length > 1;
102
+
103
+ const visibleIsGroup =
104
+ Boolean(email.listId) || replyAllParticipants.length > 1;
105
+
88
106
  const own = normalizeMailboxAddress(ownAddress);
107
+
89
108
  const visibleRecipients = [...email.toJson, ...email.ccJson].some(
90
- (recipient) => normalizeMailboxAddress(recipient.address) === own,
109
+ (recipient) => normalizeMailboxAddress(recipient.address) === own
91
110
  );
111
+
92
112
  const undisclosedLocalRecipient = !email.listId && !visibleRecipients;
93
113
  const isGroup = visibleIsGroup && !undisclosedLocalRecipient;
94
- const actions: ReplyAction[] = [{
95
- mode: "reply",
96
- label: "Reply",
97
- to: replyTargets,
98
- cc: [],
99
- }];
114
+
115
+ const actions: ReplyAction[] = [
116
+ {
117
+ mode: "reply",
118
+ label: "Reply",
119
+ to: replyTargets,
120
+ cc: [],
121
+ },
122
+ ];
123
+
100
124
  const listTargets = uniqueAddresses(
101
125
  email.listPostAddress
102
126
  ? [{ address: email.listPostAddress, name: null }]
103
127
  : [],
104
- ownAddress,
128
+ ownAddress
105
129
  ).slice(0, 1);
130
+
106
131
  if (!email.listId && visibleIsGroup) {
107
132
  actions.push({
108
133
  mode: "reply_all",
@@ -128,9 +153,13 @@ export function buildReplyPlan(ownAddress: string, email: ReplySource): ReplyPla
128
153
  ? "reply"
129
154
  : undisclosedLocalRecipient
130
155
  ? "reply"
131
- : isGroup ? "reply_all" : "reply",
156
+ : isGroup
157
+ ? "reply_all"
158
+ : "reply",
132
159
  isGroup,
133
- participants: undisclosedLocalRecipient ? replyTargets : visibleParticipants,
160
+ participants: undisclosedLocalRecipient
161
+ ? replyTargets
162
+ : visibleParticipants,
134
163
  actions,
135
164
  };
136
165
  }
@@ -1,5 +1,6 @@
1
+ import { normalizeEmail } from "@open-workspace/core/module";
1
2
  import type { Header } from "postal-mime";
2
- import { normalizeEmail } from "@open-workspace/core/worker/lib/ids.ts";
3
+
3
4
  import type { MailAddress } from "../mailbox/model";
4
5
 
5
6
  const MAX_REFERENCE_IDS = 100;
@@ -8,19 +9,31 @@ const MAX_MESSAGE_ID_BYTES = 900;
8
9
  const textEncoder = new TextEncoder();
9
10
 
10
11
  export function boundedMessageIds(values: string[]) {
11
- const unique = [...new Set(values.map((item) => item.trim()).filter(Boolean))];
12
+ const unique = [
13
+ ...new Set(
14
+ values.flatMap((item) => {
15
+ const trimmed = item.trim();
16
+
17
+ return trimmed ? [trimmed] : [];
18
+ })
19
+ ),
20
+ ];
21
+
12
22
  const newestFirst: string[] = [];
13
23
  let bytes = 0;
14
- for (let index = unique.length - 1; index >= 0; index -= 1) {
24
+
25
+ for (const value of unique.reverse()) {
15
26
  if (newestFirst.length >= MAX_REFERENCE_IDS) break;
16
- const value = unique[index]!;
17
27
  const valueBytes = textEncoder.encode(value).byteLength;
28
+
18
29
  if (valueBytes > MAX_MESSAGE_ID_BYTES) continue;
19
30
  const nextBytes = valueBytes + (newestFirst.length ? 1 : 0);
31
+
20
32
  if (bytes + nextBytes > MAX_REFERENCE_BYTES) continue;
21
33
  newestFirst.push(value);
22
34
  bytes += nextBytes;
23
35
  }
36
+
24
37
  return newestFirst.reverse();
25
38
  }
26
39
 
@@ -28,6 +41,7 @@ export function messageIds(value: string | undefined) {
28
41
  if (!value) return [];
29
42
  const bracketed = value.match(/<[^<>]+>/gu);
30
43
  const values = bracketed ?? value.split(/\s+/u);
44
+
31
45
  return boundedMessageIds(values);
32
46
  }
33
47
 
@@ -37,18 +51,26 @@ export function replyThreadHeaders(parent: {
37
51
  referencesJson: string[];
38
52
  }) {
39
53
  const parentMessageId = messageIds(parent.messageIdHeader ?? undefined)[0];
54
+
40
55
  if (!parentMessageId) return { inReplyTo: [], references: [] };
56
+
41
57
  const ancestry = parent.referencesJson.length
42
58
  ? parent.referencesJson
43
- : parent.inReplyToJson.length === 1 ? parent.inReplyToJson : [];
59
+ : parent.inReplyToJson.length === 1
60
+ ? parent.inReplyToJson
61
+ : [];
62
+
44
63
  return {
45
64
  inReplyTo: [parentMessageId],
46
65
  references: boundedMessageIds([...ancestry, parentMessageId]),
47
66
  };
48
67
  }
49
68
 
50
- export function address(address: string, name: string | null = null): MailAddress {
51
- return { address: normalizeEmail(address), name: name?.trim() || null };
69
+ export function address(
70
+ email: string,
71
+ name: string | null = null
72
+ ): MailAddress {
73
+ return { address: normalizeEmail(email), name: name?.trim() || null };
52
74
  }
53
75
 
54
76
  export function headerValue(headers: Header[], name: string) {
@@ -57,13 +79,16 @@ export function headerValue(headers: Header[], name: string) {
57
79
 
58
80
  export function listId(headers: Header[]) {
59
81
  const value = headerValue(headers, "list-id");
82
+
60
83
  return value?.match(/<([^<>]+)>/u)?.[1] ?? value;
61
84
  }
62
85
 
63
86
  export function listPostAddress(value: string | null | undefined) {
64
87
  if (!value) return null;
65
88
  const match = /<mailto:([^?>]+)(?:\?[^>]*)?>/iu.exec(value);
89
+
66
90
  if (!match?.[1]) return null;
91
+
67
92
  try {
68
93
  return normalizeEmail(decodeURIComponent(match[1]));
69
94
  } catch {