117 lines
4.1 KiB
TypeScript
117 lines
4.1 KiB
TypeScript
/**
|
|
* Password reset: request link by email and set new password with token.
|
|
*/
|
|
|
|
import { config } from '../config';
|
|
import { decrypt, hashToken, randomHex } from '../utils/crypto';
|
|
import * as userRepository from '../repositories/userRepository';
|
|
import * as passwordResetRepository from '../repositories/passwordResetRepository';
|
|
import * as refreshTokenRepository from '../repositories/refreshTokenRepository';
|
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
|
import { sendPasswordResetEmail, usesConsoleEmailTransport } from './emailService';
|
|
import { validatePassword } from './authService';
|
|
import * as settingsRepository from '../repositories/settingsRepository';
|
|
import argon2 from 'argon2';
|
|
|
|
export function buildResetPasswordUrl(rawToken: string): string {
|
|
const base = config.app.publicUrl.replace(/\/$/, '');
|
|
const path = config.app.resetPasswordPath.startsWith('/')
|
|
? config.app.resetPasswordPath
|
|
: `/${config.app.resetPasswordPath}`;
|
|
return `${base}${path}?token=${encodeURIComponent(rawToken)}`;
|
|
}
|
|
|
|
/**
|
|
* Sends reset link if account exists. Always returns generic success (no email enumeration).
|
|
*/
|
|
export async function requestPasswordReset(email: string): Promise<{
|
|
message: string;
|
|
devResetUrl?: string;
|
|
}> {
|
|
const normalized = email.trim().toLowerCase();
|
|
const generic = {
|
|
message:
|
|
'If an account exists for this email, a password reset link has been sent. Check your inbox.',
|
|
};
|
|
|
|
if (!normalized) return generic;
|
|
|
|
const { hashForIndex } = await import('../utils/crypto');
|
|
const user = await userRepository.findByEmailHash(hashForIndex(normalized));
|
|
if (!user || !user.is_enabled) return generic;
|
|
|
|
const profile = await userRepository.getSelfProfileForUser(user.id);
|
|
const toEmail = profile?.email_encrypted ? decrypt(profile.email_encrypted) : null;
|
|
if (!toEmail) return generic;
|
|
|
|
const rawToken = randomHex(32);
|
|
const tokenHash = hashToken(rawToken);
|
|
const expiresAt = new Date(
|
|
Date.now() + config.email.passwordResetExpiryHours * 60 * 60 * 1000
|
|
);
|
|
|
|
await passwordResetRepository.deleteByUserId(user.id);
|
|
await passwordResetRepository.create(user.id, tokenHash, expiresAt);
|
|
|
|
const resetUrl = buildResetPasswordUrl(rawToken);
|
|
await sendPasswordResetEmail(toEmail, resetUrl);
|
|
|
|
await auditLogRepository.create({
|
|
userId: user.id,
|
|
action: 'password_reset_requested',
|
|
resourceType: 'user',
|
|
resourceId: user.id,
|
|
metadata: { transport: config.email.transport },
|
|
});
|
|
|
|
if (usesConsoleEmailTransport()) {
|
|
return {
|
|
message:
|
|
'Console email mode: no message was sent. Use the reset link below (also logged in backend container output).',
|
|
devResetUrl: resetUrl,
|
|
};
|
|
}
|
|
return generic;
|
|
}
|
|
|
|
export async function resetPasswordWithToken(
|
|
rawToken: string,
|
|
newPassword: string
|
|
): Promise<{ message: string }> {
|
|
const trimmed = rawToken?.trim();
|
|
if (!trimmed) throw new Error('Reset token is required');
|
|
|
|
const policy = await settingsRepository.getSettings();
|
|
validatePassword(newPassword, policy);
|
|
|
|
const tokenHash = hashToken(trimmed);
|
|
const row = await passwordResetRepository.findValidByTokenHash(tokenHash);
|
|
if (!row) throw new Error('Invalid or expired reset link');
|
|
|
|
const user = await userRepository.findById(row.user_id);
|
|
if (!user) throw new Error('User not found');
|
|
|
|
const passwordHash = await argon2.hash(newPassword, { type: argon2.argon2id });
|
|
await userRepository.updatePassword(row.user_id, passwordHash);
|
|
await passwordResetRepository.markUsed(row.id);
|
|
await passwordResetRepository.deleteByUserId(row.user_id);
|
|
await refreshTokenRepository.deleteByUserId(row.user_id);
|
|
|
|
await auditLogRepository.create({
|
|
userId: row.user_id,
|
|
action: 'password_reset_completed',
|
|
resourceType: 'user',
|
|
resourceId: row.user_id,
|
|
});
|
|
|
|
return { message: 'Password updated successfully. You can sign in with your new password.' };
|
|
}
|
|
|
|
export async function validateResetToken(rawToken: string): Promise<{ valid: boolean }> {
|
|
const trimmed = rawToken?.trim();
|
|
if (!trimmed) return { valid: false };
|
|
const tokenHash = hashToken(trimmed);
|
|
const row = await passwordResetRepository.findValidByTokenHash(tokenHash);
|
|
return { valid: !!row };
|
|
}
|