-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (95 loc) · 2.7 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"use strict";
const url = require("url");
const restModifier = require("resp-modifier");
function rewriteLinksModifierCreate(originalURL) {
const parsedOriginalURL = url.parse(originalURL);
const originalHost = parsedOriginalURL.hostname;
const originalPort = parsedOriginalURL.port;
let fullOriginalURL = originalHost;
if (originalHost && originalPort) {
if (parseInt(originalPort, 10) !== 80) {
fullOriginalURL = `${originalHost}:${originalPort}`;
}
}
return {
fn(req, res, match) {
const requestHost = req.headers.host;
let mathed = match;
/**
* Reject subdomains
*/
if (mathed[0] === ".") {
return mathed;
}
const captured = mathed[0] === "'" || mathed[0] === '"' ? mathed[0] : "";
/**
* allow http https
* @type {string}
*/
const pre = "//";
if (mathed[0] === "'" || mathed[0] === '"') {
mathed = mathed.slice(1);
}
/**
* parse the url
* @type {number|*}
*/
const out = url.parse(mathed);
/**
* If host not set, just do a simple replace
*/
if (!out.host) {
fullOriginalURL = fullOriginalURL.replace(/^(\/)/, "");
return captured + mathed.replace(fullOriginalURL, requestHost);
}
/**
* Only add trailing slash if one was
* present in the original mathed
*/
let path = out.path || "";
if (path === "/") {
if (mathed.slice(-1) === "/") {
path = "/";
} else {
path = "";
}
}
let port = "";
if (out.port && parseInt(out.port, 10) !== 80) {
port = `:${out.port}`;
}
let hash = "";
if (out.hash) {
({ hash } = out);
}
/**
* Finally append all of parsed url
*/
return [captured, pre, requestHost, port, path, hash].join("");
},
match: new RegExp(
`https?:\\\\/\\\\/${fullOriginalURL}|('|")\\/\\/${fullOriginalURL}|https?://${fullOriginalURL}(/)?|('|")(https?://|/|\\.)?${fullOriginalURL}(/)?(.*?)(?=[ ,'"\\s])`,
"g"
)
};
}
module.exports = function createRewriteLinkMiddleware(options) {
if (!options.originalURL) {
throw new Error("Parameter 'originalURL' is required");
}
let originalURLs = options.originalURL;
if (!Array.isArray(originalURLs)) {
originalURLs = [originalURLs];
}
const rules = [];
originalURLs.forEach(originalURL => {
rules.push(rewriteLinksModifierCreate(originalURL));
});
return restModifier.create({
blacklist: options.blacklist,
hostBlacklist: options.hostBlacklist,
ignore: options.ignore,
rules,
whitelist: options.whitelist
}).middleware;
};