Cleanup helpers
[oweals/peertube.git] / server / helpers / peertube-crypto.ts
1 import { BCRYPT_SALT_SIZE, PRIVATE_RSA_KEY_SIZE } from '../initializers'
2 import { AccountInstance } from '../models/account/account-interface'
3 import { bcryptComparePromise, bcryptGenSaltPromise, bcryptHashPromise, createPrivateKey, getPublicKey } from './core-utils'
4 import { jsig } from './custom-jsonld-signature'
5 import { logger } from './logger'
6
7 async function createPrivateAndPublicKeys () {
8   logger.info('Generating a RSA key...')
9
10   const { key } = await createPrivateKey(PRIVATE_RSA_KEY_SIZE)
11   const { publicKey } = await getPublicKey(key)
12
13   return { privateKey: key, publicKey }
14 }
15
16 function isSignatureVerified (fromAccount: AccountInstance, signedDocument: object) {
17   const publicKeyObject = {
18     '@context': jsig.SECURITY_CONTEXT_URL,
19     '@id': fromAccount.url,
20     '@type':  'CryptographicKey',
21     owner: fromAccount.url,
22     publicKeyPem: fromAccount.publicKey
23   }
24
25   const publicKeyOwnerObject = {
26     '@context': jsig.SECURITY_CONTEXT_URL,
27     '@id': fromAccount.url,
28     publicKey: [ publicKeyObject ]
29   }
30
31   const options = {
32     publicKey: publicKeyObject,
33     publicKeyOwner: publicKeyOwnerObject
34   }
35
36   return jsig.promises.verify(signedDocument, options)
37     .catch(err => {
38       logger.error('Cannot check signature.', err)
39       return false
40     })
41 }
42
43 function signObject (byAccount: AccountInstance, data: any) {
44   const options = {
45     privateKeyPem: byAccount.privateKey,
46     creator: byAccount.url
47   }
48
49   return jsig.promises.sign(data, options)
50 }
51
52 function comparePassword (plainPassword: string, hashPassword: string) {
53   return bcryptComparePromise(plainPassword, hashPassword)
54 }
55
56 async function cryptPassword (password: string) {
57   const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
58
59   return bcryptHashPromise(password, salt)
60 }
61
62 // ---------------------------------------------------------------------------
63
64 export {
65   isSignatureVerified,
66   comparePassword,
67   createPrivateAndPublicKeys,
68   cryptPassword,
69   signObject
70 }