Generate inline script SHA for Content-Security-Policy

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.

Content-Security-Policy: script-src {{ .Data.Integrity }};
1 Like

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…

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.


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


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.

1 Like

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

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


GitHub issue opened here: