Computing integrity checksums for JS/CSS

The hot new security feature for the web is Subresource Integrity: basically, for each resource (Javascript, CSS) that your page loads, you specify an ‘integrity’ attribute which is a cryptographic hash of the expected contents of the resource. This prevents bad actors from doing nasty things like modifying your scripts on-the-fly before serving them to the user.

I’ve been thinking about ways to support this in Middleman, and it seems to me that you’d need an extension that runs after the resources are generated, but before the HTML pages are written out. Looking at the documentation for extensions, it seems that there are hooks for :after_configuration and :after_build, but I think the first one is probably too early, and the second is probably too late.

You could have an :after_build hook that scanned the resource files and wrote the appropriate hashes into a data file that could then be loaded on the next build – but that would mean that you’d need to build at least twice to get everything right.

So my first question is, is there a way to execute code at the appropriate time, i.e. before the HTML pages are built, but after any Javascript has been copied into the build directory, Sass has run to generate the stylesheets etc.?

The second question is, are there good (complete) examples of writing extensions? I started with the minimal example given on the custom extensions page, but it just dies during the build with an error “undefined method ‘registered’ for class”, so I suspect that the documentation hasn’t kept pace with the code and that something else needs to be added to the minimal example to make it work.

Any tips or suggestions would be gratefully received.

Answering my own question, 15 hours later …

It turns out that there isn’t a really good way to do this. Middleman’s build order is such that subresources like stylesheets and Javascripts get written out into the output directory in more or less random order. Stylesheets may get written first (although I don’t know if that’s something you can rely on), but in any case there’s no hook that can be called after all the resources are written, but before the main build of HTML files.

This might be a nice feature for a future version of Middleman (hint, hint). In fact, I’d argue strongly for subresource hashing being built into the Middleman core at some point in the future. According to Caniuse, this feature has about 76% support currently and that number will rise once iOS Safari moves it from ‘experimental’ to ‘fully-supported’ status (IE, as ever, is a lost cause).

So I’ve written a very simple extension to do subresource hash computation. It’s something of a hack, and it doesn’t get around the build-twice issue. Still, in case it’s useful to anyone, you can find it at: