@ultimat3/mail 31.24.0 → 31.26.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.
- package/CLAUDE.md +13 -1
- package/README.md +57 -0
- package/package.json +9 -7
- package/src/errors.ts +7 -0
- package/src/inbound-attachments.ts +109 -0
- package/src/inbound-mail.ts +95 -0
- package/src/inbound-message.ts +82 -0
- package/src/inbound-resend.ts +140 -0
- package/src/inbound-ses.ts +138 -0
- package/src/inbound-types.ts +152 -0
- package/src/inbound.ts +29 -0
- package/src/mime-parse-address.ts +144 -0
- package/src/mime-parse-decode.ts +113 -0
- package/src/mime-parse-errors.ts +72 -0
- package/src/mime-parse-headers.ts +202 -0
- package/src/mime-parse.ts +169 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Single responsibility: SES receiving, as an `inboundMail()` provider. A receipt rule's SNS action
|
|
2
|
+
// posts the WHOLE message (`content`, raw MIME, UTF8 or BASE64) inside an SNS envelope: the SNS
|
|
3
|
+
// signature is proven first (`sns-signature.ts`, the delivery receiver's verifier), then the
|
|
4
|
+
// `Received` notification is read. Any other SNS type (a subscription) is the delivery receiver's.
|
|
5
|
+
|
|
6
|
+
import { type Clock, ConfigInvalidError, finiteCount } from '@ultimat3/core';
|
|
7
|
+
import { t, validate } from '@ultimat3/schema';
|
|
8
|
+
import { parseDeliveryJson } from './delivery-event';
|
|
9
|
+
import { deliveryEventInvalid } from './delivery-event-errors';
|
|
10
|
+
import type { MailFetch } from './driver-resend';
|
|
11
|
+
import type { InboundDoor, InboundProvider, InboundRow, WebhookInbound } from './inbound-types';
|
|
12
|
+
import { bytesOf } from './mime-parse-decode';
|
|
13
|
+
import { inboundMalformed, inboundTooLarge } from './mime-parse-errors';
|
|
14
|
+
import { DEFAULT_SNS_TOLERANCE_MS, sesEventReceiver } from './ses-event-receiver';
|
|
15
|
+
import type { SnsCertificateFetch } from './sns-certificate-cache';
|
|
16
|
+
import { snsTopicRegion } from './sns-signature';
|
|
17
|
+
|
|
18
|
+
export interface SesInboundOptions {
|
|
19
|
+
/** The topic ARNs the receipt rule's SNS action publishes to. Required: SNS signs for anyone. */
|
|
20
|
+
readonly topicArns: readonly string[];
|
|
21
|
+
/** GET a verified SubscriptionConfirmation's SubscribeURL. Off: the subscription stays pending. */
|
|
22
|
+
readonly confirmSubscriptions?: boolean | undefined;
|
|
23
|
+
/** Default `DEFAULT_SNS_TOLERANCE_MS`. */
|
|
24
|
+
readonly toleranceMs?: number | undefined;
|
|
25
|
+
readonly clock?: Clock | undefined;
|
|
26
|
+
readonly fetchCertificate?: SnsCertificateFetch | undefined;
|
|
27
|
+
readonly fetch?: MailFetch | undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const verdict = t.object({ status: t.string }).optional();
|
|
31
|
+
const received = t.object({
|
|
32
|
+
notificationType: t.literal('Received'),
|
|
33
|
+
mail: t.object({ messageId: t.string }),
|
|
34
|
+
receipt: t.object({
|
|
35
|
+
recipients: t.array(t.string),
|
|
36
|
+
spamVerdict: verdict,
|
|
37
|
+
virusVerdict: verdict,
|
|
38
|
+
spfVerdict: verdict,
|
|
39
|
+
dkimVerdict: verdict,
|
|
40
|
+
dmarcVerdict: verdict,
|
|
41
|
+
action: t.object({ encoding: t.enum(['UTF8', 'BASE64']).optional() }),
|
|
42
|
+
}),
|
|
43
|
+
content: t.string.optional(),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** The verified envelope, read again for the one field the delivery receiver does not hand back. */
|
|
47
|
+
const notification = t.object({ Type: t.literal('Notification'), Message: t.string });
|
|
48
|
+
|
|
49
|
+
const VERDICTS = ['spam', 'virus', 'spf', 'dkim', 'dmarc'] as const;
|
|
50
|
+
|
|
51
|
+
/** A verified SNS `Message` → the queue row, or a refusal that names the problem. */
|
|
52
|
+
export function sesInboundRow(message: string): {
|
|
53
|
+
readonly eventId: string;
|
|
54
|
+
readonly row: InboundRow;
|
|
55
|
+
} {
|
|
56
|
+
const parsed = validate(received, parseDeliveryJson('ses', message));
|
|
57
|
+
if (parsed.issues !== undefined) throw deliveryEventInvalid('ses', 'notification');
|
|
58
|
+
const { mail, receipt, content } = parsed.value;
|
|
59
|
+
if (content === undefined) throw inboundMalformed('content-missing');
|
|
60
|
+
const verdicts: Record<string, string> = {};
|
|
61
|
+
for (const name of VERDICTS) {
|
|
62
|
+
const status = receipt[`${name}Verdict`]?.status;
|
|
63
|
+
if (status !== undefined) verdicts[name] = status;
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
eventId: mail.messageId,
|
|
67
|
+
row: {
|
|
68
|
+
provider: 'ses',
|
|
69
|
+
recipients: receipt.recipients,
|
|
70
|
+
content,
|
|
71
|
+
encoding: receipt.action.encoding ?? 'UTF8',
|
|
72
|
+
verdicts,
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function rawOf(row: InboundRow, maxBytes: number): Uint8Array {
|
|
78
|
+
if (row.provider !== 'ses') throw inboundMalformed('row');
|
|
79
|
+
// Bounded on the encoded length first: base64 is 4/3 of the bytes, UTF-8 at least 1 per char.
|
|
80
|
+
if (row.content.length > Math.ceil((maxBytes * 4) / 3) + 4)
|
|
81
|
+
throw inboundTooLarge('maxBytes', maxBytes);
|
|
82
|
+
if (row.encoding === 'UTF8') return new TextEncoder().encode(row.content);
|
|
83
|
+
try {
|
|
84
|
+
return bytesOf(atob(row.content.replace(/\s/g, '')));
|
|
85
|
+
} catch {
|
|
86
|
+
throw inboundMalformed('base64');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function sesInbound(options: SesInboundOptions): InboundProvider {
|
|
91
|
+
const topicArns = new Set(options.topicArns);
|
|
92
|
+
if (topicArns.size === 0 || [...topicArns].some((arn) => snsTopicRegion(arn) === undefined)) {
|
|
93
|
+
throw new ConfigInvalidError({
|
|
94
|
+
cause: 'sesInbound needs at least one topic ARN, and every one must be an SNS topic ARN',
|
|
95
|
+
fix: "sesInbound({ topicArns: ['arn:aws:sns:us-east-1:123456789012:inbound-mail'] }) — the topic the receipt rule's SNS action publishes to (aws ses describe-active-receipt-rule-set)",
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const toleranceMs = finiteCount(
|
|
99
|
+
'sesInbound',
|
|
100
|
+
'toleranceMs',
|
|
101
|
+
options.toleranceMs ?? DEFAULT_SNS_TOLERANCE_MS,
|
|
102
|
+
1,
|
|
103
|
+
);
|
|
104
|
+
// ONE verifier: the delivery receiver proves the SNS signature over these exact bytes (and owns
|
|
105
|
+
// the SubscriptionConfirmation protocol); only then is the same body read for its `Message`.
|
|
106
|
+
const verifier = sesEventReceiver({
|
|
107
|
+
topicArns: [...topicArns],
|
|
108
|
+
confirmSubscriptions: options.confirmSubscriptions,
|
|
109
|
+
toleranceMs,
|
|
110
|
+
// The route already read the body under `inboundMail({ maxBodyBytes })`; one ceiling, not two.
|
|
111
|
+
maxBytes: Number.MAX_SAFE_INTEGER,
|
|
112
|
+
clock: options.clock,
|
|
113
|
+
fetchCertificate: options.fetchCertificate,
|
|
114
|
+
fetch: options.fetch,
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
name: 'ses',
|
|
119
|
+
async door(inbound: WebhookInbound): Promise<InboundDoor> {
|
|
120
|
+
const outcome = await verifier.receive(inbound.request());
|
|
121
|
+
if (outcome.type === 'subscription') {
|
|
122
|
+
return { answer: Response.json({ ok: true, confirmed: outcome.confirmed }) };
|
|
123
|
+
}
|
|
124
|
+
const envelope = validate(
|
|
125
|
+
notification,
|
|
126
|
+
parseDeliveryJson('ses', new TextDecoder().decode(inbound.bytes)),
|
|
127
|
+
);
|
|
128
|
+
if (envelope.issues !== undefined) {
|
|
129
|
+
// Verified and not a Notification: an UnsubscribeConfirmation. Nothing to queue.
|
|
130
|
+
return { answer: Response.json({ ok: true }) };
|
|
131
|
+
}
|
|
132
|
+
return sesInboundRow(envelope.value.Message);
|
|
133
|
+
},
|
|
134
|
+
async mime(row, maxBytes) {
|
|
135
|
+
return rawOf(row, maxBytes);
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// Single responsibility: the shapes `inboundMail()` speaks — the typed message a handler receives,
|
|
2
|
+
// its attachments as storage references, the provider port each inbound format implements, and
|
|
3
|
+
// the declaration. Apart from the factory so each file keeps one job.
|
|
4
|
+
|
|
5
|
+
import type { Ctx } from '@ultimat3/core';
|
|
6
|
+
import type { WebhookReceiverDefinition } from '@ultimat3/jobs';
|
|
7
|
+
import type { StorageDriver, UploadPolicy } from '@ultimat3/storage';
|
|
8
|
+
import type { MimeLimits } from './mime-parse';
|
|
9
|
+
import type { InboundAddress } from './mime-parse-address';
|
|
10
|
+
import type { HeaderField } from './mime-parse-headers';
|
|
11
|
+
|
|
12
|
+
/** What jobs' `verify` is handed, read off the definition (jobs exports no name for it). */
|
|
13
|
+
export type WebhookInbound = Parameters<WebhookReceiverDefinition['verify']>[0];
|
|
14
|
+
type HandleArgs = Parameters<WebhookReceiverDefinition['handle']>[0];
|
|
15
|
+
|
|
16
|
+
export type InboundProviderName = 'ses' | 'resend';
|
|
17
|
+
|
|
18
|
+
interface InboundAttachmentBase {
|
|
19
|
+
/** SENDER-CONTROLLED and unsanitised: never a path, never unescaped into HTML. */
|
|
20
|
+
readonly filename: string | undefined;
|
|
21
|
+
/** As the sender declared it. */
|
|
22
|
+
readonly declaredType: string;
|
|
23
|
+
readonly size: number;
|
|
24
|
+
/** SENDER-CONTROLLED and unsanitised (`cid:` references in `html`). */
|
|
25
|
+
readonly contentId: string | undefined;
|
|
26
|
+
readonly inline: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Stored: the bytes are at `key`, under the type the sniff agreed with. Not stored: `refusal` is
|
|
31
|
+
* storage's `X_STORAGE_*` code, `X_MAIL_INBOUND_MALFORMED` for a part whose transfer encoding did
|
|
32
|
+
* not decode, `'verdict'` for an SES virus FAIL, or `'disabled'` under `attachments: false` — the message still arrives: one bad file
|
|
33
|
+
* never loses the mail around it.
|
|
34
|
+
*/
|
|
35
|
+
export type InboundAttachment =
|
|
36
|
+
| (InboundAttachmentBase & {
|
|
37
|
+
readonly stored: true;
|
|
38
|
+
readonly key: string;
|
|
39
|
+
readonly contentType: string;
|
|
40
|
+
/** base64 SHA-256 of the stored bytes. */
|
|
41
|
+
readonly checksum: string;
|
|
42
|
+
})
|
|
43
|
+
| (InboundAttachmentBase & { readonly stored: false; readonly refusal: string });
|
|
44
|
+
|
|
45
|
+
export interface InboundMessage {
|
|
46
|
+
readonly provider: InboundProviderName;
|
|
47
|
+
/** The provider's id for this message, and the receiver's dedupe key. */
|
|
48
|
+
readonly eventId: string;
|
|
49
|
+
/**
|
|
50
|
+
* Who the provider says the message was delivered to, from its signed payload — never a header.
|
|
51
|
+
* SES: the receipt's recipients, the SMTP envelope, Bcc included. Resend: its `to`, which Resend
|
|
52
|
+
* does not document as the envelope: route only on addresses of your own receiving domain.
|
|
53
|
+
*/
|
|
54
|
+
readonly recipients: readonly string[];
|
|
55
|
+
readonly messageId: string | undefined;
|
|
56
|
+
readonly from: InboundAddress | undefined;
|
|
57
|
+
readonly to: readonly InboundAddress[];
|
|
58
|
+
readonly cc: readonly InboundAddress[];
|
|
59
|
+
readonly replyTo: readonly InboundAddress[];
|
|
60
|
+
readonly subject: string;
|
|
61
|
+
/** The `Date:` header as an instant, or `undefined` when absent or unreadable. */
|
|
62
|
+
readonly date: Date | undefined;
|
|
63
|
+
readonly text: string | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* SENDER-CONTROLLED and unsanitised — scripts, trackers, forms. Never render it on the app's own
|
|
66
|
+
* origin; show it in a sandboxed frame or reduce it to text.
|
|
67
|
+
*/
|
|
68
|
+
readonly html: string | undefined;
|
|
69
|
+
/** Every top-level header in order, decoded — `Received` repeats, so never a record. */
|
|
70
|
+
readonly headers: readonly HeaderField[];
|
|
71
|
+
readonly attachments: readonly InboundAttachment[];
|
|
72
|
+
/** The provider's spam/virus/SPF/DKIM/DMARC verdicts, as it spelled them, when it sent any. */
|
|
73
|
+
readonly verdicts: Readonly<Record<string, string>>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The queue row: what the door read out of the VERIFIED body. JSON, `.sensitive()` in the row. */
|
|
77
|
+
export type InboundRow =
|
|
78
|
+
| {
|
|
79
|
+
readonly provider: 'ses';
|
|
80
|
+
readonly recipients: readonly string[];
|
|
81
|
+
readonly content: string;
|
|
82
|
+
readonly encoding: 'BASE64' | 'UTF8';
|
|
83
|
+
readonly verdicts: { readonly [name: string]: string };
|
|
84
|
+
}
|
|
85
|
+
| {
|
|
86
|
+
readonly provider: 'resend';
|
|
87
|
+
readonly recipients: readonly string[];
|
|
88
|
+
readonly emailId: string;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** What a provider's door answers: a message to queue, or its own protocol's response. */
|
|
92
|
+
export type InboundDoor =
|
|
93
|
+
| { readonly eventId: string; readonly row: InboundRow }
|
|
94
|
+
| { readonly answer: Response };
|
|
95
|
+
|
|
96
|
+
/** One inbound format. Built by `sesInbound()` / `resendInbound()`, which refuse config at boot. */
|
|
97
|
+
export interface InboundProvider {
|
|
98
|
+
readonly name: InboundProviderName;
|
|
99
|
+
/** Signature FIRST, over the exact bytes; only then is anything parsed. */
|
|
100
|
+
door(inbound: WebhookInbound): Promise<InboundDoor>;
|
|
101
|
+
/** The raw RFC 5322 bytes: from the row (SES), or the provider's API (Resend). */
|
|
102
|
+
mime(row: InboundRow, maxBytes: number): Promise<Uint8Array>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface InboundAttachmentOptions {
|
|
106
|
+
/** Absent: the app's default disk, resolved per message. */
|
|
107
|
+
readonly disk?: (() => StorageDriver) | undefined;
|
|
108
|
+
/** Default `uploadPolicy({ maxBytes: 10 MiB, allowedContentTypes: INBOUND_ATTACHMENT_TYPES })`. */
|
|
109
|
+
readonly policy?: UploadPolicy | undefined;
|
|
110
|
+
/** Default `'inbound-mail'`; under `org/<orgId>/` when the receiver is tenanted. */
|
|
111
|
+
readonly prefix?: string | undefined;
|
|
112
|
+
/**
|
|
113
|
+
* Store a message's attachments even when the provider's virus verdict is `FAIL`. Default false:
|
|
114
|
+
* each arrives `stored: false`, refusal `'verdict'` — `handle` still sees the message and the
|
|
115
|
+
* verdict, and nothing infected reaches a disk a `/_storage` route can serve.
|
|
116
|
+
*/
|
|
117
|
+
readonly keepOnVirusFail?: boolean | undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface InboundHandleArgs {
|
|
121
|
+
readonly message: InboundMessage;
|
|
122
|
+
readonly orgId: string | undefined;
|
|
123
|
+
readonly ctx: Ctx;
|
|
124
|
+
readonly step: HandleArgs['step'];
|
|
125
|
+
readonly attempt: number;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface InboundMailDefinition {
|
|
129
|
+
/** The job's durable name. */
|
|
130
|
+
readonly name: string;
|
|
131
|
+
/** Absolute, outside `/api` and `/_x` — jobs' `webhookReceiver()` rule. */
|
|
132
|
+
readonly path: string;
|
|
133
|
+
/**
|
|
134
|
+
* A thunk, built on the first delivery and kept: a provider's credentials are environment only
|
|
135
|
+
* the receiving role holds, and every role imports this declaration. A throw (`X_CONFIG_INVALID`
|
|
136
|
+
* for an unset secret) answers that delivery and is asked again on the next one.
|
|
137
|
+
*/
|
|
138
|
+
readonly provider: () => InboundProvider;
|
|
139
|
+
/** The webhook body's ceiling, enforced while it streams. Default 1 MiB (SNS caps at 256 KiB). */
|
|
140
|
+
readonly maxBodyBytes?: number | undefined;
|
|
141
|
+
/** `'none'`, or the org a message belongs to, from `InboundMessage.recipients`' rule. */
|
|
142
|
+
readonly tenant: 'none' | ((recipients: readonly string[]) => string | undefined);
|
|
143
|
+
/** At least once per message: key your own writes on `message.eventId`. */
|
|
144
|
+
handle(args: InboundHandleArgs): Promise<unknown>;
|
|
145
|
+
/** Defaults to `DEFAULT_MIME_LIMITS`. */
|
|
146
|
+
readonly limits?: Partial<MimeLimits> | undefined;
|
|
147
|
+
/** `false` stores nothing: every attachment arrives `stored: false`, refusal `'disabled'`. */
|
|
148
|
+
readonly attachments?: InboundAttachmentOptions | false | undefined;
|
|
149
|
+
readonly retry?: WebhookReceiverDefinition['retry'];
|
|
150
|
+
readonly queue?: string | undefined;
|
|
151
|
+
readonly rateLimit?: WebhookReceiverDefinition['rateLimit'];
|
|
152
|
+
}
|
package/src/inbound.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Single responsibility: the public API of `@ultimat3/mail/inbound` — received email. A subpath
|
|
2
|
+
// and not the barrel for the reason `events.ts` is one: only an app's receiving route needs SNS or
|
|
3
|
+
// Svix verification and a MIME parser, and every serving role loads the barrel to send.
|
|
4
|
+
|
|
5
|
+
export {
|
|
6
|
+
DEFAULT_INBOUND_PREFIX,
|
|
7
|
+
INBOUND_ATTACHMENT_TYPES,
|
|
8
|
+
} from './inbound-attachments';
|
|
9
|
+
export { DEFAULT_INBOUND_BODY_BYTES, inboundMail } from './inbound-mail';
|
|
10
|
+
export type { ResendInboundOptions } from './inbound-resend';
|
|
11
|
+
export { resendInbound } from './inbound-resend';
|
|
12
|
+
export type { SesInboundOptions } from './inbound-ses';
|
|
13
|
+
export { sesInbound } from './inbound-ses';
|
|
14
|
+
export type {
|
|
15
|
+
InboundAttachment,
|
|
16
|
+
InboundAttachmentOptions,
|
|
17
|
+
InboundDoor,
|
|
18
|
+
InboundHandleArgs,
|
|
19
|
+
InboundMailDefinition,
|
|
20
|
+
InboundMessage,
|
|
21
|
+
InboundProvider,
|
|
22
|
+
InboundProviderName,
|
|
23
|
+
InboundRow,
|
|
24
|
+
} from './inbound-types';
|
|
25
|
+
export type { MimeAttachment, MimeLimits, ParsedMime } from './mime-parse';
|
|
26
|
+
export { DEFAULT_MIME_LIMITS, parseMime } from './mime-parse';
|
|
27
|
+
export type { InboundAddress } from './mime-parse-address';
|
|
28
|
+
export type { InboundLimit, InboundMalformation } from './mime-parse-errors';
|
|
29
|
+
export type { HeaderField } from './mime-parse-headers';
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Single responsibility: an RFC 5322 address-list header (`From`, `To`, `Cc`, `Reply-To`) →
|
|
2
|
+
// `{ address, name }` entries. Commas inside quotes, angle brackets and comments do not split;
|
|
3
|
+
// a group (`team: a@x.test, b@x.test;`) yields its members. Lenient: nothing here refuses.
|
|
4
|
+
// Parse the RAW header: RFC 2047 words are decoded in the phrase only, after the split (§5(3)).
|
|
5
|
+
|
|
6
|
+
import { decodeWords, encodedWordAt } from './mime-parse-headers';
|
|
7
|
+
|
|
8
|
+
export interface InboundAddress {
|
|
9
|
+
/** The addr-spec, as written — never lower-cased: a local part is case-sensitive. */
|
|
10
|
+
readonly address: string;
|
|
11
|
+
/** The display phrase, RFC 2047 decoded, or `undefined`. */
|
|
12
|
+
readonly name: string | undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Top-level commas only; `;` closes a group and splits too. */
|
|
16
|
+
function entries(value: string): string[] {
|
|
17
|
+
const out: string[] = [];
|
|
18
|
+
let current = '';
|
|
19
|
+
let quoted = false;
|
|
20
|
+
let angle = 0;
|
|
21
|
+
let comment = 0;
|
|
22
|
+
for (let at = 0; at < value.length; at += 1) {
|
|
23
|
+
const char = value.charAt(at);
|
|
24
|
+
const word = encodedWordAt(value, at);
|
|
25
|
+
if (word !== undefined) {
|
|
26
|
+
current += word;
|
|
27
|
+
at += word.length - 1;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (char === '\\') {
|
|
31
|
+
current += char + value.charAt(at + 1);
|
|
32
|
+
at += 1;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (char === '"' && comment === 0) quoted = !quoted;
|
|
36
|
+
else if (!quoted && char === '(') comment += 1;
|
|
37
|
+
else if (!quoted && char === ')' && comment > 0) comment -= 1;
|
|
38
|
+
else if (!quoted && comment === 0 && char === '<') angle += 1;
|
|
39
|
+
else if (!quoted && comment === 0 && char === '>' && angle > 0) angle -= 1;
|
|
40
|
+
else if (!quoted && comment === 0 && angle === 0 && (char === ',' || char === ';')) {
|
|
41
|
+
out.push(current);
|
|
42
|
+
current = '';
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
current += char;
|
|
46
|
+
}
|
|
47
|
+
out.push(current);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Comments (nested, `\` escapes) replaced by a space, in one pass. No regex in this file may
|
|
53
|
+
* retry from every position of a sender's header: `(?:[^()\\]|\\.)*` over `(\(\(…` was quadratic.
|
|
54
|
+
*/
|
|
55
|
+
function stripComments(text: string): string {
|
|
56
|
+
let out = '';
|
|
57
|
+
let depth = 0;
|
|
58
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
59
|
+
const char = text.charAt(at);
|
|
60
|
+
if (char === '\\' && depth > 0) at += 1;
|
|
61
|
+
else if (char === '(') depth += 1;
|
|
62
|
+
else if (char === ')' && depth > 0) {
|
|
63
|
+
depth -= 1;
|
|
64
|
+
if (depth === 0) out += ' ';
|
|
65
|
+
} else if (depth === 0) out += char;
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The first top-level comment's text, or `undefined`. */
|
|
71
|
+
function firstComment(text: string): string | undefined {
|
|
72
|
+
const open = text.indexOf('(');
|
|
73
|
+
if (open < 0) return undefined;
|
|
74
|
+
const close = text.indexOf(')', open);
|
|
75
|
+
return close < 0 ? undefined : text.slice(open + 1, close);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const unquote = (text: string): string => {
|
|
79
|
+
const inner =
|
|
80
|
+
text.length >= 2 && text.startsWith('"') && text.endsWith('"') ? text.slice(1, -1) : text;
|
|
81
|
+
return inner.replace(/\\(.)/g, '$1').trim();
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Where a group's display name ends: the first colon outside quotes and encoded words, before
|
|
86
|
+
* any `<` or `@` — or -1. A scan, never `(?:"[^"]*"|=\?…\?=|[^"<@:])*:`, whose overlapping
|
|
87
|
+
* alternatives backtrack exponentially on a long value with no colon.
|
|
88
|
+
*/
|
|
89
|
+
function groupColon(text: string): number {
|
|
90
|
+
let quoted = false;
|
|
91
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
92
|
+
const char = text.charAt(at);
|
|
93
|
+
if (char === '"') quoted = !quoted;
|
|
94
|
+
if (quoted) continue;
|
|
95
|
+
const word = encodedWordAt(text, at);
|
|
96
|
+
if (word !== undefined) at += word.length - 1;
|
|
97
|
+
else if (char === ':') return at;
|
|
98
|
+
else if (char === '<' || char === '@') return -1;
|
|
99
|
+
}
|
|
100
|
+
return -1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** `phrase <addr-spec> (comment)?` by index, never by backtracking regex. */
|
|
104
|
+
function angleForm(
|
|
105
|
+
text: string,
|
|
106
|
+
): { readonly phrase: string; readonly address: string } | undefined {
|
|
107
|
+
const close = text.lastIndexOf('>');
|
|
108
|
+
if (close < 0) return undefined;
|
|
109
|
+
const open = text.lastIndexOf('<', close);
|
|
110
|
+
if (open < 0) return undefined;
|
|
111
|
+
const address = text.slice(open + 1, close);
|
|
112
|
+
if (address.includes('>')) return undefined;
|
|
113
|
+
const tail = text.slice(close + 1).trim();
|
|
114
|
+
if (tail !== '' && !(tail.startsWith('(') && tail.endsWith(')'))) return undefined;
|
|
115
|
+
return { phrase: text.slice(0, open), address: address.trim() };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function one(entry: string): InboundAddress | undefined {
|
|
119
|
+
let text = entry.trim();
|
|
120
|
+
const colon = groupColon(text);
|
|
121
|
+
if (colon >= 0) text = text.slice(colon + 1).trim();
|
|
122
|
+
if (text === '') return undefined;
|
|
123
|
+
const angle = angleForm(text);
|
|
124
|
+
if (angle !== undefined) {
|
|
125
|
+
const phrase = decodeWords(unquote(stripComments(angle.phrase).trim())).trim();
|
|
126
|
+
return angle.address === ''
|
|
127
|
+
? undefined
|
|
128
|
+
: { address: angle.address, name: phrase === '' ? undefined : phrase };
|
|
129
|
+
}
|
|
130
|
+
// A bare addr-spec, perhaps with a trailing comment as its name (`jane@x.test (Jane)`).
|
|
131
|
+
const quoted = firstComment(text);
|
|
132
|
+
const comment = quoted === undefined ? undefined : decodeWords(quoted).trim();
|
|
133
|
+
const address = stripComments(text).trim();
|
|
134
|
+
if (address === '') return undefined;
|
|
135
|
+
return { address, name: comment === undefined || comment === '' ? undefined : comment };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function parseAddressList(value: string | undefined): readonly InboundAddress[] {
|
|
139
|
+
if (value === undefined) return [];
|
|
140
|
+
return entries(value).flatMap((entry) => {
|
|
141
|
+
const parsed = one(entry);
|
|
142
|
+
return parsed === undefined ? [] : [parsed];
|
|
143
|
+
});
|
|
144
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Single responsibility: the byte-level decodes an inbound part needs — a lossless binary string
|
|
2
|
+
// both ways, Content-Transfer-Encoding (base64, quoted-printable, identity), and a charset label
|
|
3
|
+
// to text. Each refusal is `X_MAIL_INBOUND_MALFORMED`; an unknown CHARSET is not one (UTF-8 reads it).
|
|
4
|
+
|
|
5
|
+
import { inboundMalformed } from './mime-parse-errors';
|
|
6
|
+
|
|
7
|
+
const UTF16 = new TextDecoder('utf-16le');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Bytes → one char per byte (U+0000–U+00FF), natively: each byte widened to a UTF-16 code unit
|
|
11
|
+
* and decoded in one call. Never `TextDecoder('latin1')` (that is windows-1252), and never a
|
|
12
|
+
* `fromCharCode` loop — that took half a second per MiB.
|
|
13
|
+
*/
|
|
14
|
+
export function binaryOf(bytes: Uint8Array): string {
|
|
15
|
+
return UTF16.decode(new Uint16Array(bytes));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The inverse of `binaryOf`: every char is below 256 by construction. */
|
|
19
|
+
export function bytesOf(binary: string): Uint8Array {
|
|
20
|
+
const out = new Uint8Array(binary.length);
|
|
21
|
+
for (let at = 0; at < binary.length; at += 1) out[at] = binary.charCodeAt(at) & 0xff;
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const BASE64_BODY = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
26
|
+
|
|
27
|
+
function base64(binary: string): Uint8Array {
|
|
28
|
+
const compact = binary.replace(/[\t\n\r ]/g, '');
|
|
29
|
+
// A bad length is padded (clients truncate the final `=`), a bad alphabet is refused.
|
|
30
|
+
if (!BASE64_BODY.test(compact) || compact.length % 4 === 1) throw inboundMalformed('base64');
|
|
31
|
+
const padded = compact.padEnd(Math.ceil(compact.length / 4) * 4, '=');
|
|
32
|
+
try {
|
|
33
|
+
return bytesOf(atob(padded));
|
|
34
|
+
} catch {
|
|
35
|
+
throw inboundMalformed('base64');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const HEX_PAIR = /^[0-9A-Fa-f]{2}$/;
|
|
40
|
+
|
|
41
|
+
const isBlank = (code: number): boolean => code === 0x20 || code === 0x09;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Transport padding (spaces/tabs before a line break) dropped, in ONE pass. Never a regex like
|
|
45
|
+
* `/[\t ]+(?=\r?\n)/g`: with no newline after a long run it retries from every space, which is
|
|
46
|
+
* quadratic — 100 KB of spaces held the event loop for 50 s.
|
|
47
|
+
*/
|
|
48
|
+
function trimLineEnds(binary: string): string {
|
|
49
|
+
const lines = binary.split('\n');
|
|
50
|
+
for (let index = 0; index < lines.length - 1; index += 1) {
|
|
51
|
+
const line = lines[index] ?? '';
|
|
52
|
+
const cr = line.endsWith('\r') ? 1 : 0;
|
|
53
|
+
let end = line.length - cr;
|
|
54
|
+
while (end > 0 && isBlank(line.charCodeAt(end - 1))) end -= 1;
|
|
55
|
+
lines[index] = line.slice(0, end) + (cr === 1 ? '\r' : '');
|
|
56
|
+
}
|
|
57
|
+
return lines.join('\n');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** RFC 2045 §6.7. A stray `=` is kept literally, as the RFC recommends a robust decoder does. */
|
|
61
|
+
function quotedPrintable(binary: string): Uint8Array {
|
|
62
|
+
const text = trimLineEnds(binary);
|
|
63
|
+
// Decoding only shrinks: the output never outgrows the input.
|
|
64
|
+
const out = new Uint8Array(text.length);
|
|
65
|
+
let length = 0;
|
|
66
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
67
|
+
const char = text.charCodeAt(at);
|
|
68
|
+
if (char !== 0x3d) {
|
|
69
|
+
out[length++] = char;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (text.startsWith('\r\n', at + 1)) at += 2;
|
|
73
|
+
else if (text[at + 1] === '\n') at += 1;
|
|
74
|
+
else if (HEX_PAIR.test(text.slice(at + 1, at + 3))) {
|
|
75
|
+
out[length++] = Number.parseInt(text.slice(at + 1, at + 3), 16);
|
|
76
|
+
at += 2;
|
|
77
|
+
} else out[length++] = char;
|
|
78
|
+
}
|
|
79
|
+
return out.slice(0, length);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A part's body, decoded by its declared Content-Transfer-Encoding (absent is 7bit). */
|
|
83
|
+
export function decodeTransfer(body: string, encoding: string | undefined): Uint8Array {
|
|
84
|
+
const label = (encoding ?? '7bit').trim().toLowerCase();
|
|
85
|
+
if (label === 'base64') return base64(body);
|
|
86
|
+
if (label === 'quoted-printable') return quotedPrintable(body);
|
|
87
|
+
if (label === '7bit' || label === '8bit' || label === 'binary') return bytesOf(body);
|
|
88
|
+
throw inboundMalformed('transfer-encoding');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Text under its declared charset; a label the runtime does not know reads as UTF-8. */
|
|
92
|
+
export function decodeCharset(bytes: Uint8Array, charset: string | undefined): string {
|
|
93
|
+
try {
|
|
94
|
+
return new TextDecoder(charset ?? 'utf-8').decode(bytes);
|
|
95
|
+
} catch {
|
|
96
|
+
// `TextDecoder` refuses an unknown label with a RangeError; the bytes are still text.
|
|
97
|
+
return new TextDecoder('utf-8').decode(bytes);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Decoded bytes of a Q-encoded word (RFC 2047 §4.2): `_` is a space, `=XX` a byte. */
|
|
102
|
+
export function qWord(text: string): Uint8Array {
|
|
103
|
+
return quotedPrintable(text.replaceAll('_', ' '));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Decoded bytes of a B-encoded word, or `undefined` — a bad encoded word is left as written. */
|
|
107
|
+
export function bWord(text: string): Uint8Array | undefined {
|
|
108
|
+
try {
|
|
109
|
+
return base64(text);
|
|
110
|
+
} catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Single responsibility: the two refusals an inbound message earns once its signature verified —
|
|
2
|
+
// bytes that are not MIME this parser reads, and bytes past a declared bound. Closed vocabularies,
|
|
3
|
+
// so no cause ever echoes a sender's bytes; both are terminal: a retry reads the same message.
|
|
4
|
+
|
|
5
|
+
import { MailError } from './errors';
|
|
6
|
+
|
|
7
|
+
/** What could not be read. Every value is a fact about the message, never a quote from it. */
|
|
8
|
+
export type InboundMalformation =
|
|
9
|
+
| 'empty'
|
|
10
|
+
| 'header'
|
|
11
|
+
| 'boundary-missing'
|
|
12
|
+
| 'boundary-invalid'
|
|
13
|
+
| 'boundary-absent'
|
|
14
|
+
| 'boundary-unclosed'
|
|
15
|
+
| 'transfer-encoding'
|
|
16
|
+
| 'base64'
|
|
17
|
+
| 'content-missing'
|
|
18
|
+
| 'raw-unavailable'
|
|
19
|
+
| 'row';
|
|
20
|
+
|
|
21
|
+
const MALFORMED: Readonly<Record<InboundMalformation, string>> = {
|
|
22
|
+
empty: 'is empty or opens with no header section',
|
|
23
|
+
header: 'has a header line with no field name and colon (RFC 5322 §2.2)',
|
|
24
|
+
'boundary-missing': 'declares a multipart part with no boundary parameter (RFC 2046 §5.1.1)',
|
|
25
|
+
'boundary-invalid': 'declares a multipart boundary longer than 70 characters or empty',
|
|
26
|
+
'boundary-absent': 'declares a multipart part whose body never names its boundary',
|
|
27
|
+
'boundary-unclosed': 'declares a multipart part whose closing --boundary-- never arrives',
|
|
28
|
+
'transfer-encoding': 'declares a Content-Transfer-Encoding outside 7bit/8bit/binary/base64/QP',
|
|
29
|
+
base64: 'declares base64 for a part whose body is not base64',
|
|
30
|
+
'content-missing': 'is an SES notification that carries no message content',
|
|
31
|
+
'raw-unavailable': 'is a Resend email whose raw MIME the API does not offer',
|
|
32
|
+
row: 'was queued in a row this receiver did not write — another producer enqueued its job name',
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const MALFORMED_FIX: ReadonlyMap<InboundMalformation, string> = new Map([
|
|
36
|
+
[
|
|
37
|
+
'content-missing',
|
|
38
|
+
'aws ses describe-active-receipt-rule-set — the rule needs an SNS action with Encoding BASE64; SES omits content over 150 KB, which this receiver cannot read',
|
|
39
|
+
],
|
|
40
|
+
[
|
|
41
|
+
'raw-unavailable',
|
|
42
|
+
"curl -sS https://api.resend.com/emails/receiving/<email id> -H 'Authorization: Bearer <RESEND_API_KEY>' — raw is null until Resend stores the message; the job retries",
|
|
43
|
+
],
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
export const inboundMalformed = (problem: InboundMalformation): MailError =>
|
|
47
|
+
new MailError({
|
|
48
|
+
code: 'X_MAIL_INBOUND_MALFORMED',
|
|
49
|
+
cause: `an inbound message ${MALFORMED[problem]}`,
|
|
50
|
+
fix:
|
|
51
|
+
MALFORMED_FIX.get(problem) ??
|
|
52
|
+
'x jobs list --state dead --json — the row is the record: the sending client wrote MIME no retry can repair, so answer the sender out of band',
|
|
53
|
+
meta: { problem },
|
|
54
|
+
// A raw file Resend has not stored YET is the one malformation time repairs.
|
|
55
|
+
...(problem === 'raw-unavailable' ? { retry: 'retryable' as const } : {}),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/** Which bound an inbound message crossed. Each is an `InboundLimits` field. */
|
|
59
|
+
export type InboundLimit =
|
|
60
|
+
| 'maxBytes'
|
|
61
|
+
| 'maxParts'
|
|
62
|
+
| 'maxDepth'
|
|
63
|
+
| 'maxAttachments'
|
|
64
|
+
| 'maxHeaderBytes';
|
|
65
|
+
|
|
66
|
+
export const inboundTooLarge = (limit: InboundLimit, max: number): MailError =>
|
|
67
|
+
new MailError({
|
|
68
|
+
code: 'X_MAIL_INBOUND_TOO_LARGE',
|
|
69
|
+
cause: `an inbound message crosses its ${limit} bound of ${max} — refused whole, never truncated`,
|
|
70
|
+
fix: `inboundMail({ limits: { ${limit}: ${max * 2} } }) — only if mail this large is mail you expect; a sender past the bound is refused, not read`,
|
|
71
|
+
meta: { limit, max },
|
|
72
|
+
});
|