Server: forbid to make friends with a non https server
[oweals/peertube.git] / server / middlewares / secure.js
1 'use strict'
2
3 const logger = require('../helpers/logger')
4 const mongoose = require('mongoose')
5 const peertubeCrypto = require('../helpers/peertube-crypto')
6
7 const Pod = mongoose.model('Pod')
8
9 const secureMiddleware = {
10   checkSignature,
11   decryptBody
12 }
13
14 function checkSignature (req, res, next) {
15   const host = req.body.signature.host
16   Pod.loadByHost(host, function (err, pod) {
17     if (err) {
18       logger.error('Cannot get signed host in decryptBody.', { error: err })
19       return res.sendStatus(500)
20     }
21
22     if (pod === null) {
23       logger.error('Unknown pod %s.', host)
24       return res.sendStatus(403)
25     }
26
27     logger.debug('Decrypting body from %s.', host)
28
29     const signatureOk = peertubeCrypto.checkSignature(pod.publicKey, host, req.body.signature.signature)
30
31     if (signatureOk === true) {
32       return next()
33     }
34
35     logger.error('Signature is not okay in decryptBody for %s.', req.body.signature.host)
36     return res.sendStatus(403)
37   })
38 }
39
40 function decryptBody (req, res, next) {
41   peertubeCrypto.decrypt(req.body.key, req.body.data, function (err, decrypted) {
42     if (err) {
43       logger.error('Cannot decrypt data.', { error: err })
44       return res.sendStatus(500)
45     }
46
47     try {
48       req.body.data = JSON.parse(decrypted)
49       delete req.body.key
50     } catch (err) {
51       logger.error('Error in JSON.parse', { error: err })
52       return res.sendStatus(500)
53     }
54
55     next()
56   })
57 }
58
59 // ---------------------------------------------------------------------------
60
61 module.exports = secureMiddleware