referrerPolicy.js 775 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. const utils = require('../utils');
  3. // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Referrer-Policy
  4. const ALLOWED_POLICIES_ENUM = [
  5. 'no-referrer',
  6. 'no-referrer-when-downgrade',
  7. 'origin',
  8. 'origin-when-cross-origin',
  9. 'same-origin',
  10. 'strict-origin',
  11. 'strict-origin-when-cross-origin',
  12. 'unsafe-url',
  13. '',
  14. ];
  15. module.exports = options => {
  16. return async function referrerPolicy(ctx, next) {
  17. await next();
  18. const opts = utils.merge(options, ctx.securityOptions.refererPolicy);
  19. if (utils.checkIfIgnore(opts, ctx)) { return; }
  20. const policy = opts.value;
  21. if (!ALLOWED_POLICIES_ENUM.includes(policy)) {
  22. throw new Error('"' + policy + '" is not available."');
  23. }
  24. ctx.set('referrer-policy', policy);
  25. };
  26. };