PeerTube/server/helpers/otp.ts

59 lines
1.0 KiB
TypeScript
Raw Normal View History

import { Secret, TOTP } from 'otpauth'
2022-10-10 04:12:23 -05:00
import { CONFIG } from '@server/initializers/config'
import { WEBSERVER } from '@server/initializers/constants'
2022-10-10 04:12:23 -05:00
import { decrypt } from './peertube-crypto'
2022-10-10 04:12:23 -05:00
async function isOTPValid (options: {
encryptedSecret: string
token: string
}) {
2022-10-10 04:12:23 -05:00
const { token, encryptedSecret } = options
const secret = await decrypt(encryptedSecret, CONFIG.SECRETS.PEERTUBE)
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
}
}