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