index.js

14.3 KB v1.0
import { EventEmitter } from 'node:events';
import SMTPConnection from '../smtp-connection/index.js';
import wellKnown from '../well-known/index.js';
import * as shared from '../shared/index.js';
import XOAuth2 from '../xoauth2/index.js';
import * as errors from '../errors.js';
import * as packageData from '../package-info.js';
// The keys a message's `auth` may set on top of the transport's auth settings: the ones that
// say who logs in and with what. Everything else in the auth block (accessUrl, clientId,
// clientSecret, customHeaders, customParams, tls, privateKey, serviceClient and the rest)
// names the endpoint the credentials go to or is a secret of the application itself, and
// a message that could set `auth.accessUrl` and force a refresh would have the transport's
// client secret and refresh token posted to a URL of its choosing
const MESSAGE_AUTH_KEYS = ['type', 'user', 'pass', 'accessToken', 'refreshToken', 'expires'];
/**
 * Creates a SMTP transport object for Nodemailer
 *
 * @constructor
 * @param options Connection options
 */
class SMTPTransport extends EventEmitter {
    constructor(options) {
        super();
        this.supportsAbortSignal = true;
        options = options || {};
        if (typeof options === 'string') {
            options = {
                url: options
            };
        }
        let urlData;
        let service = options.service;
        if (typeof options.getSocket === 'function') {
            this.getSocket = options.getSocket;
        }
        if (options.url) {
            urlData = shared.parseConnectionUrl(options.url);
            service = service || urlData.service;
        }
        this.options = shared.assign(false, // create new object
        options, // regular options
        urlData, // url options
        (service && wellKnown(service)) // wellknown options
        );
        this.logger = shared.getLogger(this.options, {
            component: this.options.component || 'smtp-transport'
        });
        this.name = 'SMTP';
        this.version = packageData.version + '[client:' + packageData.version + ']';
        if (this.options.auth) {
            this.auth = this.getAuth({});
        }
    }
    /**
     * Placeholder function for creating proxy sockets. This method immediatelly returns
     * without a socket
     *
     * @param options Connection options
     * @param callback Callback function to run with the socket keys
     */
    getSocket(options, callback) {
        // return immediatelly
        setImmediate(() => callback(null, false));
    }
    getAuth(authOpts) {
        if (!authOpts) {
            if (this.auth && this.auth.oauth2 && this.mailer) {
                // Transport-level auth is resolved in the constructor, before the Mail wrapper
                // assigns `this.mailer`, so a provision callback registered with
                // `transporter.set('oauth2_provision_cb', ...)` has to be re-checked here
                this.auth.oauth2.provisionCallback = this.mailer.get('oauth2_provision_cb') || this.auth.oauth2.provisionCallback;
            }
            return this.auth;
        }
        const authData = Object.assign({}, this.options.auth && typeof this.options.auth === 'object' ? this.options.auth : {});
        if (typeof authOpts === 'object') {
            // see MESSAGE_AUTH_KEYS
            shared.copyOwnKeys(authData, authOpts, key => !MESSAGE_AUTH_KEYS.includes(key));
        }
        if (Object.keys(authData).length === 0) {
            return false;
        }
        switch ((authData.type || '').toString().toUpperCase()) {
            case 'OAUTH2': {
                if (!authData.service && !authData.user) {
                    return false;
                }
                const oauth2 = new XOAuth2(authData, this.logger);
                oauth2.provisionCallback = (this.mailer && this.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback;
                oauth2.on('token', (token) => this.mailer.emit('token', token));
                oauth2.on('error', err => this.emit('error', err));
                return {
                    type: 'OAUTH2',
                    user: authData.user,
                    oauth2,
                    method: 'XOAUTH2'
                };
            }
            default:
                return {
                    type: (authData.type || '').toString().toUpperCase() || 'LOGIN',
                    user: authData.user,
                    credentials: {
                        user: authData.user || '',
                        pass: authData.pass,
                        options: authData.options
                    },
                    method: (authData.method || '').trim().toUpperCase() || this.options.authMethod || false
                };
        }
    }
    /**
     * Sends an e-mail using the selected settings
     *
     * @param mail Mail object
     * @param callback Callback function
     */
    send(mail, callback) {
        const signal = mail.data.signal;
        let returned = false;
        let connection;
        let perCallAuth;
        const cleanupPerCallAuth = () => {
            if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
                perCallAuth.oauth2.removeAllListeners();
            }
            perCallAuth = null;
        };
        const finish = (err, info) => {
            if (returned) {
                return;
            }
            returned = true;
            signal?.removeEventListener('abort', onAbort);
            cleanupPerCallAuth();
            connection?.close();
            callback(err, info);
        };
        function onAbort() {
            finish(errors.createAbortError(signal));
        }
        if (signal) {
            signal.addEventListener('abort', onAbort, { once: true });
            if (signal.aborted) {
                setImmediate(onAbort);
                return;
            }
        }
        // the proxy handshake, if any, counts against connectionTimeout as well
        const connectStartedAt = Date.now();
        this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
            if (returned) {
                socketOptions && socketOptions.connection?.destroy();
                return;
            }
            if (err) {
                return finish(err);
            }
            let options = this.options;
            if (socketOptions && socketOptions.connection) {
                this.logger.info({
                    tnx: 'proxy',
                    remoteAddress: socketOptions.connection.remoteAddress,
                    remotePort: socketOptions.connection.remotePort,
                    destHost: options.host || '',
                    destPort: options.port || '',
                    action: 'connected'
                }, 'Using proxied socket from %s:%s to %s:%s', socketOptions.connection.remoteAddress, socketOptions.connection.remotePort, options.host || '', options.port || '');
                // only copy options if we need to modify it
                options = Object.assign(shared.assign(false, options), socketOptions);
            }
            const smtp = (connection = new SMTPConnection(options));
            smtp._connectStartedAt = connectStartedAt;
            smtp.once('error', err => finish(err));
            const sendMessage = () => {
                const envelope = mail.message.getEnvelope();
                const messageId = mail.message.messageId();
                const recipients = [].concat(envelope.to || []);
                if (recipients.length > 3) {
                    recipients.push('...and ' + recipients.splice(2).length + ' more');
                }
                if (mail.data.dsn) {
                    envelope.dsn = mail.data.dsn;
                }
                // RFC 8689: Pass requireTLSExtensionEnabled to envelope for MAIL FROM parameter
                if (mail.data.requireTLSExtensionEnabled) {
                    envelope.requireTLSExtensionEnabled = mail.data.requireTLSExtensionEnabled;
                }
                this.logger.info({
                    tnx: 'send',
                    messageId
                }, 'Sending message %s to <%s>', messageId, recipients.join(', '));
                smtp.send(envelope, mail.message.createReadStream(), (err, info) => {
                    if (returned) {
                        // the connection error handler has already reported this send
                        return;
                    }
                    if (err) {
                        this.logger.error({
                            err,
                            tnx: 'send'
                        }, 'Send error for %s: %s', messageId, err.message);
                        return finish(err);
                    }
                    info.envelope = {
                        from: envelope.from,
                        to: envelope.to
                    };
                    info.messageId = messageId;
                    try {
                        return finish(null, info);
                    }
                    catch (E) {
                        this.logger.error({
                            err: E,
                            tnx: 'callback'
                        }, 'Callback error for %s: %s', messageId, E.message);
                    }
                });
            };
            smtp.connect(err => {
                if (returned) {
                    return;
                }
                if (err) {
                    // the server closed the connection before the greeting
                    return finish(err);
                }
                perCallAuth = this.getAuth(mail.data.auth);
                if (perCallAuth && (smtp.allowsAuth || options.forceAuth)) {
                    smtp.login(perCallAuth, err => {
                        cleanupPerCallAuth();
                        if (returned) {
                            return;
                        }
                        if (err) {
                            return finish(err);
                        }
                        sendMessage();
                    });
                }
                else {
                    sendMessage();
                }
            });
        });
    }
    verify(callback) {
        let promise;
        if (!callback) {
            promise = new Promise((resolve, reject) => {
                callback = shared.callbackPromise(resolve, reject);
            });
        }
        // the error paths hand over the error alone
        const done = callback;
        // the proxy handshake, if any, counts against connectionTimeout as well
        const connectStartedAt = Date.now();
        this.getSocket(Object.assign({}, this.options, { connectStartedAt }), (err, socketOptions) => {
            if (err) {
                return done(err);
            }
            let options = this.options;
            if (socketOptions && socketOptions.connection) {
                this.logger.info({
                    tnx: 'proxy',
                    remoteAddress: socketOptions.connection.remoteAddress,
                    remotePort: socketOptions.connection.remotePort,
                    destHost: options.host || '',
                    destPort: options.port || '',
                    action: 'connected'
                }, 'Using proxied socket from %s:%s to %s:%s', socketOptions.connection.remoteAddress, socketOptions.connection.remotePort, options.host || '', options.port || '');
                options = Object.assign(shared.assign(false, options), socketOptions);
            }
            const connection = new SMTPConnection(options);
            connection._connectStartedAt = connectStartedAt;
            let returned = false;
            let perCallAuth;
            const cleanupPerCallAuth = () => {
                if (perCallAuth && perCallAuth !== this.auth && perCallAuth.oauth2) {
                    perCallAuth.oauth2.removeAllListeners();
                }
                perCallAuth = null;
            };
            connection.once('error', err => {
                if (returned) {
                    return;
                }
                returned = true;
                cleanupPerCallAuth();
                connection.close();
                return done(err);
            });
            connection.once('end', () => {
                if (returned) {
                    return;
                }
                returned = true;
                cleanupPerCallAuth();
                return done(new Error('Connection closed'));
            });
            const finalize = () => {
                if (returned) {
                    return;
                }
                returned = true;
                cleanupPerCallAuth();
                connection.quit();
                return done(null, true);
            };
            connection.connect(err => {
                if (returned) {
                    return;
                }
                if (err) {
                    returned = true;
                    connection.close();
                    return done(err);
                }
                perCallAuth = this.getAuth({});
                if (perCallAuth && (connection.allowsAuth || options.forceAuth)) {
                    connection.login(perCallAuth, err => {
                        cleanupPerCallAuth();
                        if (returned) {
                            return;
                        }
                        if (err) {
                            returned = true;
                            connection.close();
                            return done(err);
                        }
                        finalize();
                    });
                }
                else if (!perCallAuth && connection.allowsAuth && options.forceAuth) {
                    const err = new Error('Authentication info was not provided');
                    err.code = errors.ENOAUTH;
                    returned = true;
                    cleanupPerCallAuth();
                    connection.close();
                    return done(err);
                }
                else {
                    finalize();
                }
            });
        });
        return promise;
    }
    /**
     * Releases resources
     */
    close() {
        if (this.auth && this.auth.oauth2) {
            this.auth.oauth2.removeAllListeners();
        }
        this.emit('close');
    }
}
export default SMTPTransport;