games_app/backend/dist-test-faq/services/emailVerificationService.js

162 lines
7.0 KiB
JavaScript

"use strict";
/**
* Email verification orchestration: token issuance, delivery, and confirmation.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildVerifyUrl = buildVerifyUrl;
exports.sendVerificationEmailForUser = sendVerificationEmailForUser;
exports.verifyEmailToken = verifyEmailToken;
exports.requestVerificationResendByEmail = requestVerificationResendByEmail;
exports.sendVerificationAfterRegister = sendVerificationAfterRegister;
const config_1 = require("../config");
const crypto_1 = require("../utils/crypto");
const userRepository = __importStar(require("../repositories/userRepository"));
const emailVerificationRepository = __importStar(require("../repositories/emailVerificationRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const emailService_1 = require("./emailService");
/**
* Builds the web app URL users open to complete verification.
* @param rawToken - Single-use token from the email link query string
*/
function buildVerifyUrl(rawToken) {
const base = config_1.config.app.publicUrl.replace(/\/$/, '');
const path = config_1.config.app.verifyEmailPath.startsWith('/')
? config_1.config.app.verifyEmailPath
: `/${config_1.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
*/
async function sendVerificationEmailForUser(userId) {
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 ? (0, crypto_1.decrypt)(profile.email_encrypted) : null;
if (!email)
throw new Error('No email on file. Update your profile email first.');
const rawToken = (0, crypto_1.randomHex)(32);
const tokenHash = (0, crypto_1.hashToken)(rawToken);
const expiresAt = new Date(Date.now() + config_1.config.email.verificationExpiryHours * 60 * 60 * 1000);
await emailVerificationRepository.deleteByUserId(userId);
await emailVerificationRepository.create(userId, tokenHash, expiresAt);
const verifyUrl = buildVerifyUrl(rawToken);
await (0, emailService_1.sendVerificationEmail)(email, verifyUrl);
await auditLogRepository.create({
userId,
action: 'email_verification_sent',
resourceType: 'user',
resourceId: userId,
metadata: { transport: config_1.config.email.transport },
});
const result = {
message: (0, emailService_1.usesConsoleEmailTransport)()
? 'Console email mode: use the verification link below (also logged in backend output).'
: 'Verification email sent. Check your inbox.',
};
if ((0, emailService_1.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
*/
async function verifyEmailToken(rawToken) {
const trimmed = rawToken?.trim();
if (!trimmed)
throw new Error('Verification token is required');
const tokenHash = (0, crypto_1.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).
*/
async function requestVerificationResendByEmail(email) {
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 Promise.resolve().then(() => __importStar(require('../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 ((0, emailService_1.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
*/
async function sendVerificationAfterRegister(userId) {
try {
await sendVerificationEmailForUser(userId);
}
catch (e) {
console.warn('[email] Post-register verification skipped:', e instanceof Error ? e.message : e);
}
}
//# sourceMappingURL=emailVerificationService.js.map