@open-workspace/email 0.2.0 → 0.4.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 (223) hide show
  1. package/README.md +23 -20
  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_dry_moon_knight.sql +77 -0
  11. package/migrations/meta/0000_snapshot.json +248 -106
  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 +78 -26
  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 +90 -34
  127. package/worker/jmap/eventsource.ts +169 -0
  128. package/worker/jmap/methods.ts +1716 -361
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +207 -0
  131. package/worker/jmap/routes.ts +448 -86
  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 +84 -52
  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 +283 -171
  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 +871 -542
  184. package/worker/mail/safety-routes.ts +329 -202
  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 +153 -91
  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 +597 -227
  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 +1761 -737
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +7 -14
  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 -126
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/migrations/0000_email.sql +0 -53
  218. package/shared/mail-rules.ts +0 -156
  219. package/worker/admin/report-routes.ts +0 -164
  220. package/worker/mail/reported-messages.ts +0 -68
  221. package/worker/mailbox/legacy-migrations.ts +0 -41
  222. package/worker/mailbox/migrations.ts +0 -10
  223. package/worker/mailbox/rules.ts +0 -110
@@ -37,178 +37,283 @@ type Clause = {
37
37
  /** Number of words seen before the first comment of the clause. */
38
38
  wordsBeforeComment: number | null;
39
39
  };
40
+
40
41
  const CLAUSE_KEYWORDS = new Set(["from", "by", "via", "with", "id", "for"]);
41
42
 
43
+ type RouteScanState = {
44
+ current: Clause | null;
45
+ token: string;
46
+ comment: string;
47
+ depth: number;
48
+ };
49
+
42
50
  /** Tokenizes the route part into keyword clauses at comment depth 0. */
