23
Migrating Helmet for Express.js from v4.x to v5.x
A routine I have is to go through my (most important) projects I maintain and update the node dependencies to be up to date, this is to ensure that I don't have software running on deprecated and unsecure dependencies.
I also do this quite often as it keeps the upgrade process to a minimum and if something break, it's easier to find what's the cause.
And today, while doing this maintenance, I had a migration issue with a security package I use on all my node.js projects: Helmet.
If you don't know what Helmet is, in short, is a package that protects your node server from common http attacks. It's not the only solution you should have and it doesn't shield you from every attack, but it's a good starting point.
In my case I had a problem with an application, which lives in a subdomain, and it needs to access to some scripts from the parent domain.
In version 4.x we had a couple of security features that you had to enable manually, which updated the headers preventing your site to access to any resources outside your current domain.
By default in this version you only needed to disable the contentSecurityPolicy
with this version to allow your domain to access to CDN content or resources outside your domain.
As I didn't set this feature in my code, no such header was sent and so my site could access to resources from the main domain.
But in version 5.x, now these security features, helmet.crossOriginEmbedderPolicy()
and helmet.crossOriginResourcePolicy()
are enable by default, this means that every requests from the Express.js server will return the following headers:
"Cross-Origin-Embedder-Policy: require-corp"
"Cross-Origin-Resource-Policy: same-origin"
This will prevent any communication between my subdomain and the parent domain or any CDN I need, like Google Fonts for example.
To allow external resources to be allowed from my server, I had to update my Helmet configuration on my server from this:
/**
* Add helmet to prevent XSS attacks
*/
server.use(helmet({
contentSecurityPolicy: false,
}));
To this:
/**
* Add helmet to prevent XSS attacks
*/
server.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}));
Essentially what this will do is to set the Cross-Origin-Embedder-Policy
header to be the default value unsafe-none
.
Again, if you do not need to access to any resources outside your domain, it's better to enable this security feature.
But if you like in my situation, unless somebody can propose a better solution, the above configuration will let you application to work as before.
23