import he from 'he';
import libmime from 'libmime';
import addressparser from 'nodemailer/lib/addressparser';
import punycode from 'punycode.js';
// An RFC 2047 encoded word
const ENCODED_WORD = /[=]\?[^?]+\?[BbQq]\?[^?]*\?[=]/;
/**
* Decodes the addresses addressparser produced, in place: encoded words in display names, an
* internationalized (punycode) domain, and the members of a group.
*
* @internal
*/
export function decodeAddresses(addresses, decoder = libmime, decodePunycode = true) {
for (let address of addresses) {
address.name = (address.name || '').toString().trim();
// An encoded word decodes into the display name and nothing else, whatever it
// decodes to. RFC 2047 section 5 keeps encoded words out of the addr-spec, so a
// name that decodes to "CEO" <[email protected]> is still only a name: parsing it
// again would report an address the header never carried
if (address.name) {
try {
address.name = decoder.decodeWords(address.name);
}
catch {
//ignore, keep as is
}
}
// Security fix: detect RFC 2047 encoded-words in the address field.
// Per RFC 2047 Section 5, encoded-words MUST NOT appear in addr-spec.
// If found, decode and validate; reject if result is not a simple local@domain.
if (address.address && ENCODED_WORD.test(address.address)) {
try {
let decodedAddr = decoder.decodeWords(address.address);
if (/^[^\s@]+@[^\s@]+$/.test(decodedAddr) && !/[=]\?/.test(decodedAddr)) {
address.address = decodedAddr;
}
else {
address.address = '';
}
}
catch {
address.address = '';
}
}
if (decodePunycode && address.address && /@xn--/.test(address.address)) {
try {
address.address =
address.address.slice(0, address.address.lastIndexOf('@') + 1) +
punycode.toUnicode(address.address.slice(address.address.lastIndexOf('@') + 1));
}
catch {
// Not a valid punycode string; keep as is
}
}
if (address.group) {
decodeAddresses(address.group, decoder, decodePunycode);
}
}
}
/**
* Formats parsed addresses for an HTML context, every value HTML-escaped.
*
* @internal
*/
export function formatAddressesHTML(value) {
let formatSingleLevel = (addresses) => addresses
.map(address => {
let str = '<span class="mp_address_group">';
if (address.name) {
str += '<span class="mp_address_name">' + he.encode(address.name) + (address.group ? ': ' : '') + '</span>';
}
if (address.address) {
let link = '<a href="mailto:' + he.encode(address.address) + '" class="mp_address_email">' + he.encode(address.address) + '</a>';
if (address.name) {
str += ' <' + link + '>';
}
else {
str += link;
}
}
if (address.group) {
str += formatSingleLevel(address.group) + ';';
}
return str + '</span>';
})
.join(', ');
return formatSingleLevel([].concat(value || []));
}
/**
* Formats parsed addresses as plain text, display names quoted.
*
* @internal
*/
export function formatAddressesText(value) {
let formatSingleLevel = (addresses) => addresses
.map(address => {
let str = '';
if (address.name) {
// a quoted-string, so a quote or backslash inside the name is escaped
str += `"${address.name.replace(/["\\]/g, '\\$&')}"` + (address.group ? ': ' : '');
}
if (address.address) {
let link = address.address;
if (address.name) {
str += ' <' + link + '>';
}
else {
str += link;
}
}
if (address.group) {
str += formatSingleLevel(address.group) + ';';
}
return str;
})
.join(', ');
return formatSingleLevel([].concat(value || []));
}
/**
* Parses the value of an address header (`From`, `To`, `Cc`, `Reply-To` and the like) into the
* {@link AddressObject} `MailParser` and `simpleParser` produce for one: display names have their
* encoded words decoded, an internationalized (punycode) domain is decoded to Unicode (unless
* `decodePunycode` is false), and an
* address part that hides an encoded word is dropped unless it decodes to a plain `local@domain`
* (RFC 2047 keeps encoded words out of the address, so `[email protected]` naming
* another address is not taken at its word).
*
* The value is the header value without the `Name:` prefix, as a string. Line folding may be left
* in. Raw 8-bit bytes have to be decoded into the string first, eg. `buffer.toString('utf-8')`.
* Several values (a header that occurs more than once) can be given as an array: each is parsed
* on its own and the addresses are listed in order.
*
* @param value The header value, or several of them
* @param options See {@link ParseAddressHeaderOptions}
*/
export function parseAddressHeader(value, options) {
let addresses = [];
for (let entry of [].concat(value)) {
if (typeof entry !== 'string' || !entry) {
continue;
}
let parsed = addressparser(entry, { flatten: !!options?.flatten });
decodeAddresses(parsed, libmime, options?.decodePunycode !== false);
for (let address of parsed) {
addresses.push(address);
}
}
return withLazyFormats(addresses);
}
/**
* The AddressObject for parsed addresses, with `html` and `text` built on first read: a caller
* that only wants the addresses (eg. for an SMTP envelope) pays for neither. Both stay enumerable
* and assignable, to read, compare, serialize and overwrite like the plain values they were.
*/
function withLazyFormats(addresses) {
let html;
let text;
const result = { value: addresses };
Object.defineProperties(result, {
html: {
enumerable: true,
get: () => (html ??= formatAddressesHTML(addresses)),
set: value => {
html = value;
}
},
text: {
enumerable: true,
get: () => (text ??= formatAddressesText(addresses)),
set: value => {
text = value;
}
}
});
return result;
}