// Accounts 1.9.0 (docs/APP-1.0-PLAN.md ยง8): the church's email and WhatsApp settings for a product // that sends with them (messaging.get, messaging.changed), and the WhatsApp opt-out for every // product (whatsapp.optout, Accounts' own WAWP webhook, turning WhatsApp back on). import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import { after, before, beforeEach, describe, test } from 'node:test'; import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH, messagingChangedSchema, messagingGetReplySchema, userUpdatedSchema } from '@crosscode/contracts'; import { LINK_HEADERS, openLinkValue, signedHeaders } from '@crosscode/contracts/signing'; import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js'; import type { MemoryMessenger } from '../src/lib/messages.js'; import { runDue } from '../src/links/deliveries.js'; import { messagingChanged } from '../src/links/messaging.js'; import { handleWhatsappWebhook, whatsappWebhookUrl } from '../src/links/whatsappWebhook.js'; import { isStopKeyword, phoneFromChatId } from '../src/accounts/whatsapp.js'; let h: Harness; let messenger: MemoryMessenger; before(async () => { h = await startHarness(); messenger = h.messenger as MemoryMessenger; }); after(async () => { await h.close(); }); beforeEach(async () => { h.received.length = 0; messenger.whatsappOn = true; messenger.whatsapps.length = 0; await h.db.delivery.deleteMany({}); }); /** A request from the harness's linked product (signed with its link's secret). */ async function ask(body: Record) { const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body }); const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: PRODUCT_ID, secret: h.linkSecret, rawBody: raw }) } }); return { status: res.status, body: (await res.json()) as Record }; } const sent = (path: string) => h.received.filter((r) => r.path === path).map((r) => JSON.parse(r.body) as Record); describe('messaging.get', () => { test('nothing set up: both parts null', async () => { const r = await ask({ type: 'messaging.get' }); assert.equal(r.status, 200, JSON.stringify(r.body)); assert.ok(messagingGetReplySchema.safeParse(r.body).success); assert.equal(r.body.email, null); assert.equal(r.body.whatsapp, null); }); test('gives the settings with the password and token sealed for this link only, and never keeps the reply', async () => { await h.ctx.settings.setMany({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_user: 'hello@hope.test', smtp_pass: 'mail-pass', smtp_from: 'hello@hope.test', wawp_access_token: 'wa-token', wawp_instance_id: 'HOPE01' }); const r = await ask({ type: 'messaging.get' }); assert.equal(r.status, 200, JSON.stringify(r.body)); const reply = messagingGetReplySchema.parse(r.body); assert.equal(reply.email?.host, 'smtp.hope.test'); assert.equal(reply.email?.user, 'hello@hope.test'); assert.notEqual(reply.email?.pass, 'mail-pass'); assert.equal(openLinkValue(h.linkSecret, reply.email!.pass!), 'mail-pass'); assert.equal(openLinkValue(h.linkSecret, reply.whatsapp!.accessToken), 'wa-token'); assert.equal(reply.whatsapp?.instanceId, 'HOPE01'); assert.doesNotMatch(JSON.stringify(r.body), /mail-pass|wa-token/); const link = await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } }); assert.ok(link?.messagingWantedAt, 'remembered as wanting messaging.changed'); assert.equal((await h.db.productRequest.findMany({ where: { type: 'messaging.get' } })).length, 0); }); }); describe('messaging.changed', () => { test('an admin changing WhatsApp tells the products that asked', async () => { await ask({ type: 'messaging.get' }); await messagingChanged(h.ctx, { email: false, whatsapp: true }); await runDue(h.ctx); const calls = sent(MESSAGING_CHANGED_PATH); assert.equal(calls.length, 1); assert.ok(messagingChangedSchema.safeParse(calls[0]).success); assert.equal(calls[0]!.whatsapp, true); assert.equal(calls[0]!.email, false); assert.ok(h.received.find((x) => x.path === MESSAGING_CHANGED_PATH && h.signedByLink(x)), 'signed with the link'); assert.ok(await h.ctx.settings.get('messaging_updated_at')); }); test('not to the product that made the change, nor for unrelated settings', async () => { await ask({ type: 'messaging.get' }); await messagingChanged(h.ctx, { email: true, whatsapp: false }, PRODUCT_ID); await messagingChanged(h.ctx, { email: false, whatsapp: false }); await runDue(h.ctx); assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0); }); test('a product that never asked isn\'t told', async () => { await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { messagingWantedAt: null } }); await messagingChanged(h.ctx, { email: true, whatsapp: true }); await runDue(h.ctx); assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0); }); }); describe('whatsapp.optout', () => { test('opts out every account with the number, turns WhatsApp news off and tells the products', async () => { const a = await h.makeAccount({ email: 'stop1@hope.test', phone: '+27825550001', phoneVerified: true, newsWhatsApp: true }); const r = await ask({ type: 'whatsapp.optout', phone: '+27825550001', receivedAt: new Date().toISOString(), keyword: 'STOP' }); assert.equal(r.status, 200, JSON.stringify(r.body)); assert.equal(r.body.accounts, 1); const after = (await h.db.account.findUnique({ where: { id: a.id } }))!; assert.equal(after.whatsappOptedOut, true); assert.equal(after.newsWhatsApp, false); await runDue(h.ctx); const updated = h.received.map((x) => JSON.parse(x.body) as Record).find((b) => b.type === 'user.updated' && b.sub === a.id); assert.ok(updated, 'user.updated sent'); assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, true); }); test('keeps a number without an account: an account made with it later starts opted out', async () => { const r = await ask({ type: 'whatsapp.optout', phone: '+27825550002', receivedAt: new Date().toISOString(), keyword: 'STOP' }); assert.equal(r.body.accounts, 0); const ensured = await ask({ type: 'people.ensure', name: 'Later Person', email: 'later@hope.test', phone: '+27825550002', returnUrl: `${h.productUrl}/` }); assert.equal(ensured.status, 200, JSON.stringify(ensured.body)); const a = (await h.db.account.findUnique({ where: { id: ensured.body.sub as string } }))!; assert.equal(a.whatsappOptedOut, true); }); test('a code for someone who replied STOP goes by email, never WhatsApp', async () => { await h.makeAccount({ email: 'stop3@hope.test', password: 'Correct-horse-1', phone: '+27825550003', twoFactorMethod: 'whatsapp', whatsappOptedOut: true }); const r = await h.signIn(new Browser(), 'stop3@hope.test', 'Correct-horse-1'); assert.ok('pending' in r); assert.equal(r.pending.stage, 'two_factor'); assert.match(String(r.pending.sentTo), /@hope\.test$/); assert.equal(messenger.whatsapps.filter((w) => w.to === '+27825550003').length, 0); }); }); describe('Accounts\' own WAWP webhook', () => { const message = (from: string, body: string, fromMe = false) => ({ event: 'message', payload: { from, body, fromMe } }); test('reads STOP and phone numbers as Cross Events does', () => { for (const s of ['STOP', ' stop ', 'Stop!', 'unsubscribe', 'STOPP', 'opt out']) assert.ok(isStopKeyword(s), s); for (const s of ['stop the music', 'please stop', '', 'STOPPED']) assert.ok(!isStopKeyword(s), s); assert.equal(phoneFromChatId('27825550004@c.us'), '+27825550004'); assert.equal(phoneFromChatId('1234567890-123@g.us'), null); assert.equal(phoneFromChatId('12345@lid'), null); }); test('ignores a call without the secret', async () => { const { url } = await whatsappWebhookUrl(h.ctx); assert.match(url, /\/api\/v2\/webhooks\/whatsapp\?secret=/); await h.makeAccount({ email: 'stop4@hope.test', phone: '+27825550004' }); assert.equal(await handleWhatsappWebhook(h.ctx, { secret: 'wrong' }, message('27825550004@c.us', 'STOP')), 'ignored'); const res = await fetch(`${h.publicUrl}/api/v2/webhooks/whatsapp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550004@c.us', 'STOP')) }); assert.equal(res.status, 200); assert.equal((await h.db.account.findUnique({ where: { email: 'stop4@hope.test' } }))!.whatsappOptedOut, false); }); test('a STOP through the real address opts the number out and answers once', async () => { const { url } = await whatsappWebhookUrl(h.ctx); await h.makeAccount({ email: 'stop5@hope.test', phone: '+27825550005' }); const path = url.slice(url.indexOf('/api/')); const res = await fetch(`${h.publicUrl}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550005@c.us', 'Stop')) }); assert.equal(res.status, 200); assert.equal((await h.db.account.findUnique({ where: { email: 'stop5@hope.test' } }))!.whatsappOptedOut, true); assert.ok(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550005' } })); const replies = messenger.whatsapps.filter((w) => w.to === '+27825550005'); assert.equal(replies.length, 1); assert.match(replies[0]!.text, /won't get WhatsApp messages from Hope Family Church/); assert.ok((await whatsappWebhookUrl(h.ctx)).lastSeenAt); }); test('other messages, and the church\'s own, change nothing', async () => { const { url } = await whatsappWebhookUrl(h.ctx); const secret = new URL(url).searchParams.get('secret'); await h.makeAccount({ email: 'stop6@hope.test', phone: '+27825550006' }); assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'Thanks!')), 'seen'); assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'STOP', true)), 'seen'); assert.equal((await h.db.account.findUnique({ where: { email: 'stop6@hope.test' } }))!.whatsappOptedOut, false); }); }); describe('turning WhatsApp back on', () => { test('on the account page: every product may send it again, and the number\'s STOP is forgotten', async () => { await ask({ type: 'whatsapp.optout', phone: '+27825550007', receivedAt: new Date().toISOString(), keyword: 'STOP' }); const a = await h.makeAccount({ email: 'stop7@hope.test', password: 'Correct-horse-1', phone: '+27825550007', whatsappOptedOut: true, whatsappOptedOutAt: new Date() }); const browser = new Browser(); const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin'); const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'stop7@hope.test', password: 'Correct-horse-1' }); assert.equal(step.body.stage, 'done', JSON.stringify(step.body)); await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account'); const me = await h.api(browser, 'GET', '/api/v2/me'); assert.equal(me.body.whatsappOptedOut, true); // News on WhatsApp can't be ticked while it's off. await h.api(browser, 'PUT', '/api/v2/me/news', { email: false, whatsapp: true }); assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.newsWhatsApp, false); const on = await h.api(browser, 'POST', '/api/v2/me/whatsapp-on'); assert.equal(on.status, 200, JSON.stringify(on.body)); assert.equal(on.body.whatsappOptedOut, false); assert.equal(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550007' } }), null); await runDue(h.ctx); const updated = h.received.map((x) => JSON.parse(x.body) as Record).filter((b) => b.type === 'user.updated' && b.sub === a.id).at(-1); assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, false); }); });