forked from frux/csp-header
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (62 loc) · 1.43 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
68
69
70
71
72
73
var allowedPolicies = [
'base-uri',
'default-src',
'script-src',
'style-src',
'img-src',
'frame-src',
'script-src',
'child-src',
'connect-src',
'object-src',
'media-src',
'font-src',
'form-action',
'frame-ancestors',
'plugin-types'
];
/**
* Builds Content-Security-Policy header
* @param policies {object} Policies
* @returns {string}
*/
function buildCSPString(policies, reportUri){
var cspString = Object.keys(policies).map(function(policyName){
return policyName + ' ' + policies[policyName].join(' ');
}).join('; ') + ';';
if(typeof reportUri === 'string'){
cspString += ' report-uri ' + reportUri + ';';
}
return cspString;
}
function csp(params){
var policies;
// params should be an object
if(typeof params !== 'object'){
return;
}
// property policies is required
if(typeof params.policies !== 'object'){
return;
}
// filter disallowed policies
policies = Object.keys(params.policies).reduce(function(policies, policyName){
if(allowedPolicies.indexOf(policyName) > -1){
policies[policyName] = params.policies[policyName];
}
return policies;
}, {});
return buildCSPString(policies, params['report-uri']);
}
/**
* Build nonce param
* @param nonceId {string} Nonce param id
* @returns {string} Nonce param
*/
csp.nonce = function(nonceId){
return '\'nonce-' + nonceId + '\'';
};
csp.SELF = '\'self\'';
csp.INLINE = '\'unsafe-inline\'';
csp.EVAL = '\'unsafe-eval\'';
module.exports = csp;