Socket
Socket
Sign inDemoInstall

helmet

Package Overview
Dependencies
Maintainers
2
Versions
132
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

helmet - npm Package Compare versions

Comparing version 3.23.3 to 4.0.0-alpha.1

dist/index.d.ts

37

CHANGELOG.md
# Changelog
## 4.0.0 - Unreleased
### Added
- `helmet.contentSecurityPolicy`:
- If no `default-src` directive is supplied, an error is thrown
- Directive lists can be any iterable, not just arrays
### Changed
- This package no longer has dependencies. This should have no effect on end users, other than speeding up installation time.
- `helmet.contentSecurityPolicy`:
- There is now a default set of directives if none are supplied
- Duplicate keys now throw an error
- This middleware is more lenient
- `helmet.xssFilter` now disables the buggy XSS filter by default. See [#230](https://github.com/helmetjs/helmet/issues/230)
### Removed
- Dropped support for old Node versions. Node 10+ is now required
- `helmet.featurePolicy`. If you still need it, use the `feature-policy` package on npm.
- `helmet.hpkp`. If you still need it, use the `hpkp` package on npm.
- `helmet.noCache`. If you still need it, use the `nocache` package on npm.
- `helmet.contentSecurityPolicy`:
- Removed browser sniffing (including the `browserSniff` and `disableAndroid` parameters)
- Removed conditional support. This includes directive functions and support for a function as the `reportOnly`. [Read this if you need help.](https://github.com/helmetjs/helmet/wiki/Conditionally-using-middleware)
- Removed a lot of checks—you should be checking your CSP with a different tool
- Removed support for legacy headers (and therefore the `setAllHeaders` parameter). [Read this if you need help.](https://github.com/helmetjs/helmet/wiki/Setting-legacy-Content-Security-Policy-headers-in-Helmet-4)
- Removed the `loose` option
- `helmet.frameguard`:
- Dropped support for the `ALLOW-FROM` action. [Read more here.](https://github.com/helmetjs/helmet/wiki/How-to-use-X%E2%80%93Frame%E2%80%93Options's-%60ALLOW%E2%80%93FROM%60-directive)
- `helmet.hidePoweredBy` no longer accepts arguments. See [this article](https://github.com/helmetjs/helmet/wiki/How-to-set-a-custom-X%E2%80%93Powered%E2%80%93By-header) to see how to replicate the removed behavior. See [#224](https://github.com/helmetjs/helmet/issues/224).
- `helmet.hsts`:
- Dropped support for `includeSubdomains` with a lowercase D. See [#231](https://github.com/helmetjs/helmet/issues/231)
- Dropped support for `setIf`. [Read this if you need help.](https://github.com/helmetjs/helmet/wiki/Conditionally-using-middleware). See [#232](https://github.com/helmetjs/helmet/issues/232)
- `helmet.xssFilter` no longer accepts options. Read ["How to disable blocking with X–XSS–Protection"](https://github.com/helmetjs/helmet/wiki/How-to-disable-blocking-with-X%E2%80%93XSS%E2%80%93Protection) and ["How to enable the `report` directive with X–XSS–Protection"](https://github.com/helmetjs/helmet/wiki/How-to-enable-the-%60report%60-directive-with-X%E2%80%93XSS%E2%80%93Protection) if you need the legacy behavior.
## 3.23.3 - 2020-06-26

@@ -4,0 +41,0 @@

170

dist/index.js

@@ -5,91 +5,111 @@ "use strict";

};
var expect_ct_1 = __importDefault(require("./middlewares/expect-ct"));
var x_dns_prefetch_control_1 = __importDefault(require("./middlewares/x-dns-prefetch-control"));
var x_download_options_1 = __importDefault(require("./middlewares/x-download-options"));
var x_frame_options_1 = __importDefault(require("./middlewares/x-frame-options"));
var depd = require("depd");
var deprecate = depd("helmet");
var DEFAULT_MIDDLEWARE = [
"dnsPrefetchControl",
"frameguard",
"hidePoweredBy",
"hsts",
"ieNoOpen",
"noSniff",
"xssFilter",
];
var middlewares = [
"contentSecurityPolicy",
"dnsPrefetchControl",
"expectCt",
"featurePolicy",
"frameguard",
"hidePoweredBy",
"hsts",
"ieNoOpen",
"noSniff",
"permittedCrossDomainPolicies",
"referrerPolicy",
"xssFilter",
"hpkp",
"noCache",
];
function helmet(options) {
if (options === void 0) { options = {}; }
Object.defineProperty(exports, "__esModule", { value: true });
const content_security_policy_1 = __importDefault(require("./middlewares/content-security-policy"));
const expect_ct_1 = __importDefault(require("./middlewares/expect-ct"));
const referrer_policy_1 = __importDefault(require("./middlewares/referrer-policy"));
const strict_transport_security_1 = __importDefault(require("./middlewares/strict-transport-security"));
const x_content_type_options_1 = __importDefault(require("./middlewares/x-content-type-options"));
const x_dns_prefetch_control_1 = __importDefault(require("./middlewares/x-dns-prefetch-control"));
const x_download_options_1 = __importDefault(require("./middlewares/x-download-options"));
const x_frame_options_1 = __importDefault(require("./middlewares/x-frame-options"));
const x_permitted_cross_domain_policies_1 = __importDefault(require("./middlewares/x-permitted-cross-domain-policies"));
const x_powered_by_1 = __importDefault(require("./middlewares/x-powered-by"));
const x_xss_protection_1 = __importDefault(require("./middlewares/x-xss-protection"));
function noop() { }
function helmet(options = {}) {
if (options.constructor.name === "IncomingMessage") {
throw new Error("It appears you have done something like `app.use(helmet)`, but it should be `app.use(helmet())`.");
}
var stack = middlewares.reduce(function (result, middlewareName) {
var middleware = helmet[middlewareName];
var middlewareOptions = options[middlewareName];
var isDefault = DEFAULT_MIDDLEWARE.indexOf(middlewareName) !== -1;
if (middlewareOptions === false) {
return result;
// This is overly verbose. It'd be nice to condense this while still being type-safe.
if (Object.values(options).some((option) => option === true)) {
throw new Error("Helmet no longer supports `true` as a middleware option. Remove the property from your options to fix this error.");
}
const middlewareFunctions = [];
if (options.contentSecurityPolicy === undefined) {
middlewareFunctions.push(content_security_policy_1.default());
}
else if (options.contentSecurityPolicy !== false) {
middlewareFunctions.push(content_security_policy_1.default(options.contentSecurityPolicy));
}
if (options.dnsPrefetchControl === undefined) {
middlewareFunctions.push(x_dns_prefetch_control_1.default());
}
else if (options.dnsPrefetchControl !== false) {
middlewareFunctions.push(x_dns_prefetch_control_1.default(options.dnsPrefetchControl));
}
if (options.expectCt === undefined) {
middlewareFunctions.push(expect_ct_1.default());
}
else if (options.expectCt !== false) {
middlewareFunctions.push(expect_ct_1.default(options.expectCt));
}
if (options.frameguard === undefined) {
middlewareFunctions.push(x_frame_options_1.default());
}
else if (options.frameguard !== false) {
middlewareFunctions.push(x_frame_options_1.default(options.frameguard));
}
if (options.hidePoweredBy !== false) {
if (options.hidePoweredBy !== undefined) {
console.warn("hidePoweredBy does not take options. Remove the property to silence this warning.");
}
else if (middlewareOptions === true) {
middlewareOptions = {};
middlewareFunctions.push(x_powered_by_1.default());
}
if (options.hsts === undefined || options.hsts === true) {
middlewareFunctions.push(strict_transport_security_1.default());
}
else if (options.hsts !== false) {
middlewareFunctions.push(strict_transport_security_1.default(options.hsts));
}
if (options.ieNoOpen !== false) {
if (options.ieNoOpen !== undefined) {
console.warn("ieNoOpen does not take options. Remove the property to silence this warning.");
}
if (middlewareOptions != null) {
return result.concat(middleware(middlewareOptions));
middlewareFunctions.push(x_download_options_1.default());
}
if (options.noSniff !== false) {
if (options.noSniff !== undefined) {
console.warn("noSniff does not take options. Remove the property to silence this warning.");
}
else if (isDefault) {
return result.concat(middleware({}));
middlewareFunctions.push(x_content_type_options_1.default());
}
if (options.permittedCrossDomainPolicies === undefined) {
middlewareFunctions.push(x_permitted_cross_domain_policies_1.default());
}
else if (options.permittedCrossDomainPolicies !== false) {
middlewareFunctions.push(x_permitted_cross_domain_policies_1.default(options.permittedCrossDomainPolicies));
}
if (options.referrerPolicy === undefined) {
middlewareFunctions.push(referrer_policy_1.default());
}
else if (options.referrerPolicy !== false) {
middlewareFunctions.push(referrer_policy_1.default(options.referrerPolicy));
}
if (options.xssFilter !== false) {
if (options.xssFilter !== undefined) {
console.warn("xssFilter does not take options. Remove the property to silence this warning.");
}
return result;
}, []);
return function helmet(req, res, next) {
var index = 0;
function internalNext() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (args.length > 0) {
next.apply(void 0, args);
return;
}
var middleware = stack[index];
if (!middleware) {
return next();
}
index++;
middleware(req, res, internalNext);
middlewareFunctions.push(x_xss_protection_1.default());
}
return function helmetMiddleware(req, res, next) {
// All of Helmet's middleware is synchronous today, so we can get away with this.
// If that changes, we'll need to do something smarter here.
for (const middlewareFunction of middlewareFunctions) {
middlewareFunction(req, res, noop);
}
internalNext();
next();
};
}
helmet.contentSecurityPolicy = require("helmet-csp");
helmet.contentSecurityPolicy = content_security_policy_1.default;
helmet.dnsPrefetchControl = x_dns_prefetch_control_1.default;
helmet.expectCt = expect_ct_1.default;
helmet.frameguard = x_frame_options_1.default;
helmet.hidePoweredBy = require("hide-powered-by");
helmet.hsts = require("hsts");
helmet.hidePoweredBy = x_powered_by_1.default;
helmet.hsts = strict_transport_security_1.default;
helmet.ieNoOpen = x_download_options_1.default;
helmet.noSniff = require("dont-sniff-mimetype");
helmet.permittedCrossDomainPolicies = require("helmet-crossdomain");
helmet.referrerPolicy = require("referrer-policy");
helmet.xssFilter = require("x-xss-protection");
helmet.featurePolicy = deprecate.function(require("feature-policy"), "helmet.featurePolicy is deprecated (along with the HTTP header) and will be removed in helmet@4. You can use the `feature-policy` module instead.");
helmet.hpkp = deprecate.function(require("hpkp"), "helmet.hpkp is deprecated and will be removed in helmet@4. You can use the `hpkp` module instead. For more, see https://github.com/helmetjs/helmet/issues/180.");
helmet.noCache = deprecate.function(require("nocache"), "helmet.noCache is deprecated and will be removed in helmet@4. You can use the `nocache` module instead. For more, see https://github.com/helmetjs/helmet/issues/215.");
helmet.noSniff = x_content_type_options_1.default;
helmet.permittedCrossDomainPolicies = x_permitted_cross_domain_policies_1.default;
helmet.referrerPolicy = referrer_policy_1.default;
helmet.xssFilter = x_xss_protection_1.default;
module.exports = helmet;
exports.default = helmet;

@@ -7,23 +7,24 @@ "use strict";

}
else if (typeof value === "number" && value >= 0) {
else if (typeof value === "number" &&
value >= 0 &&
Number.isFinite(value)) {
return Math.floor(value);
}
else {
throw new Error(value + " is not a valid value for maxAge. Please choose a positive integer.");
throw new Error(`Expect-CT: ${JSON.stringify(value)} is not a valid value for maxAge. Please choose a positive integer.`);
}
}
function getHeaderValueFromOptions(options) {
var directives = [];
const directives = [];
if (options.enforce) {
directives.push("enforce");
}
directives.push("max-age=" + parseMaxAge(options.maxAge));
directives.push(`max-age=${parseMaxAge(options.maxAge)}`);
if (options.reportUri) {
directives.push("report-uri=\"" + options.reportUri + "\"");
directives.push(`report-uri="${options.reportUri}"`);
}
return directives.join(", ");
}
function expectCt(options) {
if (options === void 0) { options = {}; }
var headerValue = getHeaderValueFromOptions(options);
function expectCt(options = {}) {
const headerValue = getHeaderValueFromOptions(options);
return function expectCtMiddleware(_req, res, next) {

@@ -30,0 +31,0 @@ res.setHeader("Expect-CT", headerValue);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function xDnsPrefetchControl(options) {
if (options === void 0) { options = {}; }
var headerValue = options.allow ? "on" : "off";
function xDnsPrefetchControl(options = {}) {
const headerValue = options.allow ? "on" : "off";
return function xDnsPrefetchControlMiddleware(_req, res, next) {

@@ -7,0 +6,0 @@ res.setHeader("X-DNS-Prefetch-Control", headerValue);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function parseActionOption(actionOption) {
var invalidActionErr = new Error('action must be undefined, "DENY", "ALLOW-FROM", or "SAMEORIGIN".');
if (actionOption === undefined) {
actionOption = "SAMEORIGIN";
function getHeaderValueFromOptions({ action = "SAMEORIGIN", }) {
action = String(action).toUpperCase();
if (action === "SAME-ORIGIN") {
return "SAMEORIGIN";
}
else if (actionOption instanceof String) {
actionOption = actionOption.valueOf();
else if (action === "DENY" || action === "SAMEORIGIN") {
return action;
}
var result;
if (typeof actionOption === "string") {
result = actionOption.toUpperCase();
else if (action === "ALLOW-FROM") {
throw new Error("X-Frame-Options no longer supports `ALLOW-FROM` due to poor browser support. See <https://github.com/helmetjs/helmet/wiki/How-to-use-X%E2%80%93Frame%E2%80%93Options's-%60ALLOW%E2%80%93FROM%60-directive> for more info.");
}
else {
throw invalidActionErr;
throw new Error(`X-Frame-Options received an invalid action ${JSON.stringify(action)}`);
}
if (result === "ALLOWFROM") {
result = "ALLOW-FROM";
}
else if (result === "SAME-ORIGIN") {
result = "SAMEORIGIN";
}
if (["DENY", "ALLOW-FROM", "SAMEORIGIN"].indexOf(result) === -1) {
throw invalidActionErr;
}
return result;
}
function parseDomainOption(domainOption) {
if (domainOption instanceof String) {
domainOption = domainOption.valueOf();
}
if (typeof domainOption !== "string") {
throw new Error("ALLOW-FROM action requires a string domain parameter.");
}
else if (!domainOption.length) {
throw new Error("domain parameter must not be empty.");
}
return domainOption;
}
function getHeaderValueFromOptions(options) {
var action = parseActionOption(options.action);
if (action === "ALLOW-FROM") {
var domain = parseDomainOption(options.domain);
return action + " " + domain;
}
else {
return action;
}
}
function xFrameOptions(options) {
if (options === void 0) { options = {}; }
var headerValue = getHeaderValueFromOptions(options);
function xFrameOptions(options = {}) {
const headerValue = getHeaderValueFromOptions(options);
return function xFrameOptionsMiddleware(_req, res, next) {

@@ -55,0 +21,0 @@ res.setHeader("X-Frame-Options", headerValue);

@@ -5,16 +5,11 @@ {

"contributors": [
"Evan Hahn <me@evanhahn.com> (https://evanhahn.com)"
"Evan Hahn <me@evanhahn.com> (https://evanhahn.com)",
"Ameen Abdeen <ameen.abdeen.se@gmail.com>"
],
"description": "help secure Express/Connect apps with various HTTP headers",
"version": "3.23.3",
"version": "4.0.0-alpha.1",
"keywords": [
"express",
"security",
"headers",
"express",
"connect",
"x-frame-options",
"x-powered-by",
"csp",
"hsts",
"clickjack"
"headers"
],

@@ -31,3 +26,3 @@ "homepage": "https://helmetjs.github.io/",

"engines": {
"node": ">=4.0.0"
"node": ">=10.0.0"
},

@@ -42,25 +37,31 @@ "files": [

"dist/index.js",
"dist/index.d.ts",
"dist/middlewares/content-security-policy/index.js",
"dist/middlewares/content-security-policy/index.d.ts",
"dist/middlewares/expect-ct/index.js",
"dist/middlewares/expect-ct/index.d.ts",
"dist/middlewares/referrer-policy/index.js",
"dist/middlewares/referrer-policy/index.d.ts",
"dist/middlewares/strict-transport-security/index.js",
"dist/middlewares/strict-transport-security/index.d.ts",
"dist/middlewares/x-content-type-options/index.js",
"dist/middlewares/x-content-type-options/index.d.ts",
"dist/middlewares/x-dns-prefetch-control/index.js",
"dist/middlewares/x-dns-prefetch-control/index.d.ts",
"dist/middlewares/x-download-options/index.js",
"dist/middlewares/x-frame-options/index.js"
"dist/middlewares/x-download-options/index.d.ts",
"dist/middlewares/x-frame-options/index.js",
"dist/middlewares/x-frame-options/index.d.ts",
"dist/middlewares/x-permitted-cross-domain-policies/index.js",
"dist/middlewares/x-permitted-cross-domain-policies/index.d.ts",
"dist/middlewares/x-powered-by/index.js",
"dist/middlewares/x-powered-by/index.d.ts",
"dist/middlewares/x-xss-protection/index.js",
"dist/middlewares/x-xss-protection/index.d.ts"
],
"dependencies": {
"depd": "2.0.0",
"dont-sniff-mimetype": "1.1.0",
"feature-policy": "0.3.0",
"helmet-crossdomain": "0.4.0",
"helmet-csp": "2.10.0",
"hide-powered-by": "1.1.0",
"hpkp": "2.0.0",
"hsts": "2.2.0",
"nocache": "2.1.0",
"referrer-policy": "1.2.0",
"x-xss-protection": "1.3.0"
},
"dependencies": {},
"devDependencies": {
"@types/connect": "^3.4.33",
"@types/depd": "^1.1.32",
"@types/jest": "^26.0.3",
"@types/supertest": "^2.0.9",
"@types/supertest": "^2.0.10",
"@typescript-eslint/eslint-plugin": "^3.4.0",

@@ -80,5 +81,5 @@ "@typescript-eslint/parser": "^3.4.0",

"lint": "npm run lint:eslint && npm run lint:prettier",
"lint:eslint": "eslint '**/*.ts'",
"lint:prettier": "prettier --check '**/*{md,js,json,ts}'",
"format": "prettier --write '**/*{md,js,json,ts}'",
"lint:eslint": "eslint \"**/*.ts\"",
"lint:prettier": "prettier --check \"**/*{md,js,json,ts}\"",
"format": "prettier --write \"**/*{md,js,json,ts}\"",
"clean": "rm -rf dist",

@@ -85,0 +86,0 @@ "build": "npm run clean && tsc",

@@ -10,7 +10,5 @@ # Helmet

[Looking for a version of Helmet that supports the Koa framework?](https://github.com/venables/koa-helmet)
## Quick start
First, run `npm install helmet --save` for your app. Then, in an Express (or Connect) app:
First, run `npm install helmet --save` for your app. Then, in an Express app:

@@ -28,14 +26,46 @@ ```js

It's best to `use` Helmet early in your middleware stack so that its headers are sure to be set.
## How it works
You can also use its pieces individually:
Helmet is [Connect](https://github.com/senchalabs/connect)-style middleware, which is compatible with frameworks like [Express](https://expressjs.com/). (If you need support for Koa, see [`koa-helmet`](https://github.com/venables/koa-helmet).)
The top-level `helmet` function is a wrapper around 11 smaller middlewares.
In other words, these two things are equivalent:
```js
// This...
app.use(helmet());
// ...is equivalent to this:
app.use(helmet.contentSecurityPolicy());
app.use(helmet.dnsPrefetchControl());
app.use(helmet.expectCt());
app.use(helmet.frameguard());
app.use(helmet.hidePoweredBy());
app.use(helmet.hsts());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.referrerPolicy());
app.use(helmet.xssFilter());
app.use(helmet.frameguard());
```
You can disable a middleware that's normally enabled by default. This will disable `frameguard` but include the other defaults.
## Reference
<details>
<summary><code>helmet(options)</code></summary>
Helmet is the top-level middleware for this module, including all 11 others.
All 11 middlewares are enabled by default.
```js
// Includes all 11 middlewares
app.use(helmet());
```
If you want to disable one, pass options to `helmet`. For example, to disable `frameguard`:
```js
// Includes 10 middlewares, skipping `helmet.frameguard`
app.use(

@@ -48,5 +78,6 @@ helmet({

You can also set options for a middleware. Setting options like this will _always_ include the middleware, whether or not it's a default.
Most of the middlewares have options, which are documented in more detail below. For example, to pass `{ action: "deny" }` to `frameguard`:
```js
// Includes all 11 middlewares, setting an option for `helmet.frameguard`
app.use(

@@ -61,22 +92,339 @@ helmet({

_If you're using Express 3, make sure these middlewares are listed before `app.router`._
Each middleware's name is listed below.
## How it works
</details>
Helmet is a collection of 11 smaller middleware functions that set HTTP response headers. Running `app.use(helmet())` will not include all of these middleware functions by default.
<details>
<summary><code>helmet.contentSecurityPolicy(options)</code></summary>
| Module | Default? |
| ------------------------------------------------------------------------------------------------------------- | -------- |
| [contentSecurityPolicy](https://helmetjs.github.io/docs/csp/) for setting Content Security Policy | |
| [crossdomain](https://helmetjs.github.io/docs/crossdomain/) for handling Adobe products' crossdomain requests | |
| [dnsPrefetchControl](https://helmetjs.github.io/docs/dns-prefetch-control) controls browser DNS prefetching | ✓ |
| [expectCt](https://helmetjs.github.io/docs/expect-ct/) for handling Certificate Transparency | |
| [frameguard](https://helmetjs.github.io/docs/frameguard/) to prevent clickjacking | ✓ |
| [hidePoweredBy](https://helmetjs.github.io/docs/hide-powered-by) to remove the X-Powered-By header | ✓ |
| [hsts](https://helmetjs.github.io/docs/hsts/) for HTTP Strict Transport Security | ✓ |
| [ieNoOpen](https://helmetjs.github.io/docs/ienoopen) sets X-Download-Options for IE8+ | ✓ |
| [noSniff](https://helmetjs.github.io/docs/dont-sniff-mimetype) to keep clients from sniffing the MIME type | ✓ |
| [referrerPolicy](https://helmetjs.github.io/docs/referrer-policy) to hide the Referer header | |
| [xssFilter](https://helmetjs.github.io/docs/xss-filter) adds some small XSS protections | ✓ |
`helmet.contentSecurityPolicy` sets the `Content-Security-Policy` header which helps mitigate cross-site scripting attacks, among other things. See [MDN's introductory article on Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP).
You can see more in [the documentation](https://helmetjs.github.io/docs/).
This middleware performs very little validation. You should rely on CSP checkers like [CSP Evaluator](https://csp-evaluator.withgoogle.com/) instead.
`options.directives` is an object. Each key is a directive name in camel case (such as `defaultSrc`) or kebab case (such as `default-src`). Each value is an iterable (usually an array) of strings for that directive.
`options.reportOnly` is a boolean, defaulting to `false`. If `true`, [the `Content-Security-Policy-Report-Only` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only) will be set instead.
If no directives are supplied, the following policy is set (whitespace added for readability):
default-src 'self';
base-uri 'self';
block-all-mixed-content;
font-src 'self' https: data:;
frame-ancestors 'self';
img-src 'self' data:;
object-src 'none';
script-src 'self';
script-src-attr 'none';
style-src 'self' https: 'unsafe-inline';
upgrade-insecure-requests
Examples:
```js
// Sets "Content-Security-Policy: default-src 'self';script-src 'self' example.com;object-src 'none';upgrade-insecure-requests"
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "example.com"],
objectSrc: ["'none'"],
upgradeInsecureRequests: [],
},
})
);
// Sets "Content-Security-Policy: default-src 'self';script-src 'self' example.com;object-src 'none'"
app.use(
helmet.contentSecurityPolicy({
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "example.com"],
"object-src": ["'none'"],
},
})
);
// Sets the "Content-Security-Policy-Report-Only" header instead
app.use(
helmet.contentSecurityPolicy({
directives: {
/* ... */
},
reportOnly: true,
})
);
```
See [this wiki page](https://github.com/helmetjs/helmet/wiki/Conditionally-using-middleware#i-want-to-use-some-middleware-with-different-options) to see how to set directives conditionally (to set per-request nonces, for example).
You can install this module separately as `helmet-csp`.
</details>
<details>
<summary><code>helmet.expectCt(options)</code></summary>
`helmet.expectCt` sets the `Expect-CT` header which helps mitigate misissued SSL certificates. See [MDN's article on Certificate Transparency](https://developer.mozilla.org/en-US/docs/Web/Security/Certificate_Transparency) and the [`Expect-CT` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect-CT) for more.
`options.maxAge` is the number of seconds to expect Certificate Transparency. It defaults to `0`.
`options.enforce` is a boolean. If `true`, the user agent (usually a browser) should refuse future connections that violate its Certificate Transparency policy. Defaults to `false`.
`options.reportUri` is a string. If set, complying user agents will report Certificate Transparency failures to this URL. Unset by default.
Examples:
```js
// Sets "Expect-CT: max-age=86400"
app.use(
helmet.expectCt({
maxAge: 86400,
})
);
// Sets "Expect-CT: max-age=86400, enforce, report-uri="https://example.com/report"
app.use(
helmet.expectCt({
maxAge: 86400,
enforce: true,
reportUri: "https://example.com/report",
})
);
```
You can install this module separately as `expect-ct`.
</details>
<details>
<summary><code>helmet.referrerPolicy(options)</code></summary>
`helmet.referrerPolicy` sets the `Referrer-Policy` header which controls what information is set in [the `Referer` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer). See ["Referer header: privacy and security concerns"](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) and [the header's documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) on MDN for more.
`options.policy` is a string or array of strings representing the policy. If passed as an array, it will be joined with commas, which is useful when setting [a fallback policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#Specifying_a_fallback_policy). It defaults to `no-referrer`.
Examples:
```js
// Sets "Referrer-Policy: no-referrer"
app.use(
helmet.referrerPolicy({
policy: "no-referrer",
})
);
// Sets "Referrer-Policy: origin,unsafe-url"
app.use(
helmet.referrerPolicy({
policy: ["origin", "unsafe-url"],
})
);
```
You can install this module separately as `referrer-policy`.
</details>
<details>
<summary><code>helmet.hsts(options)</code></summary>
`helmet.hsts` sets the `Strict-Transport-Security` header which tells browsers to prefer HTTPS over insecure HTTP. See [the documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) for more.
`options.maxAge` is the number of seconds browsers should remember to prefer HTTPS. If passed a non-integer, the value is rounded down. It defaults to `15552000`, which is 180 days.
`options.includeSubDomains` is a boolean which dictates whether to include the `includeSubDomains` directive, which makes this policy extend to subdomains. It defaults to `true`.
`options.preload` is a boolean. If true, it adds the `preload` directive, expressing intent to add your HSTS policy to browsers. See [the "Preloading Strict Transport Security" section on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security#Preloading_Strict_Transport_Security) for more. It defaults to `false`.
Examples:
```js
// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains"
app.use(
helmet.strictTransportSecurity({
maxAge: 123456,
})
);
// Sets "Strict-Transport-Security: max-age=123456"
app.use(
helmet.strictTransportSecurity({
maxAge: 123456,
includeSubDomains: false,
})
);
// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains; preload"
app.use(
helmet.strictTransportSecurity({
maxAge: 63072000,
preload: true,
})
);
```
You can install this module separately as `hsts`.
</details>
<details>
<summary><code>helmet.noSniff()</code></summary>
`helmet.noSniff` sets the `X-Content-Type-Options` header to `nosniff`. This mitigates [MIME type sniffing](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#MIME_sniffing) which can cause security vulnerabilities. See [documentation for this header on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options) for more.
This middleware takes no options.
Example:
```js
// Sets "X-Content-Type-Options: nosniff"
app.use(helmet.noSniff());
```
You can install this module separately as `dont-sniff-mimetype`.
</details>
<details>
<summary><code>helmet.dnsPrefetchControl(options)</code></summary>
`helmet.dnsPrefetchControl` sets the `X-DNS-Prefetch-Control` header to help control DNS prefetching, which can improve user privacy at the expense of performance. See [documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control) for more.
`options.allow` is a boolean dictating whether to enable DNS prefetching. It defaults to `false`.
Examples:
```js
// Sets "X-DNS-Prefetch-Control: off"
app.use(
helmet.dnsPrefetchControl({
allow: false,
})
);
// Sets "X-DNS-Prefetch-Control: on"
app.use(
helmet.dnsPrefetchControl({
allow: true,
})
);
```
You can install this module separately as `dns-prefetch-control`.
</details>
<details>
<summary><code>helmet.ieNoOpen()</code></summary>
`helmet.ieNoOpen` sets the `X-Download-Options` header, which is specific to Internet Explorer 8. It forces potentially-unsafe downloads to be saved, mitigating execution of HTML in your site's context. For more, see [this old post on MSDN](https://docs.microsoft.com/en-us/archive/blogs/ie/ie8-security-part-v-comprehensive-protection).
This middleware takes no options.
Examples:
```js
// Sets "X-Download-Options: noopen"
app.use(helmet.ieNoOpen());
```
You can install this module separately as `ienoopen`.
</details>
<details>
<summary><code>helmet.frameguard(options)</code></summary>
`helmet.frameguard` sets the `X-Frame-Options` header to help you mitigate [clickjacking attacks](https://en.wikipedia.org/wiki/Clickjacking). This header is superseded by [the `frame-ancestors` Content Security Policy directive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors) but is still useful on old browsers. For more, see [the documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options).
`options.action` is a string that specifies which directive to use—either `DENY` or `SAMEORIGIN`. (A legacy directive, `ALLOW-FROM`, is not supported by this middleware. [Read more here.](https://github.com/helmetjs/helmet/wiki/How-to-use-X%E2%80%93Frame%E2%80%93Options's-%60ALLOW%E2%80%93FROM%60-directive)) It defaults to `SAMEORIGIN`.
Examples:
```js
// Sets "X-Frame-Options: DENY"
app.use(
helmet.frameguard({
action: "deny",
})
);
// Sets "X-Frame-Options: SAMEORIGIN"
app.use(
helmet.frameguard({
action: "sameorigin",
})
);
```
You can install this module separately as `frameguard`.
</details>
<details>
<summary><code>helmet.permittedCrossDomainPolicies(options)</code></summary>
`helmet.permittedCrossDomainPolicies` sets the `X-Permitted-Cross-Domain-Policies` header, which tells some clients (mostly Adobe products) your domain's policy for loading cross-domain content. See [the description on OWASP](https://owasp.org/www-project-secure-headers/) for more.
`options.permittedPolicies` is a string that must be `"none"`, `"master-only"`, `"by-content-type"`, or `"all"`. It defaults to `"none"`.
Examples:
```js
// Sets "X-Permitted-Cross-Domain-Policies: none"
app.use(
helmet.permittedCrossDomainPolicies({
permittedPolicies: "none",
})
);
// Sets "X-Permitted-Cross-Domain-Policies: by-content-type"
app.use(
helmet.permittedCrossDomainPolicies({
permittedPolicies: "by-content-type",
})
);
```
You can install this module separately as `helmet-crossdomain`.
</details>
<details>
<summary><code>helmet.hidePoweredBy(options)</code></summary>
`helmet.hidePoweredBy` removes the `X-Powered-By` header, which is set by default in some frameworks (like Express). Removing the header offers very limited security benefits (see [this discussion](https://github.com/expressjs/express/pull/2813#issuecomment-159270428)) and is mostly removed to save bandwidth.
This middleware takes no options.
If you're using Express, this middleware will work, but you should use `app.disable("x-powered-by")` instead.
Examples:
```js
// Removes the X-Powered-By header if it was set.
app.use(helmet.hidePoweredBy());
```
You can install this module separately as `hide-powered-by`.
</details>
<details>
<summary><code>helmet.xssFilter(options)</code></summary>
`helmet.xssFilter` disables browsers' buggy cross-site scripting filter by setting the `X-XSS-Protection` header to `0`. See [discussion about disabling the header here](https://github.com/helmetjs/helmet/issues/230) and [documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection).
This middleware takes no options.
Examples:
```js
// Sets "X-XSS-Protection: 0"
app.use(helmet.xssFilter());
```
You can install this module separately as `x-xss-protection`.
</details>
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc