forked from SVasilev/http-headers-validation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (55 loc) · 1.78 KB
/
index.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
/* global window */
'use strict';
function isString(value) {
return Object.prototype.toString.call(value) === '[object String]';
}
function range(start, end) {
var rangeResult = [];
for (var i = start; i < end; i++) {
rangeResult.push(i);
}
return rangeResult;
}
function invalidTypeOrLength(value) {
return !isString(value) || value.length === 0;
}
// Inspired by Node.js: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
var httpHeaderValidationAPI = {
validateHeaderName: function(headerName) {
if (invalidTypeOrLength(headerName)) {
return false;
}
var validCharCodes = []
.concat(range(48, 58)) // 0-9
.concat(range(65, 91)) // a-z
.concat(range(97, 123)) // A-Z
.concat([94, 95, 96, 124, 126]) // ^, _, `, |, ~
.concat([33, 35, 36, 37, 38, 39, 42, 43, 45, 46]); // !, #, $, %, &, ', *, +, -, .,
return headerName.split('').map(function(character) {
return character.charCodeAt(0);
}).every(function(charCode) {
return validCharCodes.indexOf(charCode) !== -1;
});
},
validateHeaderValue: function(headerValue) {
if (invalidTypeOrLength(headerValue)) {
return false;
}
return headerValue.split('').map(function(character) {
return character.charCodeAt(0);
}).every(function(charCode) {
return (charCode > 31 && charCode <= 255 && charCode !== 127) || charCode === 9;
});
},
validateHeader: function(name, value) {
if (invalidTypeOrLength(name) || invalidTypeOrLength(value)) {
return false;
}
return this.validateHeaderName(name) && this.validateHeaderValue(value);
}
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = httpHeaderValidationAPI;
} else {
window.headerUtils = httpHeaderValidationAPI;
}