2023-07-31 14:34:36 +02:00
|
|
|
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'
|
2023-07-31 14:34:36 +02:00
|
|
|
import { decrypt } from './peertube-crypto.js'
|
2022-10-05 15:37:15 +02:00
|
|
|
|
2022-10-10 11:12:23 +02:00
|
|
|
async function isOTPValid (options: {
|
|
|
|
encryptedSecret: string
|
2022-10-05 15:37:15 +02:00
|
|
|
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)
|
2022-10-05 15:37:15 +02:00
|
|
|
|
2024-11-04 09:25:26 +01:00
|
|
|
const totp = new TOTP({
|
|
|
|
...baseOTPOptions(),
|
2022-10-05 15:37:15 +02:00
|
|
|
|
2024-11-04 09:25:26 +01:00
|
|
|
secret
|
|
|
|
})
|
2022-10-05 15:37:15 +02:00
|
|
|
|
2024-11-04 09:25:26 +01:00
|
|
|
const delta = totp.validate({
|
|
|
|
token,
|
|
|
|
window: 1
|
|
|
|
})
|
2022-10-05 15:37:15 +02:00
|
|
|
|
2024-11-04 09:25:26 +01:00
|
|
|
if (delta === null) return false
|
2022-10-05 15:37:15 +02:00
|
|
|
|
2024-11-04 09:25:26 +01:00
|
|
|
return true
|
|
|
|
} catch (err) {
|
|
|
|
logger.error('Cannot decrypt/validate OTP', { err })
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
2022-10-05 15:37:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2022-10-05 15:37:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function baseOTPOptions () {
|
|
|
|
return {
|
|
|
|
issuer: WEBSERVER.HOST,
|
|
|
|
algorithm: 'SHA1',
|
|
|
|
digits: 6,
|
|
|
|
period: 30
|
|
|
|
}
|
|
|
|
}
|