2022-10-05 09:37:15 -04:00
|
|
|
import { Secret, TOTP } from 'otpauth'
|
2022-10-10 05:12:23 -04:00
|
|
|
import { CONFIG } from '@server/initializers/config'
|
2022-10-05 09:37:15 -04:00
|
|
|
import { WEBSERVER } from '@server/initializers/constants'
|
2022-10-10 05:12:23 -04:00
|
|
|
import { decrypt } from './peertube-crypto'
|
2022-10-05 09:37:15 -04:00
|
|
|
|
2022-10-10 05:12:23 -04:00
|
|
|
async function isOTPValid (options: {
|
|
|
|
encryptedSecret: string
|
2022-10-05 09:37:15 -04:00
|
|
|
token: string
|
|
|
|
}) {
|
2022-10-10 05:12:23 -04:00
|
|
|
const { token, encryptedSecret } = options
|
|
|
|
|
|
|
|
const secret = await decrypt(encryptedSecret, CONFIG.SECRETS.PEERTUBE)
|
2022-10-05 09:37:15 -04:00
|
|
|
|
|
|
|
const totp = new TOTP({
|
|
|
|
...baseOTPOptions(),
|
|
|
|
|
|
|
|
secret
|
|
|
|
})
|
|
|
|
|
|
|
|
const delta = totp.validate({
|
|
|
|
token,
|
|
|
|
window: 1
|
|
|
|
})
|
|
|
|
|
|
|
|
if (delta === null) return false
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
function generateOTPSecret (email: string) {
|
|
|
|
const totp = new TOTP({
|
|
|
|
...baseOTPOptions(),
|
|
|
|
|
|
|
|
label: email,
|
|
|
|
secret: new Secret()
|
|
|
|
})
|
|
|
|
|
|
|
|
return {
|
|
|
|
secret: totp.secret.base32,
|
|
|
|
uri: totp.toString()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
isOTPValid,
|
|
|
|
generateOTPSecret
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function baseOTPOptions () {
|
|
|
|
return {
|
|
|
|
issuer: WEBSERVER.HOST,
|
|
|
|
algorithm: 'SHA1',
|
|
|
|
digits: 6,
|
|
|
|
period: 30
|
|
|
|
}
|
|
|
|
}
|