unoffical wafrn mirror
wafrn.net
atproto
social-network
activitypub
1import * as OTPAuth from 'otpauth'
2
3export default async function verifyTotp(mfaDetail: any, token: string) {
4 if (mfaDetail.type == "totp") {
5 const totp = new OTPAuth.TOTP({
6 algorithm: mfaDetail.data.algorithm,
7 digits: mfaDetail.data.digits,
8 period: mfaDetail.data.period,
9 secret: OTPAuth.Secret.fromBase32(mfaDetail.data.secret)
10 });
11
12 // check when the last OTP code was used. If recently we'll invalidate it, and you'll need to wait another 30 seconds
13 const counter = totp.counter();
14 if (mfaDetail.lastUsedData?.counter >= counter) {
15 return false;
16 }
17
18 // otherwise we'll check if the token you provided is correct
19 const delta = totp.validate({ token: token, window: 1 })
20 if (delta !== null) {
21 // update the MFA details to store the current counter value
22 mfaDetail.lastUsedData = {
23 counter: totp.counter()
24 }
25 await mfaDetail.save()
26
27 // and we're in
28 return true;
29 }
30 }
31 return false;
32}