@remit/mailbox-service 0.0.99 → 0.0.101

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.
@@ -1,7 +1,12 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { describe, it } from "node:test";
3
- import { MessageCategory } from "@remit/domain-enums";
4
- import { simpleParser } from "mailparser";
3
+ import type { MessageItem } from "@remit/data-ports";
4
+ import {
5
+ MessageCategory,
6
+ SenderOverride,
7
+ SenderTrust,
8
+ } from "@remit/domain-enums";
9
+ import { type ParsedMail, simpleParser } from "mailparser";
5
10
  import {
6
11
  classifyByHeaders,
7
12
  extractAuthenticity,
@@ -9,6 +14,7 @@ import {
9
14
  extractHasListUnsubscribe,
10
15
  extractProviderSpam,
11
16
  } from "./classifyByHeaders.js";
17
+ import { classifyPlacement } from "./classifyPlacement.js";
12
18
 
13
19
  const buildEml = (lines: string[]): Buffer => Buffer.from(lines.join("\r\n"));
14
20
 
@@ -576,3 +582,308 @@ describe("extractHasListUnsubscribe", () => {
576
582
  assert.equal(extractHasListUnsubscribe(parsed), true);
577
583
  });
578
584
  });
585
+
586
+ const messageFrom = (parsed: ParsedMail): MessageItem => ({
587
+ messageId: "m-1",
588
+ mailboxId: "mb-1",
589
+ uid: 1,
590
+ sequenceNumber: 1,
591
+ rfc822Size: 1,
592
+ internalDate: 1,
593
+ envelopeId: "e-1",
594
+ rootBodyPartId: "bp-1",
595
+ status: "active",
596
+ syncStatus: "synced",
597
+ abandonedMutation: "none",
598
+ category: "uncategorized",
599
+ classificationState: "NotExamined",
600
+ authenticityVerdict: "NotEvaluated",
601
+ hasListUnsubscribe: false,
602
+ movedByRemit: false,
603
+ createdAt: 1,
604
+ updatedAt: 1,
605
+ providerSpam: extractProviderSpam(parsed) ?? undefined,
606
+ authResult: extractAuthResult(parsed) ?? undefined,
607
+ authenticity: extractAuthenticity(parsed) ?? undefined,
608
+ });
609
+
610
+ const inboxVerdict = (parsed: ParsedMail) =>
611
+ classifyPlacement(
612
+ messageFrom(parsed),
613
+ "inbox",
614
+ SenderTrust.Unknown,
615
+ SenderOverride.None,
616
+ );
617
+
618
+ const withBody = (lines: string[]): string[] => [...lines, "", "body"];
619
+
620
+ describe("Authentication-Results adversarial findings (#657)", () => {
621
+ it("keeps the aligned dkim result when a comment carries a semicolon", async () => {
622
+ const parsed = await parse(
623
+ withBody([
624
+ "From: Alice <alice@acme.example>",
625
+ "Authentication-Results: gw.example; dkim=fail (1024-bit key; unprotected) header.d=acme.example; dkim=pass header.d=relay.example; dmarc=fail (p=REJECT) header.from=acme.example",
626
+ "X-Spam-Status: No, score=0.1",
627
+ ]),
628
+ );
629
+ assert.deepEqual(extractAuthResult(parsed), {
630
+ dmarc: "Fail",
631
+ spf: undefined,
632
+ dkim: "Fail",
633
+ });
634
+ });
635
+
636
+ it("checks alignment even when an unrelated dkim=pass is present", async () => {
637
+ const header = (extra: string) =>
638
+ parse(
639
+ withBody([
640
+ "From: Alice <alice@acme.example>",
641
+ `Authentication-Results: gw.corp.example; ${extra}dkim=fail (body hash did not verify) header.d=acme.example; dmarc=fail (p=REJECT) header.from=acme.example`,
642
+ "X-Spam-Status: No, score=0.1",
643
+ ]),
644
+ );
645
+ const without = await header("");
646
+ const withEsp = await header("dkim=pass header.d=esp-mailer.example; ");
647
+ assert.deepEqual(extractAuthResult(withEsp), extractAuthResult(without));
648
+ assert.deepEqual(inboxVerdict(withEsp), inboxVerdict(without));
649
+ assert.equal(inboxVerdict(withEsp).action, "leave");
650
+ });
651
+
652
+ it("never junks list mail whose relay stripped the original signature", async () => {
653
+ const parsed = await parse(
654
+ withBody([
655
+ "From: Alice <alice@acme.example>",
656
+ "To: list@googlegroups.example",
657
+ "Authentication-Results: mx.google.example; dkim=pass header.d=googlegroups.example; spf=pass smtp.mailfrom=googlegroups.example; dmarc=fail (p=REJECT) header.from=acme.example",
658
+ "List-Id: <list.googlegroups.example>",
659
+ "X-Spam-Status: No, score=0.2",
660
+ ]),
661
+ );
662
+ assert.equal(extractAuthenticity(parsed), null);
663
+ assert.equal(inboxVerdict(parsed).action, "leave");
664
+ });
665
+
666
+ it("never lets a prepended header override the raw signing domain", async () => {
667
+ const parsed = await parse(
668
+ withBody([
669
+ "Authentication-Results: anything-i-like; dkim=pass header.d=bank.example",
670
+ "From: Security <security@bank.example>",
671
+ "To: victim@example.com",
672
+ "Subject: Verify your account",
673
+ "DKIM-Signature: v=1; a=rsa-sha256; d=phish-host.example; s=sel; b=xxx",
674
+ "X-Spam-Status: No, score=0.1",
675
+ ]),
676
+ );
677
+ assert.deepEqual(extractAuthenticity(parsed), {
678
+ fromDomain: "bank.example",
679
+ dkimDomain: "phish-host.example",
680
+ dkimMismatch: true,
681
+ });
682
+ });
683
+
684
+ it("never lets a prepended header hide the receiving MTA's dmarc=fail", async () => {
685
+ const lines = (order: "forged-first" | "real-first") => {
686
+ const forged =
687
+ "Authentication-Results: whatever; dkim=pass header.d=evil-mimic.example; dmarc=pass header.from=evil-mimic.example";
688
+ const real = "Authentication-Results: mx.example.com; dmarc=fail";
689
+ return withBody([
690
+ ...(order === "forged-first" ? [forged, real] : [real, forged]),
691
+ "From: Support <support@evil-mimic.example>",
692
+ "To: me@example.com",
693
+ "Subject: Verify your account",
694
+ "DKIM-Signature: v=1; a=rsa-sha256; d=relay.example.net; s=sel; b=xxx",
695
+ "X-Spam-Status: No, score=0.1",
696
+ ]);
697
+ };
698
+ for (const order of ["forged-first", "real-first"] as const) {
699
+ const parsed = await parse(lines(order));
700
+ assert.equal(extractAuthResult(parsed)?.dmarc, "Fail", order);
701
+ assert.equal(inboxVerdict(parsed).action, "move-to-junk", order);
702
+ }
703
+ });
704
+
705
+ it("never lets a sender-added aligned dkim=pass override the receiver's verdict", async () => {
706
+ const receivers = [
707
+ "Authentication-Results: mx.me.example; dkim=fail header.d=phish.example; dmarc=fail header.from=bank.example",
708
+ "Authentication-Results: mx.me.example; dkim=none; dmarc=fail header.from=bank.example",
709
+ ];
710
+ const forged = "Authentication-Results: x; dkim=pass header.d=bank.example";
711
+ for (const [receiver, expected] of [
712
+ [receivers[0], "Fail"],
713
+ [receivers[1], "None"],
714
+ ] as const) {
715
+ for (const headers of [
716
+ [receiver, forged],
717
+ [forged, receiver],
718
+ ]) {
719
+ const parsed = await parse(
720
+ withBody([...headers, "From: B <s@bank.example>"]),
721
+ );
722
+ assert.equal(
723
+ extractAuthResult(parsed)?.dkim,
724
+ expected,
725
+ headers.join(" | "),
726
+ );
727
+ }
728
+ }
729
+ });
730
+
731
+ it("never reads dkim=fail out of another method's comment", async () => {
732
+ const parsed = await parse(
733
+ withBody([
734
+ "From: Alice <alice@acme.example>",
735
+ "Authentication-Results: mx.example.net; arc=fail (i=1 spf=fail; dkim=fail",
736
+ " header.d=arcsigner.example; dmarc=fail); spf=pass smtp.mailfrom=acme.example;",
737
+ " dmarc=pass header.from=acme.example",
738
+ ]),
739
+ );
740
+ assert.deepEqual(extractAuthResult(parsed), {
741
+ dmarc: "Pass",
742
+ spf: "Pass",
743
+ dkim: undefined,
744
+ });
745
+ });
746
+
747
+ it("reads dmarc from its own resinfo, not from an arc comment", async () => {
748
+ const parsed = await parse(
749
+ withBody([
750
+ "From: Alice <alice@acme.example>",
751
+ "Authentication-Results: gw.example; arc=pass (i=1 dmarc=fail fromdomain=acme.example); dmarc=pass header.from=acme.example",
752
+ ]),
753
+ );
754
+ assert.equal(extractAuthResult(parsed)?.dmarc, "Pass");
755
+ });
756
+
757
+ describe("grammar edge cases", () => {
758
+ const dkimFor = async (value: string) =>
759
+ extractAuthResult(
760
+ await parse(
761
+ withBody([
762
+ "From: Alice <alice@acme.example>",
763
+ `Authentication-Results: ${value}`,
764
+ ]),
765
+ ),
766
+ )?.dkim;
767
+
768
+ it("aligns a signing domain written with a trailing root dot", async () => {
769
+ assert.equal(
770
+ await dkimFor(
771
+ "gw.example; dkim=fail header.d=esp.example; dkim=pass header.d=acme.example.",
772
+ ),
773
+ "Pass",
774
+ );
775
+ });
776
+
777
+ it("never aligns a header.i without an @", async () => {
778
+ assert.equal(
779
+ await dkimFor(
780
+ "gw.example; dkim=fail header.d=esp.example; dkim=pass header.i=acme.example",
781
+ ),
782
+ "Fail",
783
+ );
784
+ });
785
+
786
+ it("never aligns a result whose header.i falls outside header.d", async () => {
787
+ assert.equal(
788
+ await dkimFor(
789
+ "gw.example; dkim=fail header.d=esp.example; dkim=pass header.d=acme.example header.i=@evil.example",
790
+ ),
791
+ "Fail",
792
+ );
793
+ });
794
+
795
+ it("aligns through header.i when header.d is absent", async () => {
796
+ assert.equal(
797
+ await dkimFor(
798
+ "gw.example; dkim=fail header.d=esp.example; dkim=pass header.i=alice@mail.acme.example",
799
+ ),
800
+ "Pass",
801
+ );
802
+ });
803
+
804
+ it("reads upper-case tokens", async () => {
805
+ const parsed = await parse(
806
+ withBody([
807
+ "From: Alice <alice@acme.example>",
808
+ "Authentication-Results: GW.EXAMPLE; DKIM=FAIL HEADER.D=EVIL.EXAMPLE; DMARC=FAIL",
809
+ ]),
810
+ );
811
+ assert.deepEqual(extractAuthResult(parsed), {
812
+ dmarc: "Fail",
813
+ spf: undefined,
814
+ dkim: "Fail",
815
+ });
816
+ });
817
+
818
+ it("reads a folded header whose continuation starts with dkim=", async () => {
819
+ const parsed = await parse(
820
+ withBody([
821
+ "From: Alice <alice@acme.example>",
822
+ "Authentication-Results: mx.example.com;",
823
+ "\tdkim=pass header.d=acme.example;",
824
+ "\tdmarc=fail header.from=acme.example",
825
+ ]),
826
+ );
827
+ assert.deepEqual(extractAuthResult(parsed), {
828
+ dmarc: "Fail",
829
+ spf: undefined,
830
+ dkim: "Pass",
831
+ });
832
+ });
833
+
834
+ it("prefers the aligned result wherever it is listed", async () => {
835
+ assert.equal(
836
+ await dkimFor(
837
+ "gw.example; dkim=fail header.d=esp-mailer.example; dkim=pass header.d=acme.example; dmarc=fail",
838
+ ),
839
+ "Pass",
840
+ );
841
+ });
842
+
843
+ it("reads dkim=fail with no domain", async () => {
844
+ assert.equal(await dkimFor("gw.example; dkim=fail; dmarc=fail"), "Fail");
845
+ });
846
+
847
+ it("never reads an unrecognised result as a pass", async () => {
848
+ assert.equal(
849
+ await dkimFor(
850
+ "gw.example; dkim=pass header.d=acme.example; dkim=permerror header.d=acme.example",
851
+ ),
852
+ undefined,
853
+ );
854
+ });
855
+ });
856
+
857
+ describe("fail closed", () => {
858
+ it("yields no result for an empty header", async () => {
859
+ const parsed = await parse(
860
+ withBody([
861
+ "From: Alice <alice@acme.example>",
862
+ "Authentication-Results: ",
863
+ ]),
864
+ );
865
+ assert.equal(extractAuthResult(parsed), null);
866
+ });
867
+
868
+ it("yields no result for a header that does not parse", async () => {
869
+ const parsed = await parse(
870
+ withBody([
871
+ "From: Alice <alice@acme.example>",
872
+ "Authentication-Results: mx.example; dmarc=pass (unterminated",
873
+ ]),
874
+ );
875
+ assert.equal(extractAuthResult(parsed), null);
876
+ });
877
+
878
+ it("ignores an unparseable header beside one that parses", async () => {
879
+ const parsed = await parse(
880
+ withBody([
881
+ "Authentication-Results: forged; dmarc=pass )",
882
+ "From: Alice <alice@acme.example>",
883
+ "Authentication-Results: mx.example.com; dmarc=fail header.from=acme.example",
884
+ ]),
885
+ );
886
+ assert.equal(extractAuthResult(parsed)?.dmarc, "Fail");
887
+ });
888
+ });
889
+ });
@@ -6,6 +6,11 @@ import type {
6
6
  ParsedMail,
7
7
  StructuredHeader,
8
8
  } from "mailparser";
