games_app/backend/src/services/emailVerificationService.ts
2026-07-02 12:14:21 +02:00

144 lines
5.1 KiB
TypeScript

/**
* Email verification orchestration: token issuance, delivery, and confirmation.
*/
import { config } from '../config';
import { decrypt, hashToken, randomHex } from '../utils/crypto';
import * as userRepository from '../repositories/userRepository';
import * as emailVerificationRepository from '../repositories/emailVerificationRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { sendVerificationEmail, usesConsoleEmailTransport } from './emailService';
/**
* Builds the web app URL users open to complete verification.
* @param rawToken - Single-use token from the email link query string
*/
export function buildVerifyUrl(rawToken: string): string {
const base = config.app.publicUrl.replace(/\/$/, '');
const path = config.app.verifyEmailPath.startsWith('/')
? config.app.verifyEmailPath
: `/${config.app.verifyEmailPath}`;
return `${base}${path}?token=${encodeURIComponent(rawToken)}`;
}
/**
* Creates a verification token, emails the link, and returns optional dev URL.
* @param userId - Authenticated user UUID
* @throws When user not found, already verified, or email missing
*/
export async function sendVerificationEmailForUser(
userId: string
): Promise<{ message: string; devVerifyUrl?: string }> {
const user = await userRepository.findById(userId);
if (!user) throw new Error('User not found');
if (user.email_verified) throw new Error('Email is already verified');
const profile = await userRepository.getSelfProfileForUser(userId);
const email = profile?.email_encrypted ? decrypt(profile.email_encrypted) : null;
if (!email) throw new Error('No email on file. Update your profile email first.');
const rawToken = randomHex(32);
const tokenHash = hashToken(rawToken);
const expiresAt = new Date(
Date.now() + config.email.verificationExpiryHours * 60 * 60 * 1000
);
await emailVerificationRepository.deleteByUserId(userId);
await emailVerificationRepository.create(userId, tokenHash, expiresAt);
const verifyUrl = buildVerifyUrl(rawToken);
await sendVerificationEmail(email, verifyUrl);
await auditLogRepository.create({
userId,
action: 'email_verification_sent',
resourceType: 'user',
resourceId: userId,
metadata: { transport: config.email.transport },
});
const result: { message: string; devVerifyUrl?: string } = {
message: usesConsoleEmailTransport()
? 'Console email mode: use the verification link below (also logged in backend output).'
: 'Verification email sent. Check your inbox.',
};
if (usesConsoleEmailTransport()) {
result.devVerifyUrl = verifyUrl;
}
return result;
}
/**
* Confirms email ownership using a token from the verification link.
* @param rawToken - Token from query string or request body
* @throws When token is invalid, expired, or already used
*/
export async function verifyEmailToken(rawToken: string): Promise<{ message: string; userId: string }> {
const trimmed = rawToken?.trim();
if (!trimmed) throw new Error('Verification token is required');
const tokenHash = hashToken(trimmed);
const row = await emailVerificationRepository.findValidByTokenHash(tokenHash);
if (!row) throw new Error('Invalid or expired verification link');
const user = await userRepository.findById(row.user_id);
if (!user) throw new Error('User not found');
await userRepository.setEmailVerified(row.user_id, true);
await emailVerificationRepository.markUsed(row.id);
await emailVerificationRepository.deleteByUserId(row.user_id);
await auditLogRepository.create({
userId: row.user_id,
action: 'email_verified',
resourceType: 'user',
resourceId: row.user_id,
});
return { message: 'Email verified successfully', userId: row.user_id };
}
/**
* Sends a new verification link by email. Always returns a generic message (no enumeration).
*/
export async function requestVerificationResendByEmail(email: string): Promise<{
message: string;
devVerifyUrl?: string;
}> {
const generic = {
message:
'If an account exists for this email and is not yet verified, a confirmation link has been sent. Check your inbox.',
};
const normalized = email.trim().toLowerCase();
if (!normalized) return generic;
const { hashForIndex } = await import('../utils/crypto');
const user = await userRepository.findByEmailHash(hashForIndex(normalized));
if (!user || user.is_enabled === false || user.email_verified) return generic;
const sent = await sendVerificationEmailForUser(user.id);
if (usesConsoleEmailTransport() && sent.devVerifyUrl) {
return {
message:
'Console email mode: no message was sent. Use the verification link below if an account exists.',
devVerifyUrl: sent.devVerifyUrl,
};
}
return generic;
}
/**
* Fire-and-forget verification email after registration (errors logged only).
* @param userId - Newly registered user UUID
*/
export async function sendVerificationAfterRegister(userId: string): Promise<void> {
try {
await sendVerificationEmailForUser(userId);
} catch (e) {
console.warn('[email] Post-register verification skipped:', e instanceof Error ? e.message : e);
}
}