aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/otp.ts
blob: a32cc96210b8cab68ca34216dc7cbf0e582a9a79 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Secret, TOTP } from 'otpauth'
import { CONFIG } from '@server/initializers/config'
import { WEBSERVER } from '@server/initializers/constants'
import { decrypt } from './peertube-crypto'

async function isOTPValid (options: {
  encryptedSecret: string
  token: string
}) {
  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
  }
}