9
+ import {
10
+ type AuthenticationResult,
11
+ type AuthenticationResults,
12
+ parseAuthenticationResults,
13
+ } from "./authenticationResults.js";
9
14
  import { hasMachineHeader, isMachineLocalPart } from "./machineSenders.js";
10
15
  import { SOCIAL_DOMAINS } from "./socialDomains.js";
11
16
  import { TRANSACTIONAL_DOMAINS } from "./transactionalDomains.js";
@@ -139,41 +144,104 @@ export const extractAuthenticity = (
139
144
  };
140
145
  };
141
146
 
142
- const extractVerdict = (
143
- text: string,
144
- mechanism: string,
147
+ const RESULTS_BY_FAVOURABILITY = [
148
+ "fail",
149
+ "softfail",
150
+ "neutral",
151
+ "none",
152
+ "unrecognised",
153
+ "pass",
154
+ ] as const;
155
+
156
+ type RankedResult = (typeof RESULTS_BY_FAVOURABILITY)[number];
157
+
158
+ const VERDICT_BY_RESULT: ReadonlyMap<RankedResult, AuthVerdictValue> = new Map([
159
+ ["fail", AuthResultVerdict.Fail],
160
+ ["softfail", AuthResultVerdict.Softfail],
161
+ ["neutral", AuthResultVerdict.Neutral],
162
+ ["none", AuthResultVerdict.None],
163
+ ["pass", AuthResultVerdict.Pass],
164
+ ]);
165
+
166
+ const isRankedResult = (result: string): result is RankedResult =>
167
+ (RESULTS_BY_FAVOURABILITY as readonly string[]).includes(result);
168
+
169
+ const rankOf = (result: string): number =>
170
+ RESULTS_BY_FAVOURABILITY.indexOf(
171
+ isRankedResult(result) ? result : "unrecognised",
172
+ );
173
+
174
+ const leastFavourableVerdict = (
175
+ results: AuthenticationResult[],
145
176
  ): AuthVerdictValue | undefined => {
146
- const match = text.match(new RegExp(`${mechanism}=(\\w+)`, "i"));
147
- if (!match) return undefined;
148
- const raw = match[1].toLowerCase();
149
- const map: Record<string, AuthVerdictValue> = {
150
- pass: AuthResultVerdict.Pass,
151
- fail: AuthResultVerdict.Fail,
152
- none: AuthResultVerdict.None,
153
- neutral: AuthResultVerdict.Neutral,
154
- softfail: AuthResultVerdict.Softfail,
155
- };
156
- return map[raw];
177
+ if (results.length === 0) return undefined;
178
+ const worst = Math.min(...results.map((r) => rankOf(r.result)));
179
+ return VERDICT_BY_RESULT.get(RESULTS_BY_FAVOURABILITY[worst]);
180
+ };
181
+
182
+ const normaliseDomain = (value: string | undefined): string | null => {
183
+ if (value === undefined) return null;
184
+ const domain = value.trim().toLowerCase().replace(/\.$/, "");
185
+ return domain.length > 0 ? domain : null;
186
+ };
187
+
188
+ const identityDomain = (value: string | undefined): string | null => {
189
+ if (value === undefined) return null;
190
+ const at = value.lastIndexOf("@");
191
+ if (at < 0) return null;
192
+ return normaliseDomain(value.slice(at + 1));
193
+ };
194
+
195
+ const dkimSigningDomain = (result: AuthenticationResult): string | null => {
196
+ const signing = normaliseDomain(result.properties.get("header.d"));
197
+ const hasIdentity = result.properties.has("header.i");
198
+ const identity = identityDomain(result.properties.get("header.i"));
199
+ if (hasIdentity && identity === null) return null;
200
+ if (signing === null) return identity;
201
+ if (identity === null) return signing;
202
+ const identityWithinSigning =
203
+ identity === signing || identity.endsWith(`.${signing}`);
204
+ return identityWithinSigning ? signing : null;
205
+ };
206
+
207
+ const dkimResultsForFrom = (
208
+ results: AuthenticationResult[],
209
+ fromDomain: string | null,
210
+ ): AuthenticationResult[] => {
211
+ if (!fromDomain) return results;
212
+ const aligned = results.filter((r) => {
213
+ const domain = dkimSigningDomain(r);
214
+ return domain !== null && domainsAligned(domain, fromDomain);
215
+ });
216
+ return aligned.length > 0 ? aligned : results;
157
217
  };
158
218
 
159
- /**
160
- * Extract provider authentication-results verdict from the Authentication-Results header.
161
- * Returns null when the header is absent.
162
- */
163
219
  export const extractAuthResult = (
164
220
  parsed: ParsedMail,
165
221
  ): MessageAuthResult | null => {
166
- const line = parsed.headerLines.find(
167
- (l) => l.key.toLowerCase() === "authentication-results",
168
- );
169
- if (!line) return null;
222
+ const headers = parsed.headerLines
223
+ .filter((l) => l.key.toLowerCase() === "authentication-results")
224
+ .map((l) => parseAuthenticationResults(stripHeaderName(l.line)))
225
+ .filter((h): h is AuthenticationResults => h !== null);
226
+ if (headers.length === 0) return null;
170
227
 
171
- const text = stripHeaderName(line.line);
172
- const dmarc = extractVerdict(text, "dmarc");
173
- const spf = extractVerdict(text, "spf");
174
- const dkim = extractVerdict(text, "dkim");
228
+ const fromDomain = getFromDomain(parsed);
229
+ const byMethod = (
230
+ results: AuthenticationResult[],
231
+ method: string,
232
+ ): AuthenticationResult[] => results.filter((r) => r.method === method);
233
+ const acrossHeaders = (method: string): AuthenticationResult[] =>
234
+ headers.flatMap((h) => byMethod(h.results, method));
175
235
 
176
- return { dmarc, spf, dkim };
236
+ return {
237
+ dmarc: leastFavourableVerdict(acrossHeaders("dmarc")),
238
+ spf: leastFavourableVerdict(acrossHeaders("spf")),
239
+ dkim: leastFavourableVerdict(
240
+ headers.flatMap((h) =>
241
+ dkimResultsForFrom(byMethod(h.results, "dkim"), fromDomain),
242
+ ),
243
+ ),
244
+ };
177
245
  };
178
246
 
179
247
  /**
package/src/index.ts CHANGED
@@ -28,7 +28,7 @@ export {
28
28
  type BodySyncLogger,
29
29
  BodySyncService,
30
30
  type ConnectionGetter,
31
- extractPrimaryFromEmail,
31
+ extractSnippet,
32
32
  type FetchBodyResult,
33
33
  type PlacementConfig,
34
34
  type QuarantineConfig,
@@ -48,6 +48,21 @@ export {
48
48
  type ResolveExhaustedBodySyncResult,
49
49
  resolveExhaustedBodySyncFailures,
50
50
  } from "./body-sync-terminal.js";
51
+ export {
52
+ backfillClassifications,
53
+ type ClassificationBackfillCheckpoint,
54
+ type ClassificationBackfillCheckpointStore,
55
+ type ClassificationBackfillDeps,
56
+ type ClassificationBackfillLogger,
57
+ type ClassificationBackfillOptions,
58
+ type ClassificationBackfillProgress,
59
+ type ClassificationBackfillResult,
60
+ type ClassificationBackfillTotals,
61
+ } from "./classification-backfill.js";
62
+ export {
63
+ classifyParsedMessage,
64
+ extractPrimaryFromEmail,
65
+ } from "./classify-message.js";
51
66
  // Connection factory
52
67
  export {
53
68
  createConnection,
@@ -3,9 +3,27 @@ import type {
3
3
  ThreadMessageItem,
4
4
  } from "@remit/data-ports";
5
5
  import { NotFoundError } from "@remit/data-ports/errors";
6
+ import { MessageCategory } from "@remit/domain-enums";
6
7
 
7
8
  export type MessageCategoryValue = ThreadMessageItem["category"];
8
9
 
10
+ /**
11
+ * RFC 034 Decision 3.1: `Message.category` is written once and never mutated
12
+ * after — RFC 030's message-list GSI sort key depends on it never churning.
13
+ * "Already decided" is any real category, so a message that carries one is
14
+ * never re-categorized by a re-entrant pass.
15
+ *
16
+ * `uncategorized` fails this test whether or not the classifier has run, which
17
+ * is deliberate: this asks what the row holds, not what was done to it. Whether
18
+ * the classifier has run is {@link Message.classificationState}, and it is the
19
+ * skip guard in `BodySyncService.syncBodies` — not this one — that keeps a
20
+ * declined message from being examined twice.
21
+ */
22
+ export const hasDecidedCategory = (
23
+ category: MessageCategoryValue | undefined,
24
+ ): boolean =>
25
+ category !== undefined && category !== MessageCategory.uncategorized;
26
+
9
27
  export interface MessageCategoryDenormalizeDeps {
10
28
  threadMessageService: Pick<
11
29
  IThreadMessageRepository,