]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/otp.ts
Encrypt OTP secret
[github/Chocobozzz/PeerTube.git] / server / helpers / otp.ts
CommitLineData
56f47830 1import { Secret, TOTP } from 'otpauth'
a3e5f804 2import { CONFIG } from '@server/initializers/config'
56f47830 3import { WEBSERVER } from '@server/initializers/constants'
a3e5f804 4import { decrypt } from './peertube-crypto'
56f47830 5
a3e5f804
C
6async function isOTPValid (options: {
7 encryptedSecret: string
56f47830
C
8 token: string
9}) {
a3e5f804
C
10 const { token, encryptedSecret } = options
11
12 const secret = await decrypt(encryptedSecret, CONFIG.SECRETS.PEERTUBE)
56f47830
C
13
14 const totp = new TOTP({
15 ...baseOTPOptions(),
16
17 secret
18 })
19
20 const delta = totp.validate({
21 token,
22 window: 1
23 })
24
25 if (delta === null) return false
26
27 return true
28}
29
30function generateOTPSecret (email: string) {
31 const totp = new TOTP({
32 ...baseOTPOptions(),
33
34 label: email,
35 secret: new Secret()
36 })
37
38 return {
39 secret: totp.secret.base32,
40 uri: totp.toString()
41 }
42}
43
44export {
45 isOTPValid,
46 generateOTPSecret
47}
48
49// ---------------------------------------------------------------------------
50
51function baseOTPOptions () {
52 return {
53 issuer: WEBSERVER.HOST,
54 algorithm: 'SHA1',
55 digits: 6,
56 period: 30
57 }
58}