PeerTube/server/core/helpers/otp.ts

65 lines
1.2 KiB
TypeScript
Raw Normal View History

import { CONFIG } from '@server/initializers/config.js'
import { WEBSERVER } from '@server/initializers/constants.js'
2024-11-04 09:25:26 +01:00
import { Secret, TOTP } from 'otpauth'
import { logger } from './logger.js'
import { decrypt } from './peertube-crypto.js'
2022-10-10 11:12:23 +02:00
async function isOTPValid (options: {
encryptedSecret: string
token: string
}) {
2022-10-10 11:12:23 +02:00
const { token, encryptedSecret } = options
2024-11-04 09:25:26 +01:00
try {
const secret = await decrypt(encryptedSecret, CONFIG.SECRETS.PEERTUBE)
2024-11-04 09:25:26 +01:00
const totp = new TOTP({
...baseOTPOptions(),
2024-11-04 09:25:26 +01:00
secret
})
2024-11-04 09:25:26 +01:00
const delta = totp.validate({
token,
window: 1
})
2024-11-04 09:25:26 +01:00
if (delta === null) return false
2024-11-04 09:25:26 +01:00
return true
} catch (err) {
logger.error('Cannot decrypt/validate OTP', { err })
return false
}
}
function generateOTPSecret (email: string) {
const totp = new TOTP({
...baseOTPOptions(),
label: email,
secret: new Secret()
})
return {
secret: totp.secret.base32,
uri: totp.toString()
}
}
export {
2024-11-04 09:25:26 +01:00
generateOTPSecret, isOTPValid
}
// ---------------------------------------------------------------------------
function baseOTPOptions () {
return {
issuer: WEBSERVER.HOST,
algorithm: 'SHA1',
digits: 6,
period: 30
}
}