UNPKG

@wepublish/api

Version:
147 lines 6.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MailgunMailProvider = void 0; const tslib_1 = require("tslib"); const client_1 = require("@prisma/client"); const crypto_1 = tslib_1.__importDefault(require("crypto")); const form_data_1 = tslib_1.__importDefault(require("form-data")); const mail_provider_interface_1 = require("./mail-provider.interface"); const base_mail_provider_1 = require("./base-mail-provider"); function mapMailgunEventToMailLogState(event) { switch (event) { case 'accepted': return client_1.MailLogState.accepted; case 'delivered': return client_1.MailLogState.delivered; case 'failed': return client_1.MailLogState.bounced; case 'rejected': return client_1.MailLogState.rejected; default: return null; } } class MailgunMailProvider extends base_mail_provider_1.BaseMailProvider { constructor(props) { super(props); this.auth = Buffer.from(`api:${props.apiKey}`).toString('base64'); this.baseDomain = props.baseDomain; this.mailDomain = props.mailDomain; this.webhookEndpointSecret = props.webhookEndpointSecret; this.mailgunClient = props.mailgunClient; } verifyWebhookSignature(props) { const encodedToken = crypto_1.default .createHmac('sha256', this.webhookEndpointSecret) .update(props.timestamp.concat(props.token)) .digest('hex'); return encodedToken === props.signature; } webhookForSendMail({ req }) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const { body } = req; if (!body.signature) { throw new Error('No signature in webhook body'); } const { signature, token, timestamp } = body.signature; if (!timestamp || !token || !signature || !this.verifyWebhookSignature({ timestamp, token, signature })) { throw new Error('Webhook signature failed'); } if (!body['event-data']) { throw new Error('No event-data in webhook body'); } if (!body['event-data']['user-variables']) { throw new Error('No user-variables in webhook body'); } const mailLogStatuses = []; const state = mapMailgunEventToMailLogState(body['event-data'].event); const mailLogID = body['event-data']['user-variables'].mail_log_id; if (state !== null && mailLogID !== undefined) { mailLogStatuses.push({ state, mailLogID, mailData: JSON.stringify(body['event-data']) }); } return mailLogStatuses; }); } sendMail(props) { var _a; return tslib_1.__awaiter(this, void 0, void 0, function* () { const form = new form_data_1.default(); form.append('from', this.fromAddress); form.append('to', props.recipient); form.append('subject', props.subject); form.append('text', (_a = props.message) !== null && _a !== void 0 ? _a : ''); if (props.messageHtml) { form.append('html', props.messageHtml); } if (props.template) { form.append('template', props.template); for (const [key, value] of Object.entries(props.templateData || {})) { // Enforce max length of 16kb per key => https://documentation.mailgun.com/en/latest/api-sending.html let serializedValue = ''; if (typeof value === 'number') { serializedValue = value; } else if (typeof value === 'string') { serializedValue = value.substring(0, 15000); } else { serializedValue = JSON.stringify(value).substring(0, 15000); } form.append(`v:${key}`, serializedValue); } } form.append('v:mail_log_id', props.mailLogID); return new Promise((resolve, reject) => { form.submit({ protocol: 'https:', host: this.baseDomain, path: `/v3/${this.mailDomain}/messages`, method: 'POST', headers: { Accept: 'application/json', Authorization: `Basic ${this.auth}` } }, (err, res) => { return err || res.statusCode !== 200 ? reject(err || res) : resolve(); }); }); }); } getTemplates() { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { const response = yield this.mailgunClient.domains.domainTemplates.list(this.mailDomain); const templates = response.items.map(mailTemplateResponse => { return { name: mailTemplateResponse.name, uniqueIdentifier: mailTemplateResponse.name, createdAt: new Date(mailTemplateResponse.createdAt), updatedAt: new Date(mailTemplateResponse.createdAt) }; }); return templates; } catch (e) { if (this.isMailgunApiError(e)) { throw new mail_provider_interface_1.MailProviderError(e.details); } throw new mail_provider_interface_1.MailProviderError(String(e)); } }); } isMailgunApiError(error) { return error.type === 'MailgunAPIError'; } getTemplateUrl(template) { return `https://app.mailgun.com/app/sending/domains/${this.mailDomain}/templates/details/${template.externalMailTemplateId}`; } } exports.MailgunMailProvider = MailgunMailProvider; //# sourceMappingURL=mailgun-mail-provider.js.map