34
34
//
35
35
36
36
var cspSrcs ;
37
+ var cachedCsp ; // Avoid constructing the header out of cspSrcs when possible.
38
+
37
39
// CSP keywords have to be single-quoted.
38
40
var unsafeInline = "'unsafe-inline'" ;
39
41
var unsafeEval = "'unsafe-eval'" ;
@@ -70,8 +72,11 @@ var removeCspSrc = function (directive, src) {
70
72
cspSrcs [ directive ] = _ . without ( cspSrcs [ directive ] || [ ] , src ) ;
71
73
} ;
72
74
75
+ // Prepare for a change to cspSrcs. Ensure that we have a key in the dictionary
76
+ // and clear any cached CSP.
73
77
var ensureDirective = function ( directive ) {
74
78
cspSrcs = cspSrcs || { } ;
79
+ cachedCsp = null ;
75
80
if ( ! _ . has ( cspSrcs , directive ) )
76
81
cspSrcs [ directive ] = _ . clone ( cspSrcs [ "default-src" ] ) ;
77
82
} ;
@@ -95,6 +100,9 @@ _.extend(BrowserPolicy.content, {
95
100
if ( ! cspSrcs || _ . isEmpty ( cspSrcs ) )
96
101
return null ;
97
102
103
+ if ( cachedCsp )
104
+ return cachedCsp ;
105
+
98
106
var header = _ . map ( cspSrcs , function ( srcs , directive ) {
99
107
srcs = srcs || [ ] ;
100
108
if ( _ . isEmpty ( srcs ) )
@@ -107,10 +115,12 @@ _.extend(BrowserPolicy.content, {
107
115
return header ;
108
116
} ,
109
117
_reset : function ( ) {
118
+ cachedCsp = null ;
110
119
setDefaultPolicy ( ) ;
111
120
} ,
112
121
113
122
setPolicy : function ( csp ) {
123
+ cachedCsp = null ;
114
124
parseCsp ( csp ) ;
115
125
} ,
116
126
@@ -174,6 +184,7 @@ _.extend(BrowserPolicy.content, {
174
184
} ) ;
175
185
} ,
176
186
disallowAll : function ( ) {
187
+ cachedCsp = null ;
177
188
cspSrcs = {
178
189
"default-src" : [ ]
179
190
} ;
@@ -203,6 +214,7 @@ _.each(["script", "object", "img", "media",
203
214
cspSrcs [ directive ] . push ( src ) ;
204
215
} ;
205
216
BrowserPolicy . content [ disallowMethodName ] = function ( ) {
217
+ cachedCsp = null ;
206
218
cspSrcs [ directive ] = [ ] ;
207
219
} ;
208
220
BrowserPolicy . content [ allowDataMethodName ] = function ( ) {
0 commit comments