@ultimat3/mail 31.25.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.
@@ -0,0 +1,202 @@
1
+ // Single responsibility: one MIME header section, read — unfold, split into ordered fields,
2
+ // decode RFC 2047 encoded words, and read a structured value's parameters (RFC 2045 §5.1, with
3
+ // RFC 2231 continuations and charsets). Bounded by the caller's `maxHeaderBytes`.
4
+
5
+ import { bWord, bytesOf, decodeCharset, qWord } from './mime-parse-decode';
6
+ import { inboundMalformed, inboundTooLarge } from './mime-parse-errors';
7
+
8
+ export interface HeaderField {
9
+ readonly name: string;
10
+ /** Unfolded, RFC 2047 decoded, trimmed: for display, never for structure. */
11
+ readonly value: string;
12
+ /**
13
+ * Unfolded and trimmed, encoded words as sent. Structure (address lists, parameters) is read
14
+ * from this: a decoded `,` `;` `:` `<` `"` is text, never a delimiter (RFC 2047 §5(3)).
15
+ */
16
+ readonly raw: string;
17
+ }
18
+
19
+ /** RFC 5322 §3.6.8: printable ASCII except the colon. */
20
+ const FIELD_NAME = /^[!-9;-~]+$/;
21
+ const ENCODED_WORD = /=\?([^?\s]+)\?([BbQq])\?([^?\s]*)\?=/g;
22
+ const ENCODED_WORD_AT = /=\?[^?\s]+\?[BbQq]\?[^?\s]*\?=/y;
23
+
24
+ /** The encoded word starting at `at`, whole, or `undefined` — a tokenizer keeps it atomic. */
25
+ export function encodedWordAt(value: string, at: number): string | undefined {
26
+ if (value.charAt(at) !== '=' || value.charAt(at + 1) !== '?') return undefined;
27
+ ENCODED_WORD_AT.lastIndex = at;
28
+ return ENCODED_WORD_AT.exec(value)?.[0];
29
+ }
30
+
31
+ /**
32
+ * RFC 2047 words → text. Adjacent words (only whitespace between) lose that whitespace (§6.2),
33
+ * and adjacent words of ONE charset are decoded together, so a character split across two words
34
+ * survives. A word that does not decode is kept as written, never refused.
35
+ */
36
+ export function decodeWords(value: string): string {
37
+ let out = '';
38
+ let last = 0;
39
+ let group: { charset: string; bytes: number[] } | undefined;
40
+ const flush = (): void => {
41
+ if (group !== undefined) out += decodeCharset(Uint8Array.from(group.bytes), group.charset);
42
+ group = undefined;
43
+ };
44
+ for (const match of value.matchAll(ENCODED_WORD)) {
45
+ const gap = value.slice(last, match.index);
46
+ last = match.index + match[0].length;
47
+ const charset = String(match[1]).split('*')[0]?.toLowerCase() ?? '';
48
+ const text = String(match[3]);
49
+ const bytes = String(match[2]).toUpperCase() === 'B' ? bWord(text) : qWord(text);
50
+ const adjacent = group !== undefined && gap.trim() === '';
51
+ if (bytes === undefined) {
52
+ flush();
53
+ out += gap + match[0];
54
+ continue;
55
+ }
56
+ if (adjacent && group?.charset === charset) {
57
+ group.bytes.push(...bytes);
58
+ continue;
59
+ }
60
+ flush();
61
+ if (!adjacent) out += gap;
62
+ group = { charset, bytes: [...bytes] };
63
+ }
64
+ flush();
65
+ return out + value.slice(last);
66
+ }
67
+
68
+ /**
69
+ * The header section (binary string, one char per byte) → fields in order. Raw 8-bit is read as
70
+ * UTF-8 (RFC 6532); a non-blank line with no `name:` is `X_MAIL_INBOUND_MALFORMED`.
71
+ */
72
+ export function parseHeaderSection(head: string, maxHeaderBytes: number): readonly HeaderField[] {
73
+ if (head.length > maxHeaderBytes) throw inboundTooLarge('maxHeaderBytes', maxHeaderBytes);
74
+ const fields: HeaderField[] = [];
75
+ const unfolded = head.replace(/\r?\n(?=[\t ])/g, '');
76
+ for (const line of unfolded.split(/\r?\n/)) {
77
+ if (line.trim() === '') continue;
78
+ const colon = line.indexOf(':');
79
+ const name = colon > 0 ? line.slice(0, colon).trimEnd() : '';
80
+ if (!FIELD_NAME.test(name)) throw inboundMalformed('header');
81
+ const raw = decodeCharset(bytesOf(line.slice(colon + 1)), 'utf-8').trim();
82
+ fields.push({ name, value: decodeWords(raw).trim(), raw });
83
+ }
84
+ return fields;
85
+ }
86
+
87
+ /** The first field named `name`, case-insensitively, as RFC 5322 field names compare. */
88
+ export function headerOf(fields: readonly HeaderField[], name: string): string | undefined {
89
+ const wanted = name.toLowerCase();
90
+ return fields.find((field) => field.name.toLowerCase() === wanted)?.value;
91
+ }
92
+
93
+ /** The same field's `raw` — what every structured reader (addresses, parameters) parses. */
94
+ export function rawHeaderOf(fields: readonly HeaderField[], name: string): string | undefined {
95
+ const wanted = name.toLowerCase();
96
+ return fields.find((field) => field.name.toLowerCase() === wanted)?.raw;
97
+ }
98
+
99
+ export interface StructuredValue {
100
+ /** Lower-cased: `multipart/mixed`, `attachment`. */
101
+ readonly value: string;
102
+ /** Parameter names lower-cased; values unquoted and decoded. A Map: names are the sender's. */
103
+ readonly params: ReadonlyMap<string, string>;
104
+ }
105
+
106
+ /** Splits on `;` outside double quotes. */
107
+ function segments(value: string): string[] {
108
+ const out: string[] = [];
109
+ let current = '';
110
+ let quoted = false;
111
+ for (let at = 0; at < value.length; at += 1) {
112
+ const char = value.charAt(at);
113
+ const word = encodedWordAt(value, at);
114
+ if (word !== undefined) {
115
+ current += word;
116
+ at += word.length - 1;
117
+ } else if (char === '\\' && quoted) {
118
+ current += char + value.charAt(at + 1);
119
+ at += 1;
120
+ } else if (char === '"') {
121
+ quoted = !quoted;
122
+ current += char;
123
+ } else if (char === ';' && !quoted) {
124
+ out.push(current);
125
+ current = '';
126
+ } else current += char;
127
+ }
128
+ out.push(current);
129
+ return out;
130
+ }
131
+
132
+ const unquote = (text: string): string =>
133
+ text.startsWith('"') && text.endsWith('"') && text.length >= 2
134
+ ? text.slice(1, -1).replace(/\\(.)/g, '$1')
135
+ : text;
136
+
137
+ const percentDecoded = (text: string): string =>
138
+ text.replace(/%([0-9A-Fa-f]{2})/g, (_, hex: string) =>
139
+ String.fromCharCode(Number.parseInt(hex, 16)),
140
+ );
141
+
142
+ interface Piece {
143
+ readonly text: string;
144
+ readonly extended: boolean;
145
+ }
146
+
147
+ /**
148
+ * RFC 2231 §3–4: `name*0`, `name*1*`… joined in index order. Only an EXTENDED piece is
149
+ * percent-decoded, and only piece 0 may open with `charset'lang'`; the bytes are decoded once.
150
+ */
151
+ function continued(pieces: ReadonlyMap<number, Piece>): string {
152
+ let binary = '';
153
+ let charset: string | undefined;
154
+ for (let index = 0; pieces.has(index); index += 1) {
155
+ const piece = pieces.get(index);
156
+ if (piece === undefined) break;
157
+ let text = piece.text;
158
+ if (piece.extended && index === 0) {
159
+ const [label, , ...rest] = text.split("'");
160
+ if (rest.length > 0) {
161
+ charset = label === '' ? undefined : label;
162
+ text = rest.join("'");
163
+ }
164
+ }
165
+ binary += piece.extended
166
+ ? percentDecoded(text)
167
+ : String.fromCharCode(...new TextEncoder().encode(text));
168
+ }
169
+ return decodeCharset(bytesOf(binary), charset);
170
+ }
171
+
172
+ /**
173
+ * `type/subtype; a=b; c*=utf-8''x; d*0=…` → value + parameters. Read from a RAW header: a plain
174
+ * value is RFC 2047 decoded only after it is split out. An extended `name*` (or `name*0…`) beats
175
+ * a plain `name` — RFC 2231 §4.1's fallback for old readers — and the two never join.
176
+ */
177
+ export function parseStructured(header: string | undefined): StructuredValue {
178
+ const [head = '', ...rest] = segments(header ?? '');
179
+ const plain = new Map<string, string>();
180
+ const extended = new Map<string, Map<number, Piece>>();
181
+ for (const segment of rest) {
182
+ const eq = segment.indexOf('=');
183
+ if (eq < 1) continue;
184
+ const key = segment.slice(0, eq).trim().toLowerCase();
185
+ const text = unquote(segment.slice(eq + 1).trim());
186
+ const match = /^([^*]+)(?:\*(\d{1,3}))?(\*)?$/.exec(key);
187
+ if (match === null) continue;
188
+ const [, base = key, index, star] = match;
189
+ if (index === undefined && star === undefined) {
190
+ if (!plain.has(base)) plain.set(base, text);
191
+ continue;
192
+ }
193
+ const pieces = extended.get(base) ?? new Map<number, Piece>();
194
+ const at = index === undefined ? 0 : Number(index);
195
+ if (!pieces.has(at)) pieces.set(at, { text, extended: star === '*' });
196
+ extended.set(base, pieces);
197
+ }
198
+ const params = new Map<string, string>();
199
+ for (const [name, text] of plain) params.set(name, decodeWords(text));
200
+ for (const [name, pieces] of extended) if (pieces.has(0)) params.set(name, continued(pieces));
201
+ return { value: head.trim().toLowerCase(), params };
202
+ }
@@ -0,0 +1,169 @@
1
+ // Single responsibility: raw RFC 5322 bytes → the message's top-level headers, its text and HTML
2
+ // bodies and its attachments as bytes. Bounded before it allocates: total bytes, parts, nesting
3
+ // depth, attachments and each header section. Every refusal is coded (`mime-parse-errors.ts`).
4
+ // In-tree, no dependency: the bar in docs/idea/18-build-vs-wrap.md is not met by a walk this size.
5
+
6
+ import { isUltimateError } from '@ultimat3/core';
7
+ import { binaryOf, decodeCharset, decodeTransfer } from './mime-parse-decode';
8
+ import { inboundMalformed, inboundTooLarge } from './mime-parse-errors';
9
+ import {
10
+ type HeaderField,
11
+ headerOf,
12
+ parseHeaderSection,
13
+ parseStructured,
14
+ rawHeaderOf,
15
+ } from './mime-parse-headers';
16
+
17
+ export interface MimeLimits {
18
+ /** The whole message. */
19
+ readonly maxBytes: number;
20
+ /** Every node of the tree, multipart containers included. */
21
+ readonly maxParts: number;
22
+ /** Multipart nesting below the top level. */
23
+ readonly maxDepth: number;
24
+ readonly maxAttachments: number;
25
+ /** One header section, in bytes. */
26
+ readonly maxHeaderBytes: number;
27
+ }
28
+
29
+ export const DEFAULT_MIME_LIMITS: MimeLimits = Object.freeze({
30
+ maxBytes: 10 * 1024 * 1024,
31
+ maxParts: 100,
32
+ maxDepth: 8,
33
+ maxAttachments: 20,
34
+ maxHeaderBytes: 64 * 1024,
35
+ });
36
+
37
+ export interface MimeAttachment {
38
+ readonly filename: string | undefined;
39
+ /** As declared, lower-cased, parameters dropped; `application/octet-stream` when undeclared. */
40
+ readonly contentType: string;
41
+ readonly contentId: string | undefined;
42
+ readonly inline: boolean;
43
+ /** Empty when `refusal` is set. */
44
+ readonly bytes: Uint8Array;
45
+ /** `X_MAIL_INBOUND_MALFORMED` when this part's transfer encoding did not decode. */
46
+ readonly refusal?: string | undefined;
47
+ }
48
+
49
+ export interface ParsedMime {
50
+ readonly headers: readonly HeaderField[];
51
+ readonly text: string | undefined;
52
+ readonly html: string | undefined;
53
+ readonly attachments: readonly MimeAttachment[];
54
+ }
55
+
56
+ interface Walk {
57
+ readonly limits: MimeLimits;
58
+ parts: number;
59
+ text: string | undefined;
60
+ html: string | undefined;
61
+ readonly attachments: MimeAttachment[];
62
+ }
63
+
64
+ /** Head and body of one entity (binary string). No blank line: all head, empty body. */
65
+ function split(entity: string): { readonly head: string; readonly body: string } {
66
+ // A part may open with the blank line itself: no headers, all body (RFC 2046 §5.1.1).
67
+ const match = /^\r?\n|\r?\n\r?\n/.exec(entity);
68
+ if (match === null) return { head: entity, body: '' };
69
+ return { head: entity.slice(0, match.index), body: entity.slice(match.index + match[0].length) };
70
+ }
71
+
72
+ const BOUNDARY = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/;
73
+ const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
74
+
75
+ /** The body parts between `--boundary` lines; preamble and epilogue dropped (RFC 2046 §5.1.1). */
76
+ function bodyParts(body: string, boundary: string): string[] {
77
+ if (!BOUNDARY.test(boundary)) throw inboundMalformed('boundary-invalid');
78
+ // The CRLF before a delimiter belongs to the delimiter, so it is not part of the body before it.
79
+ const delimiter = new RegExp(
80
+ `(?:^|\\r?\\n)--${escapeRegExp(boundary)}(--)?[\\t ]*(?=\\r?\\n|$)`,
81
+ 'g',
82
+ );
83
+ const parts: string[] = [];
84
+ let start: number | undefined;
85
+ let closed = false;
86
+ for (const match of body.matchAll(delimiter)) {
87
+ if (start !== undefined) parts.push(body.slice(start, match.index).replace(/^\r?\n/, ''));
88
+ if (match[1] === '--') {
89
+ closed = true;
90
+ break;
91
+ }
92
+ start = match.index + match[0].length;
93
+ }
94
+ if (start === undefined) throw inboundMalformed('boundary-absent');
95
+ if (!closed) throw inboundMalformed('boundary-unclosed');
96
+ return parts;
97
+ }
98
+
99
+ /** A non-body part's bytes, or the refusal its transfer encoding earned — never the message's. */
100
+ function attachmentBytes(body: string, encoding: string | undefined) {
101
+ try {
102
+ return { bytes: decodeTransfer(body, encoding) };
103
+ } catch (error) {
104
+ if (!isUltimateError(error)) throw error;
105
+ return { bytes: new Uint8Array(0), refusal: error.code };
106
+ }
107
+ }
108
+
109
+ function leaf(walk: Walk, headers: readonly HeaderField[], body: string): void {
110
+ const contentType = parseStructured(rawHeaderOf(headers, 'content-type'));
111
+ const disposition = parseStructured(rawHeaderOf(headers, 'content-disposition'));
112
+ const encoding = headerOf(headers, 'content-transfer-encoding');
113
+ // RFC 2045 §5.2: no Content-Type (or one with no slash) is text/plain — for a BODY.
114
+ const declared = contentType.value.includes('/') ? contentType.value : undefined;
115
+ const type = declared ?? 'text/plain';
116
+ const filename = disposition.params.get('filename') ?? contentType.params.get('name');
117
+ const isBody =
118
+ disposition.value !== 'attachment' &&
119
+ filename === undefined &&
120
+ (type === 'text/plain' || type === 'text/html');
121
+ if (isBody) {
122
+ // A body that cannot be decoded is the message unread: that one stays a refusal.
123
+ const text = decodeCharset(decodeTransfer(body, encoding), contentType.params.get('charset'));
124
+ // Split bodies (a client's text, image, text) are read as one, in order.
125
+ if (type === 'text/plain') walk.text = (walk.text ?? '') + text;
126
+ else walk.html = (walk.html ?? '') + text;
127
+ return;
128
+ }
129
+ if (walk.attachments.length >= walk.limits.maxAttachments) {
130
+ throw inboundTooLarge('maxAttachments', walk.limits.maxAttachments);
131
+ }
132
+ const contentId = headerOf(headers, 'content-id')?.replace(/^<|>$/g, '');
133
+ walk.attachments.push({
134
+ filename,
135
+ // An undeclared FILE is opaque bytes: as text/plain it would pass a text allowlist unsniffed.
136
+ contentType: declared ?? 'application/octet-stream',
137
+ contentId: contentId === '' ? undefined : contentId,
138
+ inline: disposition.value === 'inline',
139
+ ...attachmentBytes(body, encoding),
140
+ });
141
+ }
142
+
143
+ function entity(walk: Walk, raw: string, depth: number): readonly HeaderField[] {
144
+ walk.parts += 1;
145
+ if (walk.parts > walk.limits.maxParts) throw inboundTooLarge('maxParts', walk.limits.maxParts);
146
+ const { head, body } = split(raw);
147
+ const headers = parseHeaderSection(head, walk.limits.maxHeaderBytes);
148
+ const contentType = parseStructured(rawHeaderOf(headers, 'content-type'));
149
+ if (!contentType.value.startsWith('multipart/')) {
150
+ leaf(walk, headers, body);
151
+ return headers;
152
+ }
153
+ if (depth >= walk.limits.maxDepth) throw inboundTooLarge('maxDepth', walk.limits.maxDepth);
154
+ const boundary = contentType.params.get('boundary');
155
+ if (boundary === undefined || boundary === '') throw inboundMalformed('boundary-missing');
156
+ for (const part of bodyParts(body, boundary)) entity(walk, part, depth + 1);
157
+ return headers;
158
+ }
159
+
160
+ /** Parse one message. Throws `X_MAIL_INBOUND_TOO_LARGE` / `X_MAIL_INBOUND_MALFORMED`, coded. */
161
+ export function parseMime(bytes: Uint8Array, limits: MimeLimits = DEFAULT_MIME_LIMITS): ParsedMime {
162
+ if (bytes.byteLength > limits.maxBytes) throw inboundTooLarge('maxBytes', limits.maxBytes);
163
+ const raw = binaryOf(bytes);
164
+ // A message opens with a header field: no first line of the form `name:` is not RFC 5322.
165
+ if (!/^[!-9;-~]+[\t ]*:/.test(raw)) throw inboundMalformed('empty');
166
+ const walk: Walk = { limits, parts: 0, text: undefined, html: undefined, attachments: [] };
167
+ const headers = entity(walk, raw, 0);
168
+ return { headers, text: walk.text, html: walk.html, attachments: walk.attachments };
169
+ }