@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
@@ -1,5 +1,5 @@
1
- import type { SenderIntel } from "../../shared/mail-sender-intel";
2
1
  import { normalizeIp } from "../../shared/mail-received";
2
+ import type { SenderIntel } from "../../shared/mail-sender-intel";
3
3
  import type { DnsResolver } from "./doh";
4
4
  import { organizationalDomain } from "./org-domain";
5
5
 
@@ -11,13 +11,21 @@ function expandIpv6(ip: string) {
11
11
  const [head = "", tail = ""] = ip.split("::");
12
12
  const left = head ? head.split(":") : [];
13
13
  const right = ip.includes("::") ? (tail ? tail.split(":") : []) : [];
14
- const fill = Array.from({ length: 8 - left.length - right.length }, () => "0");
15
- return [...left, ...fill, ...right].map((group) => group.padStart(4, "0")).join("");
14
+
15
+ const fill = Array.from(
16
+ { length: 8 - left.length - right.length },
17
+ () => "0"
18
+ );
19
+
20
+ return [...left, ...fill, ...right]
21
+ .map((group) => group.padStart(4, "0"))
22
+ .join("");
16
23
  }
17
24
 
18
25
  /** `1.2.3.4` → `4.3.2.1`; IPv6 → nibble-reversed hex, as used under in-addr.arpa / ip6.arpa. */
19
26
  export function reversedIp(ip: string) {
20
27
  if (ip.includes(":")) return [...expandIpv6(ip)].reverse().join(".");
28
+
21
29
  return ip.split(".").reverse().join(".");
22
30
  }
23
31
 
@@ -31,27 +39,45 @@ const GENERIC_PTR_WORDS =
31
39
  /** Auto-generated access-network names such as `1-2-3-4.dsl.example.net`. */
32
40
  export function isGenericPtr(name: string, ip: string) {
33
41
  const host = name.toLocaleLowerCase();
42
+
34
43
  if (!ip.includes(":")) {
35
44
  const octets = ip.split(".");
36
45
  const forward = octets.join("[.-]");
37
46
  const backward = [...octets].reverse().join("[.-]");
38
- if (new RegExp(`(?:^|\\D)(?:${forward}|${backward})(?:\\D|$)`, "u").test(host)) return true;
39
- const hex = octets.map((octet) => Number(octet).toString(16).padStart(2, "0")).join("");
47
+
48
+ if (
49
+ new RegExp(`(?:^|\\D)(?:${forward}|${backward})(?:\\D|$)`, "u").test(host)
50
+ ) {
51
+ return true;
52
+ }
53
+
54
+ const hex = octets
55
+ .map((octet) => Number(octet).toString(16).padStart(2, "0"))
56
+ .join("");
57
+
40
58
  if (host.includes(hex)) return true;
41
59
  }
60
+
42
61
  const firstLabels = host.split(".").slice(0, -2).join(".");
62
+
43
63
  return GENERIC_PTR_WORDS.test(firstLabels);
44
64
  }
45
65
 
46
66
  /** `"15169 | 8.8.8.0/24 | US | arin | 1992-12-01"` (first ASN wins for multi-origin prefixes). */
47
67
  export function parseCymruOrigin(value: string) {
48
- const [asns, prefix, country, registry] = value.split("|").map((part) => part.trim());
68
+ const [asns, prefix, country, registry] = value
69
+ .split("|")
70
+ .map((part) => part.trim());
71
+
49
72
  const asn = Number(asns?.split(/\s+/u)[0]);
73
+
50
74
  if (!Number.isInteger(asn) || asn <= 0) return null;
75
+
51
76
  return {
52
77
  asn,
53
78
  prefix: prefix || null,
54
- country: country && /^[a-z]{2}$/iu.test(country) ? country.toUpperCase() : null,
79
+ country:
80
+ country && /^[a-z]{2}$/iu.test(country) ? country.toUpperCase() : null,
55
81
  registry: registry?.toLocaleLowerCase() || null,
56
82
  };
57
83
  }
