@open-workspace/email 0.3.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 (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,155 @@
1
+ import type { AppEnv } from "@open-workspace/core/module";
2
+ import { timed } from "@open-workspace/core/module";
3
+ import type { Context } from "hono";
4
+
5
+ import { mailS3 } from "./r2-presigned-urls";
6
+ import { fetchProxiedRemoteMedia } from "./remote-proxy";
7
+
8
+ /*
9
+ * The colo-local Cache API in front of R2 message bodies and remote images.
10
+ * Entries live under synthetic URLs (an .invalid host the Worker never
11
+ * serves), so only this code reads them: no client request reaches one.
12
+ * Both caches are best effort; a failing cache falls through to the source.
13
+ */
14
+
15
+ /** Stored bodies never change; a day bounds how long a deleted one lingers. */
16
+ const BODY_TTL_SECONDS = 24 * 60 * 60;
17
+
18
+ /** Bodies above this go straight to R2 every time. */
19
+ const MAX_CACHED_BODY_BYTES = 2 * 1024 * 1024;
20
+
21
+ /** Remote images are shared by everyone who opens the same newsletter. */
22
+ const REMOTE_TTL_SECONDS = 24 * 60 * 60;
23
+
24
+ async function openCache(name: string) {
25
+ try {
26
+ return await caches.open(name);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ function background(c: Context<AppEnv>, work: Promise<unknown>) {
33
+ const guarded = work.catch(() => undefined);
34
+
35
+ try {
36
+ c.executionCtx.waitUntil(guarded);
37
+ } catch {
38
+ // No execution context (in-process calls): the promise still runs.
39
+ }
40
+ }
41
+
42
+ async function sha256Hex(value: string) {
43
+ const digest = await crypto.subtle.digest(
44
+ "SHA-256",
45
+ new TextEncoder().encode(value)
46
+ );
47
+
48
+ return [...new Uint8Array(digest)]
49
+ .map((byte) => byte.toString(16).padStart(2, "0"))
50
+ .join("");
51
+ }
52
+
53
+ /**
54
+ * A stored message body (HTML) by its R2 key: from this colo's cache when an
55
+ * earlier request put it there, else from R2, then cached.
56
+ */
57
+ export async function readStoredBody(c: Context<AppEnv>, key: string) {
58
+ const cache = await openCache("openworkspace:mail-bodies");
59
+
60
+ // The bucket name keeps workspaces that share a zone apart.
61
+ const request = new Request(
62
+ `https://mail-bodies.openworkspace.invalid/v1/${encodeURIComponent(mailS3(c.env).bucketName)}/${encodeURIComponent(key)}`
63
+ );
64
+
65
+ const hit = cache
66
+ ? await timed(c, "cache", "body", () =>
67
+ cache.match(request).catch(() => undefined)
68
+ )
69
+ : undefined;
70
+
71
+ if (hit) return await hit.text();
72
+
73
+ const object = await timed(c, "r2", "body", () =>
74
+ c.env.MAIL_STORAGE.get(key)
75
+ );
76
+
77
+ if (!object) return null;
78
+ const html = await object.text();
79
+
80
+ if (cache && object.size <= MAX_CACHED_BODY_BYTES) {
81
+ background(
82
+ c,
83
+ cache.put(
84
+ request,
85
+ new Response(html, {
86
+ headers: {
87
+ "content-type": "text/html; charset=utf-8",
88
+ "cache-control": `max-age=${BODY_TTL_SECONDS}`,
89
+ },
90
+ })
91
+ )
92
+ );
93
+ }
94
+
95
+ return html;
96
+ }
97
+
98
+ /**
99
+ * A remote image through the proxy's guards (remote-proxy.ts): from this
100
+ * colo's cache, keyed by the URL alone, or fetched, then cached. `beforeFetch`
101
+ * runs only when the origin is about to be asked (rate limiting); returning
102
+ * false stops there with `limited`.
103
+ */
104
+ export async function proxiedRemoteImage(
105
+ c: Context<AppEnv>,
106
+ url: string,
107
+ beforeFetch: () => Promise<boolean>
108
+ ): Promise<
109
+ | { outcome: "ok"; body: ArrayBuffer | ReadableStream; contentType: string }
110
+ | { outcome: "limited" }
111
+ > {
112
+ const cache = await openCache("openworkspace:mail-remote");
113
+
114
+ const request = new Request(
115
+ `https://mail-remote.openworkspace.invalid/v1/${await sha256Hex(url)}`
116
+ );
117
+
118
+ const hit = cache
119
+ ? await timed(c, "cache", "remote", () =>
120
+ cache.match(request).catch(() => undefined)
121
+ )
122
+ : undefined;
123
+
124
+ if (hit?.body) {
125
+ return {
126
+ outcome: "ok",
127
+ body: hit.body,
128
+ contentType:
129
+ hit.headers.get("content-type") ?? "application/octet-stream",
130
+ };
131
+ }
132
+
133
+ if (!(await beforeFetch())) return { outcome: "limited" };
134
+
135
+ const remote = await timed(c, "fetch", "origin", () =>
136
+ fetchProxiedRemoteMedia(url)
137
+ );
138
+
139
+ if (cache) {
140
+ background(
141
+ c,
142
+ cache.put(
143
+ request,
144
+ new Response(remote.body.slice(0), {
145
+ headers: {
146
+ "content-type": remote.contentType,
147
+ "cache-control": `max-age=${REMOTE_TTL_SECONDS}`,
148
+ },
149
+ })
150
+ )
151
+ );
152
+ }
153
+
154
+ return { outcome: "ok", body: remote.body, contentType: remote.contentType };
155
+ }
@@ -1,43 +1,109 @@
1
1
  import type { InboundAuthentication } from "../../shared/mail-authentication";
2
+ import type { SenderIntel } from "../../shared/mail-sender-intel";
2
3
  import type { mailboxStub } from "../mailbox";
3
4
  import type { Email } from "../mailbox/schema";
4
5
  import { linkDomains } from "./link-domains";
5
- import { collectSenderIntel, senderIntelWorthStoring } from "./sender-intel";
6
+ import {
7
+ collectSenderIntel,
8
+ senderIntelWorthStoring,
9
+ storedSenderIntel,
10
+ } from "./sender-intel";
6
11
 
7
- export function headerAuthentication(email: Email): InboundAuthentication | null {
12
+ export function headerAuthentication(
13
+ email: Email
14
+ ): InboundAuthentication | null {
8
15
  const stored = email.authenticationResultsJson;
16
+
9
17
  return stored?.version === 1 ? stored : null;
10
18
  }
11
19
 
12
20
  /**
13
- * Ingestion skips storing sender intelligence when every lookup failed; such
14
- * a message gets it on view, with the same lookups. A result that failed again
15
- * is returned for display but not stored, so a later view retries.
21
+ * A view retries lookups that all failed only after this long. The failed
22
+ * result is stored (and shown) meanwhile, so opening the message again does
23
+ * not wait on DNS that just failed.
24
+ */
25
+ export const SENDER_INTEL_RETRY_MS = 60 * 60 * 1000;
26
+
27
+ /**
28
+ * Whether a received message still needs sender intelligence: ingestion
29
+ * stores none when every lookup failed, and a stored failure is retried once
30
+ * it is older than `SENDER_INTEL_RETRY_MS`.
31
+ */
32
+ export function senderIntelPending(email: Email, now = Date.now()) {
33
+ if (email.direction !== "incoming" || !headerAuthentication(email)) {
34
+ return false;
35
+ }
36
+
37
+ const stored = storedSenderIntel(email.senderIntelJson);
38
+
39
+ if (!stored) return true;
40
+
41
+ return (
42
+ stored.source === "live" &&
43
+ !senderIntelWorthStoring(stored) &&
44
+ now - stored.checkedAt >= SENDER_INTEL_RETRY_MS
45
+ );
46
+ }
47
+
48
+ type SenderIntelContext = {
49
+ bodyHtml: string | null;
50
+ workspaceDomains: readonly string[];
51
+ dqsKey: string | null;
52
+ };
53
+
54
+ // One lookup per message at a time in this isolate: the reader's background
55
+ // fill and its follow-up request share it.
56
+ const inFlight = new Map<string, Promise<SenderIntel>>();
57
+
58
+ /**
59
+ * Looks up and stores sender intelligence for a message that needs it (see
60
+ * `senderIntelPending`); a result where every lookup failed is stored too,
61
+ * so it is retried only after `SENDER_INTEL_RETRY_MS`. Returns the message
62
+ * with the intelligence it now has.
16
63
  */
17
64
  export async function withSenderIntel(
18
65
  env: Env,
19
66
  mailbox: ReturnType<typeof mailboxStub>,
20
67
  email: Email,
21
- context: { bodyHtml: string | null; workspaceDomains: readonly string[]; dqsKey: string | null },
68
+ context: SenderIntelContext
22
69
  ): Promise<Email> {
23
- if (email.direction !== "incoming" || email.senderIntelJson || !headerAuthentication(email)) return email;
24
- try {
25
- const intel = await collectSenderIntel({
26
- authentication: headerAuthentication(email),
27
- fromAddress: email.fromJson[0]?.address ?? "",
28
- linkDomains: linkDomains({
29
- html: context.bodyHtml,
30
- text: [email.bodyText, email.quotedText],
70
+ if (!senderIntelPending(email)) return email;
71
+ const key = `${mailbox.id.toString()}:${email.id}`;
72
+ let work = inFlight.get(key);
73
+
74
+ if (!work) {
75
+ const previous =
76
+ storedSenderIntel(email.senderIntelJson)?.checkedAt ?? null;
77
+
78
+ work = (async () => {
79
+ const intel = await collectSenderIntel({
80
+ authentication: headerAuthentication(email),
81
+ fromAddress: email.fromJson[0]?.address ?? "",
82
+ linkDomains: linkDomains({
83
+ html: context.bodyHtml,
84
+ text: [email.bodyText, email.quotedText],
85
+ workspaceDomains: context.workspaceDomains,
86
+ }),
31
87
  workspaceDomains: context.workspaceDomains,
32
- }),
33
- workspaceDomains: context.workspaceDomains,
34
- dqsKey: context.dqsKey,
35
- bucket: env.MAIL_STORAGE,
36
- });
37
- if (senderIntelWorthStoring(intel)) await mailbox.setEmailSenderIntel(email.id, intel);
38
- return { ...email, senderIntelJson: intel };
88
+ dqsKey: context.dqsKey,
89
+ bucket: env.MAIL_STORAGE,
90
+ });
91
+
92
+ await mailbox.setEmailSenderIntel(email.id, intel, previous);
93
+
94
+ return intel;
95
+ })().finally(() => inFlight.delete(key));
96
+ inFlight.set(key, work);
97
+ }
98
+
99
+ try {
100
+ return { ...email, senderIntelJson: await work };
39
101
  } catch (error) {
40
- console.error(`Could not collect sender intelligence for ${email.id}`, error);
102
+ console.error(
103
+ `Could not collect sender intelligence for ${email.id}`,
104
+ error
105
+ );
106
+
41
107
  return email;
42
108
  }
43
109
  }
@@ -1,4 +1,5 @@
1
1
  import { getDomainWithoutSuffix } from "tldts";
2
+
2
3
  import { organizationalDomain } from "./org-domain";
3
4
 
4
5
  // --- Punycode (RFC 3492 decoding only) ------------------------------------
@@ -13,91 +14,165 @@ function adapt(delta: number, points: number, first: boolean) {
13
14
  let value = first ? Math.floor(delta / DAMP) : delta >> 1;
14
15
  value += Math.floor(value / points);
15
16
  let k = 0;
17
+
16
18
  while (value > ((BASE - T_MIN) * T_MAX) >> 1) {
17
19
  value = Math.floor(value / (BASE - T_MIN));
18
20
  k += BASE;
19
21
  }
22
+
20
23
  return k + Math.floor(((BASE - T_MIN + 1) * value) / (value + SKEW));
21
24
  }
22
25
 
23
26
  function digit(code: number) {
24
27
  if (code >= 48 && code <= 57) return code - 22;
28
+
25
29
  if (code >= 65 && code <= 90) return code - 65;
30
+
26
31
  if (code >= 97 && code <= 122) return code - 97;
32
+
27
33
  return BASE;
28
34
  }
29
35
 
30
36
  export function decodePunycodeLabel(input: string) {
31
37
  const delimiter = input.lastIndexOf("-");
32
- const output = delimiter > 0 ? [...input.slice(0, delimiter)].map((char) => char.codePointAt(0)!) : [];
38
+ const basic = delimiter > 0 ? input.slice(0, delimiter) : "";
39
+
40
+ // RFC 3492 §6.2: the part before the delimiter holds basic (ASCII) code points only.
41
+ const output = Array.from(basic, (char) => char.charCodeAt(0));
42
+
43
+ if (output.some((code) => code >= 0x80)) return null;
44
+
33
45
  let n = 128;
34
46
  let i = 0;
35
47
  let bias = 72;
48
+
36
49
  for (let index = delimiter > 0 ? delimiter + 1 : 0; index < input.length;) {
37
50
  const oldI = i;
51
+
38
52
  for (let w = 1, k = BASE; ; k += BASE) {
39
53
  if (index >= input.length) return null;
40
54
  const value = digit(input.charCodeAt(index++));
55
+
41
56
  if (value >= BASE) return null;
42
57
  i += value * w;
43
58
  const t = k <= bias ? T_MIN : k >= bias + T_MAX ? T_MAX : k - bias;
59
+
44
60
  if (value < t) break;
45
61
  w *= BASE - t;
46
62
  }
63
+
47
64
  bias = adapt(i - oldI, output.length + 1, oldI === 0);
48
65
  n += Math.floor(i / (output.length + 1));
49
66
  i %= output.length + 1;
50
- if (n > 0x10ffff) return null;
67
+
68
+ if (n > 0x10_ff_ff) return null;
51
69
  output.splice(i++, 0, n);
52
70
  }
71
+
53
72
  return String.fromCodePoint(...output);
54
73
  }
55
74
 
56
75
  /** `xn--` labels decoded to Unicode; other labels unchanged. */
57
76
  export function domainToUnicode(domain: string) {
58
- return domain.split(".").map((label) =>
59
- label.toLocaleLowerCase().startsWith("xn--") ? decodePunycodeLabel(label.slice(4)) ?? label : label
60
- ).join(".");
77
+ return domain
78
+ .split(".")
79
+ .map((label) =>
80
+ label.toLocaleLowerCase().startsWith("xn--")
81
+ ? (decodePunycodeLabel(label.slice(4)) ?? label)
82
+ : label
83
+ )
84
+ .join(".");
61
85
  }
62
86
 
63
87
  // --- Confusable skeleton (a practical subset of UTS #39) ------------------
64
88
 
65
- const CONFUSABLES: Record<string, string> = {
66
- // Cyrillic
67
- "а": "a", "в": "b", "е": "e", "ё": "e", "к": "k", "м": "m", "н": "h", "о": "o", "р": "p", "с": "c",
68
- "т": "t", "у": "y", "х": "x", "ѕ": "s", "і": "i", "ї": "i", "ј": "j", "ԁ": "d", "һ": "h", "ӏ": "l",
69
- "ԛ": "q", "ԝ": "w", "ɡ": "g",
70
- // Greek
71
- "α": "a", "β": "b", "ε": "e", "η": "n", "ι": "i", "κ": "k", "ν": "v", "ο": "o", "ρ": "p", "τ": "t",
72
- "υ": "u", "χ": "x", "ω": "w",
73
- // Look-alike digits and symbols
74
- "0": "o", "1": "l", "3": "e", "5": "s", "|": "l", "ı": "i", "ł": "l", "ø": "o", "đ": "d",
75
- };
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
+ );
76
141
 
77
142
  /** Lowercased, accent-free, confusables folded, with multi-letter look-alikes merged. */
78
143
  export function confusableSkeleton(value: string) {
79
144
  const folded = [...value.normalize("NFKD").toLocaleLowerCase()]
80
- .filter((char) => !/\p{M}/u.test(char))
81
- .map((char) => CONFUSABLES[char] ?? char)
145
+ .flatMap((char) =>
146
+ /\p{M}/u.test(char) ? [] : [CONFUSABLES.get(char) ?? char]
147
+ )
82
148
  .join("");
83
- return folded.replaceAll("rn", "m").replaceAll("vv", "w").replaceAll("cl", "d").replace(/i/gu, "l");
149
+
150
+ return folded
151
+ .replaceAll("rn", "m")
152
+ .replaceAll("vv", "w")
153
+ .replaceAll("cl", "d")
154
+ .replaceAll("i", "l");
84
155
  }
85
156
 
86
157
  export function levenshtein(left: string, right: string) {
87
158
  if (left === right) return 0;
88
159
  let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
160
+
89
161
  for (let i = 1; i <= left.length; i += 1) {
90
162
  const current = [i];
163
+
91
164
  for (let j = 1; j <= right.length; j += 1) {
92
165
  current[j] = Math.min(
93
- current[j - 1]! + 1,
94
- previous[j]! + 1,
95
- previous[j - 1]! + (left[i - 1] === right[j - 1] ? 0 : 1),
166
+ current[j - 1] + 1,
167
+ previous[j] + 1,
168
+ previous[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1)
96
169
  );
97
170
  }
171
+
98
172
  previous = current;
99
173
  }
100
- return previous[right.length]!;
174
+
175
+ return previous[right.length];
101
176
  }
102
177
 
103
178
  /** Registrable label without the public suffix, e.g. `demo` for `mail.demo.example`. */
@@ -107,6 +182,7 @@ function registrableLabel(domain: string) {
107
182
 
108
183
  function maxEdits(length: number) {
109
184
  if (length < 4) return 0;
185
+
110
186
  return length < 7 ? 1 : 2;
111
187
  }
112
188
 
@@ -115,26 +191,51 @@ function maxEdits(length: number) {
115
191
  * registrable labels after Unicode/punycode confusable folding, and the
116
192
  * whole registrable name without separators (`demo-examp1e.com` vs `demo.example`).
117
193
  */
118
- export function lookalikeOf(senderDomain: string | null, workspaceDomains: readonly string[]) {
194
+ export function lookalikeOf(
195
+ senderDomain: string | null,
196
+ workspaceDomains: readonly string[]
197
+ ) {
119
198
  if (!senderDomain) return null;
120
199
  const unicode = domainToUnicode(senderDomain.toLocaleLowerCase());
121
200
  const senderOrg = organizationalDomain(senderDomain) ?? senderDomain;
122
- const senderLabel = confusableSkeleton(registrableLabel(domainToUnicode(senderOrg)));
123
- const senderFlat = senderLabel.replace(/[^\p{L}\p{N}]/gu, "");
201
+
202
+ const senderLabel = confusableSkeleton(
203
+ registrableLabel(domainToUnicode(senderOrg))
204
+ );
205
+
206
+ const senderFlat = senderLabel.replaceAll(/[^\p{L}\p{N}]/gu, "");
207
+
124
208
  for (const workspace of workspaceDomains) {
125
209
  const own = workspace.toLocaleLowerCase();
126
210
  const ownOrg = organizationalDomain(own) ?? own;
211
+
127
212
  if (senderOrg === ownOrg) continue;
128
213
  const ownLabel = confusableSkeleton(registrableLabel(ownOrg));
129
- const ownFlat = confusableSkeleton(ownOrg).replace(/[^\p{L}\p{N}]/gu, "");
214
+
215
+ const ownFlat = confusableSkeleton(ownOrg).replaceAll(
216
+ /[^\p{L}\p{N}]/gu,
217
+ ""
218
+ );
219
+
130
220
  if (ownLabel.length < 3) continue;
221
+
131
222
  // Same name under another suffix, or a homoglyph/punycode spelling of it.
132
- if (senderLabel === ownLabel || senderFlat === ownFlat) return { domain: unicode, resembles: own };
133
- if (levenshtein(senderLabel, ownLabel) <= maxEdits(ownLabel.length)) return { domain: unicode, resembles: own };
134
- if (ownFlat.length >= 6 && levenshtein(senderFlat, ownFlat) <= maxEdits(ownFlat.length)) {
223
+ if (senderLabel === ownLabel || senderFlat === ownFlat) {
224
+ return { domain: unicode, resembles: own };
225
+ }
226
+
227
+ if (levenshtein(senderLabel, ownLabel) <= maxEdits(ownLabel.length)) {
228
+ return { domain: unicode, resembles: own };
229
+ }
230
+
231
+ if (
232
+ ownFlat.length >= 6 &&
233
+ levenshtein(senderFlat, ownFlat) <= maxEdits(ownFlat.length)
234
+ ) {
135
235
  return { domain: unicode, resembles: own };
136
236
  }
137
237
  }
238
+
138
239
  return null;
139
240
  }
140
241
 
@@ -142,34 +243,55 @@ export function lookalikeOf(senderDomain: string | null, workspaceDomains: reado
142
243
 
143
244
  export function normalizedPersonName(value: string | null | undefined) {
144
245
  if (!value) return "";
246
+
145
247
  return value
146
248
  .normalize("NFKC")
147
249
  .toLocaleLowerCase()
148
- .replace(/[^\p{L}\p{N}\s]/gu, " ")
149
- .replace(/\s+/gu, " ")
250
+ .replaceAll(/[^\p{L}\p{N}\s]/gu, " ")
251
+ .replaceAll(/\s+/gu, " ")
150
252
  .trim();
151
253
  }
152
254
 
153
255
  /** Internal names worth protecting: at least two words, so "Support" alone never matches. */
154
- export function protectedNames(names: Array<string | null | undefined>) {
256
+ export function protectedNames(names: (string | null | undefined)[]) {
155
257
  const result = new Map<string, string>();
258
+
156
259
  for (const name of names) {
260
+ if (!name) continue;
157
261
  const normalized = normalizedPersonName(name);
158
- if (normalized.split(" ").length >= 2 && normalized.length >= 5) result.set(normalized, name!.trim().replace(/\s+/gu, " "));
262
+
263
+ if (normalized.split(" ").length >= 2 && normalized.length >= 5) {
264
+ result.set(normalized, name.trim().replaceAll(/\s+/gu, " "));
265
+ }
159
266
  }
267
+
160
268
  return result;
161
269
  }
162
270
 
163
271
  /** The internal person an external From display name copies, if any. */
164
- export function impersonatedName(displayName: string | null | undefined, names: ReadonlyMap<string, string>) {
272
+ export function impersonatedName(
273
+ displayName: string | null | undefined,
274
+ names: ReadonlyMap<string, string>
275
+ ) {
165
276
  const normalized = normalizedPersonName(displayName);
277
+
166
278
  if (!normalized) return null;
279
+
167
280
  return names.get(normalized) ?? null;
168
281
  }
169
282
 
170
283
  /** `"ceo@ourco.com" <x@elsewhere.example>`: an address in the name that is not the sender. */
171
- export function embeddedAddress(displayName: string | null | undefined, fromAddress: string) {
172
- const match = displayName?.match(/[^\s<>"'()@]+@[a-z0-9.-]+\.[a-z]{2,}/iu)?.[0];
284
+ export function embeddedAddress(
285
+ displayName: string | null | undefined,
286
+ fromAddress: string
287
+ ) {
288
+ const match = displayName?.match(
289
+ /[^\s<>"'()@]+@[a-z0-9.-]+\.[a-z]{2,}/iu
290
+ )?.[0];
291
+
173
292
  if (!match) return null;
174
- return match.toLocaleLowerCase() === fromAddress.toLocaleLowerCase() ? null : match;
293
+
294
+ return match.toLocaleLowerCase() === fromAddress.toLocaleLowerCase()
295
+ ? null
296
+ : match;
175
297
  }