securities.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const compose = require('koa-compose');
  3. const path = require('path');
  4. const assert = require('assert');
  5. const createMatch = require('egg-path-matching');
  6. module.exports = (_, app) => {
  7. const options = app.config.security;
  8. const middlewares = [];
  9. const defaultMiddleware = (options.defaultMiddleware || '').split(',');
  10. if (options.match || options.ignore) {
  11. app.coreLogger.warn('[egg-security] Please set `match` or `ignore` on sub config');
  12. }
  13. // format csrf.cookieDomain
  14. const orginalCookieDomain = options.csrf.cookieDomain;
  15. if (orginalCookieDomain && typeof orginalCookieDomain !== 'function') {
  16. options.csrf.cookieDomain = () => orginalCookieDomain;
  17. }
  18. defaultMiddleware.forEach(middlewareName => {
  19. middlewareName = middlewareName.trim();
  20. const opt = options[middlewareName];
  21. if (opt === false) {
  22. app.coreLogger.warn('[egg-security] Please use `config.security.%s = { enable: false }` instead of `config.security.%s = false`', middlewareName, middlewareName);
  23. }
  24. assert(opt === false || typeof opt === 'object',
  25. `config.security.${middlewareName} must be an object, or false(if you turn it off)`);
  26. if (opt === false || opt && opt.enable === false) {
  27. return;
  28. }
  29. if (middlewareName === 'csrf' && opt.useSession && !app.plugins.session) {
  30. throw new Error('csrf.useSession enabled, but session plugin is disabled');
  31. }
  32. // use opt.match first (compatibility)
  33. if (opt.match && opt.ignore) {
  34. app.coreLogger.warn('[egg-security] `options.match` and `options.ignore` are both set, using `options.match`');
  35. opt.ignore = undefined;
  36. }
  37. if (!opt.ignore && opt.blackUrls) {
  38. app.deprecate('[egg-security] Please use `config.security.xframe.ignore` instead, `config.security.xframe.blackUrls` will be removed very soon');
  39. opt.ignore = opt.blackUrls;
  40. }
  41. opt.matching = createMatch(opt);
  42. const fn = require(path.join(__dirname, '../../lib/middlewares', middlewareName))(opt, app);
  43. middlewares.push(fn);
  44. app.coreLogger.info('[egg-security] use %s middleware', middlewareName);
  45. });
  46. app.coreLogger.info('[egg-security] compose %d middlewares into one security middleware',
  47. middlewares.length);
  48. return compose(middlewares);
  49. };