Events 3.1.0, Accounts 1.2.0, contracts 1.9.0: the move needs Accounts' email

A church moved sign-in to Accounts without email set up there: codes and
password links couldn't be sent, sign-in failed with a 500, nobody could
get in.

- contracts 1.9.0: messaging.status/test/set (SMTP, WAWP; secrets sealed);
  people.ensure answers emailSent.
- Accounts 1.2.0: SendError instead of a 500; WhatsApp codes fall back to
  email; forgot password says email isn't set up; setup only offers
  methods that work; messaging.* (test, save only what worked); test
  WhatsApp in admin; WAWP from .env.
- Events 3.1.0: Settings -> Sign-in shows what Accounts can send and
  copies this site's SMTP/WAWP into it (secrets stay on the server), test
  then save; Move disabled and refused (EMAIL_NOT_READY) without email.
Tests: Accounts 54, contracts 218, Events 774, test:accounts 16 (also on
Postgres).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 21:41:31 +02:00
co-authored by Claude Opus 5.5
parent 4b28fc485b
commit cc18b7b514
44 changed files with 2568 additions and 51 deletions
@@ -0,0 +1,85 @@
/**
* Email and WhatsApp for the church's Accounts (3.1.0). Accounts sends its own sign-in codes and
* password links, with its own settings, which a move doesn't bring along: a church that moved
* sign-in without them couldn't sign in at all. Settings → Sign-in therefore shows what Accounts can
* send, offers this site's own SMTP and WAWP settings to copy (the password and token stay on the
* server: blank means "use this site's"), tests them through Accounts, and saves them there only
* once the test worked (`crosscode.identity-request/1` messaging.*, contracts 1.9.0). The move
* itself needs Accounts' email to work (move.ts).
*/
import type { MessagingStatusReply, MessagingTestReply } from '@crosscode/contracts';
import { accounts } from './client';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
const whatsapp = require('../utils/whatsapp') as { getConfig(): Promise<{ token: string; instanceId: string }> };
/* eslint-enable @typescript-eslint/no-require-imports */
type Smtp = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
/** This site's SMTP settings, as utils/email.js reads them (the database, then the .env). */
async function eventsSmtp(): Promise<Smtp | null> {
const env = process.env;
const host = await getSetting('smtp_host', env.SMTP_HOST || env.EMAIL_HOST || '');
if (!host) return null;
const port = parseInt(await getSetting('smtp_port', env.SMTP_PORT || env.EMAIL_PORT || '587'), 10) || 587;
return {
host,
port,
secure: String(await getSetting('smtp_secure', env.SMTP_SECURE || env.EMAIL_SECURE || 'false')).toLowerCase() === 'true',
user: await getSetting('smtp_user', env.SMTP_USER || env.EMAIL_USER || ''),
pass: await getSetting('smtp_pass', env.SMTP_PASS || env.EMAIL_PASS || ''),
from: await getSetting('smtp_from', env.MAIL_FROM || env.EMAIL_FROM || ''),
};
}
/** What this site has, to offer for copying: never the password or token themselves. */
export async function eventsMessaging() {
const smtp = await eventsSmtp();
const wa = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
return {
email: smtp ? { host: smtp.host, port: smtp.port, secure: smtp.secure, user: smtp.user, from: smtp.from || smtp.user, hasPass: !!smtp.pass } : null,
whatsapp: wa.instanceId ? { instanceId: wa.instanceId, hasToken: !!wa.token } : null,
};
}
/** What Accounts can send now. */
export async function accountsMessaging(): Promise<Omit<MessagingStatusReply, 'schema'>> {
const r = await (await accounts()).request<MessagingStatusReply>({ type: 'messaging.status', actor: null });
return { email: r.email, whatsapp: r.whatsapp };
}
export type MessagingInput = {
email?: { host: string; port: number; secure: boolean; user: string; from: string; pass?: string | null; to: string };
whatsapp?: { instanceId: string; accessToken?: string | null; to: string };
};
/**
* Tests (and with `save`, saves) settings in Accounts. A blank password or token means this site's
* own; Accounts gets it sealed with the link's secret. Returns Accounts' answer per part.
*/
export async function sendToAccounts(input: MessagingInput, opts: { save: boolean; actor: string | null }): Promise<Omit<MessagingTestReply, 'schema'>> {
const auth = await accounts();
let email;
if (input.email) {
const own = await eventsSmtp();
const pass = input.email.pass ? input.email.pass : (own?.pass ?? '');
email = {
settings: { host: input.email.host.trim(), port: input.email.port, secure: input.email.secure, user: input.email.user.trim(), from: input.email.from.trim(), pass: pass ? auth.seal(pass) : null },
to: input.email.to.trim(),
};
}
let wa;
if (input.whatsapp) {
const own = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
const token = input.whatsapp.accessToken ? input.whatsapp.accessToken : own.token;
wa = { settings: { instanceId: input.whatsapp.instanceId.trim(), accessToken: token ? auth.seal(token) : null }, to: input.whatsapp.to.trim() };
}
const r = await auth.request<MessagingTestReply>({
type: opts.save ? 'messaging.set' : 'messaging.test',
actor: opts.actor,
...(email ? { email } : {}),
...(wa ? { whatsapp: wa } : {}),
}, { timeoutMs: 60000 });
return { email: r.email, whatsapp: r.whatsapp, status: r.status };
}
+15
View File
@@ -17,6 +17,7 @@ import crypto from 'node:crypto';
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, accountsLink, AccountsUnavailable } from './client';
import { accountsMessaging } from './messaging';
import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
@@ -159,6 +160,8 @@ export type CheckResult = {
admins: { id: string; name: string; email: string }[];
noticeConflict: { accountsVersions: number[]; eventsVersions: number[] } | null;
withTwoFactor: number;
/** 3.1.0: what Accounts can send. The move needs email (codes and password links); WhatsApp codes go by email when WhatsApp can't. */
messaging: { email: boolean; whatsapp: boolean; whatsappTwoFactor: number };
};
async function connected() {
@@ -199,9 +202,15 @@ export async function check(): Promise<CheckResult> {
admins: people.filter((p) => p.role === 'admin').map((p) => ({ id: p.id, name: p.name, email: p.email })),
noticeConflict: !begin.noticesTaken && eventsNotices.length ? { accountsVersions: begin.accountsNoticeVersions, eventsVersions: eventsNotices.map((n) => n.version - 1) } : null,
withTwoFactor: people.filter((p) => p.twoFactorEnabled).length,
messaging: await messagingNow(people),
};
}
async function messagingNow(people: Row[]) {
const status = await accountsMessaging();
return { email: status.email.ready, whatsapp: status.whatsapp.ready, whatsappTwoFactor: people.filter((p) => p.twoFactorEnabled && p.twoFactorMethod === 'whatsapp').length };
}
export type MoveReport = {
movedAt: string;
by: string;
@@ -262,6 +271,12 @@ export async function moveNewPeople(actor: string | null = null): Promise<{ move
/** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */
export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise<MoveReport> {
const auth = await connected();
// 3.1.0: without email in Accounts nobody can get a code or a password link there, so nobody
// could sign in after the move. Set it up first (Settings → Sign-in → Email and WhatsApp).
const messaging = await accountsMessaging();
if (!messaging.email.ready) {
throw new MoveError("The church's Accounts can't send email yet, so people couldn't get their sign-in codes or password links there. Set up its email first (copy this site's, test it, save it), then move.", 'EMAIL_NOT_READY');
}
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) throw new MoveError('A move is already running.', 'RUNNING');
await setSetting(RUNNING_KEY, new Date().toISOString());
@@ -5,6 +5,7 @@ import { single } from '../paging';
import { authMode } from '../../accounts/mode';
import { check, move, MoveError, status, undo } from '../../accounts/move';
import { accounts, accountsLink, AccountsUnavailable } from '../../accounts/client';
import { accountsMessaging, eventsMessaging, sendToAccounts } from '../../accounts/messaging';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../../config/db');
@@ -94,6 +95,7 @@ export const signInCheck = defineRoute({
admins: z.array(person.extend({ id: z.string() })),
noticeConflict: z.object({ accountsVersions: z.array(z.number()), eventsVersions: z.array(z.number()) }).nullable(),
withTwoFactor: z.number().int(),
messaging: z.object({ email: z.boolean(), whatsapp: z.boolean(), whatsappTwoFactor: z.number().int() }).describe('3.1.0: what Accounts can send; the move needs email'),
})),
async handler() {
return { data: await check().catch(asApiError) };
@@ -132,6 +134,103 @@ export const signInUndo = defineRoute({
},
});
// ─── Email and WhatsApp for Accounts (3.1.0) ────────────────────────────────
const messagingOverview = z.object({
events: z.object({
email: z.object({ host: z.string(), port: z.number().int(), secure: z.boolean(), user: z.string(), from: z.string(), hasPass: z.boolean() }).nullable(),
whatsapp: z.object({ instanceId: z.string(), hasToken: z.boolean() }).nullable(),
}).describe("This site's own settings, to copy (never the password or token)"),
accounts: z.object({
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
}).nullable().describe("What the church's Accounts can send (null: it can't be reached)"),
accountsError: z.string().nullable(),
});
export const signInMessaging = defineRoute({
method: 'get',
path: '/settings/sign-in/messaging',
tag: 'Accounts',
summary: "Email and WhatsApp: this site's, and what Accounts can send",
access: 'admin',
response: single(messagingOverview),
async handler() {
const events = await eventsMessaging();
try {
return { data: { events, accounts: await accountsMessaging(), accountsError: null } };
} catch (e) {
return { data: { events, accounts: null, accountsError: (e as Error).message } };
}
},
});
/** 082 123 4567 → +27821234567 (as Accounts keeps phone numbers). */
const toE164 = (raw: string) => {
const d = raw.replace(/\D/g, '');
if (raw.trim().startsWith('+')) return `+${d}`;
return d.startsWith('0') && d.length === 10 ? `+27${d.slice(1)}` : `+${d}`;
};
const messagingBody = z.object({
email: z.object({
host: z.string().trim().min(1).max(253),
port: z.number().int().min(1).max(65535),
secure: z.boolean(),
user: z.string().max(254),
from: z.string().trim().min(3).max(320),
pass: z.string().max(500).nullable().optional().describe("Blank: this site's own password"),
to: z.email().describe('Where the test email goes'),
}).optional(),
whatsapp: z.object({
instanceId: z.string().trim().min(1).max(200),
accessToken: z.string().max(500).nullable().optional().describe("Blank: this site's own token"),
to: z.string().trim().min(8).max(30).describe('The phone the test message goes to'),
}).optional(),
});
const messagingResult = z.object({ ok: z.boolean(), error: z.string().nullable(), saved: z.boolean() }).nullable();
const messagingAnswer = single(z.object({ email: messagingResult, whatsapp: messagingResult, status: z.object({ email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }), whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }) }) }));
async function messagingFor(body: z.infer<typeof messagingBody>, user: { id: string; role: string }, req: unknown, save: boolean) {
if (!body.email && !body.whatsapp) throw new ApiError('VALIDATION_FAILED', 'Give email or WhatsApp settings.');
const actor = (await prisma.user.findUnique({ where: { id: user.id }, select: { accountId: true } }))?.accountId ?? null;
const input = { ...(body.email ? { email: body.email } : {}), ...(body.whatsapp ? { whatsapp: { ...body.whatsapp, to: toE164(body.whatsapp.to) } } : {}) };
const out = await sendToAccounts(input, { save, actor }).catch(asApiError);
if (save) {
await logAdminAction({ actorId: user.id, actorRole: user.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_messaging', metadata: { email: out.email && { ok: out.email.ok, saved: out.email.saved, host: body.email?.host }, whatsapp: out.whatsapp && { ok: out.whatsapp.ok, saved: out.whatsapp.saved } }, ip: getClientIp(req) });
}
return { data: out };
}
export const signInMessagingTest = defineRoute({
method: 'post',
path: '/settings/sign-in/messaging/test',
tag: 'Accounts',
summary: 'Test email / WhatsApp settings through Accounts (nothing saved)',
description: "Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.",
access: 'admin',
body: messagingBody,
response: messagingAnswer,
async handler({ body, user, req }) {
return messagingFor(body, user!, req, false);
},
});
export const signInMessagingSave = defineRoute({
method: 'post',
path: '/settings/sign-in/messaging',
tag: 'Accounts',
summary: 'Save email / WhatsApp settings in Accounts (after a test)',
description: 'Accounts tests each part as /test does, and saves it only if its test worked.',
access: 'admin',
body: messagingBody,
response: messagingAnswer,
async handler({ body, user, req }) {
return messagingFor(body, user!, req, true);
},
});
// ─── An admin, for someone's account (sign-in through Accounts) ─────────────
const idParams = z.object({ id: z.uuid() });