app.js 799 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. // there is no global.URL in node 8
  3. const URL = require('url').URL;
  4. module.exports = app => {
  5. // put before other core middlewares
  6. app.config.coreMiddlewares.unshift('cors');
  7. // if security plugin enabled, and origin config is not provided, will only allow safe domains support CORS.
  8. app.config.cors.origin = app.config.cors.origin || function corsOrigin(ctx) {
  9. // origin is {protocol}{hostname}{port}...
  10. const origin = ctx.get('origin');
  11. if (!origin) return '';
  12. if (typeof ctx.isSafeDomain !== 'function') return origin;
  13. let parsedUrl;
  14. try {
  15. parsedUrl = new URL(origin);
  16. } catch (err) {
  17. return '';
  18. }
  19. if (ctx.isSafeDomain(parsedUrl.hostname) || ctx.isSafeDomain(origin)) {
  20. return origin;
  21. }
  22. return '';
  23. };
  24. };