Async signature and various fixes
[oweals/peertube.git] / server / helpers / requests.ts
1 import * as replay from 'request-replay'
2 import * as request from 'request'
3 import * as Promise from 'bluebird'
4
5 import {
6   RETRY_REQUESTS,
7   REMOTE_SCHEME,
8   CONFIG
9 } from '../initializers'
10 import { PodInstance } from '../models'
11 import { sign } from './peertube-crypto'
12
13 type MakeRetryRequestParams = {
14   url: string,
15   method: 'GET'|'POST',
16   json: Object
17 }
18 function makeRetryRequest (params: MakeRetryRequestParams) {
19   return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
20     replay(
21       request(params, (err, response, body) => err ? rej(err) : res({ response, body })),
22       {
23         retries: RETRY_REQUESTS,
24         factor: 3,
25         maxTimeout: Infinity,
26         errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
27       }
28     )
29   })
30 }
31
32 type MakeSecureRequestParams = {
33   method: 'GET'|'POST'
34   toPod: PodInstance
35   path: string
36   data?: Object
37 }
38 function makeSecureRequest (params: MakeSecureRequestParams) {
39   return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
40     const requestParams = {
41       url: REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path,
42       json: {}
43     }
44
45     if (params.method !== 'POST') {
46       return rej(new Error('Cannot make a secure request with a non POST method.'))
47     }
48
49     const host = CONFIG.WEBSERVER.HOST
50
51     let dataToSign
52     if (params.data) {
53       dataToSign = params.data
54     } else {
55       // We do not have data to sign so we just take our host
56       // It is not ideal but the connection should be in HTTPS
57       dataToSign = host
58     }
59
60     sign(dataToSign).then(signature => {
61       requestParams.json['signature'] = {
62         host, // Which host we pretend to be
63         signature
64       }
65
66       // If there are data informations
67       if (params.data) {
68         requestParams.json['data'] = params.data
69       }
70
71       request.post(requestParams, (err, response, body) => err ? rej(err) : res({ response, body }))
72     })
73   })
74 }
75
76 // ---------------------------------------------------------------------------
77
78 export {
79   makeRetryRequest,
80   makeSecureRequest
81 }