/** * 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 11): Accounts takes WAWP's webhook itself, for a church * without Cross Events (a WAWP number sends replies to one address; with Events, Events receives * them and passes a STOP on with `whatsapp.optout`). * * POST /api/v2/webhooks/whatsapp?secret=… (WAWP's `message` event) * * WAWP doesn't sign webhooks, so the address carries a secret only Accounts and WAWP know * (Admin → Email and WhatsApp shows it to paste into WAWP). Always answers 200 quickly, so WAWP * never retries; only a STOP from a phone number is acted on. */ import crypto from 'node:crypto'; import express, { type Request, type Response } from 'express'; import type { Ctx } from '../context.js'; import { isStopKeyword, optOutNumber, phoneFromChatId } from '../accounts/whatsapp.js'; export const WHATSAPP_WEBHOOK_PATH = '/api/v2/webhooks/whatsapp'; /** The secret in the webhook's address, made on first use. */ async function webhookSecret(ctx: Ctx): Promise { const saved = await ctx.settings.get('wawp_webhook_secret'); if (saved) return saved; const secret = crypto.randomBytes(24).toString('base64url'); await ctx.settings.set('wawp_webhook_secret', secret); return secret; } /** The address to paste into WAWP's webhook settings (event: message), and when it last called. */ export async function whatsappWebhookUrl(ctx: Ctx) { return { url: `${ctx.config.publicUrl.replace(/\/$/, '')}${WHATSAPP_WEBHOOK_PATH}?secret=${encodeURIComponent(await webhookSecret(ctx))}`, lastSeenAt: await ctx.settings.get('wawp_webhook_last_seen'), }; } function secretMatches(given: string, secret: string) { return given.length === secret.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(secret)); } export async function handleWhatsappWebhook(ctx: Ctx, query: { secret?: unknown }, body: unknown): Promise<'ignored' | 'seen' | 'stopped'> { const secret = await ctx.settings.get('wawp_webhook_secret'); if (!secret || !secretMatches(String(query.secret ?? ''), secret)) return 'ignored'; await ctx.settings.set('wawp_webhook_last_seen', ctx.now().toISOString()); const payload = ((body as { payload?: Record })?.payload ?? {}) as { fromMe?: boolean; body?: unknown; from?: unknown }; if (payload.fromMe || !isStopKeyword(payload.body)) return 'seen'; const phone = phoneFromChatId(payload.from); // Groups, channels and senders WhatsApp only names by a "LID" have no number to opt out. if (!phone) return 'seen'; await optOutNumber(ctx, phone, { keyword: String(payload.body).trim().toUpperCase().slice(0, 40), source: 'accounts', receivedAt: ctx.now() }); // The one message after a STOP: what it did and how to undo it. const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'the church'; await ctx.messenger.whatsapp({ to: phone, text: `You won't get WhatsApp messages from ${church} any more. To turn them back on, go to ${ctx.config.publicUrl.replace(/\/$/, '')}/account.` }) .catch((e: Error) => console.warn('[whatsapp webhook] confirmation not sent:', e.message)); return 'stopped'; } export function whatsappWebhookRouter(ctx: Ctx) { const r = express.Router(); r.post(WHATSAPP_WEBHOOK_PATH, express.json({ limit: '256kb' }), async (req: Request, res: Response) => { try { await handleWhatsappWebhook(ctx, req.query as { secret?: unknown }, req.body); } catch (e) { console.error('[whatsapp webhook]', (e as Error).message); } res.json({ ok: true }); }); return r; }