-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
219 lines (186 loc) · 5.63 KB
/
index.js
File metadata and controls
219 lines (186 loc) · 5.63 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
require("dotenv").config();
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const helmet = require("helmet");
const compression = require("compression");
const rateLimit = require("express-rate-limit");
const cors = require("cors");
const winston = require("winston");
require("winston-daily-rotate-file");
const app = express();
/* =========================================================
CONFIGURATION
========================================================= */
const PORT = process.env.PORT || 7812;
const MODE = process.env.PROXY_MODE || "reverse"; // reverse | forward
const SERVER_URL = process.env.SERVER_URL;
const API_KEY = process.env.API_KEY || null;
const ALLOWED_ORIGIN = process.env.ALLOWED_ORIGIN || "*";
const REQUEST_LIMIT = process.env.REQUEST_LIMIT || "10mb";
const TRUST_PROXY = process.env.TRUST_PROXY === "true";
const IP_WHITELIST = process.env.IP_WHITELIST
? process.env.IP_WHITELIST.split(",")
: null;
if (MODE === "reverse" && !SERVER_URL) {
console.error("SERVER_URL is required in reverse mode");
process.exit(1);
}
if (TRUST_PROXY) {
app.set("trust proxy", 1);
}
/* =========================================================
LOGGER (Winston + Daily Rotation)
========================================================= */
const transport = new winston.transports.DailyRotateFile({
filename: "logs/proxy-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
});
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
transport,
new winston.transports.Console({
format: winston.format.simple(),
}),
],
});
/* =========================================================
SECURITY MIDDLEWARE
========================================================= */
app.use(helmet());
app.use(compression());
app.use(express.json({ limit: REQUEST_LIMIT }));
app.use(express.urlencoded({ extended: true, limit: REQUEST_LIMIT }));
const limiter = rateLimit({
windowMs: 60 * 1000,
max: 300,
});
app.use(limiter);
app.use(cors({ origin: ALLOWED_ORIGIN }));
/* =========================================================
ACCESS CONTROL
========================================================= */
// Optional API key protection
if (API_KEY) {
app.use((req, res, next) => {
if (req.headers["x-api-key"] !== API_KEY) {
logger.warn("Unauthorized access attempt", { ip: req.ip });
return res.status(401).json({ error: "Unauthorized" });
}
next();
});
}
// Optional IP whitelist
if (IP_WHITELIST) {
app.use((req, res, next) => {
if (!IP_WHITELIST.includes(req.ip)) {
logger.warn("Blocked IP", { ip: req.ip });
return res.status(403).json({ error: "Forbidden" });
}
next();
});
}
/* =========================================================
REQUEST LOGGING
========================================================= */
app.use((req, res, next) => {
logger.info("Incoming request", {
method: req.method,
url: req.originalUrl,
ip: req.ip,
});
next();
});
/* =========================================================
HEALTH + READINESS
========================================================= */
app.get("/health", (req, res) => {
res.status(200).json({
status: "OK",
mode: MODE,
uptime: process.uptime(),
});
});
app.get("/ready", (req, res) => {
res.status(200).json({ ready: true });
});
/* =========================================================
REVERSE PROXY (DEFAULT)
========================================================= */
if (MODE === "reverse") {
app.use(
"/",
createProxyMiddleware({
target: SERVER_URL,
changeOrigin: true,
ws: true,
proxyTimeout: 20000,
timeout: 20000,
secure: true,
onError(err, req, res) {
logger.error("Proxy error", { message: err.message });
res.status(502).json({ error: "Bad Gateway" });
},
onProxyReq(proxyReq, req) {
proxyReq.setHeader("X-Forwarded-For", req.ip);
},
})
);
}
/* =========================================================
FORWARD PROXY (LOCKED DOWN)
========================================================= */
if (MODE === "forward") {
app.use(
"/",
createProxyMiddleware({
router: (req) => {
if (!req.query.url) {
throw new Error("Missing ?url parameter");
}
return req.query.url;
},
changeOrigin: true,
secure: true,
onError(err, req, res) {
logger.error("Forward proxy error", { message: err.message });
res.status(400).json({ error: "Invalid target URL" });
},
})
);
}
/* =========================================================
GLOBAL ERROR HANDLER
========================================================= */
app.use((err, req, res, next) => {
logger.error("Unhandled error", { message: err.message });
res.status(500).json({ error: "Internal Server Error" });
});
/* =========================================================
START SERVER
========================================================= */
const server = app.listen(PORT, () => {
logger.info("Proxy server started", {
port: PORT,
mode: MODE,
target: SERVER_URL || "dynamic",
});
});
/* =========================================================
GRACEFUL SHUTDOWN
========================================================= */
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
function shutdown() {
logger.info("Shutting down gracefully...");
server.close(() => {
logger.info("Server closed");
process.exit(0);
});
}