PeerTube/middlewares/secure.js

51 lines
1.5 KiB
JavaScript
Raw Normal View History

2015-11-07 11:40:13 -06:00
;(function () {
'use strict'
var fs = require('fs')
2016-01-31 04:23:52 -06:00
var ursa = require('ursa')
2015-11-07 11:40:13 -06:00
2016-01-30 10:05:22 -06:00
var logger = require('../helpers/logger')
2016-02-04 14:10:33 -06:00
var Pods = require('../models/pods')
2016-01-31 04:23:52 -06:00
var utils = require('../helpers/utils')
2015-11-07 11:40:13 -06:00
2016-02-04 14:16:27 -06:00
var secureMiddleware = {
2016-01-31 04:23:52 -06:00
decryptBody: decryptBody
}
2015-11-07 11:40:13 -06:00
2016-01-31 04:23:52 -06:00
function decryptBody (req, res, next) {
2016-02-04 14:10:33 -06:00
var url = req.body.signature.url
Pods.findByUrl(url, function (err, pod) {
2015-11-07 11:40:13 -06:00
if (err) {
logger.error('Cannot get signed url in decryptBody.', { error: err })
return res.sendStatus(500)
}
if (pod === null) {
2016-02-04 14:10:33 -06:00
logger.error('Unknown pod %s.', url)
return res.sendStatus(403)
2015-11-07 11:40:13 -06:00
}
2016-02-04 14:10:33 -06:00
logger.debug('Decrypting body from %s.', url)
2015-11-07 11:40:13 -06:00
var crt = ursa.createPublicKey(pod.publicKey)
var signature_ok = crt.hashAndVerify('sha256', new Buffer(req.body.signature.url).toString('hex'), req.body.signature.signature, 'hex')
if (signature_ok === true) {
2016-01-31 04:23:52 -06:00
var myKey = ursa.createPrivateKey(fs.readFileSync(utils.getCertDir() + 'peertube.key.pem'))
2015-11-07 11:40:13 -06:00
var decryptedKey = myKey.decrypt(req.body.key, 'hex', 'utf8')
req.body.data = JSON.parse(utils.symetricDecrypt(req.body.data, decryptedKey))
2015-12-06 14:36:57 -06:00
delete req.body.key
2015-11-07 11:40:13 -06:00
} else {
logger.error('Signature is not okay in decryptBody for %s.', req.body.signature.url)
return res.sendStatus(403)
2015-11-07 11:40:13 -06:00
}
next()
})
}
2016-01-31 04:23:52 -06:00
// ---------------------------------------------------------------------------
2016-02-04 14:16:27 -06:00
module.exports = secureMiddleware
2015-11-07 11:40:13 -06:00
})()