43
51
  function routeClauses(route: string) {
44
52
  const clauses = new Map<string, Clause>();
45
- const state: { current: Clause | null; token: string; comment: string; depth: number } = {
53
+
54
+ const state: RouteScanState = {
46
55
  current: null,
47
56
  token: "",
48
57
  comment: "",
49
58
  depth: 0,
50
59
  };
60
+
51
61
  const flushToken = () => {
52
62
  if (!state.token) return;
53
63
  const keyword = state.token.toLocaleLowerCase();
64
+
54
65
  if (CLAUSE_KEYWORDS.has(keyword) && !clauses.has(keyword)) {
55
66
  state.current = { words: [], comments: [], wordsBeforeComment: null };
56
67
  clauses.set(keyword, state.current);
57
68
  } else {
58
69
  state.current?.words.push(state.token);
59
70
  }
71
+
60
72
  state.token = "";
61
73
  };
74
+
62
75
  for (let index = 0; index < route.length; index += 1) {
63
- const char = route[index]!;
76
+ const char = route.charAt(index);
77
+
64
78
  if (char === "\\" && state.depth > 0) {
65
79
  state.comment += route.slice(index, index + 2);
66
80
  index += 1;
67
81
  continue;
68
82
  }
83
+
69
84
  if (char === "(") {
70
85
  if (state.depth === 0) flushToken();
71
86
  else state.comment += char;
72
87
  state.depth += 1;
73
88
  continue;
74
89
  }
90
+
75
91
  if (char === ")" && state.depth > 0) {
76
92
  state.depth -= 1;
93
+
77
94
  if (state.depth === 0) {
78
95
  const clause = state.current;
96
+
79
97
  if (clause) {
80
98
  clause.comments.push(state.comment.trim());
81
99
  clause.wordsBeforeComment ??= clause.words.length;
82
100
  }
101
+
83
102
  state.comment = "";
84
103
  } else {
85
104
  state.comment += char;
86
105
  }
106
+
87
107
  continue;
88
108
  }
109
+
89
110
  if (state.depth > 0) {
90
111
  state.comment += char;
91
112
  continue;
92
113
  }
114
+
93
115
  if (/\s/u.test(char)) flushToken();
94
116
  else state.token += char;
95
117
  }
118
+
96
119
  flushToken();
120
+
97
121
  return clauses;
98
122
  }
99
123
 
100
124
  // --- IP addresses ---------------------------------------------------------
101
125
 
126
+ function ipv4Octets(value: string): [number, number, number, number] | null {
127
+ const parts = value.split(".");
128
+
129
+ if (
130
+ parts.length !== 4 ||
131
+ !parts.every((octet) => /^\d{1,3}$/u.test(octet) && Number(octet) <= 255)
132
+ ) {
133
+ return null;
134
+ }
135
+
136
+ const [a, b, c, d] = parts.map(Number);
137
+
138
+ if (
139
+ a === undefined ||
140
+ b === undefined ||
141
+ c === undefined ||
142
+ d === undefined
143
+ ) {
144
+ return null;
145
+ }
146
+
147
+ return [a, b, c, d];
148
+ }
149
+
102
150
  function ipv4(value: string) {
103
- const octets = value.split(".");
104
- if (octets.length !== 4) return null;
105
- if (!octets.every((octet) => /^\d{1,3}$/u.test(octet) && Number(octet) <= 255)) return null;
106
- return octets.map(Number).join(".");
151
+ return ipv4Octets(value)?.join(".") ?? null;
107
152
  }
108
153
 
109
154
  function ipv6(value: string) {
110
- let text = value.toLocaleLowerCase().replace(/^ipv6:/u, "").replace(/%.*$/u, "");
155
+ let text = value
156
+ .toLocaleLowerCase()
157
+ .replace(/^ipv6:/u, "")
158
+ .replace(/%.*$/u, "");
159
+
111
160
  let tail: number[] = [];
112
161
  const v4 = /:(\d{1,3}(?:\.\d{1,3}){3})$/u.exec(text);
162
+
113
163
  if (v4) {
114
- const embedded = ipv4(v4[1]!);
164
+ const embedded = ipv4Octets(v4[1]);
165
+
115
166
  if (!embedded) return null;
116
- const [a, b, c, d] = embedded.split(".").map(Number) as [number, number, number, number];
167
+
168
+ const [a, b, c, d] = embedded;
169
+
117
170
  tail = [(a << 8) | b, (c << 8) | d];
118
171
  text = `${text.slice(0, v4.index)}:`;
172
+
119
173
  if (text.endsWith("::")) text = text.slice(0, -1);
120
174
  else text = text.slice(0, -1);
121
175
  }
176
+
122
177
  const halves = text.split("::");
178
+
123
179
  if (halves.length > 2) return null;
180
+
124
181
  const parse = (part: string) =>
125
- part ? part.split(":").map((group) => (/^[0-9a-f]{1,4}$/u.test(group) ? Number.parseInt(group, 16) : Number.NaN)) : [];
126
- const head = parse(halves[0]!);
127
- const rest = halves.length === 2 ? parse(halves[1]!) : [];
182
+ part
183
+ ? part
184
+ .split(":")
185
+ .map((group) =>
186
+ /^[0-9a-f]{1,4}$/u.test(group)
187
+ ? Number.parseInt(group, 16)
188
+ : Number.NaN
189
+ )
190
+ : [];
191
+
192
+ const [first = "", second] = halves;
193
+ const head = parse(first);
194
+ const rest = second === undefined ? [] : parse(second);
128
195
  const total = 8 - tail.length;
196
+
129
197
  if ([...head, ...rest].some(Number.isNaN)) return null;
130
198
  let groups: number[];
199
+
131
200
  if (halves.length === 2) {
132
201
  const missing = total - head.length - rest.length;
202
+
133
203
  if (missing < 1) return null;
134
- groups = [...head, ...Array<number>(missing).fill(0), ...rest];
204
+ groups = [...head, ...Array.from({ length: missing }, () => 0), ...rest];
135
205
  } else {
136
206
  if (head.length !== total) return null;
137
207
  groups = head;
138
208
  }
209
+
139
210
  groups = [...groups, ...tail];
140
211
  // RFC 5952: compress the longest run (length >= 2) of zero groups.
141
212
  let bestStart = -1;
142
213
  let bestLength = 0;
214
+
143
215
  for (let start = 0; start < 8;) {
144
216
  if (groups[start] !== 0) {
145
217
  start += 1;
146
218
  continue;
147
219
  }
220
+
148
221
  let end = start;
222
+
149
223
  while (end < 8 && groups[end] === 0) end += 1;
224
+
150
225
  if (end - start > bestLength && end - start >= 2) {
151
226
  bestStart = start;
152
227
  bestLength = end - start;
153
228
  }
229
+
154
230
  start = end;
155
231
  }
232
+
156
233
  const hex = groups.map((group) => group.toString(16));
234
+
157
235
  if (bestStart < 0) return hex.join(":");
236
+
158
237
  return `${hex.slice(0, bestStart).join(":")}::${hex.slice(bestStart + bestLength).join(":")}`;
159
238
  }
160
239
 
161
240
  /** Validates an IPv4 or IPv6 literal and returns its canonical form. */
162
241
  export function normalizeIp(value: string | null | undefined) {
163
242
  if (!value) return null;
164
- const trimmed = value.trim().replace(/^\[|\]$/gu, "");
243
+ const trimmed = value.trim().replaceAll(/^\[|\]$/gu, "");
244
+
165
245
  return trimmed.includes(":") ? ipv6(trimmed) : ipv4(trimmed);
166
246
  }
167
247
 
168
248
  function fromClauseIp(clause: Clause) {
169
249
  const parts = [clause.words.join(" "), ...clause.comments];
250
+
170
251
  for (const part of parts) {
171
252
  for (const match of part.matchAll(/\[(?:IPv6:)?([0-9a-f:.]+)\]/giu)) {
172
253
  const ip = normalizeIp(match[1]);
254
+
173
255
  if (ip) return { ip, part, literal: match[0] };
174
256
  }
175
257
  }
258
+
176
259
  // Bare literals in parentheses: Cloudflare "(192.0.2.1)", Microsoft "(2603:…::12)".
177
260
  for (const comment of clause.comments) {
178
261
  const ip = normalizeIp(comment);
262
+
179
263
  if (ip) return { ip, part: comment, literal: comment };
180
264
  }
265
+
181
266
  return null;
182
267
  }
183
268
 
184
269
  function heloName(clause: Clause) {
185
270
  for (const comment of clause.comments) {
186
271
  const helo = /\bhelo[= ]\s*([^\s)\]]+)/iu.exec(comment)?.[1];
272
+
187
273
  if (helo) return helo;
188
274
  }
