-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
202 lines (162 loc) · 6.16 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import express from 'express';
import fetch from 'node-fetch';
import path from 'path';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import cookieParser from 'cookie-parser';
import DomainValidator from './domain-validator.js';
import cors from 'cors';
const __dirname = path.resolve();
const app = express();
app.use(express.json())
app.use(cookieParser());
const ALLOW_CORS = (process.env.ALLOW_CORS || "false").toLowerCase();
const ALLOWED_CORS_DOMAINS = process.env.ALLOWED_CORS_DOMAINS || "*";
if(ALLOW_CORS === "true"){
console.log(`设置了允许跨域,域名为${ALLOWED_CORS_DOMAINS}`)
const corsOptions = {
origin: ALLOWED_CORS_DOMAINS,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
headers: '*',
credentials: true,
optionsSuccessStatus: 204
};
app.use(cors(corsOptions));
}
app.use("/*", (req, resp, next) => {
const baseUrl = req.baseUrl;
if(baseUrl !== "" && baseUrl !== "/" && baseUrl !== "/auth/login"){
if(PASSWORD !== ""){
const authentication = req.cookies["Authentication"] || req.headers["authorization"] || ""
if(authentication !== ""){
if(authentication.indexOf("Basic") === 0){
const encodedstr = authentication.substring(6)
const decodedstr = Buffer.from(encodedstr, 'base64').toString('ascii');
const userpass = decodedstr.split(":")
if(userpass.length === 2){
const password = userpass[1]
if(password === PASSWORD){
next()
}else{
resp.status(401).send("wrong password")
}
}else{
resp.status(400).send("unknown authorization type")
}
}else if (authentication.indexOf("Bearer") === 0){
let jwttoken = authentication.substring(7)
jwt.verify(jwttoken,SIGN_KEY,(err, _decoded)=>{
if(err){
resp.status(401).send(err.toString())
}else{
next()
}
})
}else{
resp.status(400).send("unknown authorization type")
}
}else{
resp.status(401).send("authorization is empty")
}
}else{
next()
}
}else{
next()
}
})
async function proxyResquest(proxypath,req,resp){
try {
const proxyurl = new URL(proxypath)
const proxyhost = proxyurl.hostname
let headers = new Headers(req.headers)
headers.set("host", proxyhost)
headers.delete("accept-encoding")
const proxyResp = await fetch(proxypath, {
headers: headers,
redirect: "manual"
});
if(proxyResp.status === 200){
let proxyRespHeaders = new Headers(proxyResp.headers);
proxyRespHeaders.delete("content-security-policy");
proxyRespHeaders.delete("content-security-policy-report-only");
proxyRespHeaders.delete("clear-site-data");
proxyRespHeaders.delete("content-encoding")
proxyRespHeaders.set("access-control-expose-headers", "*");
proxyRespHeaders.set("access-control-allow-origin", "*");
if(!proxyRespHeaders.has("content-disposition")){
if(FORCE_DOWNLOAD !== "false"){
proxyRespHeaders.set("content-disposition", "attachment");
}
}
for (const [key, value] of proxyRespHeaders.entries()) {
resp.set(key, value);
}
proxyResp.body.pipe(resp);
}else if(proxyResp.status === 301 || proxyResp.status === 302){
let proxyRespHeaders = proxyResp.headers;
const location = proxyRespHeaders.get("location")
proxyResquest(location,req,resp)
}else{
proxyResp.body.pipe(resp);
}
} catch (error) {
resp.status(400).send(error.toString());
}
}
app.get("/proxy/*", async (req, resp) => {
const proxypath = req.url.substring(7);
try {
const proxyurl = new URL(proxypath)
const proxyhost = proxyurl.hostname
const reqhost = req.hostname
if(reqhost === "" || reqhost === proxyhost){
throw new Error("url is not allowed")
}
if(ALLOWED_DOMAINS !== "" && !DOMAIN_VALIDATOR.match(proxyhost)){
throw new Error("domain is not allowed")
}
proxyResquest(proxypath, req, resp)
} catch (error) {
resp.status(400).send(error.toString());
}
})
app.get("/", async (_req, resp) => {
resp.sendFile(path.resolve(__dirname,"index.html"));
})
app.post("/auth/check", async (req, resp) => {
resp.status(200).send("")
})
app.post("/auth/login", async(req, resp) => {
if(PASSWORD !== ""){
try{
const bodyjson = req.body;
const pwd = bodyjson["password"]
if(pwd === PASSWORD){
const authentication = jwt.sign({ foo: 'bar', exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 30 }, SIGN_KEY);
resp.status(200).json({
authentication: authentication
})
}else{
resp.status(401).send("密码错误")
}
}catch(err){
resp.status(400).send(err.toString())
}
}else{
resp.status(200).json({})
}
})
const PORT = process.env.PORT || 3000;
const PASSWORD = process.env.PASSWORD || "";
const ALLOWED_DOMAINS = process.env.ALLOWED_DOMAINS || ""
const FORCE_DOWNLOAD = (process.env.FORCE_DOWNLOAD || "").toLowerCase()
let DOMAIN_VALIDATOR = undefined
if(ALLOWED_DOMAINS !== ""){
let domains = ALLOWED_DOMAINS.split(",")
DOMAIN_VALIDATOR = new DomainValidator(domains)
}
const SIGN_KEY = uuidv4();
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});