fix(mail-ingest): enhance header processing to prioritize X-Forwarded-To for IMAP

This commit is contained in:
Luffy
2026-12-04 12:33:17 +08:00
committed by Maurice
parent a4bd40cb0a
commit b15cd49833
5 changed files with 79 additions and 11 deletions
+2
View File
@@ -45,6 +45,7 @@ interface MailEnvelope {
messageId: string | null;
deliveredTo: string | null;
xOriginalTo: string | null;
xForwardedTo: string | null;
listUnsubscribe: string | null;
precedence: string | null;
autoSubmitted: string | null;
@@ -85,6 +86,7 @@ const ENVELOPE_HEADERS: [keyof MailEnvelope, string][] = [
['messageId', 'message-id'],
['deliveredTo', 'delivered-to'],
['xOriginalTo', 'x-original-to'],
['xForwardedTo', 'x-forwarded-to'],
['listUnsubscribe', 'list-unsubscribe'],
['precedence', 'precedence'],
['autoSubmitted', 'auto-submitted'],
@@ -7,6 +7,7 @@ import { dbNow } from '../../db/types';
import { UnitOfWork } from '../database/unit-of-work';
import { MailReadService } from '../llm-parse/mail-read.service';
import type { WalkedMail } from '../llm-parse/mail-read.types';
import { addressOf } from './mail-classify';
import { MailIngestAddressService } from './mail-ingest-address.service';
import { MailIngestSettingsService } from './mail-ingest-settings.service';
import { MAIL_INGEST_LIMITS } from './mail-ingest.constants';
@@ -82,7 +83,7 @@ export class MailIngestIntakeService {
const addresses =
envelopeRecipients.length > 0
? await this.addresses.resolveAll(envelopeRecipients)
: await this.headerAddresses(mail.envelope);
: await this.headerAddresses(mail.envelope, transport === 'imap');
if (addresses.length === 0) return { status: 'refused', reason: 'unknown_address' };
const results = await addresses.reduce<Promise<MailIntakeResult[]>>(async (previous, address) => {
const done = await previous;
@@ -111,10 +112,21 @@ export class MailIngestIntakeService {
* writes, then To. The first that names one decides. A delivery header
* without a token names none: Stalwart writes the box itself there, its
* sub-address dropped, and the token then stands only in To.
*
* Gmail automatic forwarding can put a bare address such as
* trek+{token}@example.com in X-Forwarded-To. IMAP tries the topmost value
* of that header when none of the headers above names a live address.
*/
private async headerAddresses(envelope: WalkedMail['envelope']): Promise<MailIngestAddressRow[]> {
private async headerAddresses(
envelope: WalkedMail['envelope'],
useForwardedTo: boolean,
): Promise<MailIngestAddressRow[]> {
const named = await Promise.all(headerRecipients(envelope).map((list) => this.addresses.resolveAll(list)));
return named.find((addresses) => addresses.length > 0) ?? [];
const matched = named.find((addresses) => addresses.length > 0);
if (matched) return matched;
const forwardedTo = useForwardedTo ? addressOf(envelope.xForwardedTo) : null;
return forwardedTo && /^[^\s@]+@[^\s@]+$/.test(forwardedTo) ? this.addresses.resolveAll([forwardedTo]) : [];
}
private async precheck(raw: Buffer): Promise<MailIntakeRefusal | null> {
@@ -72,6 +72,7 @@ describe('walkMail: the envelope and the body', () => {
'Authentication-Results: relay.example; dkim=fail',
'Delivered-To: in+token@trek.example',
'X-Original-To: in+token@trek.example',
'x-forwarded-to: Forwarded Recipient <in+token@trek.example>',
'From: =?utf-8?B?QW5hIE3DvGxsZXI=?= <ana@example.org>',
'To: in+token@trek.example',
'Cc: ben@example.org',
@@ -96,6 +97,7 @@ describe('walkMail: the envelope and the body', () => {
messageId: '<abc@example.org>',
deliveredTo: 'in+token@trek.example',
xOriginalTo: 'in+token@trek.example',
xForwardedTo: 'Forwarded Recipient <in+token@trek.example>',
listUnsubscribe: '<https://airline.example/unsubscribe>',
precedence: 'bulk',
autoSubmitted: 'auto-generated',
@@ -112,6 +114,7 @@ describe('walkMail: the envelope and the body', () => {
const walked = walk(mail('From: a@example.org', 'Content-Type: text/plain', '', 'Hotel', ''));
expect(walked.subject).toBeNull();
expect(walked.envelope.to).toBeNull();
expect(walked.envelope.xForwardedTo).toBeNull();
expect(walked.envelope.authenticationResults).toBeNull();
});
});
@@ -52,8 +52,8 @@ afterAll(async () => {
});
const tokenIn = (address: string) => /^trek\+([a-z2-7]+)@/.exec(address)?.[1] ?? '';
function mailTo(address: string, id: string): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`];
function mailTo(address: string, id: string, headers: readonly string[] = []): Buffer {
const lines = ['From: mia@example.com', `To: ${address}`, 'Subject: Booking', `Message-ID: <${id}@x>`, ...headers];
return Buffer.from(`${lines.join('\r\n')}\r\n\r\nBooking ABC123`);
}
@@ -151,17 +151,17 @@ describe('a mail to several addresses', () => {
expect(await findRow(orm(), MailIngestMessages, { user: noah.id })).toBeNull();
});
it('reads on to To when the delivery header names the box without its token, as Stalwart writes it', async () => {
it('reads on to To without a delivery token and gives To priority over X-Forwarded-To', async () => {
const { user: mia } = await makeUser(orm());
const { user: noah } = await makeUser(orm());
const miaOwn = (await addresses().renewOwn(mia.id))?.address ?? '';
const noahOwn = (await addresses().renewOwn(noah.id))?.address ?? '';
const box = miaOwn.replace(/\+[^@]+@/, '@');
const headers = [`Delivered-To: ${box}`, `To: <${miaOwn}>`, 'From: x@example.com'];
const raw = Buffer.from(
`${headers.join('\r\n')}\r\nSubject: WG: Booking\r\nMessage-ID: <fwd@x>\r\n\r\nBooking ABC123`,
);
const raw = mailTo(`<${miaOwn}>`, 'fwd', [`Delivered-To: ${box}`, `X-Forwarded-To: ${noahOwn}`]);
expect(await t.get(MailIngestIntakeService).receive(raw, 'imap')).toEqual({ status: 'accepted' });
expect(await findRow(orm(), MailIngestMessages, { user: mia.id })).not.toBeNull();
expect(await findRow(orm(), MailIngestMessages, { user: noah.id })).toBeNull();
const nobody = Buffer.from(`Delivered-To: ${box}\r\nTo: ${box}\r\nSubject: Hi\r\nMessage-ID: <none@x>\r\n\r\nHi`);
expect(await t.get(MailIngestIntakeService).receive(nobody, 'imap')).toEqual({
@@ -169,6 +169,57 @@ describe('a mail to several addresses', () => {
reason: 'unknown_address',
});
});
it('routes IMAP mail to the trip in the topmost X-Forwarded-To when earlier headers do not match', async () => {
const { user: owner } = await makeUser(orm());
const { user: other } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id);
const tripAddress = await addresses().renewTripAddress(owner.id, trip.id);
const otherAddress = await addresses().renewOwn(other.id);
const box = 'trek@mail.example.com';
const raw = mailTo(box, 'forwarded-trip', [
`Delivered-To: ${box}`,
`X-Original-To: ${box}`,
`X-Forwarded-To: Trip <${tripAddress?.address}>`,
`X-Forwarded-To: ${otherAddress?.address}`,
]);
expect(await t.get(MailIngestIntakeService).receive(raw, 'imap')).toEqual({ status: 'accepted' });
expect(await findRow(orm(), MailIngestMessages, { user: owner.id, trip: trip.id })).not.toBeNull();
expect(await findRow(orm(), MailIngestMessages, { user: other.id })).toBeNull();
});
it('refuses empty, malformed and retired X-Forwarded-To values', async () => {
const { user } = await makeUser(orm());
const retired = await addresses().renewOwn(user.id);
const active = await addresses().renewOwn(user.id);
const box = 'trek@mail.example.com';
const intake = t.get(MailIngestIntakeService);
const samples = [
mailTo(box, 'empty', ['X-Forwarded-To:', `X-Forwarded-To: ${active?.address}`]),
mailTo(box, 'malformed', [`X-Forwarded-To: <${active?.address.split('@')[0]}>`]),
mailTo(box, 'retired', [`X-Forwarded-To: ${retired?.address}`]),
];
const results = await Promise.all(samples.map((raw) => intake.receive(raw, 'imap')));
const refused = { status: 'refused', reason: 'unknown_address' };
expect(results).toEqual([refused, refused, refused]);
expect(await countRows(orm(), MailIngestMessages, {})).toBe(0);
});
it('uses X-Forwarded-To only for IMAP without an envelope recipient', async () => {
const { user } = await makeUser(orm());
const own = await addresses().renewOwn(user.id);
const box = 'trek@mail.example.com';
const raw = mailTo(box, 'forwarded-imap-only', [`X-Forwarded-To: ${own?.address}`]);
const intake = t.get(MailIngestIntakeService);
const refused = { status: 'refused', reason: 'unknown_address' };
expect(await intake.receive(raw, 'webhook')).toEqual(refused);
expect(await intake.receive(raw, 'cloud')).toEqual(refused);
expect(await intake.receive(raw, 'imap', [box])).toEqual(refused);
expect(await countRows(orm(), MailIngestMessages, {})).toBe(0);
});
});
describe('a trip address', () => {
+1 -1
View File
@@ -67,7 +67,7 @@ Each person's token is 24 random characters.
TREK reads one mailbox every two minutes. Point a catch-all, or a mailbox with sub-addressing (`trek+anything@`), at it and use the matching address template. Read mails move to the folder `TREK/processed` and are never deleted, so anyone with access to the mailbox can read them. A mail TREK cannot take for now, because its address took its 50 mails of the day or its person has 200 bookings waiting, moves to `TREK/deferred` and is offered again on every run for three days; after that it moves to `TREK/processed` as well.
TREK files a mail under the address in the topmost `Delivered-To` header, else the topmost `X-Original-To`, which the receiving server adds, else `To`. A header that names the mailbox without its `+` part (Stalwart writes `Delivered-To` that way) names no address, so TREK reads on to the next. A mail addressed to several people's addresses reaches each of them.
TREK checks the topmost `Delivered-To`, then the topmost `X-Original-To`, then `To`, and finally the topmost `X-Forwarded-To`. It uses the first header that names an active TREK address. If `Delivered-To` names the mailbox without its `+` part (as it does on Stalwart), TREK checks the next header. A `To` header that names several active TREK addresses reaches each of them.
| Field | Default |
|---|---|