2025-03-28 02:15:25 +01:00
|
|
|
import { Totp, generateSecret } from 'time2fa';
|
|
|
|
import options from './options.js';
|
|
|
|
import totpEncryptionService from './encryption/totp_encryption.js';
|
2024-09-07 10:21:41 -07:00
|
|
|
|
2025-03-28 02:15:25 +01:00
|
|
|
function isTotpEnabled(): boolean {
|
2025-04-02 23:13:59 +02:00
|
|
|
return options.getOptionOrNull('mfaEnabled') === "true" &&
|
|
|
|
options.getOptionOrNull('mfaMethod') === "totp" &&
|
2025-03-28 04:01:18 +01:00
|
|
|
totpEncryptionService.isTotpSecretSet();
|
2025-03-28 02:15:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function createSecret(): { success: boolean; message?: string } {
|
|
|
|
try {
|
|
|
|
const secret = generateSecret();
|
|
|
|
|
|
|
|
totpEncryptionService.setTotpSecret(secret);
|
2024-09-07 10:21:41 -07:00
|
|
|
|
2025-03-28 02:15:25 +01:00
|
|
|
return {
|
|
|
|
success: true,
|
|
|
|
message: secret
|
|
|
|
};
|
|
|
|
} catch (e) {
|
|
|
|
console.error('Failed to create TOTP secret:', e);
|
|
|
|
return {
|
|
|
|
success: false,
|
|
|
|
message: e instanceof Error ? e.message : 'Unknown error occurred'
|
|
|
|
};
|
2024-09-07 11:41:54 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-03-28 02:15:25 +01:00
|
|
|
function getTotpSecret(): string | null {
|
|
|
|
return totpEncryptionService.getTotpSecret();
|
2024-09-07 10:21:41 -07:00
|
|
|
}
|
|
|
|
|
2025-03-28 02:15:25 +01:00
|
|
|
function checkForTotpSecret(): boolean {
|
|
|
|
return totpEncryptionService.isTotpSecretSet();
|
2024-09-07 10:21:41 -07:00
|
|
|
}
|
|
|
|
|
2025-03-28 02:15:25 +01:00
|
|
|
function validateTOTP(submittedPasscode: string): boolean {
|
|
|
|
const secret = getTotpSecret();
|
|
|
|
if (!secret) return false;
|
2024-09-07 10:21:41 -07:00
|
|
|
|
|
|
|
try {
|
2025-03-28 02:15:25 +01:00
|
|
|
return Totp.validate({
|
2025-03-26 00:42:19 +01:00
|
|
|
passcode: submittedPasscode,
|
2025-03-28 02:15:25 +01:00
|
|
|
secret: secret.trim()
|
2024-09-07 10:21:41 -07:00
|
|
|
});
|
|
|
|
} catch (e) {
|
2025-03-28 02:15:25 +01:00
|
|
|
console.error('Failed to validate TOTP:', e);
|
2024-09-07 10:21:41 -07:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-03-28 02:15:25 +01:00
|
|
|
function resetTotp(): void {
|
|
|
|
totpEncryptionService.resetTotpSecret();
|
|
|
|
options.setOption('mfaEnabled', 'false');
|
|
|
|
options.setOption('mfaMethod', '');
|
|
|
|
}
|
|
|
|
|
2024-09-07 10:21:41 -07:00
|
|
|
export default {
|
2024-09-07 11:41:54 -07:00
|
|
|
isTotpEnabled,
|
2025-03-28 02:15:25 +01:00
|
|
|
createSecret,
|
2025-03-25 23:14:25 +01:00
|
|
|
getTotpSecret,
|
2025-03-28 02:15:25 +01:00
|
|
|
checkForTotpSecret,
|
|
|
|
validateTOTP,
|
|
|
|
resetTotp
|
|
|
|
};
|