@@ -59,51 +85,93 @@ export function parseCymruOrigin(value: string) {
59
85
  /** `"15169 | US | arin | 2000-03-30 | GOOGLE - Google LLC, US"` → `Google LLC`. */
60
86
  export function parseCymruAsName(value: string) {
61
87
  const raw = value.split("|").slice(4).join("|").trim();
88
+
62
89
  if (!raw) return null;
63
90
  const withoutCountry = raw.replace(/,\s*[A-Z]{2}$/u, "").trim();
64
91
  const dash = withoutCountry.indexOf(" - ");
65
- const name = dash >= 0 ? withoutCountry.slice(dash + 3).trim() : withoutCountry;
92
+
93
+ const name =
94
+ dash === -1 ? withoutCountry : withoutCountry.slice(dash + 3).trim();
95
+
66
96
  return name.slice(0, 120) || null;
67
97
  }
68
98
 
69
- async function ptrIntel(resolve: DnsResolver, ip: string): Promise<IpIntel["ptr"]> {
99
+ async function ptrIntel(
100
+ resolve: DnsResolver,
101
+ ip: string
102
+ ): Promise<IpIntel["ptr"]> {
70
103
  const answer = await resolve(reverseDnsName(ip), "PTR");
71
104
  const names = [...new Set(answer.records)].filter(Boolean).slice(0, 5);
72
- if (answer.status !== "ok" || !names.length) {
105
+ const [firstName] = names;
106
+
107
+ if (answer.status !== "ok" || firstName === undefined) {
73
108
  return {
74
109
  status: answer.status === "ok" ? "nxdomain" : answer.status,
75
110
  names: [],
76
111
  confirmed: null,
77
- fcrdns: answer.status === "ok" || answer.status === "nxdomain" ? false : null,
112
+ fcrdns:
113
+ answer.status === "ok" || answer.status === "nxdomain" ? false : null,
78
114
  generic: null,
79
115
  };
80
116
  }
117
+
81
118
  const forwardType = ip.includes(":") ? "AAAA" : "A";
82
- const checks = await Promise.all(names.slice(0, MAX_CONFIRMED_PTR_NAMES).map(async (name) => {
83
- const forward = await resolve(name, forwardType);
84
- const confirmed = forward.records.some((record) => normalizeIp(record) === ip);
85
- return { name, status: forward.status, confirmed };
86
- }));
119
+
120
+ const checks = await Promise.all(
121
+ names.slice(0, MAX_CONFIRMED_PTR_NAMES).map(async (name) => {
122
+ const forward = await resolve(name, forwardType);
123
+
124
+ const confirmed = forward.records.some(
125
+ (record) => normalizeIp(record) === ip
126
+ );
127
+
128
+ return { name, status: forward.status, confirmed };
129
+ })
130
+ );
131
+
87
132
  const confirmed = checks.find((check) => check.confirmed)?.name ?? null;
88
- const answered = checks.some((check) => check.status === "ok" || check.status === "nxdomain");
133
+
134
+ const answered = checks.some(
135
+ (check) => check.status === "ok" || check.status === "nxdomain"
136
+ );
137
+
89
138
  return {
90
139
  status: "ok",
91
140
  names,
92
141
  confirmed,
93
142
  fcrdns: confirmed ? true : answered ? false : null,
94
- generic: isGenericPtr(confirmed ?? names[0]!, ip),
143
+ generic: isGenericPtr(confirmed ?? firstName, ip),
95
144
  };
96
145
  }
97
146
 
98
- async function networkIntel(resolve: DnsResolver, ip: string): Promise<IpIntel["network"]> {
99
- const empty = { asn: null, asName: null, prefix: null, country: null, registry: null };
100
- const zone = ip.includes(":") ? "origin6.asn.cymru.com" : "origin.asn.cymru.com";
147
+ async function networkIntel(
148
+ resolve: DnsResolver,
149
+ ip: string
150
+ ): Promise<IpIntel["network"]> {
151
+ const empty = {
152
+ asn: null,
153
+ asName: null,
154
+ prefix: null,
155
+ country: null,
156
+ registry: null,
157
+ };
158
+
159
+ const zone = ip.includes(":")
160
+ ? "origin6.asn.cymru.com"
161
+ : "origin.asn.cymru.com";
162
+
101
163
  const origin = await resolve(`${reversedIp(ip)}.${zone}`, "TXT");
102
164
  const parsed = origin.records.map(parseCymruOrigin).find(Boolean) ?? null;
165
+
103
166
  if (!parsed) {
104
- return { status: origin.status === "ok" ? "nxdomain" : origin.status, ...empty };
167
+ return {
168
+ status: origin.status === "ok" ? "nxdomain" : origin.status,
169
+ ...empty,
170
+ };
105
171
  }
172
+
106
173
  const name = await resolve(`AS${parsed.asn}.asn.cymru.com`, "TXT");
174
+
107
175
  return {
108
176
  status: "ok",
109
177
  ...parsed,
@@ -112,8 +180,15 @@ async function networkIntel(resolve: DnsResolver, ip: string): Promise<IpIntel["
112
180
  }
113
181
 
114
182
  /** PTR → forward confirmation and Team Cymru origin → AS name, in parallel. */
115
- export async function lookupIpIntel(resolve: DnsResolver, ip: string): Promise<IpIntel> {
116
- const [ptr, network] = await Promise.all([ptrIntel(resolve, ip), networkIntel(resolve, ip)]);
183
+ export async function lookupIpIntel(
184
+ resolve: DnsResolver,
185
+ ip: string
186
+ ): Promise<IpIntel> {
187
+ const [ptr, network] = await Promise.all([
188
+ ptrIntel(resolve, ip),
189
+ networkIntel(resolve, ip),
190
+ ]);
191
+
117
192
  return { ptr, network };
118
193
  }
119
194
 
@@ -121,15 +196,23 @@ export function heloMatchesPtr(helo: string | null, ptr: IpIntel["ptr"]) {
121
196
  if (!helo || !ptr.names.length) return null;
122
197
  const name = helo.toLocaleLowerCase().replace(/\.$/u, "");
123
198
  const org = organizationalDomain(name);
124
- return ptr.names.some((candidate) =>
125
- candidate === name || (org !== null && organizationalDomain(candidate) === org)
199
+
200
+ return ptr.names.some(
201
+ (candidate) =>
202
+ candidate === name ||
203
+ (org !== null && organizationalDomain(candidate) === org)
126
204
  );
127
205
  }
128
206
 
129
207
  /** Per-IP results are cacheable; timeouts and errors are not. */
130
208
  export function ipIntelCacheTtl(intel: IpIntel) {
131
209
  const failed = (status: string) => status === "timeout" || status === "error";
210
+
132
211
  if (failed(intel.ptr.status) || failed(intel.network.status)) return 0;
133
- if (intel.ptr.status === "nxdomain" || intel.network.status === "nxdomain") return 3_600;
212
+
213
+ if (intel.ptr.status === "nxdomain" || intel.network.status === "nxdomain") {
214
+ return 3600;
215
+ }
216
+
134
217
  return 86_400;
135
218
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A value kept in this isolate's memory for `ttlMs`. Reads in other isolates
3
+ * (and writes made elsewhere) are seen only once the entry expires, so use it
4
+ * only for inputs where that much staleness is acceptable. A failed load is
5
+ * not kept.
6
+ */
7
+ export function isolateCache<T>(
8
+ ttlMs: number,
9
+ load: (binding: D1Database) => Promise<T>
10
+ ) {
11
+ let entry: { value: Promise<T>; expiresAt: number } | null = null;
12
+
13
+ return {
14
+ get(binding: D1Database): Promise<T> {
15
+ const now = Date.now();
16
+
17
+ if (entry && entry.expiresAt > now) return entry.value;
18
+ const value = load(binding);
19
+ const current = { value, expiresAt: now + ttlMs };
20
+ entry = current;
21
+ value.catch(() => {
22
+ if (entry === current) entry = null;
23
+ });
24
+
25
+ return value;
26
+ },
27
+ /** Drops the entry, e.g. after this isolate changed the underlying rows. */
28
+ clear() {
29
+ entry = null;
30
+ },
31
+ };
32
+ }
33
+
34
+ /** How long workspace-wide inputs to the reader's sender checks are reused. */
35
+ export const WORKSPACE_CACHE_TTL_MS = 60_000;
@@ -1,4 +1,5 @@
1
1
  import { parse } from "tldts";
2
+
2
3
  import { normalizeIp } from "../../shared/mail-received";
3
4
  import { isWorkspaceDomain } from "./message-security";
4
5
  import { organizationalDomain } from "./org-domain";
@@ -9,9 +10,12 @@ const MAX_SCAN_CHARACTERS = 512 * 1024;
9
10
  function hostDomain(value: string) {
10
11
  try {
11
12
  const url = new URL(value.replaceAll("&amp;", "&"));
13
+
12
14
  if (url.protocol !== "http:" && url.protocol !== "https:") return null;
13
- const host = url.hostname.replace(/^\[|\]$/gu, "");
15
+ const host = url.hostname.replaceAll(/^\[|\]$/gu, "");
16
+
14
17
  if (normalizeIp(host)) return null;
18
+
15
19
  return organizationalDomain(host);
16
20
  } catch {
17
21
  return null;
@@ -24,34 +28,52 @@ function hostDomain(value: string) {
24
28
  */
25
29
  export function linkDomains(input: {
26
30
  html?: string | null;
27
- text?: Array<string | null | undefined>;
31
+ text?: (string | null | undefined)[];
28
32
  workspaceDomains?: readonly string[];
29
33
  limit?: number;
30
34
  }) {
31
35
  const candidates: string[] = [];
32
36
  const html = input.html?.slice(0, MAX_SCAN_CHARACTERS) ?? "";
33
- for (const match of html.matchAll(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/giu)) {
37
+
38
+ for (const match of html.matchAll(
39
+ /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/giu
40
+ )) {
34
41
  candidates.push((match[1] ?? match[2] ?? match[3] ?? "").trim());
35
42
  }
43
+
36
44
  // Visible text only: image sources and other attributes are not links.
37
- const visible = html.replace(/<[^>]*>/gu, " ");
38
- const text = [visible, ...(input.text ?? [])].filter(Boolean).join("\n").slice(0, MAX_SCAN_CHARACTERS * 2);
45
+ const visible = html.replaceAll(/<[^>]*>/gu, " ");
46
+
47
+ const text = [visible, ...(input.text ?? [])]
48
+ .filter(Boolean)
49
+ .join("\n")
50
+ .slice(0, MAX_SCAN_CHARACTERS * 2);
51
+
39
52
  for (const match of text.matchAll(/\bhttps?:\/\/[^\s<>"'()[\]{}]+/giu)) {
40
53
  candidates.push(match[0]);
41
54
  }
55
+
42
56
  // Scheme-less links people still click, such as "goo.gl/0667" typed into a
43
57
  // field a platform echoes back. A path is required so file names and plain
44
58
  // domains in prose are left alone.
45
- for (const match of text.matchAll(/(?<![@\w./-])((?:[a-z0-9-]+\.)+[a-z]{2,24})\/[^\s<>"'()[\]{}]*/giu)) {
46
- if (parse(match[1]!).isIcann) candidates.push(`https://${match[0]}`);
59
+ for (const match of text.matchAll(
60
+ /(?<![@\w./-])((?:[a-z0-9-]+\.)+[a-z]{2,24})\/[^\s<>"'()[\]{}]*/giu
61
+ )) {
62
+ if (parse(match[1]).isIcann) candidates.push(`https://${match[0]}`);
47
63
  }
64
+
48
65
  const domains: string[] = [];
66
+
49
67
  for (const candidate of candidates) {
50
68
  const domain = hostDomain(candidate);
69
+
51
70
  if (!domain || domains.includes(domain)) continue;
71
+
52
72
  if (isWorkspaceDomain(domain, input.workspaceDomains ?? [])) continue;
53
73
  domains.push(domain);
74
+
54
75
  if (domains.length >= (input.limit ?? MAX_LINK_DOMAINS)) break;
55
76
  }
77
+
56
78
  return domains;
57
79
  }
@@ -1,13 +1,19 @@
1
1
  import { mailboxStub } from "../mailbox";
2
+ import { repeatUntil } from "./repeat";
2
3
 
4
+ /** Deletes the mailbox's objects a page at a time, until a listing comes back empty. */
3
5
  async function deleteMailboxObjects(bucket: R2Bucket, mailboxId: string) {
4
6
  const prefix = `mailboxes/${mailboxId}/`;
5
- while (true) {
6
- const page = await bucket.list({ prefix, limit: 1_000 });
7
+
8
+ await repeatUntil(Number.POSITIVE_INFINITY, async () => {
9
+ const page = await bucket.list({ prefix, limit: 1000 });
7
10
  const keys = page.objects.map((object) => object.key);
8
- if (!keys.length) return;
11
+
12
+ if (!keys.length) return true;
9
13
  await bucket.delete(keys);
10
- }
14
+
15
+ return undefined;
16
+ });
11
17
  }
12
18
 
13
19
  export async function deleteMailboxStorage(env: Env, mailboxId: string) {
@@ -23,12 +23,14 @@ export async function listActiveMailboxSessions(
23
23
  db: D1Database,
24
24
  mailboxId: string,
25
25
  sessionIds: string[],
26
- now: number,
26
+ now: number
27
27
  ): Promise<ActiveMailboxSession[]> {
28
28
  if (!sessionIds.length) return [];
29
+
29
30
  // D1 allows only 100 bound parameters, so the complete ID set is bound as
30
31
  // one JSON value and expanded by SQLite instead of generating a large IN.
31
- const result = await db.prepare(`
32
+ const result = await db
33
+ .prepare(`
32
34
  with requested_sessions(id) as (
33
35
  select cast(value as text) from json_each(?)
34
36
  )
@@ -44,7 +46,10 @@ export async function listActiveMailboxSessions(
44
46
  and member.mailbox_id = ?
45
47
  where session.expires_at > ?
46
48
  and user.status = 'active'
47
- `).bind(idList(sessionIds), mailboxId, now).all<ActiveMailboxSessionRow>();
49
+ `)
50
+ .bind(idList(sessionIds), mailboxId, now)
51
+ .all<ActiveMailboxSessionRow>();
52
+
48
53
  return result.results.map((session) => ({
49
54
  id: session.id,
50
55
  tokenHash: session.token_hash,
@@ -55,10 +60,12 @@ export async function listActiveMailboxSessions(
55
60
  export async function listMailboxUsersByIds(
56
61
  db: D1Database,
57
62
  mailboxId: string,
58
- userIds: string[],
63
+ userIds: string[]
59
64
  ) {
60
65
  if (!userIds.length) return [];
61
- const result = await db.prepare(`
66
+
67
+ const result = await db
68
+ .prepare(`
62
69
  with requested_users(id) as (
63
70
  select cast(value as text) from json_each(?)
64
71
  )
@@ -68,6 +75,9 @@ export async function listMailboxUsersByIds(
68
75
  on member.user_id = requested.id
69
76
  and member.mailbox_id = ?
70
77
  inner join users user on user.id = member.user_id
71
- `).bind(idList(userIds), mailboxId).all<MailboxUserRow>();
78
+ `)
79
+ .bind(idList(userIds), mailboxId)
80
+ .all<MailboxUserRow>();
81
+
72
82
  return result.results;
73
83
  }
@@ -1,14 +1,21 @@
1
+ import {
2
+ createDb,
3
+ mailboxAddressSql,
4
+ mailboxAccess,
5
+ mailboxes,
6
+ teamMembership,
7
+ users,
8
+ emailDomain,
9
+ normalizeEmail,
10
+ normalizeMailboxAddress,
11
+ } from "@open-workspace/core/module";
12
+ import type { ListPostingPolicy } from "@open-workspace/core/shared";
1
13
  import { and, eq, sql } from "drizzle-orm";
2
- import PostalMime from "postal-mime";
3
- import type { ListPostingPolicy } from "@open-workspace/core/shared/workspace.ts";
4
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
5
- import { mailboxAddressSql } from "@open-workspace/core/worker/db/mailboxes.ts";
6
- import { domains, mailboxAccess, mailboxes, teamMembership, users } from "@open-workspace/core/worker/db/schema.ts";
7
- import { emailDomain, normalizeEmail, normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
14
+
8
15
  import { mailboxStub } from "../mailbox";
9
16
  import { parseInboundAuthentication } from "./auth-headers";
10
- import { inboundDeliveryId } from "./inbound-delivery";
11
17
  import { rawHeaderText } from "./inbound";
18
+ import { inboundDeliveryId } from "./inbound-delivery";
12
19
 
13
20
  export type MailingList = {
14
21
  id: string;
@@ -21,12 +28,19 @@ async function memberMailboxIds(db: D1Database, teamId: string) {
21
28
  const rows = await createDb(db)
22
29
  .selectDistinct({ id: mailboxes.id })
23
30
  .from(teamMembership)
24
- .innerJoin(users, and(eq(users.id, teamMembership.userId), eq(users.status, "active")))
25
- .innerJoin(mailboxes, and(
26
- eq(mailboxes.ownerUserId, teamMembership.userId),
27
- eq(mailboxes.isPrimary, true),
28
- ))
31
+ .innerJoin(
32
+ users,
33
+ and(eq(users.id, teamMembership.userId), eq(users.status, "active"))
34
+ )
35
+ .innerJoin(
36
+ mailboxes,
37
+ and(
38
+ eq(mailboxes.ownerUserId, teamMembership.userId),
39
+ eq(mailboxes.isPrimary, true)
40
+ )
41
+ )
29
42
  .where(eq(teamMembership.teamId, teamId));
43
+
30
44
  return rows.map((row) => row.id);
31
45
  }
32
46
 
@@ -36,43 +50,70 @@ async function memberMailboxIds(db: D1Database, teamId: string) {
36
50
  */
37
51
  async function verifiedSender(rawMime: ArrayBuffer) {
38
52
  let from: string | null = null;
53
+
39
54
  try {
40
- from = (await PostalMime.parse(rawHeaderText(rawMime))).from?.address ?? null;
55
+ const { default: PostalMime } = await import("postal-mime");
56
+ from =
57
+ (await PostalMime.parse(rawHeaderText(rawMime))).from?.address ?? null;
41
58
  } catch {
42
59
  return null;
43
60
  }
61
+
44
62
  if (!from) return null;
45
- const authentication = parseInboundAuthentication({ raw: rawHeaderText(rawMime), fromAddress: from });
63
+
64
+ const authentication = parseInboundAuthentication({
65
+ raw: rawHeaderText(rawMime),
66
+ fromAddress: from,
67
+ });
68
+
46
69
  const sender = normalizeEmail(from);
47
- return authentication.dmarc?.result === "pass"
48
- && authentication.dmarc.headerFrom === emailDomain(sender)
70
+
71
+ return authentication.dmarc?.result === "pass" &&
72
+ authentication.dmarc.headerFrom === emailDomain(sender)
49
73
  ? sender
50
74
  : null;
51
75
  }
52
76
 
53
- async function mayPost(db: D1Database, list: MailingList, rawMime: ArrayBuffer) {
77
+ async function mayPost(
78
+ db: D1Database,
79
+ list: MailingList,
80
+ rawMime: ArrayBuffer
81
+ ) {
54
82
  if (list.listPosting === "anyone") return true;
55
83
  const sender = await verifiedSender(rawMime);
84
+
56
85
  if (!sender) return false;
57
86
  const orm = createDb(db);
87
+
58
88
  const [mailbox] = await orm
59
89
  .select({ id: mailboxes.id })
60
90
  .from(mailboxes)
61
- .innerJoin(domains, eq(domains.id, mailboxes.domainId))
62
91
  .where(sql`${mailboxAddressSql} = ${sender}`)
63
92
  .limit(1);
93
+
64
94
  if (!mailbox) return false;
95
+
65
96
  if (list.listPosting === "workspace") return true;
97
+
66
98
  // Members post from any address they may send from.
67
99
  const [member] = await orm
68
100
  .select({ userId: mailboxAccess.userId })
69
101
  .from(mailboxAccess)
70
- .innerJoin(teamMembership, and(
71
- eq(teamMembership.userId, mailboxAccess.userId),
72
- eq(teamMembership.teamId, list.teamId),
73
- ))
74
- .where(and(eq(mailboxAccess.mailboxId, mailbox.id), eq(mailboxAccess.canSend, true)))
102
+ .innerJoin(
103
+ teamMembership,
104
+ and(
105
+ eq(teamMembership.userId, mailboxAccess.userId),
106
+ eq(teamMembership.teamId, list.teamId)
107
+ )
108
+ )
109
+ .where(
110
+ and(
111
+ eq(mailboxAccess.mailboxId, mailbox.id),
112
+ eq(mailboxAccess.canSend, true)
113
+ )
114
+ )
75
115
  .limit(1);
116
+
76
117
  return Boolean(member);
77
118
  }
78
119
 
@@ -88,33 +129,47 @@ export async function deliverToList(input: {
88
129
  receivedAt: number;
89
130
  }) {
90
131
  const { env, list, message, raw } = input;
132
+
91
133
  if (!(await mayPost(env.DB, list, raw))) {
92
- message.setReject(`You are not allowed to post to ${normalizeMailboxAddress(message.to)}`);
134
+ message.setReject(
135
+ `You are not allowed to post to ${normalizeMailboxAddress(message.to)}`
136
+ );
137
+
93
138
  return;
94
139
  }
140
+
95
141
  const recipients = await memberMailboxIds(env.DB, list.teamId);
142
+
96
143
  if (!recipients.length) return;
97
144
  const listAddress = normalizeMailboxAddress(message.to);
145
+
98
146
  const deliveryId = await inboundDeliveryId({
99
147
  mailboxId: list.id,
100
148
  envelopeFrom: message.from,
101
149
  envelopeTo: message.to,
102
150
  raw,
103
151
  });
152
+
104
153
  const objectKey = `lists/${list.id}/raw/${deliveryId}.eml`;
105
- await Promise.all(recipients.map(async (mailboxId) => mailboxStub(env, mailboxId).enqueueInbound({
106
- id: await inboundDeliveryId({
107
- mailboxId,
108
- envelopeFrom: message.from,
109
- envelopeTo: message.to,
110
- raw,
111
- }),
112
- mailboxId,
113
- rawObjectKey: objectKey,
114
- envelopeFrom: message.from,
115
- envelopeTo: message.to,
116
- listAddress,
117
- receivedAt: input.receivedAt,
118
- })));
119
- await env.MAIL_STORAGE.put(objectKey, raw, { httpMetadata: { contentType: "message/rfc822" } });
154
+ await Promise.all(
155
+ recipients.map(async (mailboxId) =>
156
+ mailboxStub(env, mailboxId).enqueueInbound({
157
+ id: await inboundDeliveryId({
158
+ mailboxId,
159
+ envelopeFrom: message.from,
160
+ envelopeTo: message.to,
161
+ raw,
162
+ }),
163
+ mailboxId,
164
+ rawObjectKey: objectKey,
165
+ envelopeFrom: message.from,
166
+ envelopeTo: message.to,
167
+ listAddress,
168
+ receivedAt: input.receivedAt,
169
+ })
170
+ )
171
+ );
172
+ await env.MAIL_STORAGE.put(objectKey, raw, {
173
+ httpMetadata: { contentType: "message/rfc822" },
174
+ });
120
175
  }