Files
crosscode-platform/apps/accounts/backend/src/lib/messages.ts
T
joshuaandClaude Opus 5.5 bbcafe61b9 Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:02 +02:00

165 lines
7.1 KiB
TypeScript

/**
* 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<void>;
whatsapp(msg: WhatsApp): Promise<void>;
/** Whether email is set up (sign-in codes, password links and new accounts need it). */
emailReady(): Promise<boolean>;
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
whatsappReady(): Promise<boolean>;
/** Sends one email with settings that aren't saved (a test before saving them). Throws why it failed. */
emailWith(settings: SmtpTry, msg: Email): Promise<void>;
/** Sends one WhatsApp message with settings that aren't saved. Throws why it failed. */
whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void>;
}
/** 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<Ctx, 'settings' | 'config'>) {}
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<void> {
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<boolean> {
return !!(await this.smtp());
}
private async wawp(): Promise<WawpTry | null> {
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<boolean> {
return !!(await this.wawp());
}
async whatsapp(msg: WhatsApp): Promise<void> {
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<void> {
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<void> {
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;
}
}