UNPKG

1.82 kBJavaScriptView Raw
1"use strict";
2function getHeaderValueFromOptions(options) {
3 var DEFAULT_POLICY = 'no-referrer';
4 var ALLOWED_POLICIES = [
5 'no-referrer',
6 'no-referrer-when-downgrade',
7 'same-origin',
8 'origin',
9 'strict-origin',
10 'origin-when-cross-origin',
11 'strict-origin-when-cross-origin',
12 'unsafe-url',
13 ''
14 ];
15 options = options || {};
16 var policyOption;
17 if ('policy' in options) {
18 policyOption = options.policy;
19 }
20 else {
21 policyOption = DEFAULT_POLICY;
22 }
23 var policies = Array.isArray(policyOption) ? policyOption : [policyOption];
24 if (policies.length === 0) {
25 throw new Error('At least one policy must be supplied.');
26 }
27 var policiesSeen = new Set();
28 policies.forEach(function (policy) {
29 if ((typeof policy !== 'string') || (ALLOWED_POLICIES.indexOf(policy) === -1)) {
30 var allowedPoliciesErrorList = ALLOWED_POLICIES.map(function (policy) {
31 if (policy.length) {
32 return "\"" + policy + "\"";
33 }
34 else {
35 return 'and the empty string';
36 }
37 }).join(', ');
38 throw new Error("\"" + policy + "\" is not a valid policy. Allowed policies: " + allowedPoliciesErrorList + ".");
39 }
40 if (policiesSeen.has(policy)) {
41 throw new Error("\"" + policy + "\" specified more than once. No duplicates are allowed.");
42 }
43 policiesSeen.add(policy);
44 });
45 return policies.join(',');
46}
47module.exports = function referrerPolicy(options) {
48 var headerValue = getHeaderValueFromOptions(options);
49 return function referrerPolicy(_req, res, next) {
50 res.setHeader('Referrer-Policy', headerValue);
51 next();
52 };
53};