Generate inline script SHA for Content-Security-Policy


#1

As the topic title says it would be great if Hugo had a method to generate the SHA value for inline scripts.

I’m not aware if there is a Go utility out there for this task.


#2
Content-Security-Policy: script-src {{ .Data.Integrity }};

#3

For some reason .Data.Integrity returns empty for inline scripts, -at least on my end-.

I had already checked it out before opening this topic and I checked again after your reply.

Here is my full JS partial (it is rendered at the bottom of my HTML):

{{- $lazy := resources.Get "js/lazysizes/lazysizes.min.js" | minify -}}
{{- $headroom := resources.Get "js/headroom.min.js" | minify -}}
{{- $init := resources.Get "js/init-headroom.js" | minify -}}
{{- $analytics := resources.Get "js/analytics.js" | minify -}}
{{- $js := slice $lazy $headroom $init $analytics | resources.Concat "js/bundle.js" -}}
{{ $secureJS := $js | resources.Fingerprint "sha256" }}
<script integrity="{{ $secureJS.Data.Integrity }}">{{ $secureJS.Content | safeJS }}</script>

Maybe I’m doing something wrong…


#4

I suspect there is an ordering issue here, which I can see may be confusing …

Can you try to add:

{{ if  $secureJS.Content }}{{ end }}

Before you access the integrity.


#5

The above condition generated the correct SHA256 for the inline script.

Thanks!

BTW integrity does not make sense for inline scripts I only plan to use the above wrapped in a if .Site.IsServer condition so that I can update my CSP headers whenever I update my scripts bundle.


#6

Can you create a GH issue about this “ordering issue”?


#7

I learn everyday something with Hugo thanks :clap: :clap: :clap: @onedrawingperday and @bep. This will help me to get my CSP headers right.


#8

GitHub issue opened here: