UNPKG

20.2 kBMarkdownView Raw
1# Helmet
2
3[![npm version](https://badge.fury.io/js/helmet.svg)](https://badge.fury.io/js/helmet)
4[![npm dependency status](https://david-dm.org/helmetjs/helmet.svg)](https://david-dm.org/helmetjs/helmet)
5[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fhelmetjs%2Fhelmet.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fhelmetjs%2Fhelmet?ref=badge_shield)
6
7Helmet helps you secure your Express apps by setting various HTTP headers. _It's not a silver bullet_, but it can help!
8
9## Quick start
10
11First, run `npm install helmet --save` for your app. Then, in an Express app:
12
13```js
14const express = require("express");
15const helmet = require("helmet");
16
17const app = express();
18
19app.use(helmet());
20
21// ...
22```
23
24## How it works
25
26Helmet 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).)
27
28The top-level `helmet` function is a wrapper around 15 smaller middlewares, 11 of which are enabled by default.
29
30In other words, these two things are equivalent:
31
32```js
33// This...
34app.use(helmet());
35
36// ...is equivalent to this:
37app.use(helmet.contentSecurityPolicy());
38app.use(helmet.dnsPrefetchControl());
39app.use(helmet.expectCt());
40app.use(helmet.frameguard());
41app.use(helmet.hidePoweredBy());
42app.use(helmet.hsts());
43app.use(helmet.ieNoOpen());
44app.use(helmet.noSniff());
45app.use(helmet.permittedCrossDomainPolicies());
46app.use(helmet.referrerPolicy());
47app.use(helmet.xssFilter());
48```
49
50To set custom options for one of the middleware, add options like this:
51
52```js
53// This sets custom options for the `referrerPolicy` middleware.
54app.use(
55 helmet({
56 referrerPolicy: { policy: "no-referrer" },
57 })
58);
59```
60
61You can also disable a middleware:
62
63```js
64// This disables the `contentSecurityPolicy` middleware but keeps the rest.
65app.use(
66 helmet({
67 contentSecurityPolicy: false,
68 })
69);
70```
71
72## Reference
73
74<details>
75<summary><code>helmet(options)</code></summary>
76
77Helmet is the top-level middleware for this module, including all 15 others.
78
7911 of 15 middlewares are included by default. `crossOriginEmbedderPolicy`, `crossOriginOpenerPolicy`, `crossOriginResourcePolicy`, and `originAgentCluster` are not included by default. They must be explicitly enabled. They will be turned on by default in the next major version of Helmet.
80
81```js
82// Includes all 11 middlewares
83app.use(helmet());
84```
85
86If you want to disable one, pass options to `helmet`. For example, to disable `frameguard`:
87
88```js
89// Includes 10 middlewares, skipping `helmet.frameguard`
90app.use(
91 helmet({
92 frameguard: false,
93 })
94);
95```
96
97Most of the middlewares have options, which are documented in more detail below. For example, to pass `{ action: "deny" }` to `frameguard`:
98
99```js
100// Includes all 11 middlewares, setting an option for `helmet.frameguard`
101app.use(
102 helmet({
103 frameguard: {
104 action: "deny",
105 },
106 })
107);
108```
109
110Each middleware's name is listed below.
111
112</details>
113
114<details>
115<summary><code>helmet.contentSecurityPolicy(options)</code></summary>
116
117`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).
118
119This middleware performs very little validation. You should rely on CSP checkers like [CSP Evaluator](https://csp-evaluator.withgoogle.com/) instead.
120
121`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 or functions for that directive. If a function appears in the iterable, it will be called with the request and response. The `default-src` can be explicitly disabled by setting its value to `helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc`.
122
123`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.
124
125If no directives are supplied, the following policy is set (whitespace added for readability):
126
127 default-src 'self';
128 base-uri 'self';
129 block-all-mixed-content;
130 font-src 'self' https: data:;
131 frame-ancestors 'self';
132 img-src 'self' data:;
133 object-src 'none';
134 script-src 'self';
135 script-src-attr 'none';
136 style-src 'self' https: 'unsafe-inline';
137 upgrade-insecure-requests
138
139You can use this default with the `options.useDefaults` option. `options.useDefaults` is `false` by default, but will be `true` in the next major version of Helmet.
140
141You can also get the default directives object with `helmet.contentSecurityPolicy.getDefaultDirectives()`.
142
143Examples:
144
145```js
146// Sets all of the defaults, but overrides `script-src` and disables the default `style-src`
147app.use(
148 helmet.contentSecurityPolicy({
149 useDefaults: true,
150 directives: {
151 "script-src": ["'self'", "example.com"],
152 "style-src": null,
153 },
154 })
155);
156
157// Sets "Content-Security-Policy: default-src 'self';script-src 'self' example.com;object-src 'none';upgrade-insecure-requests"
158app.use(
159 helmet.contentSecurityPolicy({
160 useDefaults: false,
161 directives: {
162 defaultSrc: ["'self'"],
163 scriptSrc: ["'self'", "example.com"],
164 objectSrc: ["'none'"],
165 upgradeInsecureRequests: [],
166 },
167 })
168);
169
170// Sets the "Content-Security-Policy-Report-Only" header instead
171app.use(
172 helmet.contentSecurityPolicy({
173 useDefaults: true,
174 directives: {
175 /* ... */
176 },
177 reportOnly: true,
178 })
179);
180
181// Sets the `script-src` directive to "'self' 'nonce-e33ccde670f149c1789b1e1e113b0916'" (or similar)
182app.use((req, res, next) => {
183 res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
184 next();
185});
186app.use(
187 helmet.contentSecurityPolicy({
188 useDefaults: true,
189 directives: {
190 scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
191 },
192 })
193);
194
195// Sets "Content-Security-Policy: script-src 'self'"
196app.use(
197 helmet.contentSecurityPolicy({
198 useDefaults: false,
199 directives: {
200 "default-src": helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc,
201 "script-src": ["'self'"],
202 },
203 })
204);
205```
206
207You can install this module separately as `helmet-csp`.
208
209</details>
210
211<details>
212<summary><code>helmet.crossOriginEmbedderPolicy()</code></summary>
213
214`helmet.crossOriginEmbedderPolicy` sets the `Cross-Origin-Embedder-Policy` header to `require-corp`. See [MDN's article on this header](https://developer.cdn.mozilla.net/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) for more.
215
216This middleware is not included when calling `helmet()` by default, and must be enabled explicitly. It will be enabled by default in the next major version of Helmet.
217
218Example usage with Helmet:
219
220```js
221// Uses the default Helmet options and adds the `crossOriginEmbedderPolicy` middleware.
222// Sets "Cross-Origin-Embedder-Policy: require-corp"
223app.use(helmet({ crossOriginEmbedderPolicy: true }));
224```
225
226Standalone example:
227
228```js
229// Sets "Cross-Origin-Embedder-Policy: require-corp"
230app.use(helmet.crossOriginEmbedderPolicy());
231```
232
233You can't install this module separately.
234
235</details>
236
237<details>
238<summary><code>helmet.crossOriginOpenerPolicy()</code></summary>
239
240`helmet.crossOriginOpenerPolicy` sets the `Cross-Origin-Opener-Policy` header. For more, see [MDN's article on this header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy).
241
242This middleware is not included when calling `helmet()` by default, and must be enabled explicitly. It will be enabled by default in the next major version of Helmet.
243
244Example usage with Helmet:
245
246```js
247// Uses the default Helmet options and adds the `crossOriginOpenerPolicy` middleware.
248
249// Sets "Cross-Origin-Opener-Policy: same-origin"
250app.use(helmet({ crossOriginOpenerPolicy: true }));
251
252// Sets "Cross-Origin-Opener-Policy: same-origin-allow-popups"
253app.use(
254 helmet({ crossOriginOpenerPolicy: { policy: "same-origin-allow-popups" } })
255);
256```
257
258Standalone example:
259
260```js
261// Sets "Cross-Origin-Opener-Policy: same-origin"
262app.use(helmet.crossOriginOpenerPolicy());
263
264// Sets "Cross-Origin-Opener-Policy: same-origin-allow-popups"
265app.use(helmet.crossOriginOpenerPolicy({ policy: "same-origin-allow-popups" }));
266
267// Sets "unsafe-none-Opener-Policy: unsafe-none"
268app.use(helmet.crossOriginOpenerPolicy({ policy: "unsafe-none" }));
269```
270
271You can't install this module separately.
272
273</details>
274
275<details>
276<summary><code>helmet.crossOriginResourcePolicy()</code></summary>
277
278`helmet.crossOriginResourcePolicy` sets the `Cross-Origin-Resource-Policy` header. For more, see ["Consider deploying Cross-Origin Resource Policy](https://resourcepolicy.fyi/) and [MDN's article on this header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy).
279
280This middleware is not included when calling `helmet()` by default, and must be enabled explicitly. It will be enabled by default in the next major version of Helmet.
281
282Example usage with Helmet:
283
284```js
285// Uses the default Helmet options and adds the `crossOriginResourcePolicy` middleware.
286
287// Sets "Cross-Origin-Resource-Policy: same-origin"
288app.use(helmet({ crossOriginResourcePolicy: true }));
289
290// Sets "Cross-Origin-Resource-Policy: same-site"
291app.use(helmet({ crossOriginResourcePolicy: { policy: "same-site" } }));
292```
293
294Standalone example:
295
296```js
297// Sets "Cross-Origin-Resource-Policy: same-origin"
298app.use(helmet.crossOriginResourcePolicy());
299
300// Sets "Cross-Origin-Resource-Policy: same-site"
301app.use(helmet.crossOriginResourcePolicy({ policy: "same-site" }));
302
303// Sets "Cross-Origin-Resource-Policy: cross-origin"
304app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
305```
306
307You can install this module separately as `cross-origin-resource-policy`.
308
309</details>
310
311<details>
312<summary><code>helmet.expectCt(options)</code></summary>
313
314`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.
315
316`options.maxAge` is the number of seconds to expect Certificate Transparency. It defaults to `0`.
317
318`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`.
319
320`options.reportUri` is a string. If set, complying user agents will report Certificate Transparency failures to this URL. Unset by default.
321
322Examples:
323
324```js
325// Sets "Expect-CT: max-age=86400"
326app.use(
327 helmet.expectCt({
328 maxAge: 86400,
329 })
330);
331
332// Sets "Expect-CT: max-age=86400, enforce, report-uri="https://example.com/report"
333app.use(
334 helmet.expectCt({
335 maxAge: 86400,
336 enforce: true,
337 reportUri: "https://example.com/report",
338 })
339);
340```
341
342You can install this module separately as `expect-ct`.
343
344</details>
345
346<details>
347<summary><code>helmet.referrerPolicy(options)</code></summary>
348
349`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.
350
351`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`.
352
353Examples:
354
355```js
356// Sets "Referrer-Policy: no-referrer"
357app.use(
358 helmet.referrerPolicy({
359 policy: "no-referrer",
360 })
361);
362
363// Sets "Referrer-Policy: origin,unsafe-url"
364app.use(
365 helmet.referrerPolicy({
366 policy: ["origin", "unsafe-url"],
367 })
368);
369```
370
371You can install this module separately as `referrer-policy`.
372
373</details>
374
375<details>
376<summary><code>helmet.hsts(options)</code></summary>
377
378`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.
379
380`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.
381
382`options.includeSubDomains` is a boolean which dictates whether to include the `includeSubDomains` directive, which makes this policy extend to subdomains. It defaults to `true`.
383
384`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`.
385
386Examples:
387
388```js
389// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains"
390app.use(
391 helmet.hsts({
392 maxAge: 123456,
393 })
394);
395
396// Sets "Strict-Transport-Security: max-age=123456"
397app.use(
398 helmet.hsts({
399 maxAge: 123456,
400 includeSubDomains: false,
401 })
402);
403
404// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains; preload"
405app.use(
406 helmet.hsts({
407 maxAge: 63072000,
408 preload: true,
409 })
410);
411```
412
413You can install this module separately as `hsts`.
414
415</details>
416
417<details>
418<summary><code>helmet.noSniff()</code></summary>
419
420`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.
421
422This middleware takes no options.
423
424Example:
425
426```js
427// Sets "X-Content-Type-Options: nosniff"
428app.use(helmet.noSniff());
429```
430
431You can install this module separately as `dont-sniff-mimetype`.
432
433</details>
434
435<details>
436<summary><code>helmet.originAgentCluster()</code></summary>
437
438`helmet.originAgentCluster` sets the `Origin-Agent-Cluster` header, which provides a mechanism to allow web applications to isolate their origins. Read more about it [in the spec](https://whatpr.org/html/6214/origin.html#origin-keyed-agent-clusters).
439
440This middleware is not included when calling `helmet()` by default, and must be enabled explicitly. It will be enabled by default in the next major version of Helmet.
441
442Example usage with Helmet:
443
444```js
445// Uses the default Helmet options and adds the `originAgentCluster` middleware.
446// Sets "Origin-Agent-Cluster: ?1"
447app.use(helmet({ originAgentCluster: true }));
448```
449
450Standalone example:
451
452```js
453// Sets "Origin-Agent-Cluster: ?1"
454app.use(helmet.originAgentCluster());
455```
456
457You can't install this module separately.
458
459</details>
460
461<details>
462<summary><code>helmet.dnsPrefetchControl(options)</code></summary>
463
464`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.
465
466`options.allow` is a boolean dictating whether to enable DNS prefetching. It defaults to `false`.
467
468Examples:
469
470```js
471// Sets "X-DNS-Prefetch-Control: off"
472app.use(
473 helmet.dnsPrefetchControl({
474 allow: false,
475 })
476);
477
478// Sets "X-DNS-Prefetch-Control: on"
479app.use(
480 helmet.dnsPrefetchControl({
481 allow: true,
482 })
483);
484```
485
486You can install this module separately as `dns-prefetch-control`.
487
488</details>
489
490<details>
491<summary><code>helmet.ieNoOpen()</code></summary>
492
493`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).
494
495This middleware takes no options.
496
497Examples:
498
499```js
500// Sets "X-Download-Options: noopen"
501app.use(helmet.ieNoOpen());
502```
503
504You can install this module separately as `ienoopen`.
505
506</details>
507
508<details>
509<summary><code>helmet.frameguard(options)</code></summary>
510
511`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).
512
513`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`.
514
515Examples:
516
517```js
518// Sets "X-Frame-Options: DENY"
519app.use(
520 helmet.frameguard({
521 action: "deny",
522 })
523);
524
525// Sets "X-Frame-Options: SAMEORIGIN"
526app.use(
527 helmet.frameguard({
528 action: "sameorigin",
529 })
530);
531```
532
533You can install this module separately as `frameguard`.
534
535</details>
536
537<details>
538<summary><code>helmet.permittedCrossDomainPolicies(options)</code></summary>
539
540`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.
541
542`options.permittedPolicies` is a string that must be `"none"`, `"master-only"`, `"by-content-type"`, or `"all"`. It defaults to `"none"`.
543
544Examples:
545
546```js
547// Sets "X-Permitted-Cross-Domain-Policies: none"
548app.use(
549 helmet.permittedCrossDomainPolicies({
550 permittedPolicies: "none",
551 })
552);
553
554// Sets "X-Permitted-Cross-Domain-Policies: by-content-type"
555app.use(
556 helmet.permittedCrossDomainPolicies({
557 permittedPolicies: "by-content-type",
558 })
559);
560```
561
562You can install this module separately as `helmet-crossdomain`.
563
564</details>
565
566<details>
567<summary><code>helmet.hidePoweredBy()</code></summary>
568
569`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.
570
571This middleware takes no options.
572
573If you're using Express, this middleware will work, but you should use `app.disable("x-powered-by")` instead.
574
575Examples:
576
577```js
578// Removes the X-Powered-By header if it was set.
579app.use(helmet.hidePoweredBy());
580```
581
582You can install this module separately as `hide-powered-by`.
583
584</details>
585
586<details>
587<summary><code>helmet.xssFilter()</code></summary>
588
589`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).
590
591This middleware takes no options.
592
593Examples:
594
595```js
596// Sets "X-XSS-Protection: 0"
597app.use(helmet.xssFilter());
598```
599
600You can install this module separately as `x-xss-protection`.
601
602</details>