-
Notifications
You must be signed in to change notification settings - Fork 20
/
request-digest.js
executable file
·190 lines (158 loc) · 4.87 KB
/
request-digest.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
'use strict';
//
// # Digest Client
//
// Use together with HTTP Client to perform requests to servers protected
// by digest authentication.
//
var HTTPDigest = function () {
var crypto = require('crypto');
var request = require('request');
var _ = require('lodash');
var HTTPDigest = function (username, password) {
this.nc = 0;
this.username = username;
this.password = password;
};
//
// ## Make request
//
// Wraps the http.request function to apply digest authorization.
//
HTTPDigest.prototype.request = function (options, callback) {
var self = this;
options.url = options.host + options.path;
return request(options, function (error, res) {
self._handleResponse(options, res, callback);
});
};
//
// ## Handle authentication
//
// Parse authentication headers and set response.
//
HTTPDigest.prototype._handleResponse = function handleResponse(options, res, callback) {
var challenge = this._parseDigestResponse(res.caseless.dict['www-authenticate']);
var ha1 = crypto.createHash('md5');
ha1.update([this.username, challenge.realm, this.password].join(':'));
var ha2 = crypto.createHash('md5');
ha2.update([options.method, options.path].join(':'));
var cnonceObj = this._generateCNONCE(challenge.qop);
// Generate response hash
var response = crypto.createHash('md5');
var responseParams = [
ha1.digest('hex'),
challenge.nonce
];
if (cnonceObj.cnonce) {
responseParams.push(cnonceObj.nc);
responseParams.push(cnonceObj.cnonce);
}
responseParams.push(challenge.qop);
responseParams.push(ha2.digest('hex'));
response.update(responseParams.join(':'));
// Setup response parameters
var authParams = {
username: this.username,
realm: challenge.realm,
nonce: challenge.nonce,
uri: options.path,
algorithm: "MD5",
qop: challenge.qop,
opaque: challenge.opaque,
response: response.digest('hex'),
};
authParams = this._omitNull(authParams);
if (cnonceObj.cnonce) {
authParams.nc = cnonceObj.nc;
authParams.cnonce = cnonceObj.cnonce;
}
var headers = options.headers || {};
headers.Authorization = this._compileParams(authParams);
options.headers = headers;
return request(options, function (error, response, body) {
callback(error, response, body);
});
};
//
// ## Delete null or undefined value in an object
//
HTTPDigest.prototype._omitNull = function omitNull(data) {
return _.omit(data, function(elt) {
return elt == null;
});
};
//
// ## Parse challenge digest
//
HTTPDigest.prototype._parseDigestResponse = function parseDigestResponse(digestHeader) {
var prefix = 'Digest ';
var challenge = digestHeader.substr(digestHeader.indexOf(prefix) + prefix.length);
var parts = challenge.split(',');
var length = parts.length;
var params = {};
for (var i = 0; i < length; i++) {
var paramSplitted = this._splitParams(parts[i]);
if (paramSplitted.length > 2) {
params[paramSplitted[1]] = paramSplitted[2].replace(/\"/g, '');
}
}
return params;
};
HTTPDigest.prototype._splitParams = function splitParams(paramString) {
return paramString.match(/^\s*?([a-zA-Z0-0]+)=("?(.*)"?|MD5|MD5-sess|token)\s*?$/);
};
//
// ## Parse challenge digest
//
HTTPDigest.prototype._generateCNONCE = function generateCNONCE(qop) {
var cnonce = false;
var nc = false;
if (typeof qop === 'string') {
var cnonceHash = crypto.createHash('md5');
cnonceHash.update(Math.random().toString(36));
cnonce = cnonceHash.digest('hex').substr(0, 8);
nc = this._updateNC();
}
return { cnonce: cnonce, nc: nc };
};
//
// ## Compose authorization header
//
HTTPDigest.prototype._compileParams = function compileParams(params) {
var parts = [];
for (var i in params) {
if (typeof params[i] === 'function') {
continue;
}
var param = i + '=' + (this._putDoubleQuotes(i) ? '"' : '') + params[i] + (this._putDoubleQuotes(i) ? '"' : '');
parts.push(param);
}
return 'Digest ' + parts.join(',');
};
//
// ## Define if we have to put double quotes or not
//
HTTPDigest.prototype._putDoubleQuotes = function putDoubleQuotes(i) {
var excludeList = ['qop', 'nc'];
return (_.includes(excludeList, i) ? true : false);
};
//
// ## Update and zero pad nc
//
HTTPDigest.prototype._updateNC = function updateNC() {
var max = 99999999;
this.nc++;
if (this.nc > max) {
this.nc = 1;
}
var padding = new Array(8).join('0') + '';
var nc = this.nc + '';
return padding.substr(0, 8 - nc.length) + nc;
};
// Return response handler
return HTTPDigest;
}();
module.exports = function _createDigestClient(username, password) {
return new HTTPDigest(username, password);
};