-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorigin-whitelist.js
65 lines (55 loc) · 2.06 KB
/
origin-whitelist.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'use strict';
const url = require('url');
const log = require('./logger');
// A whitelist of allowed domains for source images
class OriginWhitelist {
constructor(domainEnv) {
this.originWhitelist = null;
if (domainEnv) {
this.originWhitelist = process.env.IMGSRV_ORIGIN_WHITELIST
.split(',')
.reduce((result, item) => {
let segments = item.split('/');
let lastSegment = result[segments[0].toLowerCase()] = {};
for (let i = 1; i<segments.length; i++) {
lastSegment.__hasPaths = true;
lastSegment = lastSegment[segments[i].toLowerCase()] = {};
}
return result;
}, {});
}
}
// Emits status to console
getStatus() {
if (this.originWhitelist) {
return this.originWhitelist;
} else {
return { warning: 'No origin whitelist specified: allowing ALL origins' };
}
}
// Checks the specified URI against the whitelist, throws an error if the origin is not whitelisted
validate(uri) {
if (this.originWhitelist) {
let parsed = url.parse(uri);
let sourceHost = parsed.host.toLowerCase();
let wlItem = this.originWhitelist[sourceHost];
if (!wlItem) {
throw new Error(`Origin not whitelisted: ${sourceHost}`);
} else if (wlItem.__hasPaths) {
let dirs = parsed.path.toLowerCase()
.substr(1)
.split('/');
let i = 0;
while (wlItem.__hasPaths && i < dirs.length) {
let nextItem = wlItem[dirs[i]];
if (!nextItem) {
throw new Error(`Origin whitelisted, but missing segment: ${dirs[i]}`);
}
wlItem = nextItem;
i++;
}
}
}
}
}
module.exports.OriginWhitelist = OriginWhitelist;