node_modules: update (#322)

Co-authored-by: dawidd6 <9713907+dawidd6@users.noreply.github.com>
This commit is contained in:
Dawid Dziurla
2026-09-15 13:00:32 +02:00
committed by GitHub
parent 4a3d0f9ca3
commit 67ce3558d6
174 changed files with 25661 additions and 5540 deletions
+219
View File
@@ -0,0 +1,219 @@
import { EventEmitter } from 'node:events';
import * as shared from '../shared/index.js';
import DKIM, { type DKIMOptions } from '../dkim/index.js';
import MailMessage, { type MailDefaults, type SendMailOptions } from './mail-message.js';
import net from 'node:net';
import type { ConnectionOptions } from 'node:tls';
import type { MailComposerAlternative, MailComposerAttachment, MailComposerIcalEvent, MailComposerListHeaderEntry, MailComposerListHeaders } from '../mail-composer/index.js';
import type { NodemailerError, ResultCallback } from '../errors.js';
import type { ParsedUrl } from '../shared/url.js';
import type { MimeNodeAddress, MimeNodeEnvelope, MimeNodeEnvelopeInput, MimeNodeHeaders, MimeNodeOptions } from '../mime-node/index.js';
import type { XOAuth2ProvisionCallback } from '../xoauth2/index.js';
export type { SendMailOptions, MailDefaults, MailMessageData, MailMessageDataCallback, MailMessageContentCallback, MailMessageListHeader, MailMessageListHeaderValue } from './mail-message.js';
export type { default as MailMessage } from './mail-message.js';
/**
* The base shape of the object a transport hands back for a sent message. Every bundled
* transport sets the envelope and the Message-ID, the rest depends on the transport.
*
* The index signature keeps a transport specific field readable through this type, and it
* is also what a result type has to inherit to stay assignable to it, so the result type
* of a transport outside this package has to extend this interface rather than restate it
*/
export interface SentMessageInfo {
/** The envelope the message was sent with */
envelope: MimeNodeEnvelope;
/** Message-ID of the sent message */
messageId: string;
/** Recipient addresses the transport accepted */
accepted?: string[] | undefined;
/** Recipient addresses the transport rejected */
rejected?: string[] | undefined;
/** Recipient addresses left pending, LMTP reports these */
pending?: string[] | undefined;
/** Last response from the server */
response?: string | undefined;
/** The generated message, for the transports that hand it back instead of sending it */
message?: unknown;
/** Transport specific fields */
[key: string]: unknown;
}
/**
* Callback for sendMail, receives the transport result once the transport has taken the
* message
*/
export type SendMailCallback<T = SentMessageInfo> = (err: NodemailerError | null, info: T) => void;
/**
* Callback for verify(), success is true once the transport accepted the configuration
*/
export type VerifyCallback = (err: NodemailerError | null, success?: true) => void;
/**
* Callback a plugin calls once it is done, an error aborts the send
*/
export type PluginCallback = (err?: NodemailerError | null) => void;
/**
* A plugin registered with use(): receives the message and a callback to call once done
*/
export type PluginFunction<T = SentMessageInfo> = (mail: MailMessage<T>, callback: PluginCallback) => void;
/**
* Connection options a getSocket handler receives: the options of the transport asking for
* the socket, with the host and port to connect to
*/
export interface GetSocketOptions {
host?: string | undefined;
port?: number | string | undefined;
[key: string]: any;
}
/**
* The result of a getSocket handler, the socket to use for the connection
*/
export interface SocketOptions {
/** An established socket, the proxied connection */
connection?: net.Socket | undefined;
}
/**
* Receives the socket options from a getSocket handler, or the error that prevented the
* connection
*/
export type GetSocketCallback = (err: NodemailerError | null, socketOptions?: SocketOptions) => void;
/**
* A socket handler. Mail sets one on the transport as getSocket when a proxy is configured,
* the SMTP transports call it to get a proxied socket instead of connecting directly
*/
export type GetSocketHandler = (options: GetSocketOptions, callback: GetSocketCallback) => void;
/**
* A custom proxy handler, registered with set('proxy_handler_' + protocol, handler) for the
* protocol of the proxy url
*/
export type ProxyHandler = (proxy: ParsedUrl, options: GetSocketOptions, callback: GetSocketCallback) => void;
/**
* Well known keys of the meta store, see set() and get(): the OAuth2 token provisioning
* callback the SMTP transports use, the socks module for socks proxies, and a custom proxy
* handler per proxy protocol
*/
export interface MailMeta {
/** Called by the SMTP transports when a new OAuth2 access token is needed */
oauth2_provision_cb: XOAuth2ProvisionCallback;
/** The socks module, v1 or v2, used to connect through a socks proxy */
proxy_socks_module: any;
[key: `proxy_handler_${string}`]: ProxyHandler;
[key: string]: any;
}
/**
* A transport as consumed by Mail: any object with a name, a version and a send method
* works, the rest is optional. Mail forwards its close, isIdle and verify calls to the
* methods of the same name as they are, so their arguments are up to the transport
*/
export interface Transport<T = SentMessageInfo> {
/** Transport name, used for logging */
name: string;
/** Transport version, used for logging */
version: string;
/** Hands a message to the transport, the callback receives the transport result */
send(mail: MailMessage<T>, callback: ResultCallback<T>): void;
/** Checks the configuration, the SMTP transports connect and authenticate for it */
verify?(...args: any[]): any;
/** Closes the transport */
close?(...args: any[]): any;
/** Tells whether the transport can take a message right away */
isIdle?(...args: any[]): any;
/** Registers an event listener, the transport may emit 'log', 'error', 'idle' and 'clear' */
on?(event: string | symbol, listener: (...args: any[]) => void): this;
/** The Mail object the transport belongs to, set by Mail */
mailer?: Mail<T> | undefined;
/** Socket handler for a proxied connection, set by Mail when a proxy is configured */
getSocket?: GetSocketHandler | undefined;
}
/**
* Transport configuration as read by Mail itself. The transport reads its own options from
* the same object, see the transport for those
*/
export interface TransportOptions {
/** Bunyan compatible logger, true for the default console logger, false or unset for no logging */
logger?: shared.ExternalLogger | boolean | undefined;
/** Component name for the log lines, defaults to 'mail' */
component?: string | undefined;
/** DKIM signing options, every message is signed with these unless it carries its own */
dkim?: DKIMOptions | undefined;
/** Proxy url. http(s) proxies work as is, socks proxies need the socks module set with set('proxy_socks_module', socks) */
proxy?: string | undefined;
/** TLS options, rejectUnauthorized applies to an https proxy as well */
tls?: ConnectionOptions | undefined;
/** Reject content that points to a file path, forced onto every message */
disableFileAccess?: boolean | undefined;
/** Reject content that points to a URL, forced onto every message */
disableUrlAccess?: boolean | undefined;
/** Method to normalize header keys for custom caseing, forced onto every message */
normalizeHeaderKey?: MimeNodeOptions['normalizeHeaderKey'] | undefined;
/** Recipients allowed on one message, forced onto every message, 0 disables the limit, defaults to 100000 */
maxRecipients?: number | undefined;
/** Convert data: images in the html into embedded attachments */
attachDataUrls?: boolean | undefined;
}
/**
* The transporter object createTransport returns, a Mail instance wrapping a transport
*/
export type Transporter<T = SentMessageInfo> = Mail<T>;
/**
* Creates an object for exposing the Mail API
*
* @constructor
* @param transporter Transport object instance to pass the mails to
*/
declare class Mail<out T = SentMessageInfo> extends EventEmitter {
options: TransportOptions;
/** Message defaults given to createTransport, kept public because the DefinitelyTyped typings declared it */
_defaults: MailDefaults;
meta: Map<string, any>;
dkim: DKIM | false;
transporter: Transport<T>;
logger: shared.Logger;
/** Closes the transport, the pooled SMTP transport closes its connections */
close: () => void;
/** Tells whether the transport can take a message right away */
isIdle: () => boolean;
/** Checks the configuration, the SMTP transports connect and authenticate for it */
verify: {
(callback: VerifyCallback): void;
(): Promise<true>;
};
/** Socket handler for a proxied connection, set by setupProxy and handed to the transport on the next send */
getSocket?: GetSocketHandler | false | undefined;
constructor(transporter: Transport<T>, options?: TransportOptions, defaults?: MailDefaults);
use(step: string, plugin: PluginFunction<T>): this;
/**
* Sends an email using the preselected transport object
*
* @param data E-data description
* @param callback Callback to run once the sending succeeded or failed
*/
sendMail(data: SendMailOptions): Promise<T>;
sendMail(data: SendMailOptions, callback: SendMailCallback<T>): void;
getVersionString(): string;
/**
* Sets up proxy handler for a Nodemailer object
*
* @param proxyUrl Proxy configuration url
*/
setupProxy(proxyUrl: string): void;
set<K extends keyof MailMeta & string>(key: K, value: MailMeta[K]): Map<string, any>;
get<K extends keyof MailMeta & string>(key: K): MailMeta[K] | undefined;
}
/**
* Type aliases in the layout of @types/nodemailer, so `Mail.Options` style references keep working
*/
type MailPluginFunction<T> = PluginFunction<T>;
declare namespace Mail {
type Options = SendMailOptions;
type Address = MimeNodeAddress;
type Attachment = MailComposerAttachment;
type AttachmentLike = MailComposerAlternative;
type AmpAttachment = MailComposerAlternative;
type IcalAttachment = MailComposerIcalEvent;
type Headers = MimeNodeHeaders;
type ListHeader = MailComposerListHeaderEntry;
type ListHeaders = MailComposerListHeaders;
type Envelope = MimeNodeEnvelopeInput;
type TextEncoding = NonNullable<SendMailOptions['textEncoding']>;
type PluginFunction<T = SentMessageInfo> = MailPluginFunction<T>;
}
export default Mail;
+375
View File
@@ -0,0 +1,375 @@
import { EventEmitter } from 'node:events';
import * as shared from '../shared/index.js';
import * as mimeTypes from '../mime-funcs/mime-types.js';
import MailComposer from '../mail-composer/index.js';
import DKIM from '../dkim/index.js';
import httpProxyClient from '../smtp-connection/http-proxy-client.js';
import * as errors from '../errors.js';
import util from 'node:util';
import * as urllib from '../shared/url.js';
import * as packageData from '../package-info.js';
import MailMessage from './mail-message.js';
import net from 'node:net';
import dns from 'node:dns';
import crypto from 'node:crypto';
/**
* Recipients allowed on one message unless the caller sets its own maxRecipients. A backstop
* against a runaway or hostile recipient list rather than a delivery policy: RFC 5321 only
* asks a server to accept 100, so a real send is bounded far below this.
*/
const DEFAULT_MAX_RECIPIENTS = 100000;
/**
* Creates an object for exposing the Mail API
*
* @constructor
* @param transporter Transport object instance to pass the mails to
*/
class Mail extends EventEmitter {
constructor(transporter, options, defaults) {
super();
this.options = options || {};
this._defaults = defaults || {};
this._defaultPlugins = {
compile: [(...args) => this._convertDataImages(...args)],
stream: []
};
this._userPlugins = {
compile: [],
stream: []
};
this.meta = new Map();
this.dkim = this.options.dkim ? new DKIM(this.options.dkim) : false;
this.transporter = transporter;
this.transporter.mailer = this;
this.logger = shared.getLogger(this.options, {
component: this.options.component || 'mail'
});
this.logger.debug({
tnx: 'create'
}, 'Creating transport: %s', this.getVersionString());
// setup emit handlers for the transporter
if (typeof this.transporter.on === 'function') {
// deprecated log interface
this.transporter.on('log', log => {
this.logger.debug({
tnx: 'transport'
}, '%s: %s', log.type, log.message);
});
// transporter errors
this.transporter.on('error', err => {
this.logger.error({
err,
tnx: 'transport'
}, 'Transport Error: %s', err.message);
this.emit('error', err);
});
// indicates if the sender has became idle
this.transporter.on('idle', (...args) => {
this.emit('idle', ...args);
});
// indicates if the sender has became idle and all connections are terminated
this.transporter.on('clear', (...args) => {
this.emit('clear', ...args);
});
}
/**
* Optional methods passed to the underlying transport object
*/
['close', 'isIdle', 'verify'].forEach(method => {
this[method] = (...args) => {
if (typeof this.transporter[method] === 'function') {
if (method === 'verify' && typeof this.getSocket === 'function') {
this.transporter.getSocket = this.getSocket;
this.getSocket = false;
}
return this.transporter[method](...args);
}
this.logger.warn({
tnx: 'transport',
methodName: method
}, 'Non existing method %s called for transport', method);
return false;
};
});
// setup proxy handling
if (this.options.proxy && typeof this.options.proxy === 'string') {
this.setupProxy(this.options.proxy);
}
}
use(step, plugin) {
step = (step || '').toString();
if (!this._userPlugins.hasOwnProperty(step)) {
this._userPlugins[step] = [plugin];
}
else {
this._userPlugins[step].push(plugin);
}
return this;
}
sendMail(data, callback = null) {
let promise;
if (!callback) {
promise = new Promise((resolve, reject) => {
callback = shared.callbackPromise(resolve, reject);
});
}
const done = callback;
if (typeof this.getSocket === 'function') {
this.transporter.getSocket = this.getSocket;
this.getSocket = false;
}
const mail = new MailMessage(this, data);
this.logger.debug({
tnx: 'transport',
name: this.transporter.name,
version: this.transporter.version,
action: 'send'
}, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
this._processPlugins('compile', mail, err => {
if (err) {
this.logger.error({
err,
tnx: 'plugin',
action: 'compile'
}, 'PluginCompile Error: %s', err.message);
return done(err);
}
let recipientCount;
try {
mail.message = new MailComposer(mail.data).compile();
mail.setMailerHeader();
mail.setPriorityHeaders();
mail.setListHeaders();
recipientCount = mail.message.getEnvelope().to.length;
}
catch (err) {
// message data can throw while it is compiled, the error belongs to the callback
this.logger.error({
err,
tnx: 'transport',
action: 'send'
}, 'Compile Error: %s', err.message);
return done(err);
}
const maxRecipients = mail.data.maxRecipients === undefined ? DEFAULT_MAX_RECIPIENTS : mail.data.maxRecipients;
if (maxRecipients && recipientCount > maxRecipients) {
const err = new Error(`Message has ${recipientCount} recipients, which is over the ${maxRecipients} allowed by maxRecipients`);
err.code = errors.EMAXRECIPIENTS;
this.logger.error({
err,
tnx: 'transport',
action: 'send'
}, 'Send Error: %s', err.message);
return done(err);
}
this._processPlugins('stream', mail, err => {
if (err) {
this.logger.error({
err,
tnx: 'plugin',
action: 'stream'
}, 'PluginStream Error: %s', err.message);
return done(err);
}
if (mail.data.dkim || this.dkim) {
mail.message.processFunc(input => {
const dkim = mail.data.dkim ? new DKIM(mail.data.dkim) : this.dkim;
this.logger.debug({
tnx: 'DKIM',
messageId: mail.message.messageId(),
dkimDomains: dkim.keys.map(key => key.keySelector + '.' + key.domainName).join(', ')
}, 'Signing outgoing message with %s keys', dkim.keys.length);
return dkim.sign(input, mail.data._dkim);
});
}
this.transporter.send(mail, (...args) => {
if (args[0]) {
this.logger.error({
err: args[0],
tnx: 'transport',
action: 'send'
}, 'Send Error: %s', args[0].message);
}
done(...args);
});
});
});
return promise;
}
getVersionString() {
return util.format('%s (%s; +%s; %s/%s)', packageData.name, packageData.version, packageData.homepage, this.transporter.name, this.transporter.version);
}
/** @internal */
_processPlugins(step, mail, callback) {
step = (step || '').toString();
if (!this._userPlugins.hasOwnProperty(step)) {
return callback();
}
const userPlugins = this._userPlugins[step] || [];
const defaultPlugins = this._defaultPlugins[step] || [];
if (userPlugins.length) {
this.logger.debug({
tnx: 'transaction',
pluginCount: userPlugins.length,
step
}, 'Using %s plugins for %s', userPlugins.length, step);
}
if (userPlugins.length + defaultPlugins.length === 0) {
return callback();
}
let pos = 0;
let block = 'default';
const processPlugins = () => {
let curplugins = block === 'default' ? defaultPlugins : userPlugins;
if (pos >= curplugins.length) {
if (block === 'default' && userPlugins.length) {
block = 'user';
pos = 0;
curplugins = userPlugins;
}
else {
return callback();
}
}
const plugin = curplugins[pos++];
plugin(mail, err => {
if (err) {
return callback(err);
}
processPlugins();
});
};
processPlugins();
}
/**
* Sets up proxy handler for a Nodemailer object
*
* @param proxyUrl Proxy configuration url
*/
setupProxy(proxyUrl) {
const proxy = urllib.parse(proxyUrl);
// setup socket handler for the mailer object
this.getSocket = (options, callback) => {
const protocol = proxy.protocol.replace(/:$/, '').toLowerCase();
if (this.meta.has('proxy_handler_' + protocol)) {
return this.meta.get('proxy_handler_' + protocol)(proxy, options, callback);
}
switch (protocol) {
// Connect using a HTTP CONNECT method
case 'http':
case 'https':
httpProxyClient(proxy.href, options.port, options.host, this.options.tls || {}, (err, socket) => {
if (err) {
return callback(err);
}
return callback(null, {
connection: socket
});
});
return;
case 'socks':
case 'socks5':
case 'socks4':
case 'socks4a': {
if (!this.meta.has('proxy_socks_module')) {
let err = new Error('Socks module not loaded');
err.code = errors.EPROXY;
return callback(err);
}
const connect = (ipaddress) => {
const proxyV2 = !!this.meta.get('proxy_socks_module').SocksClient;
const socksClient = proxyV2 ? this.meta.get('proxy_socks_module').SocksClient : this.meta.get('proxy_socks_module');
const proxyType = Number(proxy.protocol.replace(/\D/g, '')) || 5;
const connectionOpts = {
proxy: {
ipaddress,
port: Number(proxy.port),
type: proxyType
},
[proxyV2 ? 'destination' : 'target']: {
host: options.host,
port: options.port
},
command: 'connect'
};
if (proxy.username || proxy.password) {
const username = proxy.username || '';
const password = proxy.password || '';
if (proxyV2) {
connectionOpts.proxy.userId = username;
connectionOpts.proxy.password = password;
}
else if (proxyType === 4) {
connectionOpts.userid = username;
}
else {
connectionOpts.authentication = {
username,
password
};
}
}
socksClient.createConnection(connectionOpts, (err, info) => {
if (err) {
return callback(err);
}
return callback(null, {
connection: info.socket || info
});
});
};
if (net.isIP(proxy.hostname)) {
return connect(proxy.hostname);
}
return dns.resolve(proxy.hostname, (err, address) => {
if (err) {
return callback(err);
}
connect(Array.isArray(address) ? address[0] : address);
});
}
}
let err = new Error('Unknown proxy configuration');
err.code = errors.EPROXY;
callback(err);
};
}
/** @internal */
_convertDataImages(mail, callback) {
if ((!this.options.attachDataUrls && !mail.data.attachDataUrls) || !mail.data.html) {
return callback();
}
mail.resolveContent(mail.data, 'html', { disableFileAccess: mail.data.disableFileAccess, disableUrlAccess: mail.data.disableUrlAccess }, (err, html) => {
if (err) {
return callback(err);
}
let cidCounter = 0;
html = (html || '')
.toString()
.replace(/(<img\b[^<>]{0,1024} src\s{0,20}=[\s"']{0,20})(data:([^;]+);[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
const cid = crypto.randomBytes(10).toString('hex') + '@localhost';
if (!mail.data.attachments) {
mail.data.attachments = [];
}
if (!Array.isArray(mail.data.attachments)) {
mail.data.attachments = [].concat(mail.data.attachments || []);
}
mail.data.attachments.push({
path: dataUri,
cid,
filename: 'image-' + ++cidCounter + '.' + mimeTypes.detectExtension(mimeType)
});
return prefix + 'cid:' + cid;
});
mail.data.html = html;
callback();
});
}
set(key, value) {
return this.meta.set(key, value);
}
get(key) {
return this.meta.get(key);
}
}
export default Mail;
+90
View File
@@ -0,0 +1,90 @@
import MimeNode, { type MimeNodePreparedHeaderValue } from '../mime-node/index.js';
import type { MailComposerOptions } from '../mail-composer/index.js';
import type { DKIMOptions } from '../dkim/index.js';
import type { SMTPEnvelopeDsn } from '../smtp-connection/index.js';
import type { SMTPTransportAuthOptions } from '../smtp-transport/index.js';
import type { NodemailerError } from '../errors.js';
import type { ResolveContentOptions } from '../shared/index.js';
import type Mail from './index.js';
import type { SentMessageInfo } from './index.js';
/**
* The message data accepted by sendMail. MailComposerOptions describes the fields the MIME
* tree is built from, the fields below are the ones the mailer reads on top of those
*/
export interface SendMailOptions extends MailComposerOptions {
/** DKIM signing options for this message, used instead of the ones of the transporter */
dkim?: DKIMOptions | undefined;
/** Recipients allowed on this message, 0 disables the limit, defaults to 100000 */
maxRecipients?: number | undefined;
/** SMTP transports: DSN parameters for the envelope, sent when the server supports the DSN extension */
dsn?: SMTPEnvelopeDsn | undefined;
/** SMTP transports: RFC 8689, send the REQUIRETLS parameter with MAIL FROM */
requireTLSExtensionEnabled?: boolean | undefined;
/** SMTP transports: per-message authentication settings, used instead of the transport level auth */
auth?: SMTPTransportAuthOptions | undefined;
/** SES transport: extra SendEmailCommand parameters merged into the API call */
ses?: {
[key: string]: unknown;
} | undefined;
}
/**
* Default message fields, the third argument of createTransport. Applied to every message
* for the fields the message does not set itself, the headers are merged one by one
*/
export type MailDefaults = SendMailOptions;
/**
* The message data as held by a MailMessage: the options the caller passed to sendMail with
* the transporter defaults applied. resolveAll rewrites the content and address fields in
* place and normalize adds the envelope, the Message-ID and the normalized headers
*/
export interface MailMessageData extends SendMailOptions {
/** Header values flattened to strings and keyed by lowercase header name, set by normalize */
normalizedHeaders?: {
[key: string]: string;
} | undefined;
}
/**
* Callback for resolveAll and normalize, receives the message data with every content value
* resolved
*/
export type MailMessageDataCallback = (err: NodemailerError | null, data: MailMessageData) => void;
/**
* Callback for resolveContent, receives the resolved content value
*/
export type MailMessageContentCallback = (err: NodemailerError | null, value?: any) => void;
/**
* A single prepared List-* header value, emitted as is
*/
export interface MailMessageListHeaderValue extends MimeNodePreparedHeaderValue {
prepared: boolean;
foldLines: boolean;
value: string;
}
/**
* A List-* header as built from the list value, one prepared value per list entry
*/
export interface MailMessageListHeader {
/** Header key, 'list-' followed by the lowercase list key */
key: string;
value: MailMessageListHeaderValue[];
}
export default class MailMessage<T = SentMessageInfo> {
mailer: Mail<T>;
data: MailMessageData;
message: MimeNode | null;
constructor(mailer: Mail<T>, data?: SendMailOptions);
resolveContent(data: {
[key: string]: any;
}, key: string | number, callback: MailMessageContentCallback): void;
resolveContent(data: {
[key: string]: any;
}, key: string | number, options: ResolveContentOptions | false | undefined, callback: MailMessageContentCallback): void;
resolveContent(data: {
[key: string]: any;
}, key: string | number, options?: ResolveContentOptions | false): Promise<any>;
resolveAll(callback: MailMessageDataCallback): void;
normalize(callback: MailMessageDataCallback): void;
setMailerHeader(): void;
setPriorityHeaders(): void;
setListHeaders(): void;
}
+300
View File
@@ -0,0 +1,300 @@
import * as shared from '../shared/index.js';
import MimeNode from '../mime-node/index.js';
import * as mimeFuncs from '../mime-funcs/index.js';
// Only an own key counts as already set. `key in obj` also matches every member of
// Object.prototype, which silently drops a transporter default legitimately named
// toString or constructor.
const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
export default class MailMessage {
constructor(mailer, data) {
this.mailer = mailer;
this.data = {};
this.message = null;
data = data || {};
const options = mailer.options || {};
const defaults = mailer._defaults || {};
shared.copyOwnKeys(this.data, data);
this.data.headers = this.data.headers || {};
// Apply defaults. `_defaults` is caller supplied too, it is the second argument of
// createTransport, so it needs the same treatment as `data` above
shared.copyOwnKeys(this.data, defaults, key => hasOwn(this.data, key));
// headers is a special case. Allow setting individual default headers
shared.copyOwnKeys(this.data.headers, defaults.headers, key => hasOwn(this.data.headers, key));
// force specific keys from transporter options
['disableFileAccess', 'disableUrlAccess', 'normalizeHeaderKey', 'maxRecipients'].forEach(key => {
if (key in options) {
this.data[key] = options[key];
}
});
// The access flags are a sandbox rather than a message field, so `defaults` counts as
// transporter configuration for them. For a transporter plugin it is the only channel
// there is, createTransport leaves `options` undefined for one, and the defaults copy
// above yields to anything the message already set, which let message data switch the
// sandbox back off. Closing is one way here, same as in resolveContent below: either
// side may switch a flag on, neither can switch off what the other closed.
['disableFileAccess', 'disableUrlAccess'].forEach(key => {
if (!(key in options) && hasOwn(defaults, key)) {
this.data[key] = this.data[key] || defaults[key];
}
});
}
resolveContent(data, key, options, callback) {
// Most plugins call this with the legacy (data, key, callback) signature, which carries
// no access policy. The policy belongs to the message, so apply it here. Explicit
// options may only tighten it, never reopen what the transporter closed.
if (!callback && typeof options === 'function') {
callback = options;
options = false;
}
options = options || {};
const policy = {
disableFileAccess: this.data.disableFileAccess || options.disableFileAccess,
disableUrlAccess: this.data.disableUrlAccess || options.disableUrlAccess
};
return shared.resolveContent(data, key, policy, callback);
}
resolveAll(callback) {
const keys = [
[this.data, 'html'],
[this.data, 'text'],
[this.data, 'watchHtml'],
[this.data, 'amp'],
[this.data, 'icalEvent']
];
if (this.data.alternatives && this.data.alternatives.length) {
this.data.alternatives.forEach((alternative, i) => {
keys.push([this.data.alternatives, i]);
});
}
if (this.data.attachments && this.data.attachments.length) {
this.data.attachments.forEach((attachment, i) => {
if (!attachment.filename) {
attachment.filename =
(attachment.path || attachment.href || '').split('/').pop().split('?').shift() ||
'attachment-' + (i + 1);
if (attachment.filename.indexOf('.') < 0) {
attachment.filename += '.' + mimeFuncs.detectExtension(attachment.contentType);
}
}
if (!attachment.contentType) {
attachment.contentType = mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin');
}
keys.push([this.data.attachments, i]);
});
}
const mimeNode = new MimeNode();
const addressKeys = ['from', 'to', 'cc', 'bcc', 'sender', 'replyTo'];
addressKeys.forEach(address => {
let value;
if (this.message) {
value = [].concat(mimeNode._parseAddresses(this.message.getHeader(address === 'replyTo' ? 'reply-to' : address)) || []);
}
else if (this.data[address]) {
value = [].concat(mimeNode._parseAddresses(this.data[address]) || []);
}
if (value && value.length) {
this.data[address] = value;
}
else if (address in this.data) {
this.data[address] = null;
}
});
const singleKeys = ['from', 'sender'];
singleKeys.forEach(address => {
if (this.data[address]) {
this.data[address] = this.data[address].shift();
}
});
let pos = 0;
const resolveNext = () => {
if (pos >= keys.length) {
return callback(null, this.data);
}
const args = keys[pos++];
if (!args[0] || !args[0][args[1]]) {
return resolveNext();
}
shared.resolveContent(...args, { disableFileAccess: this.data.disableFileAccess, disableUrlAccess: this.data.disableUrlAccess }, (err, value) => {
if (err) {
return callback(err);
}
const node = {
content: value
};
if (args[0][args[1]] && typeof args[0][args[1]] === 'object' && !Buffer.isBuffer(args[0][args[1]])) {
// The keys are the caller's, so copying them takes the same "__proto__"
// rule as the constructor. `key in node` stays as the already-set test
// here, unlike for the defaults: it also skips the Object.prototype
// member names, and letting message data land a `toString` string on a
// node only buys a TypeError the first time something stringifies it.
shared.copyOwnKeys(node, args[0][args[1]], key => key in node || ['content', 'path', 'href', 'raw'].includes(key));
}
args[0][args[1]] = node;
resolveNext();
});
};
setImmediate(() => resolveNext());
}
normalize(callback) {
const envelope = this.message.getEnvelope();
const messageId = this.message.messageId();
this.resolveAll((err, data) => {
if (err) {
return callback(err);
}
data.envelope = envelope;
data.messageId = messageId;
['html', 'text', 'watchHtml', 'amp'].forEach(key => {
if (data[key] && data[key].content) {
if (typeof data[key].content === 'string') {
data[key] = data[key].content;
}
else if (Buffer.isBuffer(data[key].content)) {
data[key] = data[key].content.toString();
}
}
});
if (data.icalEvent && Buffer.isBuffer(data.icalEvent.content)) {
data.icalEvent.content = data.icalEvent.content.toString('base64');
data.icalEvent.encoding = 'base64';
}
if (data.alternatives && data.alternatives.length) {
data.alternatives.forEach((alternative) => {
if (alternative && alternative.content && Buffer.isBuffer(alternative.content)) {
alternative.content = alternative.content.toString('base64');
alternative.encoding = 'base64';
}
});
}
if (data.attachments && data.attachments.length) {
data.attachments.forEach((attachment) => {
if (attachment && attachment.content && Buffer.isBuffer(attachment.content)) {
attachment.content = attachment.content.toString('base64');
attachment.encoding = 'base64';
}
});
}
data.normalizedHeaders = {};
Object.keys(data.headers || {}).forEach(key => {
if (shared.isProtoKey(key)) {
return;
}
let value = [].concat(data.headers[key] || []).shift();
value = (value && value.value) || value;
if (value) {
if (['references', 'in-reply-to', 'message-id', 'content-id'].includes(key)) {
value = this.message._encodeHeaderValue(key, value);
}
data.normalizedHeaders[key] = value;
}
});
if (data.list && typeof data.list === 'object') {
const listHeaders = this._getListHeaders(data.list);
listHeaders.forEach(entry => {
data.normalizedHeaders[entry.key] = entry.value.map(val => (val && val.value) || val).join(', ');
});
}
if (data.references) {
data.normalizedHeaders.references = this.message._encodeHeaderValue('references', data.references);
}
if (data.inReplyTo) {
data.normalizedHeaders['in-reply-to'] = this.message._encodeHeaderValue('in-reply-to', data.inReplyTo);
}
return callback(null, data);
});
}
setMailerHeader() {
if (!this.message || !this.data.xMailer) {
return;
}
this.message.setHeader('X-Mailer', this.data.xMailer);
}
setPriorityHeaders() {
if (!this.message || !this.data.priority) {
return;
}
switch ((this.data.priority || '').toString().toLowerCase()) {
case 'high':
this.message.setHeader('X-Priority', '1 (Highest)');
this.message.setHeader('X-MSMail-Priority', 'High');
this.message.setHeader('Importance', 'High');
break;
case 'low':
this.message.setHeader('X-Priority', '5 (Lowest)');
this.message.setHeader('X-MSMail-Priority', 'Low');
this.message.setHeader('Importance', 'Low');
break;
default:
// do not add anything, since all messages are 'Normal' by default
}
}
setListHeaders() {
if (!this.message || !this.data.list || typeof this.data.list !== 'object') {
return;
}
// add optional List-* headers
this._getListHeaders(this.data.list).forEach(listHeader => {
listHeader.value.forEach(value => {
this.message.addHeader(listHeader.key, value);
});
});
}
/** @internal */
_getListHeaders(listData) {
// make sure an url looks like <protocol:url>
return Object.keys(listData).map(key => ({
key: 'list-' + key.toLowerCase().trim(),
value: [].concat(listData[key] || []).map(value => ({
prepared: true,
foldLines: true,
value: []
.concat(value || [])
.map(value => {
if (typeof value === 'string') {
value = {
url: value
};
}
if (value && value.url) {
// strip CR/LF so a comment can't inject extra header lines. DEL is neither
// qtext nor ctext, so it can not be carried literally by either construct
// and has to become an encoded word like any other non-plaintext value
let comment = (value.comment || '').toString().replace(/\r?\n|\r/g, ' ');
const needsEncoding = !mimeFuncs.isPlainText(comment) || /\x7f/.test(comment);
if (key.toLowerCase().trim() === 'id') {
// List-ID: "comment" <domain>, where an unescaped quote or a trailing
// backslash in the comment would swallow the <domain> behind it
comment = needsEncoding ? mimeFuncs.encodeWord(comment) : mimeFuncs.quoteString(comment);
// List-ID expects a bare domain-like identifier, so strip the
// scheme prefix that _formatListUrl adds or passes through
return ((value.comment ? comment + ' ' : '') + this._formatListUrl(value.url).replace(/^<[^:]+:\/{0,2}/, '<'));
}
// List-*: <http://domain> (comment)
// the ctext specials go out as quoted-pairs, otherwise a ")" closes the
// comment early and leaves the rest as junk, an unpaired "(" opens a
// nested comment that never closes, and a trailing backslash escapes
// the closing ")" so the comment swallows whatever follows it
comment = needsEncoding ? mimeFuncs.encodeWord(comment) : comment.replace(/[()\\]/g, '\\$&');
return this._formatListUrl(value.url) + (value.comment ? ' (' + comment + ')' : '');
}
return '';
})
.filter(value => value)
.join(', ')
}))
}));
}
/** @internal */
_formatListUrl(url) {
// a url has no way to carry a control char or DEL, and the angle brackets around it
// are not a quoting construct, so anything left here lands in the header raw
url = url.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '').replace(/[\s<]+|[\s>]+/g, '');
if (/^(https?|mailto|ftp):/.test(url)) {
return '<' + url + '>';
}
if (/^[^@]+@[^@]+$/.test(url)) {
return '<mailto:' + url + '>';
}
return '<http://' + url + '>';
}
}