/** * Accounts: sign up, log in (with the 2FA code step) and changing your own details (1.51.2). * Moved from userController.js so /api/users/* (v1) and /api/v2/auth/*, /api/v2/me share it. */ import { v4 as uuidv4 } from 'uuid'; import axios from 'axios'; import { prisma } from '../v2/legacy'; import { fail, ServiceError } from './errors'; /* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */ const auth = require('../config/auth') as { generateToken(id: string, role: string, tokenVersion: number): string; hashPassword(pw: string): Promise; comparePassword(pw: string, hash: string): Promise; needsRehash(hash: string): boolean; }; const twoFactor = require('../utils/twoFactor') as { createChallenge(user: any, purpose: string, method: string): Promise<{ challengeId: string; method: string; destination: string | null }>; verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string; usedRecoveryCode?: boolean }>; recoveryCodesLeft(userId: string): Promise; issueTrustedDevice(userId: string, userAgent?: string): Promise; isTrustedDevice(userId: string, deviceToken?: string): Promise; clearTrustedDevices(userId: string): Promise; requiresTwoFactor(user: { role: string }): boolean; enforcementMethod(user: any): Promise; }; const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise }; const { getSettingSync } = require('../utils/settingsCache') as { getSettingSync(key: string, fallback: string): string }; const whatsapp = () => require('../utils/whatsapp') as { normalizeZAPhone(p: unknown): string | null; isValidZAPhone(p: unknown): boolean }; /** Who is asking, for security notices and the activity log. */ export type RequestInfo = { ip?: string; userAgent?: string }; // Org name for email subjects — falls back to Cross Code (the platform vendor) // rather than any specific customer's name when unconfigured. export function getOrgName(): string { return getSettingSync('org_name', process.env.ORG_NAME || 'Cross Code'); } const PRIVATE_IP_RE = /^(::1|::ffff:127\.|127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/; const frontendUrl = () => (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, ''); /** * Fire-and-forget: create a 24h activation token and deliver it to an inactive account — by * email if it has a real (non-guest) address, otherwise by WhatsApp if it has a phone number. * Used when a login hits an inactive account, and when staff create an account for someone. */ export async function sendActivationLink(user: { id: string; name?: string | null; email?: string | null; phoneNumber?: string | null }): Promise { const hasRealEmail = !!(user?.email && !user.email.endsWith('@guest.local')); if (!hasRealEmail && !user?.phoneNumber) return; // 3.0.0: once sign-in goes through the church's Accounts, Accounts makes (or finds) their account // and emails them a link to choose a password; there's no Events activation any more. if (hasRealEmail && (await (require('../accounts/mode') as typeof import('../accounts/mode')).viaAccounts())) { ensureAccount(user as { id: string; name?: string | null; email: string; phoneNumber?: string | null }) .catch((e: any) => console.warn('[accounts] Could not make the account:', e?.message || e)); return; } try { const token = uuidv4(); const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); await prisma.passwordReset.updateMany({ where: { userId: user.id, used: false }, data: { used: true } }); await prisma.passwordReset.create({ data: { id: uuidv4(), userId: user.id, token, expiresAt, used: false } }); const activationUrl = `${frontendUrl()}/activate-account?token=${encodeURIComponent(token)}`; if (hasRealEmail) { const { sendMail, buildAccountActivationEmail } = require('../utils/email'); const content = buildAccountActivationEmail({ name: user.name, activationUrl }); sendMail({ to: user.email, subject: `Activate your ${getOrgName()} account`, ...content }) .catch((e: any) => console.warn('[activation email] Failed:', e?.message || e)); } else { const orgName = getOrgName(); const waMessage = [ `🔓 *Activate your ${orgName} account*`, '', `Hi ${user.name || 'there'},`, '', 'Your account needs to be activated before you can log in. Tap the link below to set a password and activate your account:', '', activationUrl, '', '_This link expires in 24 hours._', ].join('\n'); const { waTextAny } = require('../utils/notify'); waTextAny(user, waMessage).catch((e: any) => console.warn('[activation WA] Failed:', e?.message || e)); } } catch (e: any) { console.warn('[activation token] Failed to create activation token:', e?.message || e); } } /** Asks Accounts for this person's account (people.ensure) and links it; they can then sign in. */ export async function ensureAccount(user: { id: string; name?: string | null; email: string; phoneNumber?: string | null }): Promise { const { accounts } = require('../accounts/client') as typeof import('../accounts/client'); const { siteUrl } = require('../feed/context') as typeof import('../feed/context'); const { phoneSchema } = require('@crosscode/contracts') as typeof import('@crosscode/contracts'); const phone = user.phoneNumber && phoneSchema.safeParse(user.phoneNumber).success ? user.phoneNumber : null; const r = await (await accounts()).request<{ sub: string; created: boolean }>({ type: 'people.ensure', actor: null, name: (user.name || user.email).slice(0, 200), email: user.email.toLowerCase(), phone, returnUrl: `${(await siteUrl()).replace(/\/+$/, '')}/`, }); const other = await prisma.user.findUnique({ where: { accountId: r.sub }, select: { id: true } }); if (!other) await prisma.user.update({ where: { id: user.id }, data: { accountId: r.sub, isActive: true } }); return r.sub; } // Fire-and-forget: a login notice with the approximate place it came from. async function sendLoginNotification(user: any, info: RequestInfo): Promise { try { const ip = info.ip || 'unknown'; const userAgent = info.userAgent || 'Unknown device'; const when = new Date().toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg' }); let location = 'Unknown location'; if (ip !== 'unknown' && !PRIVATE_IP_RE.test(ip)) { try { const geo = await axios.get(`http://ip-api.com/json/${ip}?fields=status,city,regionName,country`, { timeout: 3000 }); if (geo.data?.status === 'success') { const parts = [geo.data.city, geo.data.regionName, geo.data.country].filter(Boolean); if (parts.length) location = parts.join(', '); } } catch { /* geo lookup failure is non-fatal */ } } const { sendMail, buildLoginNotificationEmail } = require('../utils/email'); const { buildWALogin } = require('../utils/waMessages'); const content = buildLoginNotificationEmail({ name: user.name, when, location, userAgent }); // Security: always email; also WhatsApp if preferred await sendMail({ to: user.email, subject: `New login to your ${getOrgName()} account`, ...content }); const { waText } = require('../utils/notify'); await waText(user, buildWALogin({ name: user.name, when, location, userAgent })).catch(() => {}); } catch (e: any) { console.warn('[login notification] Failed:', e?.message || e); } } /** Fire-and-forget: the welcome email, with the next few upcoming events. */ export async function sendWelcomeEmail(user: any): Promise { try { const events = await prisma.event.findMany({ where: { isActive: true, startDate: { gt: new Date() } }, orderBy: { startDate: 'asc' }, take: 3, select: { title: true, startDate: true }, }); const { sendMail, buildWelcomeEmail } = require('../utils/email'); const { buildWAWelcome } = require('../utils/waMessages'); const content = buildWelcomeEmail({ name: user.name, events }); const { waText } = require('../utils/notify'); // Welcome is always sent via email; also via WhatsApp if preferred await sendMail({ to: user.email, subject: `Welcome to ${getOrgName()}!`, ...content }); await waText(user, buildWAWelcome({ name: user.name, events })).catch(() => {}); } catch (e: any) { console.warn('[welcome email] Failed:', e?.message || e); } } // Fields the login flow needs once the password (and any 2FA code) has checked out. export const LOGIN_USER_SELECT = { id: true, name: true, email: true, role: true, tokenVersion: true, isActive: true, phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, newsAskedAt: true, noticeVersionAccepted: true, } as const; type LoginUser = { id: string; name: string; email: string; role: string; tokenVersion: number; newsAskedAt: Date | null; noticeVersionAccepted: number | null } & Record; export type Session = { id: string; name: string; email: string; role: string; token: string; newsPromptPending: boolean; noticePromptPending: false | 'first' | 'updated'; deviceToken?: string; }; /** * Final step of a successful login (after the password, and the 2FA code when required): * notify, record the activity, and issue the session token. */ export async function completeLogin(user: LoginUser, info: RequestInfo, extra: { deviceToken?: string } = {}): Promise { const noticePromptPending = await (require('../utils/privacyNotice') as { noticePromptPending(u: object): Promise }).noticePromptPending(user).catch(() => false as const); // Retention: logging in keeps the account (and cancels an inactivity warning). prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {}); sendLoginNotification(user, info).catch(() => {}); logSecurityEvent({ userId: user.id, type: 'login', ip: info.ip, userAgent: info.userAgent }).catch(() => {}); return { id: user.id, name: user.name, email: user.email, role: user.role, token: auth.generateToken(user.id, user.role, user.tokenVersion), // POPIA: ask about News & announcements once (NewsPrompt on the frontend), and to accept a // privacy notice version marked as a significant change (NoticePrompt). newsPromptPending: !user.newsAskedAt, noticePromptPending, ...extra, }; } export type SignUpInput = { name: string; email: string; password: string; phoneNumber?: string | null; notificationPreference?: string; newsOptIn?: boolean }; /** A new account (signed in straight away), with the news choice and privacy notice recorded. */ export async function signUp(input: SignUpInput, info: RequestInfo) { const { name, email, password, phoneNumber, notificationPreference, newsOptIn } = input; const { normalizeZAPhone, isValidZAPhone } = whatsapp(); const phone = normalizeZAPhone(phoneNumber) || (phoneNumber ? phoneNumber.replace(/\D/g, '') || null : null); // WhatsApp needs a valid phone number; otherwise quietly use email const allowedPrefs = ['email', 'whatsapp', 'both']; let pref = allowedPrefs.includes(String(notificationPreference)) ? String(notificationPreference) : 'email'; if ((pref === 'whatsapp' || pref === 'both') && !isValidZAPhone(phoneNumber)) pref = 'email'; const userExists = await prisma.user.findFirst({ where: { OR: [{ email }, ...(phone ? [{ phoneNumber: phone }] : [])] } }); if (userExists) fail(409, 'User already exists', undefined, { v1Status: 400 }); const user = await prisma.user.create({ data: { id: uuidv4(), name, email, password: await auth.hashPassword(password), phoneNumber: phone, notificationPreference: pref as 'email' | 'whatsapp' | 'both', updatedAt: new Date() }, }); // POPIA: the sign-up form's (unticked) "news and announcements" box. Recorded either way, // so they aren't asked again at their first login. await require('../utils/privacy').setNewsPreferences( user.id, { email: newsOptIn === true, whatsapp: newsOptIn === true }, { source: 'signup', ip: info.ip, answered: true, logAll: true }, ).catch((e: any) => console.warn('[signup] news preference not saved:', e?.message || e)); // The sign-up form requires ticking "I agree to the Terms of Use and Privacy Policy". await require('../utils/privacyNotice').acceptNotice(user.id, { source: 'signup', ip: info.ip }) .catch((e: any) => console.warn('[signup] notice acceptance not saved:', e?.message || e)); sendWelcomeEmail(user).catch(() => {}); return { id: user.id, name: user.name, email: user.email, role: user.role, token: auth.generateToken(user.id, user.role, user.tokenVersion) }; } export type LoginResult = | { status: 'signed_in'; session: Session } | { status: 'code_required'; challenge: { challengeId: string; method: string; destination: string | null }; enrolling: boolean }; let standIn: Promise | null = null; /** A hash nobody's password matches, so a sign-in with an unknown email does the same work. */ const standInHash = () => (standIn ??= auth.hashPassword(uuidv4())); const MAX_ATTEMPTS = 5; const LOCK_TIME = 5 * 60 * 1000; /** * Checks an email (or phone number) and password. Five wrong passwords lock the account for * five minutes. With 2FA (or when the role needs it), a code is sent instead of a token. */ export async function logIn(input: { identifier: string; password: string; deviceToken?: string }, info: RequestInfo): Promise { const rawInput = String(input.identifier || ''); // SA local format (0xx) → international (27xx) const normalizedPhone = whatsapp().normalizeZAPhone(rawInput) || rawInput.replace(/\D/g, ''); const user = await prisma.user.findFirst({ where: { OR: [{ email: rawInput }, ...(normalizedPhone ? [{ phoneNumber: normalizedPhone }] : [])] } }); // Security (1.51.17): an unknown email answers like a wrong password — same message and // status, and a password check against a stand-in hash so it takes as long. if (!user) { await auth.comparePassword(input.password, await standInHash()); return fail(401, 'Invalid email or password', undefined, { v1Status: 400 }); } if (!user.isActive) { // Resend the activation link on each attempt, in case the earlier one expired. await sendActivationLink(user); if (user.email && !user.email.endsWith('@guest.local')) fail(401, 'Your account is not yet active. We\'ve sent you an email with a link to activate your account.'); if (user.phoneNumber) fail(401, 'Your account is not yet active. We\'ve sent you a WhatsApp message with a link to activate your account.'); fail(401, 'Your account has been deactivated'); } if (user.lockUntil && user.lockUntil > new Date()) { const minutes = Math.ceil((new Date(user.lockUntil).getTime() - Date.now()) / 60000); fail(429, `Too many attempts. Try again in ${minutes} minute(s).`, undefined, { v1Status: 400 }); } if (!(await auth.comparePassword(input.password, user.password))) { const attempts = user.failedAttempts + 1; await prisma.user.update({ where: { id: user.id }, data: { failedAttempts: attempts, lockUntil: attempts >= MAX_ATTEMPTS ? new Date(Date.now() + LOCK_TIME) : null } }); fail(401, 'Invalid email or password', undefined, { v1Status: 400 }); } // 2.0: a password saved with bcrypt (or weaker Argon2 settings) is re-hashed now we have it. const rehashed = auth.needsRehash(user.password) ? { password: await auth.hashPassword(input.password) } : {}; const updated = await prisma.user.update({ where: { id: user.id }, data: { failedAttempts: 0, lockUntil: null, ...rehashed }, select: LOGIN_USER_SELECT }); // Two-factor: the password alone isn't enough unless this browser was remembered earlier. if (updated.twoFactorEnabled && !(await twoFactor.isTrustedDevice(updated.id, input.deviceToken))) { return { status: 'code_required', challenge: await twoFactor.createChallenge(updated, 'login', updated.twoFactorMethod || 'email'), enrolling: false }; } // Admins and supervisors must use 2FA. Not set up yet: send a code to the first channel that // can take one; verifying it turns 2FA on. A trusted device can't skip this. if (!updated.twoFactorEnabled && twoFactor.requiresTwoFactor(updated)) { const method = await twoFactor.enforcementMethod(updated); if (method) return { status: 'code_required', challenge: await twoFactor.createChallenge(updated, 'login', method), enrolling: true }; } return { status: 'signed_in', session: await completeLogin(updated, info) }; } /** The second login step: the emailed or WhatsApp code for a token (and optionally remember this device). */ export async function verifyLoginCode(input: { challengeId: string; code: string; rememberDevice?: boolean }, info: RequestInfo): Promise { const challenge = await twoFactor.verifyChallenge(input.challengeId, input.code, 'login'); let user = await prisma.user.findUnique({ where: { id: challenge.userId }, select: LOGIN_USER_SELECT }); if (!user || !user.isActive) return fail(401, 'Your account has been deactivated'); // First login since 2FA became required for this role: the code proves the channel works, // so turn 2FA on with it. if (!user.twoFactorEnabled && twoFactor.requiresTwoFactor(user)) { user = await prisma.user.update({ where: { id: user.id }, data: { twoFactorEnabled: true, twoFactorMethod: challenge.method as 'email' | 'whatsapp', updatedAt: new Date() }, select: LOGIN_USER_SELECT }); logSecurityEvent({ userId: user.id, type: 'two_factor_enabled', ip: info.ip, userAgent: info.userAgent }).catch(() => {}); } // 2.3.0: a recovery code was used instead (the app or phone may be lost): it's in the activity log. if (challenge.usedRecoveryCode) { logSecurityEvent({ userId: user.id, type: 'recovery_code_used', ip: info.ip, userAgent: info.userAgent }).catch(() => {}); } const extra = input.rememberDevice === true ? { deviceToken: await twoFactor.issueTrustedDevice(user.id, info.userAgent) } : {}; return completeLogin(user, info, extra); } export type ProfileInput = { name?: string; email?: string; phoneNumber?: string | null; notificationPreference?: string; homeCampusId?: string | null; /** A new password; needs currentPassword. */ password?: string; currentPassword?: string; }; export const PROFILE_SELECT = { id: true, name: true, email: true, role: true, phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true, homeCampusId: true, tokenVersion: true, } as const; /** * Changes your own details. A new password needs the current one, signs out other devices' * remembered 2FA, and sends a security notice. Returns the account and a fresh token. */ export async function updateProfile(userId: string, input: ProfileInput, info: RequestInfo) { const user = await prisma.user.findUnique({ where: { id: userId } }); if (!user) return fail(404, 'User not found'); const { name, email, password, phoneNumber, currentPassword, notificationPreference, homeCampusId } = input; // Home campus (only while campuses are on): an active campus, or ''/null for none. let newHomeCampusId = user.homeCampusId; if (homeCampusId !== undefined && await require('../utils/campuses').campusesEnabled()) { if (!homeCampusId) newHomeCampusId = null; else { const campus = await prisma.campus.findFirst({ where: { id: String(homeCampusId), archivedAt: null }, select: { id: true } }); if (!campus) fail(400, 'Choose one of the campuses in the list.'); newHomeCampusId = campus!.id; } } // A password change needs the current password let newHashedPassword: string | undefined; if (typeof password === 'string' && password.trim().length > 0) { const newPw = password.trim(); if (!currentPassword) fail(400, 'Current password is required to set a new password'); if (!(await auth.comparePassword(currentPassword!, user.password))) fail(400, 'Current password is incorrect'); if (newPw.length < 8) fail(400, 'New password must be at least 8 characters long'); newHashedPassword = await auth.hashPassword(newPw); } const { normalizeZAPhone, isValidZAPhone } = whatsapp(); let newPhone = user.phoneNumber; if (phoneNumber !== undefined) newPhone = phoneNumber ? (normalizeZAPhone(phoneNumber) || phoneNumber.replace(/\D/g, '') || null) : null; // WhatsApp needs a valid SA phone number const { resolveNotificationPreference } = require('../utils/notificationPreference'); const newPref = resolveNotificationPreference(notificationPreference, newPhone, user.notificationPreference); // 2FA codes can't go to WhatsApp without a usable number — move them to email. const newTwoFactorMethod = user.twoFactorMethod === 'whatsapp' && !isValidZAPhone(newPhone) ? 'email' : user.twoFactorMethod; const updated = await prisma.user.update({ where: { id: userId }, data: { name: name || user.name, email: email || user.email, password: newHashedPassword ?? user.password, phoneNumber: newPhone, notificationPreference: newPref, twoFactorMethod: newTwoFactorMethod, homeCampusId: newHomeCampusId, updatedAt: new Date(), }, select: PROFILE_SELECT, }); if (newHashedPassword) { await twoFactor.clearTrustedDevices(updated.id); const { sendMail, buildPasswordChangedEmail } = require('../utils/email'); const supportEmail = getSettingSync('org_email', process.env.EMAIL_FROM || ''); const content = buildPasswordChangedEmail({ name: updated.name, when: Date.now(), supportEmail }); sendMail({ to: updated.email, subject: `Your ${getOrgName()} password was changed`, ...content }) .catch((e: any) => console.warn('[email] Failed to send password changed alert:', e?.message || e)); const { waText } = require('../utils/notify'); waText(updated, content.text).catch(() => {}); logSecurityEvent({ userId: updated.id, type: 'password_changed', ip: info.ip, userAgent: info.userAgent }).catch(() => {}); } return { user: updated, twoFactorRequired: twoFactor.requiresTwoFactor(updated), token: auth.generateToken(updated.id, updated.role, updated.tokenVersion) }; } export { ServiceError };