@open-workspace/email 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) 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.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -1,5 +1,6 @@
1
1
  import { getDomainWithoutSuffix } from "tldts";
2
2
 
3
+ import { confusablesData } from "./confusables-data";
3
4
  import { organizationalDomain } from "./org-domain";
4
5
 
5
6
  // --- Punycode (RFC 3492 decoding only) ------------------------------------
@@ -84,74 +85,54 @@ export function domainToUnicode(domain: string) {
84
85
  .join(".");
85
86
  }
86
87
 
87
- // --- Confusable skeleton (a practical subset of UTS #39) ------------------
88
-
89
- const CONFUSABLES = new Map(
90
- Object.entries({
91
- // Cyrillic
92
- а: "a",
93
- в: "b",
94
- е: "e",
95
- ё: "e",
96
- к: "k",
97
- м: "m",
98
- н: "h",
99
- о: "o",
100
- р: "p",
101
- с: "c",
102
- т: "t",
103
- у: "y",
104
- х: "x",
105
- ѕ: "s",
106
- і: "i",
107
- ї: "i",
108
- ј: "j",
109
- ԁ: "d",
110
- һ: "h",
111
- ӏ: "l",
112
- ԛ: "q",
113
- ԝ: "w",
114
- ɡ: "g",
115
- // Greek
116
- α: "a",
117
- β: "b",
118
- ε: "e",
119
- η: "n",
120
- ι: "i",
121
- κ: "k",
122
- ν: "v",
123
- ο: "o",
124
- ρ: "p",
125
- τ: "t",
126
- υ: "u",
127
- χ: "x",
128
- ω: "w",
129
- // Look-alike digits and symbols
130
- "0": "o",
131
- "1": "l",
132
- "3": "e",
133
- "5": "s",
134
- "|": "l",
135
- ı: "i",
136
- ł: "l",
137
- ø: "o",
138
- đ: "d",
139
- })
140
- );
141
-
142
- /** Lowercased, accent-free, confusables folded, with multi-letter look-alikes merged. */
143
- export function confusableSkeleton(value: string) {
144
- const folded = [...value.normalize("NFKD").toLocaleLowerCase()]
145
- .flatMap((char) =>
146
- /\p{M}/u.test(char) ? [] : [CONFUSABLES.get(char) ?? char]
147
- )
148
- .join("");
88
+ // --- UTS #39 confusable skeleton ---------------------------------------------
89
+
90
+ const CONFUSABLES = new Map<string, string>();
91
+
92
+ {
93
+ let point = 0;
94
+
95
+ for (const entry of confusablesData.split(",")) {
96
+ const [delta, to] = entry.split(":");
149
97
 
150
- return folded
151
- .replaceAll("rn", "m")
152
- .replaceAll("vv", "w")
153
- .replaceAll("cl", "d")
154
- .replaceAll("i", "l");
98
+ point += Number.parseInt(delta, 36);
99
+ CONFUSABLES.set(
100
+ String.fromCodePoint(point),
101
+ String.fromCodePoint(
102
+ ...to.split(".").map((code) => Number.parseInt(code, 36))
103
+ )
104
+ );
105
+ }
106
+ }
107
+
108
+ /**
109
+ * UTS #39 `skeleton(X) = NFD(map each character of NFD(X) via
110
+ * confusables.txt)`: two strings that look alike have the same skeleton.
111
+ * Case is kept: a capital Greek Nu is drawn like an N, its lowercase like a v.
112
+ */
113
+ export function skeleton(value: string) {
114
+ return Array.from(
115
+ value.normalize("NFD"),
116
+ (char) => CONFUSABLES.get(char) ?? char
117
+ )
118
+ .join("")
119
+ .normalize("NFD");
120
+ }
121
+
122
+ /**
123
+ * The skeletons of a text written in lowercase and in capitals. The
124
+ * confusables data is case-sensitive, so a look-alike may show in one case
125
+ * only: a capital Greek Nu in "Νikοs" is an N, its lowercase a v; "1BM"
126
+ * reads as "IBM", "1bm" not as "ibm". Folding before the skeleton would
127
+ * miss the first; folding after it would merge "Ian" (I→l) with "Lan".
128
+ * Mail shows a name as written and a domain in either case, so two texts
129
+ * that share either skeleton look alike.
130
+ */
131
+ function caseSkeletons(value: string) {
132
+ return [
133
+ skeleton(value.toLocaleLowerCase()),
134
+ skeleton(value.toLocaleUpperCase()),
135
+ ] as const;
155
136
  }
156
137
 
157
138
  export function levenshtein(left: string, right: string) {
@@ -186,10 +167,14 @@ function maxEdits(length: number) {
186
167
  return length < 7 ? 1 : 2;
187
168
  }
188
169
 
170
+ const notAlphanumeric = /[^\p{L}\p{M}\p{N}]/gu;
171
+
189
172
  /**
190
173
  * The workspace domain that `senderDomain` imitates, if any. Compares the
191
- * registrable labels after Unicode/punycode confusable folding, and the
192
- * whole registrable name without separators (`demo-examp1e.com` vs `demo.example`).
174
+ * registrable labels decoded from punycode by their UTS #39 skeletons, and
175
+ * the whole registrable name without separators (`demo-examp1e.com` vs
176
+ * `demo.example`); a few edits away (`nortwind`, `northvvind`) is close
177
+ * enough for a longer name.
193
178
  */
194
179
  export function lookalikeOf(
195
180
  senderDomain: string | null,
@@ -197,40 +182,43 @@ export function lookalikeOf(
197
182
  ) {
198
183
  if (!senderDomain) return null;
199
184
  const unicode = domainToUnicode(senderDomain.toLocaleLowerCase());
200
- const senderOrg = organizationalDomain(senderDomain) ?? senderDomain;
201
185
 
202
- const senderLabel = confusableSkeleton(
203
- registrableLabel(domainToUnicode(senderOrg))
186
+ const senderOrg = domainToUnicode(
187
+ (organizationalDomain(senderDomain) ?? senderDomain).toLocaleLowerCase()
204
188
  );
205
189
 
206
- const senderFlat = senderLabel.replaceAll(/[^\p{L}\p{N}]/gu, "");
190
+ const senderName = registrableLabel(senderOrg);
191
+ const senderLabel = caseSkeletons(senderName);
192
+ const senderFlat = skeleton(senderName.replaceAll(notAlphanumeric, ""));
207
193
 
208
194
  for (const workspace of workspaceDomains) {
209
195
  const own = workspace.toLocaleLowerCase();
210
196
  const ownOrg = organizationalDomain(own) ?? own;
211
197
 
212
- if (senderOrg === ownOrg) continue;
213
- const ownLabel = confusableSkeleton(registrableLabel(ownOrg));
214
-
215
- const ownFlat = confusableSkeleton(ownOrg).replaceAll(
216
- /[^\p{L}\p{N}]/gu,
217
- ""
218
- );
198
+ if (domainToUnicode(ownOrg) === senderOrg) continue;
199
+ const ownName = registrableLabel(ownOrg);
219
200
 
220
- if (ownLabel.length < 3) continue;
201
+ if (ownName.length < 3) continue;
202
+ const ownLabel = caseSkeletons(ownName);
203
+ const ownPlain = ownOrg.replaceAll(notAlphanumeric, "");
204
+ const ownFlat = skeleton(ownPlain);
221
205
 
222
206
  // Same name under another suffix, or a homoglyph/punycode spelling of it.
223
- if (senderLabel === ownLabel || senderFlat === ownFlat) {
207
+ if (
208
+ senderLabel[0] === ownLabel[0] ||
209
+ senderLabel[1] === ownLabel[1] ||
210
+ senderFlat === ownFlat
211
+ ) {
224
212
  return { domain: unicode, resembles: own };
225
213
  }
226
214
 
227
- if (levenshtein(senderLabel, ownLabel) <= maxEdits(ownLabel.length)) {
215
+ if (levenshtein(senderLabel[0], ownLabel[0]) <= maxEdits(ownName.length)) {
228
216
  return { domain: unicode, resembles: own };
229
217
  }
230
218
 
231
219
  if (
232
- ownFlat.length >= 6 &&
233
- levenshtein(senderFlat, ownFlat) <= maxEdits(ownFlat.length)
220
+ ownPlain.length >= 6 &&
221
+ levenshtein(senderFlat, ownFlat) <= maxEdits(ownPlain.length)
234
222
  ) {
235
223
  return { domain: unicode, resembles: own };
236
224
  }
@@ -241,27 +229,40 @@ export function lookalikeOf(
241
229
 
242
230
  // --- Display names ----------------------------------------------------------
243
231
 
244
- export function normalizedPersonName(value: string | null | undefined) {
245
- if (!value) return "";
232
+ /**
233
+ * A display name's two skeletons (see `caseSkeletons`) as compared with the
234
+ * workspace's names: invisible characters (format controls such as a
235
+ * zero-width space, soft hyphen or word joiner, and variation selectors)
236
+ * dropped, NFKC-normalized (full-width letters), punctuation and spacing
237
+ * ignored. Accents and vowel signs stay, as the skeleton keeps them:
238
+ * "Nguyen" and "Nguyễn" are not drawn alike.
239
+ */
240
+ function personNameKeys(value: string | null | undefined) {
241
+ const text = (value ?? "")
242
+ .replaceAll(/[\p{Cf}\p{Default_Ignorable_Code_Point}]/gu, "")
243
+ .normalize("NFKC");
246
244
 
247
- return value
248
- .normalize("NFKC")
249
- .toLocaleLowerCase()
250
- .replaceAll(/[^\p{L}\p{N}\s]/gu, " ")
251
- .replaceAll(/\s+/gu, " ")
252
- .trim();
245
+ return caseSkeletons(text).map((form) =>
246
+ form.replaceAll(/[^\p{L}\p{M}\p{N}]+/gu, " ").trim()
247
+ );
253
248
  }
254
249
 
255
- /** Internal names worth protecting: at least two words, so "Support" alone never matches. */
250
+ /**
251
+ * Internal names worth protecting: at least two words, so "Support" alone
252
+ * never matches. Keyed by both skeletons of the name (`personNameKeys`), so
253
+ * a copy spelled with look-alikes from any script matches as well.
254
+ */
256
255
  export function protectedNames(names: (string | null | undefined)[]) {
257
256
  const result = new Map<string, string>();
258
257
 
259
258
  for (const name of names) {
260
- if (!name) continue;
261
- const normalized = normalizedPersonName(name);
259
+ const [lower, upper] = personNameKeys(name);
260
+
261
+ if (name && lower.split(" ").length >= 2 && lower.length >= 5) {
262
+ const shown = name.trim().replaceAll(/\s+/gu, " ");
262
263
 
263
- if (normalized.split(" ").length >= 2 && normalized.length >= 5) {
264
- result.set(normalized, name.trim().replaceAll(/\s+/gu, " "));
264
+ result.set(`lower ${lower}`, shown);
265
+ result.set(`upper ${upper}`, shown);
265
266
  }
266
267
  }
267
268
 
@@ -273,11 +274,11 @@ export function impersonatedName(
273
274
  displayName: string | null | undefined,
274
275
  names: ReadonlyMap<string, string>
275
276
  ) {
276
- const normalized = normalizedPersonName(displayName);
277
+ const [lower, upper] = personNameKeys(displayName);
277
278
 
278
- if (!normalized) return null;
279
+ if (!lower) return null;
279
280
 
280
- return names.get(normalized) ?? null;
281
+ return names.get(`lower ${lower}`) ?? names.get(`upper ${upper}`) ?? null;
281
282
  }
282
283
 
283
284
  /** `"ceo@ourco.com" <x@elsewhere.example>`: an address in the name that is not the sender. */
@@ -6,15 +6,15 @@ import {
6
6
  mailboxAddressSql,
7
7
  mailboxKind,
8
8
  mailboxKindOrderSql,
9
- mailboxAccess,
10
- mailboxes,
11
9
  apiError,
12
10
  zValidator,
13
11
  } from "@open-workspace/core/module";
14
12
  import type { Database, AppEnv } from "@open-workspace/core/module";
15
- import { eq } from "drizzle-orm";
13
+ import { mailboxes } from "@open-workspace/core/schema";
14
+ import { and, eq } from "drizzle-orm";
16
15
  import { Hono } from "hono";
17
16
  import type { Context } from "hono";
17
+ import { bodyLimit } from "hono/body-limit";
18
18
  import { z } from "zod";
19
19
 
20
20
  import {
@@ -28,8 +28,7 @@ import {
28
28
  MAIL_ORGANIZE_SCOPE,
29
29
  } from "../../shared/permissions";
30
30
  import { mailboxStub } from "../mailbox";
31
- import { readCappedBody } from "./capped-body";
32
- import { rawMessageId } from "./inbound";
31
+ import { importRawMessage } from "./import";
33
32
 
34
33
  /**
35
34
  * Importing existing mail (the `open-workspace import` CLI).
@@ -78,17 +77,6 @@ const importQuerySchema = z.object({
78
77
  direction: z.enum(["incoming", "outgoing"]).optional(),
79
78
  });
80
79
 
81
- async function sha256Hex(value: string) {
82
- const digest = await crypto.subtle.digest(
83
- "SHA-256",
84
- new TextEncoder().encode(value)
85
- );
86
-
87
- return [...new Uint8Array(digest)]
88
- .map((byte) => byte.toString(16).padStart(2, "0"))
89
- .join("");
90
- }
91
-
92
80
  /** A mailbox's import target: where it is and who can open it. */
93
81
  async function importMailbox(db: Database, mailboxId: string) {
94
82
  const [mailbox] = await db
@@ -98,7 +86,13 @@ async function importMailbox(db: Database, mailboxId: string) {
98
86
  ownerUserId: mailboxes.ownerUserId,
99
87
  })
100
88
  .from(mailboxes)
101
- .where(eq(mailboxes.id, mailboxId))
89
+ .where(
90
+ and(
91
+ eq(mailboxes.id, mailboxId),
92
+ // Only an inbox keeps mail: a list's would be read by no one.
93
+ eq(mailboxes.delivery, "inbox")
94
+ )
95
+ )
102
96
  .limit(1);
103
97
 
104
98
  return mailbox ?? null;
@@ -140,22 +134,6 @@ async function authorizedMailbox(c: Context<AppEnv>, mailboxId: string) {
140
134
  );
141
135
  }
142
136
 
143
- class TooLargeError extends Error {}
144
-
145
- /** The request body, refusing one larger than `limit` without reading it all. */
146
- async function boundedBody(request: Request, limit: number) {
147
- const declared = Number(request.headers.get("content-length") ?? Number.NaN);
148
-
149
- if (declared > limit) throw new TooLargeError();
150
-
151
- if (!request.body) return new Uint8Array();
152
- const body = await readCappedBody(request.body, limit);
153
-
154
- if (!body) throw new TooLargeError();
155
-
156
- return body;
157
- }
158
-
159
137
  export const mailImportRoutes = new Hono<AppEnv>()
160
138
  .use("*", requireAuth)
161
139
  .use("*", oauthScopeAnyOf(MAIL_ORGANIZE_SCOPE, IMPORT_MAIL_SCOPE))
@@ -199,25 +177,22 @@ export const mailImportRoutes = new Hono<AppEnv>()
199
177
  .post(
200
178
  "/mailboxes/:id/messages",
201
179
  zValidator("query", importQuerySchema),
180
+ bodyLimit({
181
+ maxSize: MAX_IMPORT_MESSAGE_BYTES,
182
+ onError: (c) =>
183
+ apiError(
184
+ c,
185
+ 413,
186
+ "TOO_LARGE",
187
+ `Messages are limited to ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB, the size Email Routing delivers`
188
+ ),
189
+ }),
202
190
  async (c) => {
203
191
  const target = await authorizedMailbox(c, c.req.param("id"));
204
192
 
205
193
  if (target instanceof Response) return target;
206
194
  const input = c.req.valid("query");
207
- let raw: Uint8Array;
208
-
209
- try {
210
- raw = await boundedBody(c.req.raw, MAX_IMPORT_MESSAGE_BYTES);
211
- } catch (error) {
212
- if (!(error instanceof TooLargeError)) throw error;
213
-
214
- return apiError(
215
- c,
216
- 413,
217
- "TOO_LARGE",
218
- `Messages are limited to ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB, the size Email Routing delivers`
219
- );
220
- }
195
+ const raw = new Uint8Array(await c.req.arrayBuffer());
221
196
 
222
197
  if (!raw.byteLength) {
223
198
  return apiError(
@@ -228,44 +203,16 @@ export const mailImportRoutes = new Hono<AppEnv>()
228
203
  );
229
204
  }
230
205
 
231
- const mailbox = mailboxStub(c.env, target.id);
232
- const importId = `imp_${(await sha256Hex(input.sourceId)).slice(0, 32)}`;
233
- const known = await mailbox.findImported(importId, rawMessageId(raw));
234
-
235
- if (known) {
236
- return c.json({
237
- ok: true as const,
238
- duplicate: true as const,
239
- ...known,
240
- });
241
- }
242
-
243
- const rawObjectKey = `mailboxes/${target.id}/raw/${importId}.eml`;
244
- await c.env.MAIL_STORAGE.put(rawObjectKey, raw, {
245
- httpMetadata: { contentType: "message/rfc822" },
246
- });
247
-
248
- const seenBy =
249
- input.seen === "1"
250
- ? (
251
- await createDb(c.env.DB)
252
- .select({ userId: mailboxAccess.userId })
253
- .from(mailboxAccess)
254
- .where(eq(mailboxAccess.mailboxId, target.id))
255
- ).map((row) => row.userId)
256
- : [];
257
-
258
- const result = await mailbox.importMessage({
259
- importId,
260
- rawObjectKey,
261
- mailboxAddress: target.address,
206
+ const result = await importRawMessage({
207
+ env: c.env,
208
+ mailbox: target,
209
+ raw,
210
+ importKey: input.sourceId,
262
211
  receivedAt: input.receivedAt,
263
212
  placement: input.placement,
264
213
  folderName: input.folder ?? null,
265
- seenBy,
266
- conversationId: input.thread
267
- ? `conv_imp_${(await sha256Hex(input.thread)).slice(0, 32)}`
268
- : null,
214
+ seen: input.seen === "1",
215
+ thread: input.thread ?? null,
269
216
  direction: input.direction ?? null,
270
217
  });
271
218
 
@@ -0,0 +1,130 @@
1
+ /** Storing existing messages in a mailbox: the import routes, JMAP Email/import and backup restores all go through here. */
2
+ import { createDb } from "@open-workspace/core/module";
3
+ import { mailboxAccess } from "@open-workspace/core/schema";
4
+ import { eq } from "drizzle-orm";
5
+
6
+ import type { ImportPlacement } from "../../shared/mail-import";
7
+ import { mailboxStub } from "../mailbox";
8
+ import type {
9
+ ImportMessageInput,
10
+ ImportMessageResult,
11
+ ImportOriginal,
12
+ } from "../mailbox/support";
13
+ import { inboundMessageId, rawMessageId } from "./inbound";
14
+ import { mailboxAliases } from "./outgoing-context";
15
+ import { rawMessageKey } from "./storage-keys";
16
+
17
+ async function importIdOf(importKey: string | Uint8Array<ArrayBuffer>) {
18
+ return `imp_${(await sha256Hex(importKey)).slice(0, 32)}`;
19
+ }
20
+
21
+ /** The id a message imported under `importKey` has in its mailbox. */
22
+ export async function importedEmailId(importKey: string) {
23
+ return inboundMessageId(await importIdOf(importKey));
24
+ }
25
+
26
+ export async function importedConversationId(thread: string) {
27
+ return `conv_imp_${(await sha256Hex(thread)).slice(0, 32)}`;
28
+ }
29
+
30
+ async function sha256Hex(value: string | Uint8Array<ArrayBuffer>) {
31
+ const digest = await crypto.subtle.digest(
32
+ "SHA-256",
33
+ value instanceof Uint8Array ? value : new TextEncoder().encode(value)
34
+ );
35
+
36
+ return [...new Uint8Array(digest)]
37
+ .map((byte) => byte.toString(16).padStart(2, "0"))
38
+ .join("");
39
+ }
40
+
41
+ /** Mail sent to oneself can share its Message-ID with the received copy. */
42
+ export function importCopyKey(
43
+ raw: Uint8Array,
44
+ direction: ImportMessageInput["direction"]
45
+ ) {
46
+ if (!direction) return null;
47
+ const messageId = rawMessageId(raw);
48
+
49
+ return messageId ? { messageId, direction } : null;
50
+ }
51
+
52
+ /**
53
+ * Stores one raw message in a mailbox as an import: kept once per
54
+ * `importKey` (and per Message-ID), read for everyone who can open the
55
+ * mailbox when `seen`, threaded by `thread` when given.
56
+ */
57
+ export async function importRawMessage(
58
+ input: {
59
+ env: Env;
60
+ mailbox: { id: string; address: string };
61
+ raw: Uint8Array;
62
+ /** The message's id at its source (or its bytes); importing it again does nothing. */
63
+ importKey: string | Uint8Array<ArrayBuffer>;
64
+ receivedAt: number | null;
65
+ placement: ImportPlacement;
66
+ folderName: string | null;
67
+ thread: string | null;
68
+ direction: "incoming" | "outgoing" | null;
69
+ /** A backup's ids for the message in this mailbox: see `ImportMessageInput`. */
70
+ original?: ImportOriginal;
71
+ linkedFiles?: ImportMessageInput["linkedFiles"];
72
+ } & ({ seen: boolean } | { seenBy: string[] })
73
+ ) {
74
+ const { env, mailbox: target, raw } = input;
75
+ const mailbox = mailboxStub(env, target.id);
76
+ const importId = await importIdOf(input.importKey);
77
+ const original = input.original ?? null;
78
+
79
+ const conversationId = input.thread
80
+ ? await importedConversationId(input.thread)
81
+ : null;
82
+
83
+ const direction =
84
+ input.direction ?? (input.placement === "sent" ? "outgoing" : null);
85
+
86
+ const known = await mailbox.findImported(
87
+ inboundMessageId(importId),
88
+ original,
89
+ conversationId,
90
+ importCopyKey(raw, direction)
91
+ );
92
+
93
+ if (known) {
94
+ const duplicate: ImportMessageResult = { status: "duplicate", ...known };
95
+
96
+ return duplicate;
97
+ }
98
+
99
+ const rawObjectKey = rawMessageKey(target.id, importId);
100
+ await env.MAIL_STORAGE.put(rawObjectKey, raw, {
101
+ httpMetadata: { contentType: "message/rfc822" },
102
+ });
103
+
104
+ const [readers, aliases] = await Promise.all([
105
+ "seen" in input && input.seen
106
+ ? createDb(env.DB)
107
+ .select({ userId: mailboxAccess.userId })
108
+ .from(mailboxAccess)
109
+ .where(eq(mailboxAccess.mailboxId, target.id))
110
+ : [],
111
+ direction === null ? mailboxAliases(env.DB, target.id) : [],
112
+ ]);
113
+
114
+ const result: ImportMessageResult = await mailbox.importMessage({
115
+ importId,
116
+ rawObjectKey,
117
+ mailboxAddress: target.address,
118
+ aliases: aliases.map((alias) => alias.address),
119
+ receivedAt: input.receivedAt,
120
+ placement: input.placement,
121
+ folderName: input.folderName,
122
+ seenBy: "seenBy" in input ? input.seenBy : readers.map((row) => row.userId),
123
+ conversationId,
124
+ original,
125
+ linkedFiles: input.linkedFiles,
126
+ direction,
127
+ });
128
+
129
+ return result;
130
+ }
@@ -4,11 +4,15 @@ import {
4
4
  normalizeMailboxAddress,
5
5
  } from "@open-workspace/core/module";
6
6
 
7
+ export async function inboundMessageDigest(raw: ArrayBuffer) {
8
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", raw));
9
+ }
10
+
7
11
  export async function inboundDeliveryId(input: {
8
12
  mailboxId: string;
9
13
  envelopeFrom: string;
10
14
  envelopeTo: string;
11
- raw: ArrayBuffer;
15
+ rawDigest: Uint8Array;
12
16
  }) {
13
17
  const prefix = new TextEncoder().encode(
14
18
  [
@@ -19,10 +23,7 @@ export async function inboundDeliveryId(input: {
19
23
  ].join("\0")
20
24
  );
21
25
 
22
- const rawDigest = new Uint8Array(
23
- await crypto.subtle.digest("SHA-256", input.raw)
24
- );
25
-
26
+ const { rawDigest } = input;
26
27
  const digestInput = new Uint8Array(prefix.byteLength + rawDigest.byteLength);
27
28
  digestInput.set(prefix);
28
29
  digestInput.set(rawDigest, prefix.byteLength);