275
+
189
276
  const value = clause.words[0];
277
+
190
278
  return value && !/^\[.*\]$/u.test(value) ? value : null;
191
279
  }
192
280
 
193
281
  function reverseDnsName(found: { part: string; literal: string } | null) {
194
282
  if (!found || found.part === found.literal) return null;
195
- const before = found.part.slice(0, found.part.indexOf(found.literal)).trim().split(/\s+/u).at(-1);
283
+
284
+ const before = found.part
285
+ .slice(0, found.part.indexOf(found.literal))
286
+ .trim()
287
+ .split(/\s+/u)
288
+ .at(-1);
289
+
196
290
  if (!before) return null;
197
291
  const name = before.replace(/\.$/u, "");
198
- if (name.toLocaleLowerCase() === "unknown" || !/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/iu.test(name)) {
292
+
293
+ if (
294
+ name.toLocaleLowerCase() === "unknown" ||
295
+ !/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/iu.test(name)
296
+ ) {
199
297
  return null;
200
298
  }
299
+
201
300
  return name;
202
301
  }
203
302
 
204
303
  function tlsDetails(value: string) {
205
- const version = /\bversion=(TLS1_[0-3])\b/u.exec(value)?.[1]?.replace("_", ".")
206
- ?? /\busing (TLSv1\.[0-3])\b/u.exec(value)?.[1]
207
- ?? /\((TLS1\.[0-3])\)/u.exec(value)?.[1];
304
+ const version =
305
+ /\bversion=(TLS1_[0-3])\b/u.exec(value)?.[1]?.replace("_", ".") ??
306
+ /\busing (TLSv1\.[0-3])\b/u.exec(value)?.[1] ??
307
+ /\((TLS1\.[0-3])\)/u.exec(value)?.[1];
308
+
208
309
  if (version) return version.replace(/^TLSv?/u, "TLS ");
310
+
209
311
  if (/\bwith\s+(?:E?SMTPS|ESMTPSA|UTF8SMTPS)\b/iu.test(value)) return "TLS";
312
+
210
313
  if (/\(Google Transport Security\)/u.test(value)) return "TLS";
314
+
211
315
  if (/\bcipher[= ]/iu.test(value)) return "TLS";
316
+
212
317
  return null;
213
318
  }
214
319
 
@@ -218,6 +323,7 @@ export function parseReceived(value: string): ParsedHop {
218
323
  const segments = splitTopLevel(value, ";");
219
324
  let route: string;
220
325
  let at: Date | null = null;
326
+
221
327
  if (segments.length > 1) {
222
328
  route = segments.slice(0, -1).join(";");
223
329
  at = parseMailDate(segments.at(-1));
@@ -227,21 +333,32 @@ export function parseReceived(value: string): ParsedHop {
227
333
  at = trailing?.date ?? null;
228
334
  route = trailing ? value.slice(0, trailing.index) : value;
229
335
  }
336
+
230
337
  const clauses = routeClauses(route);
231
338
  const fromClause = clauses.get("from");
232
339
  const found = fromClause ? fromClauseIp(fromClause) : null;
233
340
  const from = fromClause ? heloName(fromClause) : null;
234
341
  const reverseDns = reverseDnsName(found);
235
342
  const withClause = clauses.get("with");
343
+
236
344
  return {
237
345
  from,
238
- reverseDns: reverseDns && reverseDns.toLocaleLowerCase() !== from?.toLocaleLowerCase()
239
- ? reverseDns
240
- : null,
346
+ reverseDns:
347
+ reverseDns && reverseDns.toLocaleLowerCase() !== from?.toLocaleLowerCase()
348
+ ? reverseDns
349
+ : null,
241
350
  ip: found?.ip ?? null,
242
351
  by: clauses.get("by")?.words[0] ?? null,
243
352
  protocol: withClause?.words.length
244
- ? withClause.words.slice(0, Math.min(withClause.wordsBeforeComment ?? withClause.words.length, 4)).join(" ") || null
353
+ ? withClause.words
354
+ .slice(
355
+ 0,
356
+ Math.min(
357
+ withClause.wordsBeforeComment ?? withClause.words.length,
358
+ 4
359
+ )
360
+ )
361
+ .join(" ") || null
245
362
  : null,
246
363
  tls: tlsDetails(value),
247
364
  id: clauses.get("id")?.words[0] ?? null,
@@ -257,26 +374,40 @@ const MAX_SKEW_MS = 10 * 60_000;
257
374
 
258
375
  /** Received headers in delivery order: the sender's first relay first. */
259
376
  export function receivedHops(raw: string): ReceivedHop[] {
260
- const values = headerFields(raw).flatMap((field) => field.name === "received" ? [field.value] : []);
377
+ const values = headerFields(raw).flatMap((field) =>
378
+ field.name === "received" ? [field.value] : []
379
+ );
380
+
261
381
  const parsed = values.map(parseReceived);
262
- const hops = parsed.map((hop, index) => ({
263
- ...hop,
264
- trusted: index === 0 && isCloudflareHop(hop),
265
- })).reverse();
382
+
383
+ const hops = parsed
384
+ .map((hop, index) => ({
385
+ ...hop,
386
+ trusted: index === 0 && isCloudflareHop(hop),
387
+ }))
388
+ .reverse();
389
+
266
390
  let previous: Date | null = null;
391
+
267
392
  return hops.map((hop) => {
268
393
  let delayMs: number | null = null;
269
394
  let skewMs: number | null = null;
395
+
270
396
  if (hop.at && previous) {
271
397
  const delta = hop.at.getTime() - previous.getTime();
398
+
272
399
  if (delta >= 0) delayMs = delta;
273
400
  else if (-delta < MAX_SKEW_MS) {
274
401
  delayMs = 0;
275
402
  skewMs = delta;
276
403
  }
277
404
  }
405
+
278
406
  // A skewed hop keeps the later reference so the next delay is not inflated.
279
- if (hop.at && (!previous || (delayMs !== null && skewMs === null))) previous = hop.at;
407
+ if (hop.at && (!previous || (delayMs !== null && skewMs === null))) {
408
+ previous = hop.at;
409
+ }
410
+
280
411
  return { ...hop, delayMs, skewMs };
281
412
  });
282
413
  }
@@ -286,13 +417,25 @@ export type IpKind = "public" | "private" | "loopback" | "reserved";
286
417
  /** Rough classification; enough to tell an internal hop from the internet. */
287
418
  export function ipKind(ip: string): IpKind {
288
419
  const lower = ip.toLowerCase();
420
+
289
421
  if (lower === "::1" || lower.startsWith("127.")) return "loopback";
290
- if (/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|f[cd][0-9a-f]{2}:|fe80:)/u.test(lower)) {
422
+
423
+ if (
424
+ /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|f[cd][0-9a-f]{2}:|fe80:)/u.test(
425
+ lower
426
+ )
427
+ ) {
291
428
  return "private";
292
429
  }
430
+
293
431
  // Documentation, shared and link-local ranges never appear on the open internet.
294
- if (/^(192\.0\.2\.|198\.51\.100\.|203\.0\.113\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|169\.254\.|2001:db8:)/u.test(lower)) {
432
+ if (
433
+ /^(192\.0\.2\.|198\.51\.100\.|203\.0\.113\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|169\.254\.|2001:db8:)/u.test(
434
+ lower
435
+ )
436
+ ) {
295
437
  return "reserved";
296
438
  }
439
+
297
440
  return "public";
298
441
  }
@@ -1,17 +1,74 @@
1
- /** Same-origin proxy path used inside sanitized HTML iframes. */
2
- export function mailRemoteProxyPath(mailboxId: string, remoteUrl: string) {
1
+ /**
2
+ * Same-origin proxy path used inside sanitized HTML iframes; `token` is the
3
+ * one the conversation response's `remoteTokens` gives for `remoteUrl`.
4
+ */
5
+ export function mailRemoteProxyPath(
6
+ mailboxId: string,
7
+ token: string,
8
+ remoteUrl: string
9
+ ) {
3
10
  const params = new URLSearchParams({
4
11
  mailboxId,
12
+ token,
5
13
  url: remoteUrl,
6
14
  });
15
+
7
16
  return `/api/mail/remote?${params.toString()}`;
8
17
  }
9
18
 
10
19
  export function isRemoteHttpUrl(value: string) {
11
20
  try {
12
21
  const url = new URL(value);
22
+
13
23
  return url.protocol === "http:" || url.protocol === "https:";
14
24
  } catch {
15
25
  return false;
16
26
  }
17
27
  }
28
+
29
+ /** More remote images than any real message holds; the rest are not proxied. */
30
+ export const MAX_REMOTE_IMAGES_PER_MESSAGE = 300;
31
+
32
+ const NAMED_ENTITIES = new Map([
33
+ ["amp", "&"],
34
+ ["quot", '"'],
35
+ ["apos", "'"],
36
+ ["lt", "<"],
37
+ ["gt", ">"],
38
+ ]);
39
+
40
+ function decodeEntities(value: string) {
41
+ return value.replaceAll(
42
+ /&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/giu,
43
+ (match, decimal, hex, name) => {
44
+ if (decimal) return String.fromCodePoint(Number(decimal));
45
+
46
+ if (hex) return String.fromCodePoint(Number.parseInt(hex, 16));
47
+
48
+ return NAMED_ENTITIES.get(name.toLowerCase()) ?? match;
49
+ }
50
+ );
51
+ }
52
+
53
+ /**
54
+ * Every http(s) URL in a message's HTML that the browser could find as an
55
+ * image source (src, srcset, background, CSS url()), as the browser reads
56
+ * it: entities decoded. A generous superset; the server signs a proxy token
57
+ * for each, and the browser proxies only URLs it has a token for.
58
+ */
59
+ export function remoteImageUrls(html: string) {
60
+ const found = new Set<string>();
61
+
62
+ for (const [match] of html.matchAll(/https?:\/\/[^\s"'<>()`]+/giu)) {
63
+ for (const raw of [match, decodeEntities(match)]) {
64
+ // A srcset or a sentence can run a comma or period into the URL.
65
+ for (const url of [raw, raw.replace(/[,.;]+$/u, "")]) {
66
+ if (isRemoteHttpUrl(url)) found.add(url);
67
+ }
68
+ }
69
+
70
+ if (found.size >= MAX_REMOTE_IMAGES_PER_MESSAGE) break;
71
+ }
72
+
73
+ return [...found].slice(0, MAX_REMOTE_IMAGES_PER_MESSAGE);
74
+ }
@@ -85,13 +85,28 @@ export type SecurityWarning =
85
85
  /** The From domain itself is listed, not only a link domain. */
86
86
  senderDomain: boolean;
87
87
  }
88
- | { kind: "zen_listed"; severity: "danger" | "caution"; ip: string; lists: string[] }
89
- | { kind: "lookalike_domain"; severity: "danger"; domain: string; resembles: string }
88
+ | {
89
+ kind: "zen_listed";
90
+ severity: "danger" | "caution";
91
+ ip: string;
92
+ lists: string[];
93
+ }
94
+ | {
95
+ kind: "lookalike_domain";
96
+ severity: "danger";
97
+ domain: string;
98
+ resembles: string;
99
+ }
90
100
  | { kind: "display_name_impersonation"; severity: "danger"; name: string }
91
101
  | { kind: "embedded_address"; severity: "caution"; claimed: string }
92
102
  | { kind: "unverified_sender"; severity: "caution"; domain: string | null }
93
103
  /** Replies go to another organization than the one in From. */
94
- | { kind: "reply_to_mismatch"; severity: "caution"; address: string; domain: string }
104
+ | {
105
+ kind: "reply_to_mismatch";
106
+ severity: "caution";
107
+ address: string;
108
+ domain: string;
109
+ }
95
110
  /**
96
111
  * Written for another address and forwarded here. Danger when it is an
97
112
  * account notice from a large provider about someone else's account.
@@ -121,5 +136,8 @@ export type SecurityWarningKind = SecurityWarning["kind"];
121
136
  /** Country flag emoji from an ISO 3166-1 alpha-2 code. */
122
137
  export function countryFlag(code: string | null | undefined) {
123
138
  if (!code || !/^[A-Z]{2}$/u.test(code)) return null;
124
- return String.fromCodePoint(...[...code].map((char) => 0x1f1e6 + char.charCodeAt(0) - 65));
139
+
140
+ return String.fromCodePoint(
141
+ ...[...code].map((char) => 0x1_f1_e6 + char.charCodeAt(0) - 65)
142
+ );
125
143
  }