You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.0 KiB

4 years ago
  1. var path = require('path');
  2. var url = require('url');
  3. var isRemoteResource = require('../utils/is-remote-resource');
  4. var hasProtocol = require('../utils/has-protocol');
  5. var HTTP_PROTOCOL = 'http:';
  6. function isAllowedResource(uri, isRemote, rules) {
  7. var match;
  8. var absoluteUri;
  9. var allowed = isRemote ? false : true;
  10. var rule;
  11. var isNegated;
  12. var normalizedRule;
  13. var i;
  14. if (rules.length === 0) {
  15. return false;
  16. }
  17. if (isRemote && !hasProtocol(uri)) {
  18. uri = HTTP_PROTOCOL + uri;
  19. }
  20. match = isRemote ?
  21. url.parse(uri).host :
  22. uri;
  23. absoluteUri = isRemote ?
  24. uri :
  25. path.resolve(uri);
  26. for (i = 0; i < rules.length; i++) {
  27. rule = rules[i];
  28. isNegated = rule[0] == '!';
  29. normalizedRule = rule.substring(1);
  30. if (isNegated && isRemote && isRemoteRule(normalizedRule)) {
  31. allowed = allowed && !isAllowedResource(uri, true, [normalizedRule]);
  32. } else if (isNegated && !isRemote && !isRemoteRule(normalizedRule)) {
  33. allowed = allowed && !isAllowedResource(uri, false, [normalizedRule]);
  34. } else if (isNegated) {
  35. allowed = allowed && true;
  36. } else if (rule == 'all') {
  37. allowed = true;
  38. } else if (isRemote && rule == 'local') {
  39. allowed = allowed || false;
  40. } else if (isRemote && rule == 'remote') {
  41. allowed = true;
  42. } else if (!isRemote && rule == 'remote') {
  43. allowed = false;
  44. } else if (!isRemote && rule == 'local') {
  45. allowed = true;
  46. } else if (rule === match) {
  47. allowed = true;
  48. } else if (rule === uri) {
  49. allowed = true;
  50. } else if (isRemote && absoluteUri.indexOf(rule) === 0) {
  51. allowed = true;
  52. } else if (!isRemote && absoluteUri.indexOf(path.resolve(rule)) === 0) {
  53. allowed = true;
  54. } else if (isRemote != isRemoteRule(normalizedRule)) {
  55. allowed = allowed && true;
  56. } else {
  57. allowed = false;
  58. }
  59. }
  60. return allowed;
  61. }
  62. function isRemoteRule(rule) {
  63. return isRemoteResource(rule) || url.parse(HTTP_PROTOCOL + '//' + rule).host == rule;
  64. }
  65. module.exports = isAllowedResource;