/** * Email (SMTP, from the admin's settings or the server's .env) and WhatsApp (WAWP, as Cross * Events). In tests a `MemoryMessenger` keeps what would have been sent. */ import nodemailer from 'nodemailer'; import type { Ctx } from '../context.js'; /** `html` (1.4.0, src/lib/emails.ts): the styled version; `text` is always sent too. */ export type Email = { to: string; subject: string; text: string; html?: string }; export type WhatsApp = { to: string; text: string }; /** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */ export type SmtpTry = { host: string; port: number; secure: boolean; user: string; pass: string; from: string }; /** WAWP settings to try before saving them (1.2.0). */ export type WawpTry = { accessToken: string; instanceId: string }; export interface Messenger { email(msg: Email): Promise; whatsapp(msg: WhatsApp): Promise; /** Whether email is set up (sign-in codes, password links and new accounts need it). */ emailReady(): Promise; /** Whether WhatsApp is set up, so it's offered as a 2FA method. */ whatsappReady(): Promise; /** Sends one email with settings that aren't saved (a test before saving them). Throws why it failed. */ emailWith(settings: SmtpTry, msg: Email): Promise; /** Sends one WhatsApp message with settings that aren't saved. Throws why it failed. */ whatsappWith(settings: WawpTry, msg: WhatsApp): Promise; } /** Thrown when a message can't be sent: the sign-in pages show it instead of failing. */ export class SendError extends Error { status = 503; constructor(message: string, public code = 'NOT_SENT') { super(message); } } function transportFor(s: SmtpTry) { return nodemailer.createTransport({ host: s.host, port: s.port, secure: s.secure, auth: s.user ? { user: s.user, pass: s.pass } : undefined, connectionTimeout: 15000, greetingTimeout: 15000, socketTimeout: 20000, }); } async function wawpSend(s: WawpTry, msg: WhatsApp) { const number = waNumber(msg.to); if (!number) throw new Error('That isn\'t a WhatsApp number.'); const res = await fetch('https://api.wawp.net/v2/send/text', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ access_token: s.accessToken, instance_id: s.instanceId, chatId: `${number}@c.us`, message: msg.text }), signal: AbortSignal.timeout(15000), }); if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`); } /** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */ export function waNumber(raw: string): string | null { let d = String(raw || '').replace(/\D/g, ''); if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`; return d.length >= 10 && d.length <= 15 ? d : null; } export class LiveMessenger implements Messenger { constructor(private readonly ctx: Pick) {} private async smtp() { const s = this.ctx.settings; const host = (await s.get('smtp_host')) || this.ctx.config.smtp?.host; if (!host) return null; const port = Number((await s.get('smtp_port')) || this.ctx.config.smtp?.port || 587); return { transport: nodemailer.createTransport({ host, port, secure: (await s.get('smtp_secure')) === 'true' || (this.ctx.config.smtp?.secure ?? port === 465), auth: { user: (await s.get('smtp_user')) || this.ctx.config.smtp?.user || '', pass: (await s.get('smtp_pass')) || this.ctx.config.smtp?.pass || '' }, }), from: (await s.get('smtp_from')) || this.ctx.config.smtp?.from || '', }; } async email(msg: Email): Promise { const smtp = await this.smtp(); if (!smtp) { if (this.ctx.config.production) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).'); console.log(`[email] (no SMTP) to ${msg.to}: ${msg.subject}\n${msg.text}`); return; } const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name; await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) }); } async emailReady(): Promise { return !!(await this.smtp()); } private async wawp(): Promise { const accessToken = (await this.ctx.settings.get('wawp_access_token')) || this.ctx.config.wawp?.accessToken; const instanceId = (await this.ctx.settings.get('wawp_instance_id')) || this.ctx.config.wawp?.instanceId; return accessToken && instanceId ? { accessToken, instanceId } : null; } async whatsappReady(): Promise { return !!(await this.wawp()); } async whatsapp(msg: WhatsApp): Promise { const s = await this.wawp(); if (!s) throw new Error('WhatsApp isn\'t set up.'); await wawpSend(s, msg); } async emailWith(settings: SmtpTry, msg: Email): Promise { const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name; await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) }); } async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise { await wawpSend(settings, msg); } } export class MemoryMessenger implements Messenger { emails: Email[] = []; whatsapps: WhatsApp[] = []; whatsappOn = false; /** Tests: false makes email fail as an unset SMTP does in production. */ emailOn = true; /** Tests: settings tried with emailWith / whatsappWith, and a host that fails. */ tried: { kind: 'email' | 'whatsapp'; settings: SmtpTry | WawpTry; to: string }[] = []; failHost: string | null = null; async email(msg: Email) { if (!this.emailOn) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).'); this.emails.push(msg); } async whatsapp(msg: WhatsApp) { if (!this.whatsappOn) throw new Error('WhatsApp isn\'t set up.'); this.whatsapps.push(msg); } async emailReady() { return this.emailOn; } async whatsappReady() { return this.whatsappOn; } async emailWith(settings: SmtpTry, msg: Email) { this.tried.push({ kind: 'email', settings, to: msg.to }); if (settings.host === this.failHost) throw new Error(`connect ECONNREFUSED ${settings.host}:${settings.port}`); this.emails.push(msg); } async whatsappWith(settings: WawpTry, msg: WhatsApp) { this.tried.push({ kind: 'whatsapp', settings, to: msg.to }); this.whatsapps.push(msg); } /** The last 6-digit code sent to `to` (tests). */ lastCode(to: string): string | null { const all = [...this.emails.filter((e) => e.to === to).map((e) => e.text), ...this.whatsapps.filter((w) => w.to === to).map((w) => w.text)]; const m = /\b(\d{6})\b/.exec(all[all.length - 1] ?? ''); return m ? m[1]! : null; } /** The last link sent to `to` (tests). */ lastLink(to: string): string | null { const e = this.emails.filter((x) => x.to === to).at(-1); const m = /(https?:\/\/\S+)/.exec(e?.text ?? ''); return m ? m[1]! : null; } }