@remit/mailbox-service 0.0.1
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.
- package/README.md +147 -0
- package/package.json +65 -0
- package/src/account-credentials.ts +128 -0
- package/src/adversarial-mime.e2e.test.ts +311 -0
- package/src/attribute-mapper.test.ts +78 -0
- package/src/attribute-mapper.ts +147 -0
- package/src/body-part-mapper.property.test.ts +354 -0
- package/src/body-part-mapper.ts +360 -0
- package/src/body-sync-queue.test.ts +124 -0
- package/src/body-sync-queue.ts +131 -0
- package/src/body-sync-terminal.test.ts +265 -0
- package/src/body-sync-terminal.ts +172 -0
- package/src/body-sync.ts +1202 -0
- package/src/connection-factory.ts +102 -0
- package/src/connection-test.ts +208 -0
- package/src/credentials.test.ts +181 -0
- package/src/filters/match.test.ts +181 -0
- package/src/filters/match.ts +143 -0
- package/src/filters/pipeline.ts +243 -0
- package/src/flag-push-terminal.test.ts +156 -0
- package/src/flag-push-terminal.ts +106 -0
- package/src/flag-push.test.ts +408 -0
- package/src/flag-push.ts +198 -0
- package/src/flag-queue.ts +500 -0
- package/src/heuristics/classifyByHeaders.test.ts +578 -0
- package/src/heuristics/classifyByHeaders.ts +369 -0
- package/src/heuristics/classifyPlacement.ts +96 -0
- package/src/heuristics/socialDomains.ts +23 -0
- package/src/heuristics/transactionalDomains.ts +26 -0
- package/src/imapflow-connect-retry.test.ts +108 -0
- package/src/imapflow-connection.e2e.test.ts +355 -0
- package/src/imapflow-connection.integ.test.ts +327 -0
- package/src/imapflow-connection.test.ts +161 -0
- package/src/imapflow-connection.ts +1374 -0
- package/src/index.ts +214 -0
- package/src/mailbox-cursor-rebuild.test.ts +171 -0
- package/src/mailbox-cursor-rebuild.ts +146 -0
- package/src/mailbox-cursor.test.ts +249 -0
- package/src/mailbox-cursor.ts +177 -0
- package/src/mailbox-management.test.ts +103 -0
- package/src/mailbox-management.ts +235 -0
- package/src/mailbox-queue.ts +258 -0
- package/src/mailbox-sync.test.ts +153 -0
- package/src/mailbox-sync.ts +590 -0
- package/src/message-move.ts +825 -0
- package/src/message-parser.ts +26 -0
- package/src/message-sync.ts +1021 -0
- package/src/mime-walker.test.ts +311 -0
- package/src/mime-walker.ts +305 -0
- package/src/outbox-queue.ts +294 -0
- package/src/pass-through-unit-of-work.ts +17 -0
- package/src/placement-move-terminal.test.ts +179 -0
- package/src/placement-move-terminal.ts +104 -0
- package/src/placement-move.ts +224 -0
- package/src/snippet.test.ts +213 -0
- package/src/snippet.ts +152 -0
- package/src/stale-message-reconcile.test.ts +82 -0
- package/src/stale-message-reconcile.ts +55 -0
- package/src/test-helpers/isolated-mailbox.ts +44 -0
- package/src/test-helpers/mailfuzz-connection.ts +27 -0
- package/src/test-helpers/mime-tree-generator.ts +461 -0
- package/src/text/normalizer.test.ts +223 -0
- package/src/text/normalizer.ts +140 -0
- package/src/types/mailparser-augment.d.ts +15 -0
- package/src/types/natural-porter-stemmer.d.ts +50 -0
- package/src/types/stopword.d.ts +69 -0
- package/src/types.ts +349 -0
- package/test/fixtures/mime/01-flat-text-plain.bodyparts.json +8 -0
- package/test/fixtures/mime/01-flat-text-plain.eml +10 -0
- package/test/fixtures/mime/01-flat-text-plain.expected.json +10 -0
- package/test/fixtures/mime/02-flat-text-html.bodyparts.json +8 -0
- package/test/fixtures/mime/02-flat-text-html.eml +10 -0
- package/test/fixtures/mime/02-flat-text-html.expected.json +10 -0
- package/test/fixtures/mime/03-alternative-text-html.bodyparts.json +20 -0
- package/test/fixtures/mime/03-alternative-text-html.eml +19 -0
- package/test/fixtures/mime/03-alternative-text-html.expected.json +16 -0
- package/test/fixtures/mime/04-mixed-html-pdf-attachment.bodyparts.json +22 -0
- package/test/fixtures/mime/04-mixed-html-pdf-attachment.eml +20 -0
- package/test/fixtures/mime/04-mixed-html-pdf-attachment.expected.json +16 -0
- package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.bodyparts.json +22 -0
- package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.eml +21 -0
- package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.expected.json +16 -0
- package/test/fixtures/mime/06-related-html-cid-image.bodyparts.json +23 -0
- package/test/fixtures/mime/06-related-html-cid-image.eml +21 -0
- package/test/fixtures/mime/06-related-html-cid-image.expected.json +16 -0
- package/test/fixtures/mime/07-mixed-alternative-related-attachment.bodyparts.json +55 -0
- package/test/fixtures/mime/07-mixed-alternative-related-attachment.eml +47 -0
- package/test/fixtures/mime/07-mixed-alternative-related-attachment.expected.json +34 -0
- package/test/fixtures/mime/08-two-pdfs-same-filename.bodyparts.json +30 -0
- package/test/fixtures/mime/08-two-pdfs-same-filename.eml +26 -0
- package/test/fixtures/mime/08-two-pdfs-same-filename.expected.json +22 -0
- package/test/fixtures/mime/09-attachment-no-filename.bodyparts.json +21 -0
- package/test/fixtures/mime/09-attachment-no-filename.eml +20 -0
- package/test/fixtures/mime/09-attachment-no-filename.expected.json +16 -0
- package/test/fixtures/mime/10-calendar-invite.bodyparts.json +22 -0
- package/test/fixtures/mime/10-calendar-invite.eml +33 -0
- package/test/fixtures/mime/10-calendar-invite.expected.json +16 -0
- package/test/fixtures/mime/11-quoted-printable-text.bodyparts.json +8 -0
- package/test/fixtures/mime/11-quoted-printable-text.eml +10 -0
- package/test/fixtures/mime/11-quoted-printable-text.expected.json +10 -0
- package/test/fixtures/mime/12-base64-binary.bodyparts.json +22 -0
- package/test/fixtures/mime/12-base64-binary.eml +20 -0
- package/test/fixtures/mime/12-base64-binary.expected.json +16 -0
- package/test/fixtures/mime/13-message-rfc822-forward.bodyparts.json +22 -0
- package/test/fixtures/mime/13-message-rfc822-forward.eml +28 -0
- package/test/fixtures/mime/13-message-rfc822-forward.expected.json +16 -0
- package/test/fixtures/mime/14-deeply-nested-5-levels.bodyparts.json +38 -0
- package/test/fixtures/mime/14-deeply-nested-5-levels.eml +34 -0
- package/test/fixtures/mime/14-deeply-nested-5-levels.expected.json +10 -0
- package/test/fixtures/mime/15-empty-text-part.bodyparts.json +21 -0
- package/test/fixtures/mime/15-empty-text-part.eml +18 -0
- package/test/fixtures/mime/15-empty-text-part.expected.json +16 -0
- package/test/fixtures/mime/16-empty-non-text-part.bodyparts.json +30 -0
- package/test/fixtures/mime/16-empty-non-text-part.eml +24 -0
- package/test/fixtures/mime/16-empty-non-text-part.expected.json +22 -0
- package/test/fixtures/mime-adversarial-e2e/01-octet-stream-pdf.eml +21 -0
- package/test/fixtures/mime-adversarial-e2e/02-nested-related-cid-image.eml +31 -0
- package/test/fixtures/mime-adversarial-e2e/03-calendar-invite.eml +33 -0
- package/test/fixtures/mime-adversarial-e2e/04-forwarded-rfc822-with-attachments.eml +42 -0
- package/test/fixtures/mime-adversarial-e2e/05-tnef-winmail.eml +25 -0
- package/test/fixtures/mime-adversarial-e2e/06-8bit-non-ascii.eml +15 -0
- package/test/fixtures/mime-adversarial-e2e/07-quoted-printable-soft-breaks.eml +17 -0
- package/test/fixtures/mime-adversarial-e2e/08-alternative-empty-text.eml +18 -0
- package/tsconfig.json +8 -0
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { AuthResultVerdict, MessageCategory } from "@remit/domain-enums";
|
|
2
|
+
import type {
|
|
3
|
+
Attachment,
|
|
4
|
+
HeaderLines,
|
|
5
|
+
Headers,
|
|
6
|
+
ParsedMail,
|
|
7
|
+
StructuredHeader,
|
|
8
|
+
} from "mailparser";
|
|
9
|
+
import { SOCIAL_DOMAINS } from "./socialDomains.js";
|
|
10
|
+
import { TRANSACTIONAL_DOMAINS } from "./transactionalDomains.js";
|
|
11
|
+
|
|
12
|
+
type Category = (typeof MessageCategory)[keyof typeof MessageCategory];
|
|
13
|
+
type AuthVerdictValue =
|
|
14
|
+
(typeof AuthResultVerdict)[keyof typeof AuthResultVerdict];
|
|
15
|
+
|
|
16
|
+
export interface MessageAuthResult {
|
|
17
|
+
dmarc?: AuthVerdictValue;
|
|
18
|
+
spf?: AuthVerdictValue;
|
|
19
|
+
dkim?: AuthVerdictValue;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface MessageProviderSpam {
|
|
23
|
+
classified: boolean;
|
|
24
|
+
score?: string;
|
|
25
|
+
source?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Structured sender-authenticity signal extracted from DKIM headers.
|
|
30
|
+
* Persisted alongside `category` during body-sync so the intelligence
|
|
31
|
+
* sidebar (#425) can render phishing verdicts without re-parsing.
|
|
32
|
+
*
|
|
33
|
+
* Present only when a DKIM-Signature header exists; absent otherwise
|
|
34
|
+
* (absence means "no signal" — no comparison was possible).
|
|
35
|
+
*/
|
|
36
|
+
export interface MessageAuthenticity {
|
|
37
|
+
/** Domain of the From header address */
|
|
38
|
+
fromDomain: string;
|
|
39
|
+
/** DKIM signing domain (d=) that was compared, when a signature is present */
|
|
40
|
+
dkimDomain?: string;
|
|
41
|
+
/** True when none of the DKIM signing domains aligns with the From domain */
|
|
42
|
+
dkimMismatch: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Header-only classification. Pure function. First match wins. Falls through
|
|
47
|
+
* to `personal` so misclassification stays in the safest bucket.
|
|
48
|
+
*
|
|
49
|
+
* Rule order matches the EDD heuristic table:
|
|
50
|
+
*
|
|
51
|
+
* 1. `Auto-Submitted: auto-generated|auto-replied` → `automated`
|
|
52
|
+
* 2. `Precedence: bulk|list|junk` → `automated`
|
|
53
|
+
* 3. `Content-Type: text/calendar` part anywhere → `transactional`
|
|
54
|
+
* 4. From-domain in TRANSACTIONAL_DOMAINS → `transactional`
|
|
55
|
+
* 5. `List-Unsubscribe` AND `List-Id` → `newsletter`
|
|
56
|
+
* 6. `List-Unsubscribe` only → `marketing`
|
|
57
|
+
* 7. DKIM `d=` differs from From domain → `automated`
|
|
58
|
+
* 8. From-domain in SOCIAL_DOMAINS → `social`
|
|
59
|
+
* 9. fallback → `personal`
|
|
60
|
+
*/
|
|
61
|
+
export const classifyByHeaders = (parsed: ParsedMail): Category => {
|
|
62
|
+
const headers = parsed.headers;
|
|
63
|
+
const lines = parsed.headerLines;
|
|
64
|
+
|
|
65
|
+
if (matchesAutoSubmitted(headers)) return MessageCategory.automated;
|
|
66
|
+
if (matchesPrecedence(headers)) return MessageCategory.automated;
|
|
67
|
+
if (hasCalendarPart(parsed.attachments)) return MessageCategory.transactional;
|
|
68
|
+
|
|
69
|
+
const fromDomain = getFromDomain(parsed);
|
|
70
|
+
|
|
71
|
+
if (fromDomain && domainMatches(fromDomain, TRANSACTIONAL_DOMAINS)) {
|
|
72
|
+
return MessageCategory.transactional;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const hasListUnsubscribe = hasHeaderLine(lines, "list-unsubscribe");
|
|
76
|
+
const hasListId = hasHeaderLine(lines, "list-id");
|
|
77
|
+
|
|
78
|
+
if (hasListUnsubscribe && hasListId) return MessageCategory.newsletter;
|
|
79
|
+
if (hasListUnsubscribe) return MessageCategory.marketing;
|
|
80
|
+
|
|
81
|
+
if (fromDomain && dkimMismatchResult(headers, lines, fromDomain).mismatch) {
|
|
82
|
+
return MessageCategory.automated;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (fromDomain && domainMatches(fromDomain, SOCIAL_DOMAINS)) {
|
|
86
|
+
return MessageCategory.social;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return MessageCategory.personal;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Extract the structured authenticity signal from parsed headers.
|
|
94
|
+
*
|
|
95
|
+
* Returns a `MessageAuthenticity` when at least one DKIM-Signature header
|
|
96
|
+
* is present (a comparison was possible). Returns `null` when there are no
|
|
97
|
+
* DKIM-Signature headers so callers can omit the field entirely — absence
|
|
98
|
+
* means "no signal", not "mismatch: false".
|
|
99
|
+
*
|
|
100
|
+
* The alignment rule exactly mirrors the category heuristic (rule 7) so the
|
|
101
|
+
* structured `dkimMismatch` boolean and the `automated` category can never
|
|
102
|
+
* disagree.
|
|
103
|
+
*/
|
|
104
|
+
export const extractAuthenticity = (
|
|
105
|
+
parsed: ParsedMail,
|
|
106
|
+
): MessageAuthenticity | null => {
|
|
107
|
+
const headers = parsed.headers;
|
|
108
|
+
const lines = parsed.headerLines;
|
|
109
|
+
const fromDomain = getFromDomain(parsed);
|
|
110
|
+
|
|
111
|
+
if (!fromDomain) return null;
|
|
112
|
+
|
|
113
|
+
const dkimDomains = extractDkimDomains(headers, lines);
|
|
114
|
+
if (dkimDomains.length === 0) return null;
|
|
115
|
+
|
|
116
|
+
const result = dkimMismatchResult(headers, lines, fromDomain);
|
|
117
|
+
|
|
118
|
+
// Pick the reported domain: first mismatching one on mismatch, first domain otherwise.
|
|
119
|
+
const reportedDomain = result.mismatchingDomain ?? dkimDomains[0];
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
fromDomain,
|
|
123
|
+
dkimDomain: reportedDomain,
|
|
124
|
+
dkimMismatch: result.mismatch,
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const extractVerdict = (
|
|
129
|
+
text: string,
|
|
130
|
+
mechanism: string,
|
|
131
|
+
): AuthVerdictValue | undefined => {
|
|
132
|
+
const match = text.match(new RegExp(`${mechanism}=(\\w+)`, "i"));
|
|
133
|
+
if (!match) return undefined;
|
|
134
|
+
const raw = match[1].toLowerCase();
|
|
135
|
+
const map: Record<string, AuthVerdictValue> = {
|
|
136
|
+
pass: AuthResultVerdict.Pass,
|
|
137
|
+
fail: AuthResultVerdict.Fail,
|
|
138
|
+
none: AuthResultVerdict.None,
|
|
139
|
+
neutral: AuthResultVerdict.Neutral,
|
|
140
|
+
softfail: AuthResultVerdict.Softfail,
|
|
141
|
+
};
|
|
142
|
+
return map[raw];
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Extract provider authentication-results verdict from the Authentication-Results header.
|
|
147
|
+
* Returns null when the header is absent.
|
|
148
|
+
*/
|
|
149
|
+
export const extractAuthResult = (
|
|
150
|
+
parsed: ParsedMail,
|
|
151
|
+
): MessageAuthResult | null => {
|
|
152
|
+
const line = parsed.headerLines.find(
|
|
153
|
+
(l) => l.key.toLowerCase() === "authentication-results",
|
|
154
|
+
);
|
|
155
|
+
if (!line) return null;
|
|
156
|
+
|
|
157
|
+
const text = stripHeaderName(line.line);
|
|
158
|
+
const dmarc = extractVerdict(text, "dmarc");
|
|
159
|
+
const spf = extractVerdict(text, "spf");
|
|
160
|
+
const dkim = extractVerdict(text, "dkim");
|
|
161
|
+
|
|
162
|
+
return { dmarc, spf, dkim };
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Extract provider spam-filter signal from X-SpamExperts-Class, X-Spam-Status,
|
|
167
|
+
* or X-HalOne-Spam-Probability headers. Returns null when none are present.
|
|
168
|
+
*/
|
|
169
|
+
export const extractProviderSpam = (
|
|
170
|
+
parsed: ParsedMail,
|
|
171
|
+
): MessageProviderSpam | null => {
|
|
172
|
+
const lines = parsed.headerLines;
|
|
173
|
+
|
|
174
|
+
const spamExperts = lines.find(
|
|
175
|
+
(l) => l.key.toLowerCase() === "x-spamexperts-class",
|
|
176
|
+
);
|
|
177
|
+
if (spamExperts) {
|
|
178
|
+
const value = stripHeaderName(spamExperts.line).trim().toLowerCase();
|
|
179
|
+
return {
|
|
180
|
+
classified: value === "spam",
|
|
181
|
+
source: "x-spamexperts-class",
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const spamStatus = lines.find((l) => l.key.toLowerCase() === "x-spam-status");
|
|
186
|
+
if (spamStatus) {
|
|
187
|
+
const text = stripHeaderName(spamStatus.line).trim();
|
|
188
|
+
const classified = text.toLowerCase().startsWith("yes");
|
|
189
|
+
const scoreMatch = text.match(/score=([\d.+-]+)/i);
|
|
190
|
+
return {
|
|
191
|
+
classified,
|
|
192
|
+
score: scoreMatch ? scoreMatch[1] : undefined,
|
|
193
|
+
source: "x-spam-status",
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const halOne = lines.find(
|
|
198
|
+
(l) => l.key.toLowerCase() === "x-halone-spam-probability",
|
|
199
|
+
);
|
|
200
|
+
if (halOne) {
|
|
201
|
+
const value = stripHeaderName(halOne.line).trim();
|
|
202
|
+
return {
|
|
203
|
+
classified: parseFloat(value) > 0.5,
|
|
204
|
+
score: value,
|
|
205
|
+
source: "x-halone-spam-probability",
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return null;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Returns true when a List-Unsubscribe header is present, indicating a
|
|
214
|
+
* bulk/mailing-list sender.
|
|
215
|
+
*/
|
|
216
|
+
export const extractHasListUnsubscribe = (parsed: ParsedMail): boolean =>
|
|
217
|
+
parsed.headerLines.some((l) => l.key.toLowerCase() === "list-unsubscribe");
|
|
218
|
+
|
|
219
|
+
const matchesAutoSubmitted = (headers: Headers): boolean => {
|
|
220
|
+
const value = readStringHeader(headers, "auto-submitted");
|
|
221
|
+
if (!value) return false;
|
|
222
|
+
const normalized = value.split(";")[0].trim().toLowerCase();
|
|
223
|
+
return normalized === "auto-generated" || normalized === "auto-replied";
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const matchesPrecedence = (headers: Headers): boolean => {
|
|
227
|
+
const value = readStringHeader(headers, "precedence");
|
|
228
|
+
if (!value) return false;
|
|
229
|
+
const normalized = value.trim().toLowerCase();
|
|
230
|
+
return (
|
|
231
|
+
normalized === "bulk" || normalized === "list" || normalized === "junk"
|
|
232
|
+
);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const hasCalendarPart = (attachments: Attachment[] | undefined): boolean => {
|
|
236
|
+
if (!attachments) return false;
|
|
237
|
+
for (const att of attachments) {
|
|
238
|
+
if ((att.contentType ?? "").toLowerCase().startsWith("text/calendar")) {
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return false;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const getFromDomain = (parsed: ParsedMail): string | null => {
|
|
246
|
+
const from = parsed.from;
|
|
247
|
+
if (!from || !from.value || from.value.length === 0) return null;
|
|
248
|
+
const address = from.value[0]?.address;
|
|
249
|
+
if (!address) return null;
|
|
250
|
+
const at = address.lastIndexOf("@");
|
|
251
|
+
if (at < 0 || at === address.length - 1) return null;
|
|
252
|
+
return address.slice(at + 1).toLowerCase();
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const domainMatches = (
|
|
256
|
+
domain: string,
|
|
257
|
+
allowList: readonly string[],
|
|
258
|
+
): boolean => {
|
|
259
|
+
for (const entry of allowList) {
|
|
260
|
+
if (domain === entry || domain.endsWith(`.${entry}`)) return true;
|
|
261
|
+
}
|
|
262
|
+
return false;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Check whether DKIM signing domain(s) align with the From domain and
|
|
267
|
+
* return a structured result so both the category heuristic and the
|
|
268
|
+
* authenticity extractor share the exact same alignment logic.
|
|
269
|
+
*
|
|
270
|
+
* Alignment: signing domain equals From domain, or one is a subdomain of
|
|
271
|
+
* the other (parent/child). Any single aligned domain is enough to consider
|
|
272
|
+
* the message non-mismatching — a legitimate re-mailer signing under a
|
|
273
|
+
* subdomain is not suspicious.
|
|
274
|
+
*
|
|
275
|
+
* On mismatch the first non-aligned domain is reported so the UI can show
|
|
276
|
+
* "signed by relay.example.net, claims example.com".
|
|
277
|
+
*/
|
|
278
|
+
const dkimMismatchResult = (
|
|
279
|
+
headers: Headers,
|
|
280
|
+
lines: HeaderLines,
|
|
281
|
+
fromDomain: string,
|
|
282
|
+
): { mismatch: boolean; mismatchingDomain: string | null } => {
|
|
283
|
+
const dkimDomains = extractDkimDomains(headers, lines);
|
|
284
|
+
if (dkimDomains.length === 0)
|
|
285
|
+
return { mismatch: false, mismatchingDomain: null };
|
|
286
|
+
let firstMismatching: string | null = null;
|
|
287
|
+
for (const d of dkimDomains) {
|
|
288
|
+
if (
|
|
289
|
+
d === fromDomain ||
|
|
290
|
+
fromDomain.endsWith(`.${d}`) ||
|
|
291
|
+
d.endsWith(`.${fromDomain}`)
|
|
292
|
+
) {
|
|
293
|
+
return { mismatch: false, mismatchingDomain: null };
|
|
294
|
+
}
|
|
295
|
+
if (!firstMismatching) firstMismatching = d;
|
|
296
|
+
}
|
|
297
|
+
return { mismatch: true, mismatchingDomain: firstMismatching };
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const extractDkimDomains = (headers: Headers, lines: HeaderLines): string[] => {
|
|
301
|
+
const domains: string[] = [];
|
|
302
|
+
|
|
303
|
+
const raw = headers.get("dkim-signature");
|
|
304
|
+
const structured = collectStructured(raw);
|
|
305
|
+
for (const s of structured) {
|
|
306
|
+
const d = s.params?.d;
|
|
307
|
+
if (typeof d === "string") domains.push(d.trim().toLowerCase());
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
for (const line of lines) {
|
|
311
|
+
if (line.key.toLowerCase() !== "dkim-signature") continue;
|
|
312
|
+
const value = stripHeaderName(line.line);
|
|
313
|
+
const match = value.match(/(?:^|;)\s*d\s*=\s*([^;\s]+)/i);
|
|
314
|
+
if (match) {
|
|
315
|
+
const candidate = match[1].trim().toLowerCase();
|
|
316
|
+
if (!domains.includes(candidate)) domains.push(candidate);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return domains;
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const collectStructured = (value: unknown): StructuredHeader[] => {
|
|
323
|
+
if (!value) return [];
|
|
324
|
+
if (Array.isArray(value)) {
|
|
325
|
+
const out: StructuredHeader[] = [];
|
|
326
|
+
for (const v of value) {
|
|
327
|
+
if (isStructuredHeader(v)) out.push(v);
|
|
328
|
+
}
|
|
329
|
+
return out;
|
|
330
|
+
}
|
|
331
|
+
if (isStructuredHeader(value)) return [value];
|
|
332
|
+
return [];
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
const isStructuredHeader = (v: unknown): v is StructuredHeader => {
|
|
336
|
+
if (!v || typeof v !== "object") return false;
|
|
337
|
+
return (
|
|
338
|
+
"value" in v &&
|
|
339
|
+
typeof (v as { value: unknown }).value === "string" &&
|
|
340
|
+
"params" in v &&
|
|
341
|
+
typeof (v as { params: unknown }).params === "object"
|
|
342
|
+
);
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
const stripHeaderName = (line: string): string => {
|
|
346
|
+
const idx = line.indexOf(":");
|
|
347
|
+
return idx >= 0 ? line.slice(idx + 1).trim() : line;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
const hasHeaderLine = (lines: HeaderLines, name: string): boolean => {
|
|
351
|
+
const lc = name.toLowerCase();
|
|
352
|
+
for (const line of lines) {
|
|
353
|
+
if (line.key.toLowerCase() === lc) return true;
|
|
354
|
+
}
|
|
355
|
+
return false;
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const readStringHeader = (
|
|
359
|
+
headers: Headers,
|
|
360
|
+
key: string,
|
|
361
|
+
): string | undefined => {
|
|
362
|
+
const value = headers.get(key);
|
|
363
|
+
if (typeof value === "string") return value;
|
|
364
|
+
if (Array.isArray(value)) {
|
|
365
|
+
const first = value[0];
|
|
366
|
+
if (typeof first === "string") return first;
|
|
367
|
+
}
|
|
368
|
+
return undefined;
|
|
369
|
+
};
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { MessageItem } from "@remit/data-ports";
|
|
2
|
+
import { SenderTrust } from "@remit/domain-enums";
|
|
3
|
+
|
|
4
|
+
type SenderTrustValue = (typeof SenderTrust)[keyof typeof SenderTrust];
|
|
5
|
+
|
|
6
|
+
export type FolderPlacement = "inbox" | "junk" | "other";
|
|
7
|
+
|
|
8
|
+
export type PlacementAction = "move-to-inbox" | "move-to-junk" | "leave";
|
|
9
|
+
|
|
10
|
+
export interface PlacementVerdict {
|
|
11
|
+
action: PlacementAction;
|
|
12
|
+
confidence: "confident" | "unsure";
|
|
13
|
+
reasons: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const isTrusted = (senderTrust: SenderTrustValue): boolean =>
|
|
17
|
+
senderTrust === SenderTrust.Vip || senderTrust === SenderTrust.Wellknown;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Tier 0 deterministic placement verdict (RFC 031, "Confident moves").
|
|
21
|
+
*
|
|
22
|
+
* Pure: the caller resolves the message's current folder placement and the
|
|
23
|
+
* sender trust; this function does no DB lookups and produces no side effects.
|
|
24
|
+
* It generalizes `shouldRescueFromJunk` into a two-directional verdict and is
|
|
25
|
+
* recall-biased — a confident move only fires when cheap, deterministic signals
|
|
26
|
+
* agree; everything else is left in place for a later LLM tier.
|
|
27
|
+
*/
|
|
28
|
+
export const classifyPlacement = (
|
|
29
|
+
message: MessageItem,
|
|
30
|
+
placement: FolderPlacement,
|
|
31
|
+
senderTrust: SenderTrustValue,
|
|
32
|
+
): PlacementVerdict => {
|
|
33
|
+
if (message.movedByRemit === true) {
|
|
34
|
+
return {
|
|
35
|
+
action: "leave",
|
|
36
|
+
confidence: "confident",
|
|
37
|
+
reasons: ["already-moved-by-remit"],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!message.providerSpam || !message.authResult) {
|
|
42
|
+
return {
|
|
43
|
+
action: "leave",
|
|
44
|
+
confidence: "unsure",
|
|
45
|
+
reasons: ["missing-signals"],
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const providerSpam = message.providerSpam.classified === true;
|
|
50
|
+
const dmarc = message.authResult.dmarc;
|
|
51
|
+
const dkimMismatch = message.authenticity?.dkimMismatch === true;
|
|
52
|
+
const trusted = isTrusted(senderTrust);
|
|
53
|
+
|
|
54
|
+
// Rescue (junk → inbox), LOW bar. Mirrors shouldRescueFromJunk's gate.
|
|
55
|
+
if (placement === "junk" && providerSpam && dmarc === "Pass") {
|
|
56
|
+
if (trusted) {
|
|
57
|
+
return {
|
|
58
|
+
action: "move-to-inbox",
|
|
59
|
+
confidence: "confident",
|
|
60
|
+
reasons: ["provider=spam", "dmarc=pass", `sender=${senderTrust}`],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
// Anti-spoof guard: an unknown sender is never auto-rescued.
|
|
64
|
+
return {
|
|
65
|
+
action: "leave",
|
|
66
|
+
confidence: "unsure",
|
|
67
|
+
reasons: ["provider=spam", "dmarc=pass", "sender=untrusted"],
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Demote (inbox → junk), HIGH bar.
|
|
72
|
+
if (placement === "inbox" && dkimMismatch) {
|
|
73
|
+
if (dmarc === "Fail" && !trusted) {
|
|
74
|
+
return {
|
|
75
|
+
action: "move-to-junk",
|
|
76
|
+
confidence: "confident",
|
|
77
|
+
reasons: ["dkim-mismatch", "dmarc=fail", "sender=untrusted"],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// DMARC-pass phishing: dkimMismatch but DMARC did not fail. Deferred to a
|
|
81
|
+
// later LLM tier — must never auto-demote here.
|
|
82
|
+
if (dmarc === "Pass") {
|
|
83
|
+
return {
|
|
84
|
+
action: "leave",
|
|
85
|
+
confidence: "unsure",
|
|
86
|
+
reasons: ["dkim-mismatch", "dmarc=pass", "deferred-to-llm"],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
action: "leave",
|
|
93
|
+
confidence: "unsure",
|
|
94
|
+
reasons: ["no-confident-signal"],
|
|
95
|
+
};
|
|
96
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hand-curated allow-list of domains whose mail is treated as `social`.
|
|
3
|
+
*
|
|
4
|
+
* Sources are notifications from social/communication platforms. Match is
|
|
5
|
+
* suffix-based on the From-domain (lowercase). `news.linkedin.com` matches
|
|
6
|
+
* an entry of `linkedin.com`. Add new entries lowercase, no leading dot.
|
|
7
|
+
*
|
|
8
|
+
* Note: GitHub deliberately does NOT appear here. It is in
|
|
9
|
+
* `transactionalDomains.ts` because the EDD prioritises receipts and
|
|
10
|
+
* security alerts. The transactional rule fires before the social rule, so
|
|
11
|
+
* placing GitHub in the transactional list ensures all GitHub mail surfaces
|
|
12
|
+
* as `transactional`.
|
|
13
|
+
*/
|
|
14
|
+
export const SOCIAL_DOMAINS = [
|
|
15
|
+
"linkedin.com",
|
|
16
|
+
"x.com",
|
|
17
|
+
"twitter.com",
|
|
18
|
+
"facebook.com",
|
|
19
|
+
"instagram.com",
|
|
20
|
+
"meetup.com",
|
|
21
|
+
"discord.com",
|
|
22
|
+
"slack.com",
|
|
23
|
+
] as const;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hand-curated allow-list of domains whose mail is treated as `transactional`.
|
|
3
|
+
*
|
|
4
|
+
* Sources are receipts, billing, security alerts, and similar
|
|
5
|
+
* person-actionable but not promotional mail. GitHub appears here (security
|
|
6
|
+
* alerts, billing receipts) and is intentionally NOT in the social allow-list
|
|
7
|
+
* — we want a GitHub security alert to surface as `transactional`, not
|
|
8
|
+
* `social`.
|
|
9
|
+
*
|
|
10
|
+
* Match is suffix-based on the From-domain (lowercase). `news.example.com`
|
|
11
|
+
* matches an entry of `example.com`. Add new entries lowercase, no leading
|
|
12
|
+
* dot.
|
|
13
|
+
*
|
|
14
|
+
* TODO: We deliberately do NOT seed banks here — the bank landscape is too
|
|
15
|
+
* geographic, and a wrong allow-list entry causes silent mis-classification.
|
|
16
|
+
* Banks should be added per-deployment by the operator.
|
|
17
|
+
*/
|
|
18
|
+
export const TRANSACTIONAL_DOMAINS = [
|
|
19
|
+
"github.com",
|
|
20
|
+
"stripe.com",
|
|
21
|
+
"paypal.com",
|
|
22
|
+
"square.com",
|
|
23
|
+
"itunes.com",
|
|
24
|
+
"apple.com",
|
|
25
|
+
"google.com",
|
|
26
|
+
] as const;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for ImapFlowConnection.connect() retry semantics.
|
|
3
|
+
*
|
|
4
|
+
* Verifies the retry policy without touching a real IMAP server:
|
|
5
|
+
* - Network errors (e.g. ECONNREFUSED) are retried with backoff before the
|
|
6
|
+
* classified MailConnectionError("network") is finally thrown.
|
|
7
|
+
* - Auth errors are thrown immediately and NEVER retried.
|
|
8
|
+
*
|
|
9
|
+
* The private `attemptConnect` and `sleep` instance methods are stubbed so the
|
|
10
|
+
* test exercises the loop logic directly and runs instantly.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import assert from "node:assert/strict";
|
|
14
|
+
import { describe, it, mock } from "node:test";
|
|
15
|
+
import { ImapFlowConnection } from "./imapflow-connection.js";
|
|
16
|
+
import { MailConnectionError } from "./types.js";
|
|
17
|
+
|
|
18
|
+
const baseConfig = {
|
|
19
|
+
host: "localhost",
|
|
20
|
+
port: 143,
|
|
21
|
+
user: "alice@example.com",
|
|
22
|
+
credentials: { kind: "password" as const, password: "s3cr3t" },
|
|
23
|
+
tls: false,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type WithPrivates = {
|
|
27
|
+
attemptConnect: () => Promise<void>;
|
|
28
|
+
sleep: (ms: number) => Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const makeErrnoError = (code: string): Error => {
|
|
32
|
+
const err = new Error(`connect ${code}`);
|
|
33
|
+
return Object.assign(err, { code });
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
describe("ImapFlowConnection.connect() retry policy", () => {
|
|
37
|
+
it("retries network errors (ECONNREFUSED) 3x with backoff, then throws classified network error", async () => {
|
|
38
|
+
const connection = new ImapFlowConnection(baseConfig);
|
|
39
|
+
const priv = connection as unknown as WithPrivates;
|
|
40
|
+
|
|
41
|
+
// Always fail with a network-level error.
|
|
42
|
+
const attempt = mock.method(priv, "attemptConnect", async () => {
|
|
43
|
+
throw makeErrnoError("ECONNREFUSED");
|
|
44
|
+
});
|
|
45
|
+
// Stub sleep so the backoff does not actually delay the test.
|
|
46
|
+
mock.method(priv, "sleep", async () => {});
|
|
47
|
+
|
|
48
|
+
await assert.rejects(
|
|
49
|
+
() => connection.connect(),
|
|
50
|
+
(error: unknown) => {
|
|
51
|
+
assert.ok(
|
|
52
|
+
error instanceof MailConnectionError,
|
|
53
|
+
"final error should be a MailConnectionError",
|
|
54
|
+
);
|
|
55
|
+
assert.equal(error.kind, "network");
|
|
56
|
+
// The host:port endpoint must appear in the message so a DNS /
|
|
57
|
+
// connect failure is self-describing in the logs (issue #835).
|
|
58
|
+
assert.match(error.message, /localhost:143/);
|
|
59
|
+
return true;
|
|
60
|
+
},
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
// 3 attempts total (the retry loop runs maxRetries times).
|
|
64
|
+
assert.equal(attempt.mock.callCount(), 3);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("succeeds on a later attempt when a transient network error clears", async () => {
|
|
68
|
+
const connection = new ImapFlowConnection(baseConfig);
|
|
69
|
+
const priv = connection as unknown as WithPrivates;
|
|
70
|
+
|
|
71
|
+
let calls = 0;
|
|
72
|
+
const attempt = mock.method(priv, "attemptConnect", async () => {
|
|
73
|
+
calls += 1;
|
|
74
|
+
if (calls < 2) {
|
|
75
|
+
throw makeErrnoError("ECONNRESET");
|
|
76
|
+
}
|
|
77
|
+
// Second attempt succeeds.
|
|
78
|
+
});
|
|
79
|
+
mock.method(priv, "sleep", async () => {});
|
|
80
|
+
|
|
81
|
+
await connection.connect();
|
|
82
|
+
|
|
83
|
+
assert.equal(attempt.mock.callCount(), 2);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("does NOT retry auth errors — throws immediately on attempt 1", async () => {
|
|
87
|
+
const connection = new ImapFlowConnection(baseConfig);
|
|
88
|
+
const priv = connection as unknown as WithPrivates;
|
|
89
|
+
|
|
90
|
+
const attempt = mock.method(priv, "attemptConnect", async () => {
|
|
91
|
+
throw new Error("Invalid credentials");
|
|
92
|
+
});
|
|
93
|
+
const sleep = mock.method(priv, "sleep", async () => {});
|
|
94
|
+
|
|
95
|
+
await assert.rejects(
|
|
96
|
+
() => connection.connect(),
|
|
97
|
+
(error: unknown) => {
|
|
98
|
+
assert.ok(error instanceof MailConnectionError);
|
|
99
|
+
assert.equal(error.kind, "auth");
|
|
100
|
+
return true;
|
|
101
|
+
},
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
// Only one attempt, no backoff sleep.
|
|
105
|
+
assert.equal(attempt.mock.callCount(), 1);
|
|
106
|
+
assert.equal(sleep.mock.callCount(), 0);
|
|
107
|
+
});
|
|
108
|
+
});
|