@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
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  import type { InboundAuthentication } from "../../shared/mail-authentication";
2
4
  import { ipKind, normalizeIp } from "../../shared/mail-received";
3
5
  import type {
@@ -7,14 +9,79 @@ import type {
7
9
  SpamhausResult,
8
10
  } from "../../shared/mail-sender-intel";
9
11
  import { resolveBimi } from "./bimi";
10
- import { createDohResolver, type DnsResolver } from "./doh";
11
- import { heloMatchesPtr, ipIntelCacheTtl, lookupIpIntel, type IpIntel } from "./ip-intel";
12
+ import { createDohResolver } from "./doh";
13
+ import type { DnsResolver } from "./doh";
14
+ import { heloMatchesPtr, ipIntelCacheTtl, lookupIpIntel } from "./ip-intel";
15
+ import type { IpIntel } from "./ip-intel";
12
16
  import { MAX_LINK_DOMAINS } from "./link-domains";
13
17
  import { isWorkspaceDomain } from "./message-security";
14
18
  import { organizationalDomain } from "./org-domain";
15
19
  import { checkSpamhaus } from "./spamhaus";
16
20
 
17
- export const SENDER_INTEL_BUDGET_MS = 1_500;
21
+ const LookupStatusSchema = z.enum([
22
+ "ok",
23
+ "nxdomain",
24
+ "timeout",
25
+ "error",
26
+ "skipped",
27
+ ]) satisfies z.ZodType<LookupStatus>;
28
+
29
+ const IpIntelSchema = z.object({
30
+ ptr: z.object({
31
+ status: LookupStatusSchema,
32
+ names: z.array(z.string()),
33
+ confirmed: z.string().nullable(),
34
+ fcrdns: z.boolean().nullable(),
35
+ generic: z.boolean().nullable(),
36
+ }),
37
+ network: z.object({
38
+ status: LookupStatusSchema,
39
+ asn: z.number().nullable(),
40
+ asName: z.string().nullable(),
41
+ prefix: z.string().nullable(),
42
+ country: z.string().nullable(),
43
+ registry: z.string().nullable(),
44
+ }),
45
+ }) satisfies z.ZodType<IpIntel>;
46
+
47
+ const SpamhausCheckSchema = z.object({
48
+ status: LookupStatusSchema,
49
+ listings: z.array(
50
+ z.object({
51
+ zone: z.enum(["zen", "dbl"]),
52
+ target: z.string(),
53
+ code: z.string(),
54
+ list: z.string(),
55
+ severity: z.enum(["abuse", "policy"]),
56
+ })
57
+ ),
58
+ error: z.string().nullable(),
59
+ });
60
+
61
+ /** A stored `sender_intel_json` column (version 1). */
62
+ const SenderIntelSchema = IpIntelSchema.extend({
63
+ version: z.literal(1),
64
+ source: z.enum(["live", "demo"]),
65
+ checkedAt: z.number(),
66
+ ip: z.string().nullable(),
67
+ ipVersion: z.union([z.literal(4), z.literal(6)]).nullable(),
68
+ heloMatchesPtr: z.boolean().nullable(),
69
+ spamhaus: z
70
+ .object({
71
+ zen: SpamhausCheckSchema,
72
+ dbl: SpamhausCheckSchema.extend({ domains: z.array(z.string()) }),
73
+ })
74
+ .nullable(),
75
+ bimi: z
76
+ .object({
77
+ domain: z.string(),
78
+ status: z.enum(["ok", "none", "invalid", "error"]),
79
+ reason: z.string().nullable(),
80
+ })
81
+ .nullable(),
82
+ }) satisfies z.ZodType<SenderIntel>;
83
+
84
+ export const SENDER_INTEL_BUDGET_MS = 1500;
18
85
  const MEMORY_CACHE_LIMIT = 500;
19
86
  const CACHE_ORIGIN = "https://sender-intel.openworkspace.invalid";
20
87
 
@@ -30,7 +97,9 @@ const memory = new Map<string, { intel: IpIntel; expiresAt: number }>();
30
97
  * Both are best effort: a failing cache never fails ingestion.
31
98
  */
32
99
  export function defaultIntelCache(): IntelCache {
33
- const request = (ip: string) => new Request(`${CACHE_ORIGIN}/ip/v1/${encodeURIComponent(ip)}`);
100
+ const request = (ip: string) =>
101
+ new Request(`${CACHE_ORIGIN}/ip/v1/${encodeURIComponent(ip)}`);
102
+
34
103
  const open = async () => {
35
104
  try {
36
105
  return await caches.open("openworkspace:sender-intel");
@@ -38,24 +107,42 @@ export function defaultIntelCache(): IntelCache {
38
107
  return null;
39
108
  }
40
109
  };
110
+
41
111
  return {
42
112
  async get(ip) {
43
113
  const hit = memory.get(ip);
114
+
44
115
  if (hit && hit.expiresAt > Date.now()) return hit.intel;
116
+
45
117
  try {
46
118
  const response = await (await open())?.match(request(ip));
47
- return response ? await response.json() as IpIntel : null;
119
+
120
+ if (!response) return null;
121
+ const cached = IpIntelSchema.safeParse(await response.json());
122
+
123
+ return cached.success ? cached.data : null;
48
124
  } catch {
49
125
  return null;
50
126
  }
51
127
  },
52
128
  async put(ip, intel, ttlSeconds) {
53
- if (memory.size >= MEMORY_CACHE_LIMIT) memory.delete(memory.keys().next().value!);
54
- memory.set(ip, { intel, expiresAt: Date.now() + ttlSeconds * 1_000 });
129
+ if (memory.size >= MEMORY_CACHE_LIMIT) {
130
+ const oldest = memory.keys().next();
131
+
132
+ if (!oldest.done) memory.delete(oldest.value);
133
+ }
134
+
135
+ memory.set(ip, { intel, expiresAt: Date.now() + ttlSeconds * 1000 });
136
+
55
137
  try {
56
- await (await open())?.put(request(ip), new Response(JSON.stringify(intel), {
57
- headers: { "content-type": "application/json", "cache-control": `max-age=${ttlSeconds}` },
58
- }));
138
+ await (
139
+ await open()
140
+ )?.put(
141
+ request(ip),
142
+ Response.json(intel, {
143
+ headers: { "cache-control": `max-age=${ttlSeconds}` },
144
+ })
145
+ );
59
146
  } catch {
60
147
  // Best effort only.
61
148
  }
@@ -66,27 +153,48 @@ export function defaultIntelCache(): IntelCache {
66
153
  function skippedIpIntel(status: LookupStatus): IpIntel {
67
154
  return {
68
155
  ptr: { status, names: [], confirmed: null, fcrdns: null, generic: null },
69
- network: { status, asn: null, asName: null, prefix: null, country: null, registry: null },
156
+ network: {
157
+ status,
158
+ asn: null,
159
+ asName: null,
160
+ prefix: null,
161
+ country: null,
162
+ registry: null,
163
+ },
70
164
  };
71
165
  }
72
166
 
73
167
  /** Resolves to `fallback` once the deadline passes, even if the work ignores the abort signal. */
74
- function withDeadline<T>(work: Promise<T>, signal: AbortSignal, fallback: () => T): Promise<T> {
168
+ function withDeadline<T>(
169
+ work: Promise<T>,
170
+ signal: AbortSignal,
171
+ fallback: () => T
172
+ ): Promise<T> {
75
173
  return new Promise((resolve) => {
76
174
  const onAbort = () => resolve(fallback());
77
- if (signal.aborted) return onAbort();
175
+
176
+ if (signal.aborted) {
177
+ onAbort();
178
+
179
+ return;
180
+ }
181
+
78
182
  signal.addEventListener("abort", onAbort, { once: true });
79
- work.then(resolve, () => resolve(fallback())).finally(() => signal.removeEventListener("abort", onAbort));
183
+ // oxlint-disable-next-line promise/catch-or-return -- then()'s second argument handles rejection
184
+ work
185
+ .then(resolve, () => resolve(fallback()))
186
+ .finally(() => signal.removeEventListener("abort", onAbort));
80
187
  });
81
188
  }
82
189
 
83
190
  /** BIMI applies only when DMARC passed under p=quarantine or p=reject. */
84
191
  export function bimiEligible(authentication: InboundAuthentication | null) {
85
192
  const dmarc = authentication?.dmarc;
193
+
86
194
  return Boolean(
87
- authentication?.fromDomain
88
- && dmarc?.result === "pass"
89
- && (dmarc.policy === "quarantine" || dmarc.policy === "reject"),
195
+ authentication?.fromDomain &&
196
+ dmarc?.result === "pass" &&
197
+ (dmarc.policy === "quarantine" || dmarc.policy === "reject")
90
198
  );
91
199
  }
92
200
 
@@ -111,56 +219,92 @@ export async function collectSenderIntel(input: {
111
219
  }): Promise<SenderIntel> {
112
220
  const now = input.now ?? Date.now();
113
221
  const signal = AbortSignal.timeout(input.budgetMs ?? SENDER_INTEL_BUDGET_MS);
114
- const resolve = input.resolver ?? createDohResolver({ fetch: input.fetch, signal });
222
+
223
+ const resolve =
224
+ input.resolver ?? createDohResolver({ fetch: input.fetch, signal });
225
+
115
226
  const cache = input.cache ?? defaultIntelCache();
116
227
  const auth = input.authentication;
117
228
  const ip = normalizeIp(auth?.remoteIp);
118
229
  const publicIp = ip && ipKind(ip) === "public" ? ip : null;
119
230
 
120
231
  const ipWork = publicIp
121
- ? withDeadline((async () => {
122
- const cached = await cache.get(publicIp);
123
- if (cached) return cached;
124
- const fresh = await lookupIpIntel(resolve, publicIp);
125
- const ttl = ipIntelCacheTtl(fresh);
126
- if (ttl > 0) await cache.put(publicIp, fresh, ttl);
127
- return fresh;
128
- })(), signal, () => skippedIpIntel("timeout"))
232
+ ? withDeadline(
233
+ (async () => {
234
+ const cached = await cache.get(publicIp);
235
+
236
+ if (cached) return cached;
237
+ const fresh = await lookupIpIntel(resolve, publicIp);
238
+ const ttl = ipIntelCacheTtl(fresh);
239
+
240
+ if (ttl > 0) await cache.put(publicIp, fresh, ttl);
241
+
242
+ return fresh;
243
+ })(),
244
+ signal,
245
+ () => skippedIpIntel("timeout")
246
+ )
129
247
  : Promise.resolve(skippedIpIntel("skipped"));
130
248
 
131
249
  const fromOrg = organizationalDomain(input.fromAddress);
250
+
132
251
  const dblDomains = [...new Set([fromOrg, ...input.linkDomains])]
133
- .filter((domain): domain is string => Boolean(domain) && !isWorkspaceDomain(domain, input.workspaceDomains))
252
+ .filter(
253
+ (domain): domain is string =>
254
+ Boolean(domain) && !isWorkspaceDomain(domain, input.workspaceDomains)
255
+ )
134
256
  .slice(0, MAX_LINK_DOMAINS);
257
+
135
258
  const spamhausWork: Promise<SpamhausResult | null> = input.dqsKey
136
259
  ? withDeadline(
137
- checkSpamhaus({ resolve, key: input.dqsKey, ip: publicIp, domains: dblDomains }),
260
+ checkSpamhaus({
261
+ resolve,
262
+ key: input.dqsKey,
263
+ ip: publicIp,
264
+ domains: dblDomains,
265
+ }),
138
266
  signal,
139
267
  () => ({
140
268
  zen: { status: "timeout", listings: [], error: null },
141
- dbl: { status: "timeout", listings: [], error: null, domains: dblDomains },
142
- }),
269
+ dbl: {
270
+ status: "timeout",
271
+ listings: [],
272
+ error: null,
273
+ domains: dblDomains,
274
+ },
275
+ })
143
276
  )
144
277
  : Promise.resolve(null);
145
278
 
146
279
  const fromDomain = auth?.fromDomain ?? null;
147
- const bimiWork: Promise<BimiResult | null> = bimiEligible(auth) && fromDomain
148
- ? withDeadline(
149
- resolveBimi({
150
- resolve,
151
- fetch: input.fetch,
152
- bucket: input.bucket,
153
- fromDomain,
154
- orgDomain: organizationalDomain(fromDomain),
280
+
281
+ const bimiWork: Promise<BimiResult | null> =
282
+ bimiEligible(auth) && fromDomain
283
+ ? withDeadline(
284
+ resolveBimi({
285
+ resolve,
286
+ fetch: input.fetch,
287
+ bucket: input.bucket,
288
+ fromDomain,
289
+ orgDomain: organizationalDomain(fromDomain),
290
+ signal,
291
+ now,
292
+ }),
155
293
  signal,
156
- now,
157
- }),
158
- signal,
159
- () => ({ domain: fromDomain, status: "error", reason: "The BIMI lookup timed out" }),
160
- )
161
- : Promise.resolve(null);
294
+ () => ({
295
+ domain: fromDomain,
296
+ status: "error",
297
+ reason: "The BIMI lookup timed out",
298
+ })
299
+ )
300
+ : Promise.resolve(null);
301
+
302
+ const [ipIntel, spamhaus, bimi] = await Promise.all([
303
+ ipWork,
304
+ spamhausWork,
305
+ bimiWork,
306
+ ]);
162
307
 
163
- const [ipIntel, spamhaus, bimi] = await Promise.all([ipWork, spamhausWork, bimiWork]);
164
308
  return {
165
309
  version: 1,
166
310
  source: "live",
@@ -177,13 +321,24 @@ export async function collectSenderIntel(input: {
177
321
  /** Lazy fills skip persisting a result where every attempted lookup failed. */
178
322
  export function senderIntelWorthStoring(intel: SenderIntel) {
179
323
  const statuses: LookupStatus[] = [intel.ptr.status, intel.network.status];
180
- if (intel.spamhaus) statuses.push(intel.spamhaus.zen.status, intel.spamhaus.dbl.status);
324
+
325
+ if (intel.spamhaus) {
326
+ statuses.push(intel.spamhaus.zen.status, intel.spamhaus.dbl.status);
327
+ }
328
+
181
329
  const attempted = statuses.filter((status) => status !== "skipped");
182
- return !attempted.length || attempted.some((status) => status === "ok" || status === "nxdomain");
330
+
331
+ return (
332
+ !attempted.length ||
333
+ attempted.some((status) => status === "ok" || status === "nxdomain")
334
+ );
183
335
  }
184
336
 
185
- export function storedSenderIntel(value: unknown): SenderIntel | null {
186
- return value && typeof value === "object" && (value as { version?: unknown }).version === 1
187
- ? value as SenderIntel
188
- : null;
337
+ /** A message's stored sender intelligence, or null when absent or of another version. */
338
+ export function storedSenderIntel(
339
+ value: SenderIntel | null | undefined
340
+ ): SenderIntel | null {
341
+ const parsed = SenderIntelSchema.safeParse(value);
342
+
343
+ return parsed.success ? parsed.data : null;
189
344
  }
@@ -15,65 +15,93 @@ import { reversedIp } from "./ip-intel";
15
15
 
16
16
  export const DQS_KEY_PATTERN = /^[a-z0-9]{20,40}$/u;
17
17
 
18
- const zenCodes: Record<string, Pick<SpamhausListing, "list" | "severity">> = {
19
- "127.0.0.2": { list: "SBL (spam source)", severity: "abuse" },
20
- "127.0.0.3": { list: "SBL CSS (snowshoe spam)", severity: "abuse" },
21
- "127.0.0.4": { list: "XBL (compromised host)", severity: "abuse" },
22
- "127.0.0.5": { list: "XBL (compromised host)", severity: "abuse" },
23
- "127.0.0.6": { list: "XBL (compromised host)", severity: "abuse" },
24
- "127.0.0.7": { list: "XBL (compromised host)", severity: "abuse" },
25
- "127.0.0.9": { list: "DROP (hijacked network)", severity: "abuse" },
26
- "127.0.0.10": { list: "PBL (ISP end-user range)", severity: "policy" },
27
- "127.0.0.11": { list: "PBL (end-user range)", severity: "policy" },
28
- };
29
-
30
- const dblCodes: Record<string, string> = {
31
- "127.0.1.2": "spam domain",
32
- "127.0.1.4": "phishing domain",
33
- "127.0.1.5": "malware domain",
34
- "127.0.1.6": "botnet C&C domain",
35
- "127.0.1.102": "abused legitimate domain (spam)",
36
- "127.0.1.103": "abused redirector or shortener",
37
- "127.0.1.104": "abused legitimate domain (phishing)",
38
- "127.0.1.105": "abused legitimate domain (malware)",
39
- "127.0.1.106": "abused legitimate domain (botnet C&C)",
40
- };
41
-
42
- const errorCodes: Record<string, string> = {
43
- "127.255.255.252": "The query was malformed",
44
- "127.255.255.254": "Queried through a public resolver without a DQS key",
45
- "127.255.255.255": "Query limit exceeded for this key",
46
- };
18
+ const zenCodes = new Map(
19
+ Object.entries({
20
+ "127.0.0.2": { list: "SBL (spam source)", severity: "abuse" },
21
+ "127.0.0.3": { list: "SBL CSS (snowshoe spam)", severity: "abuse" },
22
+ "127.0.0.4": { list: "XBL (compromised host)", severity: "abuse" },
23
+ "127.0.0.5": { list: "XBL (compromised host)", severity: "abuse" },
24
+ "127.0.0.6": { list: "XBL (compromised host)", severity: "abuse" },
25
+ "127.0.0.7": { list: "XBL (compromised host)", severity: "abuse" },
26
+ "127.0.0.9": { list: "DROP (hijacked network)", severity: "abuse" },
27
+ "127.0.0.10": { list: "PBL (ISP end-user range)", severity: "policy" },
28
+ "127.0.0.11": { list: "PBL (end-user range)", severity: "policy" },
29
+ } satisfies Record<string, Pick<SpamhausListing, "list" | "severity">>)
30
+ );
31
+
32
+ const dblCodes = new Map(
33
+ Object.entries({
34
+ "127.0.1.2": "spam domain",
35
+ "127.0.1.4": "phishing domain",
36
+ "127.0.1.5": "malware domain",
37
+ "127.0.1.6": "botnet C&C domain",
38
+ "127.0.1.102": "abused legitimate domain (spam)",
39
+ "127.0.1.103": "abused redirector or shortener",
40
+ "127.0.1.104": "abused legitimate domain (phishing)",
41
+ "127.0.1.105": "abused legitimate domain (malware)",
42
+ "127.0.1.106": "abused legitimate domain (botnet C&C)",
43
+ })
44
+ );
45
+
46
+ const errorCodes = new Map(
47
+ Object.entries({
48
+ "127.255.255.252": "The query was malformed",
49
+ "127.255.255.254": "Queried through a public resolver without a DQS key",
50
+ "127.255.255.255": "Query limit exceeded for this key",
51
+ })
52
+ );
47
53
 
48
54
  /** 127.255.255.x is never a listing: it reports a problem with the query itself. */
49
55
  export function spamhausErrorCode(code: string) {
50
- return code.startsWith("127.255.255.") ? errorCodes[code] ?? "Spamhaus returned an error code" : null;
56
+ return code.startsWith("127.255.255.")
57
+ ? (errorCodes.get(code) ?? "Spamhaus returned an error code")
58
+ : null;
51
59
  }
52
60
 
53
61
  function interpret(
54
62
  zone: "zen" | "dbl",
55
63
  target: string,
56
- answer: DnsAnswer,
64
+ answer: DnsAnswer
57
65
  ): Omit<SpamhausCheck, "status"> & { status: SpamhausCheck["status"] } {
58
- if (answer.status === "nxdomain") return { status: "ok", listings: [], error: null };
59
- if (answer.status !== "ok") return { status: answer.status, listings: [], error: null };
66
+ if (answer.status === "nxdomain") {
67
+ return { status: "ok", listings: [], error: null };
68
+ }
69
+
70
+ if (answer.status !== "ok") {
71
+ return { status: answer.status, listings: [], error: null };
72
+ }
73
+
60
74
  const error = answer.records.map(spamhausErrorCode).find(Boolean) ?? null;
75
+
61
76
  if (error) return { status: "error", listings: [], error };
77
+
62
78
  const listings = answer.records.flatMap((code): SpamhausListing[] => {
63
79
  if (zone === "zen") {
64
- const known = zenCodes[code];
80
+ const known = zenCodes.get(code);
81
+
65
82
  return known ? [{ zone, target, code, ...known }] : [];
66
83
  }
67
- const list = dblCodes[code];
68
- return list ? [{ zone, target, code, list: `DBL ${list}`, severity: "abuse" }] : [];
84
+
85
+ const list = dblCodes.get(code);
86
+
87
+ return list
88
+ ? [{ zone, target, code, list: `DBL ${list}`, severity: "abuse" }]
89
+ : [];
69
90
  });
91
+
70
92
  return { status: "ok", listings, error: null };
71
93
  }
72
94
 
73
95
  function merge(checks: SpamhausCheck[]): SpamhausCheck {
74
96
  const failed = checks.find((check) => check.status !== "ok");
97
+
75
98
  return {
76
- status: checks.length === 0 ? "skipped" : failed && checks.every((check) => check.status !== "ok") ? failed.status : "ok",
99
+ status:
100
+ checks.length === 0
101
+ ? "skipped"
102
+ : failed && checks.every((check) => check.status !== "ok")
103
+ ? failed.status
104
+ : "ok",
77
105
  listings: checks.flatMap((check) => check.listings),
78
106
  error: checks.map((check) => check.error).find(Boolean) ?? null,
79
107
  };
@@ -85,13 +113,32 @@ export async function checkSpamhaus(input: {
85
113
  ip: string | null;
86
114
  domains: string[];
87
115
  }): Promise<SpamhausResult> {
88
- const zen = input.ip
89
- ? input.resolve(`${reversedIp(input.ip)}.${input.key}.zen.dq.spamhaus.net`, "A")
90
- .then((answer) => interpret("zen", input.ip!, answer))
91
- : Promise.resolve<SpamhausCheck>({ status: "skipped", listings: [], error: null });
92
- const dbl = Promise.all(input.domains.map(async (domain) =>
93
- interpret("dbl", domain, await input.resolve(`${domain}.${input.key}.dbl.dq.spamhaus.net`, "A"))
94
- ));
116
+ const { ip } = input;
117
+
118
+ const zen = ip
119
+ ? input
120
+ .resolve(`${reversedIp(ip)}.${input.key}.zen.dq.spamhaus.net`, "A")
121
+ .then((answer) => interpret("zen", ip, answer))
122
+ : Promise.resolve<SpamhausCheck>({
123
+ status: "skipped",
124
+ listings: [],
125
+ error: null,
126
+ });
127
+
128
+ const dbl = Promise.all(
129
+ input.domains.map(async (domain) =>
130
+ interpret(
131
+ "dbl",
132
+ domain,
133
+ await input.resolve(`${domain}.${input.key}.dbl.dq.spamhaus.net`, "A")
134
+ )
135
+ )
136
+ );
137
+
95
138
  const [zenResult, dblResults] = await Promise.all([zen, dbl]);
96
- return { zen: zenResult, dbl: { ...merge(dblResults), domains: input.domains } };
139
+
140
+ return {
141
+ zen: zenResult,
142
+ dbl: { ...merge(dblResults), domains: input.domains },
143
+ };
97
144
  }