@@ -283,13 +283,19 @@ func getAttr(attrList []html.Attribute, key string) (html.Attribute, bool) {
283
283
}
284
284
285
285
func (csp * CSPContentNonceModifier ) applyNonceToNodes (node * html.Node , nonce string ) {
286
+ for child := node .FirstChild ; child != nil ; child = child .NextSibling {
287
+ csp .applyNonceToNodes (child , nonce )
288
+ }
289
+ if node .Type != html .ElementNode {
290
+ return
291
+ }
286
292
canHaveNonce := node .Data == "script" || node .Data == "style" || (node .Data == "link" && attrListHas (node .Attr , "rel" , "stylesheet" ))
287
293
styleAttr , hasStyleAttr := getAttr (node .Attr , "style" )
288
294
if canHaveNonce || hasStyleAttr {
289
295
if csp .nonceElementDecider != nil && ! csp .nonceElementDecider .ShouldModify (node ) {
290
296
return
291
297
}
292
- switch true {
298
+ switch {
293
299
case canHaveNonce :
294
300
node .Attr = append (node .Attr , html.Attribute {
295
301
Key : "nonce" ,
@@ -325,25 +331,24 @@ func (csp *CSPContentNonceModifier) applyNonceToNodes(node *html.Node, nonce str
325
331
parent .InsertBefore (styleNode , node )
326
332
327
333
classAttr , hasClassAttr := getAttr (node .Attr , "class" )
334
+ newClassAttr := className
328
335
if hasClassAttr {
329
- newAttrs := make ([]html.Attribute , 0 , len (node .Attr ))
330
- for _ , attr := range node .Attr {
331
- if attr .Key == "class" {
332
- attr .Val = classAttr .Val + " " + className
333
- }
336
+ newClassAttr = classAttr .Val + " " + className
337
+ }
338
+ var newAttrs []html.Attribute
339
+ for _ , attr := range node .Attr {
340
+ if attr .Key == "class" && hasClassAttr {
341
+ attr .Val = classAttr .Val + " " + className
342
+ }
343
+ if attr .Key != "style" && attr .Key != "class" {
334
344
newAttrs = append (newAttrs , attr )
335
345
}
336
- } else {
337
- node .Attr = append (node .Attr , html.Attribute {
338
- Key : "class" ,
339
- Val : className ,
340
- })
341
346
}
347
+ node .Attr = append (newAttrs , html.Attribute {
348
+ Key : "class" ,
349
+ Val : newClassAttr ,
350
+ })
342
351
}
343
- return
344
- }
345
- for child := node .FirstChild ; child != nil ; child = child .NextSibling {
346
- csp .applyNonceToNodes (child , nonce )
347
352
}
348
353
}
349
354
@@ -356,7 +361,7 @@ func makeNonce(length int) (string, error) {
356
361
return hex .EncodeToString (randomBytes ), nil
357
362
}
358
363
359
- const defaultNonceLength = 32
364
+ const defaultNonceLength = 10
360
365
361
366
func (csp * CSPContentNonceModifier ) ModifyContent (context FileModifierContext , content []byte ) ([]byte , error ) {
362
367
doc , err := html .Parse (bytes .NewReader (content ))
0 commit comments