helmify 0.0.0-stage → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of helmify might be problematic. Click here for more details.

package/SECURITY.md ADDED
@@ -0,0 +1,11 @@
1
+ # Security issue reporting & disclosure process
2
+
3
+ Please reach out if you think you've found a security issue.
4
+
5
+ Email Evan Hahn at <me@evanhahn.com>, on Signal at [EvanHahn.64](https://signal.me/#eu/vDide_HmUgHnNa0usMXq8oHAA0gnl5dzCqDeHyXhkeIbIiOcPVhCZKXIZteSqoc8), or [in other ways](https://evanhahn.com/contact).
6
+
7
+ My playbook for security issues:
8
+
9
+ - Acknowledge and address the concern as soon as possible
10
+ - Issue advisories (CVEs, for example) as needed. Public disclosure may be embargoed to give people time to update
11
+ - Consider patching non-current major versions depending on popularity and severity
package/index.cjs ADDED
@@ -0,0 +1,617 @@
1
+ "use strict"
2
+
3
+ Object.defineProperties(exports, {__esModule: {value: true}, [Symbol.toStringTag]: {value: "Module"}})
4
+
5
+ const dashify = str => str.replace(/[A-Z]/g, capitalLetter => "-" + capitalLetter.toLowerCase())
6
+ const errify = err => (err instanceof Error ? err : new Error(String(err)))
7
+ const isString = value => typeof value === "string"
8
+ const throwErrorIfExists = err => {
9
+ if (err) throw err
10
+ }
11
+ const getLogger = require('gloggo');
12
+ var logger = getLogger('Log');
13
+
14
+ const dangerouslyDisableDefaultSrc = Symbol("dangerouslyDisableDefaultSrc")
15
+ const SHOULD_BE_QUOTED = new Set(["none", "self", "strict-dynamic", "report-sample", "inline-speculation-rules", "unsafe-inline", "unsafe-eval", "unsafe-hashes", "wasm-unsafe-eval"])
16
+ const getDefaultDirectives = () => ({
17
+ "default-src": ["'self'"],
18
+ "base-uri": ["'self'"],
19
+ "font-src": ["'self'", "https:", "data:"],
20
+ "form-action": ["'self'"],
21
+ "frame-ancestors": ["'self'"],
22
+ "img-src": ["'self'", "data:"],
23
+ "object-src": ["'none'"],
24
+ "script-src": ["'self'"],
25
+ "script-src-attr": ["'none'"],
26
+ "style-src": ["'self'", "https:", "'unsafe-inline'"],
27
+ "upgrade-insecure-requests": []
28
+ })
29
+ const parseDirectiveName = rawDirectiveName => {
30
+ if (rawDirectiveName.length === 0 || !/^[a-z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(rawDirectiveName)) {
31
+ throw new Error(`Content-Security-Policy received an invalid directive name ${JSON.stringify(rawDirectiveName)}`)
32
+ }
33
+ return dashify(rawDirectiveName)
34
+ }
35
+ const getDirectiveValueValidationError = (directiveName, directiveValue) => (/;|,/.test(directiveValue) ? new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`) : null)
36
+ const getDirectiveValueEntryValidationError = (directiveName, directiveValueEntry) => (SHOULD_BE_QUOTED.has(directiveValueEntry) || directiveValueEntry.startsWith("nonce-") || directiveValueEntry.startsWith("sha256-") || directiveValueEntry.startsWith("sha384-") || directiveValueEntry.startsWith("sha512-") ? new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}. ${JSON.stringify(directiveValueEntry)} should be quoted`) : null)
37
+ const stringifyDirectiveValue = directiveValue => {
38
+ if (Array.isArray(directiveValue)) {
39
+ return directiveValue.every(isString) ? directiveValue.join(" ") : null
40
+ }
41
+ if (directiveValue instanceof Set) {
42
+ return stringifyDirectiveValue(Array.from(directiveValue))
43
+ }
44
+ return null
45
+ }
46
+ const parseDirectives = ({useDefaults = true, directives: rawDirectives = {}}) => {
47
+ const result = new Map(useDefaults ? Object.entries(getDefaultDirectives()) : [])
48
+ let hasDisabledDefaultSrc = false
49
+ const directiveNamesSeen = new Set()
50
+ for (const rawDirectiveName in rawDirectives) {
51
+ if (!Object.hasOwn(rawDirectives, rawDirectiveName)) {
52
+ continue
53
+ }
54
+ const directiveName = parseDirectiveName(rawDirectiveName)
55
+ if (directiveNamesSeen.has(directiveName)) {
56
+ throw new Error(`Content-Security-Policy received a duplicate directive ${JSON.stringify(directiveName)}`)
57
+ }
58
+ directiveNamesSeen.add(directiveName)
59
+ const rawDirectiveValue = rawDirectives[rawDirectiveName]
60
+ let directiveValue
61
+ if (rawDirectiveValue === null) {
62
+ if (directiveName === "default-src") {
63
+ throw new Error("Content-Security-Policy needs a default-src but it was set to `null`. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.")
64
+ }
65
+ result.delete(directiveName)
66
+ continue
67
+ } else if (typeof rawDirectiveValue === "string") {
68
+ directiveValue = [rawDirectiveValue]
69
+ } else if (rawDirectiveValue === dangerouslyDisableDefaultSrc) {
70
+ if (directiveName === "default-src") {
71
+ hasDisabledDefaultSrc = true
72
+ result.delete(directiveName)
73
+ continue
74
+ } else {
75
+ throw new Error(`Content-Security-Policy: tried to disable ${JSON.stringify(directiveName)} as if it were default-src; simply omit the key`)
76
+ }
77
+ } else if (rawDirectiveValue) {
78
+ directiveValue = rawDirectiveValue
79
+ } else {
80
+ throw new Error(`Content-Security-Policy received an invalid directive value for ${JSON.stringify(directiveName)}`)
81
+ }
82
+ for (const element of directiveValue) {
83
+ if (typeof element !== "string") continue
84
+ throwErrorIfExists(getDirectiveValueValidationError(directiveName, element) ?? getDirectiveValueEntryValidationError(directiveName, element))
85
+ }
86
+ result.set(directiveName, directiveValue)
87
+ }
88
+ if (!result.size) {
89
+ throw new Error("Content-Security-Policy has no directives. Either set some or disable the header")
90
+ }
91
+ if (!result.has("default-src") && !hasDisabledDefaultSrc) {
92
+ throw new Error("Content-Security-Policy needs a default-src but none was provided. If you really want to disable it, set it to `contentSecurityPolicy.dangerouslyDisableDefaultSrc`.")
93
+ }
94
+ let stringResult = ""
95
+ let shouldUseStringResult = true
96
+ for (const [directiveName, directiveValue] of result) {
97
+ const directiveValueString = stringifyDirectiveValue(directiveValue)
98
+ if (directiveValueString === null) {
99
+ shouldUseStringResult = false
100
+ break
101
+ } else {
102
+ if (stringResult) stringResult += ";"
103
+ stringResult += directiveValueString ? `${directiveName} ${directiveValueString}` : directiveName
104
+ }
105
+ }
106
+ return shouldUseStringResult ? stringResult : result
107
+ }
108
+ function getHeaderValue(req, res, normalizedDirectives) {
109
+ const result = []
110
+ for (const [directiveName, rawDirectiveValue] of normalizedDirectives) {
111
+ let directiveValue = ""
112
+ for (const element of rawDirectiveValue) {
113
+ if (typeof element === "function") {
114
+ let newElement
115
+ try {
116
+ newElement = element(req, res)
117
+ } catch (err) {
118
+ return errify(err)
119
+ }
120
+ const err = getDirectiveValueEntryValidationError(directiveName, newElement)
121
+ if (err) return err
122
+ directiveValue += " " + newElement
123
+ } else {
124
+ directiveValue += " " + element
125
+ }
126
+ }
127
+ if (directiveValue) {
128
+ const err = getDirectiveValueValidationError(directiveName, directiveValue)
129
+ if (err) return err
130
+ result.push(`${directiveName}${directiveValue}`)
131
+ } else {
132
+ result.push(directiveName)
133
+ }
134
+ }
135
+ return result.join(";")
136
+ }
137
+ const contentSecurityPolicy = function contentSecurityPolicy(options = {}) {
138
+ const headerName = options.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy"
139
+ const parsedDirectives = parseDirectives(options)
140
+ // A special case for performance.
141
+ if (typeof parsedDirectives === "string") {
142
+ return function contentSecurityPolicyMiddleware(_req, res, next) {
143
+ res.setHeader(headerName, parsedDirectives)
144
+ next()
145
+ }
146
+ }
147
+ return function contentSecurityPolicyMiddleware(req, res, next) {
148
+ const result = getHeaderValue(req, res, parsedDirectives)
149
+ if (result instanceof Error) {
150
+ next(result)
151
+ } else {
152
+ res.setHeader(headerName, result)
153
+ next()
154
+ }
155
+ }
156
+ }
157
+ contentSecurityPolicy.getDefaultDirectives = getDefaultDirectives
158
+ contentSecurityPolicy.dangerouslyDisableDefaultSrc = dangerouslyDisableDefaultSrc
159
+
160
+ const ALLOWED_POLICIES$2 = new Set(["require-corp", "credentialless", "unsafe-none"])
161
+ function getHeaderValueFromOptions$6({policy = "require-corp"}) {
162
+ if (ALLOWED_POLICIES$2.has(policy)) {
163
+ return policy
164
+ } else {
165
+ throw new Error(`Cross-Origin-Embedder-Policy does not support the ${JSON.stringify(policy)} policy`)
166
+ }
167
+ }
168
+ function crossOriginEmbedderPolicy(options = {}) {
169
+ const headerValue = getHeaderValueFromOptions$6(options)
170
+ return function crossOriginEmbedderPolicyMiddleware(_req, res, next) {
171
+ res.setHeader("Cross-Origin-Embedder-Policy", headerValue)
172
+ next()
173
+ }
174
+ }
175
+
176
+ const ALLOWED_POLICIES$1 = new Set(["same-origin", "same-origin-allow-popups", "noopener-allow-popups", "unsafe-none"])
177
+ function getHeaderValueFromOptions$5({policy = "same-origin"}) {
178
+ if (ALLOWED_POLICIES$1.has(policy)) {
179
+ return policy
180
+ } else {
181
+ throw new Error(`Cross-Origin-Opener-Policy does not support the ${JSON.stringify(policy)} policy`)
182
+ }
183
+ }
184
+ function crossOriginOpenerPolicy(options = {}) {
185
+ const headerValue = getHeaderValueFromOptions$5(options)
186
+ return function crossOriginOpenerPolicyMiddleware(_req, res, next) {
187
+ res.setHeader("Cross-Origin-Opener-Policy", headerValue)
188
+ next()
189
+ }
190
+ }
191
+
192
+ const ALLOWED_POLICIES = new Set(["same-origin", "same-site", "cross-origin"])
193
+ function getHeaderValueFromOptions$4({policy = "same-origin"}) {
194
+ if (ALLOWED_POLICIES.has(policy)) {
195
+ return policy
196
+ } else {
197
+ throw new Error(`Cross-Origin-Resource-Policy does not support the ${JSON.stringify(policy)} policy`)
198
+ }
199
+ }
200
+ function crossOriginResourcePolicy(options = {}) {
201
+ const headerValue = getHeaderValueFromOptions$4(options)
202
+ return function crossOriginResourcePolicyMiddleware(_req, res, next) {
203
+ res.setHeader("Cross-Origin-Resource-Policy", headerValue)
204
+ next()
205
+ }
206
+ }
207
+
208
+ function originAgentCluster() {
209
+ return function originAgentClusterMiddleware(_req, res, next) {
210
+ res.setHeader("Origin-Agent-Cluster", "?1")
211
+ next()
212
+ }
213
+ }
214
+
215
+ const ALLOWED_TOKENS = new Set(["no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url", ""])
216
+ function getHeaderValueFromOptions$3({policy = ["no-referrer"]}) {
217
+ const tokens = typeof policy === "string" ? [policy] : policy
218
+ if (tokens.length === 0) {
219
+ throw new Error("Referrer-Policy received no policy tokens")
220
+ }
221
+ const tokensSeen = new Set()
222
+ tokens.forEach(token => {
223
+ if (!ALLOWED_TOKENS.has(token)) {
224
+ throw new Error(`Referrer-Policy received an unexpected policy token ${JSON.stringify(token)}`)
225
+ } else if (tokensSeen.has(token)) {
226
+ throw new Error(`Referrer-Policy received a duplicate policy token ${JSON.stringify(token)}`)
227
+ }
228
+ tokensSeen.add(token)
229
+ })
230
+ return tokens.join(",")
231
+ }
232
+ function referrerPolicy(options = {}) {
233
+ const headerValue = getHeaderValueFromOptions$3(options)
234
+ return function referrerPolicyMiddleware(_req, res, next) {
235
+ res.setHeader("Referrer-Policy", headerValue)
236
+ next()
237
+ }
238
+ }
239
+
240
+ const DEFAULT_MAX_AGE = 365 * 24 * 60 * 60
241
+ function parseMaxAge(value = DEFAULT_MAX_AGE) {
242
+ if (value >= 0 && Number.isFinite(value)) {
243
+ return Math.floor(value)
244
+ } else {
245
+ throw new Error(`Strict-Transport-Security: ${JSON.stringify(value)} is not a valid value for maxAge. Please choose a positive integer.`)
246
+ }
247
+ }
248
+ function getHeaderValueFromOptions$2(options) {
249
+ if ("maxage" in options) {
250
+ throw new Error("Strict-Transport-Security received an unsupported property, `maxage`. Did you mean to pass `maxAge`?")
251
+ }
252
+ if ("includeSubdomains" in options) {
253
+ throw new Error('Strict-Transport-Security middleware should use `includeSubDomains` instead of `includeSubdomains`. (The correct one has an uppercase "D".)')
254
+ }
255
+ const directives = [`max-age=${parseMaxAge(options.maxAge)}`]
256
+ if (options.includeSubDomains === undefined || options.includeSubDomains) {
257
+ directives.push("includeSubDomains")
258
+ }
259
+ if (options.preload) {
260
+ directives.push("preload")
261
+ }
262
+ return directives.join("; ")
263
+ }
264
+ function strictTransportSecurity(options = {}) {
265
+ const headerValue = getHeaderValueFromOptions$2(options)
266
+ return function strictTransportSecurityMiddleware(_req, res, next) {
267
+ res.setHeader("Strict-Transport-Security", headerValue)
268
+ next()
269
+ }
270
+ }
271
+
272
+ function xContentTypeOptions() {
273
+ return function xContentTypeOptionsMiddleware(_req, res, next) {
274
+ res.setHeader("X-Content-Type-Options", "nosniff")
275
+ next()
276
+ }
277
+ }
278
+
279
+ function xDnsPrefetchControl(options = {}) {
280
+ const headerValue = options.allow ? "on" : "off"
281
+ return function xDnsPrefetchControlMiddleware(_req, res, next) {
282
+ res.setHeader("X-DNS-Prefetch-Control", headerValue)
283
+ next()
284
+ }
285
+ }
286
+
287
+ function xDownloadOptions() {
288
+ return function xDownloadOptionsMiddleware(_req, res, next) {
289
+ res.setHeader("X-Download-Options", "noopen")
290
+ next()
291
+ }
292
+ }
293
+
294
+ function getHeaderValueFromOptions$1({action = "sameorigin"}) {
295
+ const normalizedAction = typeof action === "string" ? action.toUpperCase() : action
296
+ switch (normalizedAction) {
297
+ case "SAME-ORIGIN":
298
+ return "SAMEORIGIN"
299
+ case "DENY":
300
+ case "SAMEORIGIN":
301
+ return normalizedAction
302
+ default:
303
+ throw new Error(`X-Frame-Options received an invalid action ${JSON.stringify(action)}`)
304
+ }
305
+ }
306
+ function xFrameOptions(options = {}) {
307
+ const headerValue = getHeaderValueFromOptions$1(options)
308
+ return function xFrameOptionsMiddleware(_req, res, next) {
309
+ res.setHeader("X-Frame-Options", headerValue)
310
+ next()
311
+ }
312
+ }
313
+
314
+ const ALLOWED_PERMITTED_POLICIES = new Set(["none", "master-only", "by-content-type", "all"])
315
+ function getHeaderValueFromOptions({permittedPolicies = "none"}) {
316
+ if (ALLOWED_PERMITTED_POLICIES.has(permittedPolicies)) {
317
+ return permittedPolicies
318
+ } else {
319
+ throw new Error(`X-Permitted-Cross-Domain-Policies does not support ${JSON.stringify(permittedPolicies)}`)
320
+ }
321
+ }
322
+ function xPermittedCrossDomainPolicies(options = {}) {
323
+ const headerValue = getHeaderValueFromOptions(options)
324
+ return function xPermittedCrossDomainPoliciesMiddleware(_req, res, next) {
325
+ res.setHeader("X-Permitted-Cross-Domain-Policies", headerValue)
326
+ next()
327
+ }
328
+ }
329
+
330
+ function xPoweredBy() {
331
+ return function xPoweredByMiddleware(_req, res, next) {
332
+ res.removeHeader("X-Powered-By")
333
+ next()
334
+ }
335
+ }
336
+
337
+ function xXssProtection() {
338
+ return function xXssProtectionMiddleware(_req, res, next) {
339
+ res.setHeader("X-XSS-Protection", "0")
340
+ next()
341
+ }
342
+ }
343
+
344
+ function getMiddlewareFunctionsFromOptions(options) {
345
+ const result = []
346
+ switch (options.contentSecurityPolicy) {
347
+ case undefined:
348
+ case true:
349
+ result.push(contentSecurityPolicy())
350
+ break
351
+ case false:
352
+ break
353
+ default:
354
+ result.push(contentSecurityPolicy(options.contentSecurityPolicy))
355
+ break
356
+ }
357
+ switch (options.crossOriginEmbedderPolicy) {
358
+ case undefined:
359
+ case false:
360
+ break
361
+ case true:
362
+ result.push(crossOriginEmbedderPolicy())
363
+ break
364
+ default:
365
+ result.push(crossOriginEmbedderPolicy(options.crossOriginEmbedderPolicy))
366
+ break
367
+ }
368
+ switch (options.crossOriginOpenerPolicy) {
369
+ case undefined:
370
+ case true:
371
+ result.push(crossOriginOpenerPolicy())
372
+ break
373
+ case false:
374
+ break
375
+ default:
376
+ result.push(crossOriginOpenerPolicy(options.crossOriginOpenerPolicy))
377
+ break
378
+ }
379
+ switch (options.crossOriginResourcePolicy) {
380
+ case undefined:
381
+ case true:
382
+ result.push(crossOriginResourcePolicy())
383
+ break
384
+ case false:
385
+ break
386
+ default:
387
+ result.push(crossOriginResourcePolicy(options.crossOriginResourcePolicy))
388
+ break
389
+ }
390
+ switch (options.originAgentCluster) {
391
+ case undefined:
392
+ case true:
393
+ result.push(originAgentCluster())
394
+ break
395
+ case false:
396
+ break
397
+ default:
398
+ logger.warn("Origin-Agent-Cluster does not take options. Remove the property to silence this warning.")
399
+ result.push(originAgentCluster())
400
+ break
401
+ }
402
+ switch (options.referrerPolicy) {
403
+ case undefined:
404
+ case true:
405
+ result.push(referrerPolicy())
406
+ break
407
+ case false:
408
+ break
409
+ default:
410
+ result.push(referrerPolicy(options.referrerPolicy))
411
+ break
412
+ }
413
+ if ("strictTransportSecurity" in options && "hsts" in options) {
414
+ throw new Error("Strict-Transport-Security option was specified twice. Remove the `hsts` option to fix this error.")
415
+ }
416
+ const strictTransportSecurityOption = options.strictTransportSecurity ?? options.hsts
417
+ switch (strictTransportSecurityOption) {
418
+ case undefined:
419
+ case true:
420
+ result.push(strictTransportSecurity())
421
+ break
422
+ case false:
423
+ break
424
+ default:
425
+ result.push(strictTransportSecurity(strictTransportSecurityOption))
426
+ break
427
+ }
428
+ if ("xContentTypeOptions" in options && "noSniff" in options) {
429
+ throw new Error("X-Content-Type-Options option was specified twice. Remove the `noSniff` option to fix this error.")
430
+ }
431
+ const xContentTypeOptionsOption = options.xContentTypeOptions ?? options.noSniff
432
+ switch (xContentTypeOptionsOption) {
433
+ case undefined:
434
+ case true:
435
+ result.push(xContentTypeOptions())
436
+ break
437
+ case false:
438
+ break
439
+ default:
440
+ logger.warn("X-Content-Type-Options does not take options. Remove the property to silence this warning.")
441
+ result.push(xContentTypeOptions())
442
+ break
443
+ }
444
+ if ("xDnsPrefetchControl" in options && "dnsPrefetchControl" in options) {
445
+ throw new Error("X-DNS-Prefetch-Control option was specified twice. Remove the `dnsPrefetchControl` option to fix this error.")
446
+ }
447
+ const xDnsPrefetchControlOption = options.xDnsPrefetchControl ?? options.dnsPrefetchControl
448
+ switch (xDnsPrefetchControlOption) {
449
+ case undefined:
450
+ case true:
451
+ result.push(xDnsPrefetchControl())
452
+ break
453
+ case false:
454
+ break
455
+ default:
456
+ result.push(xDnsPrefetchControl(xDnsPrefetchControlOption))
457
+ break
458
+ }
459
+ if ("xDownloadOptions" in options && "ieNoOpen" in options) {
460
+ throw new Error("X-Download-Options option was specified twice. Remove the `ieNoOpen` option to fix this error.")
461
+ }
462
+ const xDownloadOptionsOption = options.xDownloadOptions ?? options.ieNoOpen
463
+ switch (xDownloadOptionsOption) {
464
+ case undefined:
465
+ case true:
466
+ result.push(xDownloadOptions())
467
+ break
468
+ case false:
469
+ break
470
+ default:
471
+ logger.warn("X-Download-Options does not take options. Remove the property to silence this warning.")
472
+ result.push(xDownloadOptions())
473
+ break
474
+ }
475
+ if ("xFrameOptions" in options && "frameguard" in options) {
476
+ throw new Error("X-Frame-Options option was specified twice. Remove the `frameguard` option to fix this error.")
477
+ }
478
+ const xFrameOptionsOption = options.xFrameOptions ?? options.frameguard
479
+ switch (xFrameOptionsOption) {
480
+ case undefined:
481
+ case true:
482
+ result.push(xFrameOptions())
483
+ break
484
+ case false:
485
+ break
486
+ default:
487
+ result.push(xFrameOptions(xFrameOptionsOption))
488
+ break
489
+ }
490
+ if ("xPermittedCrossDomainPolicies" in options && "permittedCrossDomainPolicies" in options) {
491
+ throw new Error("X-Permitted-Cross-Domain-Policies option was specified twice. Remove the `permittedCrossDomainPolicies` option to fix this error.")
492
+ }
493
+ const xPermittedCrossDomainPoliciesOption = options.xPermittedCrossDomainPolicies ?? options.permittedCrossDomainPolicies
494
+ switch (xPermittedCrossDomainPoliciesOption) {
495
+ case undefined:
496
+ case true:
497
+ result.push(xPermittedCrossDomainPolicies())
498
+ break
499
+ case false:
500
+ break
501
+ default:
502
+ result.push(xPermittedCrossDomainPolicies(xPermittedCrossDomainPoliciesOption))
503
+ break
504
+ }
505
+ if ("xPoweredBy" in options && "hidePoweredBy" in options) {
506
+ throw new Error("X-Powered-By option was specified twice. Remove the `hidePoweredBy` option to fix this error.")
507
+ }
508
+ const xPoweredByOption = options.xPoweredBy ?? options.hidePoweredBy
509
+ switch (xPoweredByOption) {
510
+ case undefined:
511
+ case true:
512
+ result.push(xPoweredBy())
513
+ break
514
+ case false:
515
+ break
516
+ default:
517
+ logger.warn("X-Powered-By does not take options. Remove the property to silence this warning.")
518
+ result.push(xPoweredBy())
519
+ break
520
+ }
521
+ if ("xXssProtection" in options && "xssFilter" in options) {
522
+ throw new Error("X-XSS-Protection option was specified twice. Remove the `xssFilter` option to fix this error.")
523
+ }
524
+ const xXssProtectionOption = options.xXssProtection ?? options.xssFilter
525
+ switch (xXssProtectionOption) {
526
+ case undefined:
527
+ case true:
528
+ result.push(xXssProtection())
529
+ break
530
+ case false:
531
+ break
532
+ default:
533
+ logger.warn("X-XSS-Protection does not take options. Remove the property to silence this warning.")
534
+ result.push(xXssProtection())
535
+ break
536
+ }
537
+ return result
538
+ }
539
+ const helmet = Object.assign(
540
+ function helmet(options = {}) {
541
+ // People should be able to pass an options object with no prototype,
542
+ // so we want this optional chaining.
543
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
544
+ if (options.constructor?.name === "IncomingMessage") {
545
+ throw new Error("It appears you have done something like `app.use(helmet)`, but it should be `app.use(helmet())`.")
546
+ }
547
+ const middlewareFunctions = getMiddlewareFunctionsFromOptions(options)
548
+ return function helmetMiddleware(req, res, next) {
549
+ let middlewareIndex = 0
550
+ ;(function internalNext(err) {
551
+ if (err) {
552
+ next(err)
553
+ return
554
+ }
555
+ const middlewareFunction = middlewareFunctions[middlewareIndex]
556
+ if (middlewareFunction) {
557
+ middlewareIndex++
558
+ middlewareFunction(req, res, internalNext)
559
+ } else {
560
+ next()
561
+ }
562
+ })()
563
+ }
564
+ },
565
+ {
566
+ contentSecurityPolicy,
567
+ crossOriginEmbedderPolicy,
568
+ crossOriginOpenerPolicy,
569
+ crossOriginResourcePolicy,
570
+ originAgentCluster,
571
+ referrerPolicy,
572
+ strictTransportSecurity,
573
+ xContentTypeOptions,
574
+ xDnsPrefetchControl,
575
+ xDownloadOptions,
576
+ xFrameOptions,
577
+ xPermittedCrossDomainPolicies,
578
+ xPoweredBy,
579
+ xXssProtection,
580
+ // Legacy aliases
581
+ dnsPrefetchControl: xDnsPrefetchControl,
582
+ xssFilter: xXssProtection,
583
+ permittedCrossDomainPolicies: xPermittedCrossDomainPolicies,
584
+ ieNoOpen: xDownloadOptions,
585
+ noSniff: xContentTypeOptions,
586
+ frameguard: xFrameOptions,
587
+ hidePoweredBy: xPoweredBy,
588
+ hsts: strictTransportSecurity
589
+ }
590
+ )
591
+
592
+ exports.contentSecurityPolicy = contentSecurityPolicy
593
+ exports.crossOriginEmbedderPolicy = crossOriginEmbedderPolicy
594
+ exports.crossOriginOpenerPolicy = crossOriginOpenerPolicy
595
+ exports.crossOriginResourcePolicy = crossOriginResourcePolicy
596
+ exports.default = helmet
597
+ exports.dnsPrefetchControl = xDnsPrefetchControl
598
+ exports.frameguard = xFrameOptions
599
+ exports.hidePoweredBy = xPoweredBy
600
+ exports.hsts = strictTransportSecurity
601
+ exports.ieNoOpen = xDownloadOptions
602
+ exports.noSniff = xContentTypeOptions
603
+ exports.originAgentCluster = originAgentCluster
604
+ exports.permittedCrossDomainPolicies = xPermittedCrossDomainPolicies
605
+ exports.referrerPolicy = referrerPolicy
606
+ exports.strictTransportSecurity = strictTransportSecurity
607
+ exports.xContentTypeOptions = xContentTypeOptions
608
+ exports.xDnsPrefetchControl = xDnsPrefetchControl
609
+ exports.xDownloadOptions = xDownloadOptions
610
+ exports.xFrameOptions = xFrameOptions
611
+ exports.xPermittedCrossDomainPolicies = xPermittedCrossDomainPolicies
612
+ exports.xPoweredBy = xPoweredBy
613
+ exports.xXssProtection = xXssProtection
614
+ exports.xssFilter = xXssProtection
615
+
616
+ module.exports = exports.default
617
+ module.exports.default = module.exports