-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
215 lines (184 loc) · 5.04 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
const express = require("express")
const bodyParser = require("body-parser")
const { createProxyMiddleware } = require("http-proxy-middleware")
const rateLimit = require("express-rate-limit")
const cors = require("cors")
const config = require("./configuration")
const morgan = require("morgan")
const fs = require("fs")
const path = require("path")
const axios = require("axios")
const app = express()
const { LRUCache } = require("lru-cache")
const logger = require("./logger");
const options = {
max: 2000,
// how long to live in ms
ttl: 1000 * 60,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
}
const lruCache = new LRUCache(options)
let keys = []
let isReady = false
async function loadRemoteKeys() {
try {
keys = await axios
.get(config.remoteKeys.url, {
headers: { Authorization: config.remoteKeys.authorization },
})
.then((x) => x.data)
isReady = true
setTimeout(loadRemoteKeys, config.remoteKeys.interval)
} catch (e) {
isReady = false
logger.log("Error while loading keys", e)
setTimeout(loadRemoteKeys, 5000)
}
}
if (config.remoteKeys.enabled) {
loadRemoteKeys()
} else {
keys = config.apiKeys
isReady = true
}
const rateLimiter = rateLimit({
...config.rateLimit,
keyGenerator(req) {
return req.body ? req.body.key : "undefined"
},
skip(req) {
return req.body && req.body.key === config.godApiKey
},
})
const proxy = createProxyMiddleware({
changeOrigin: true,
secure: false,
target: config.node.url,
onProxyReq(proxyReq, req) {
const data = JSON.stringify({ ...req.body, key: config.node.key })
proxyReq.setHeader("Content-Length", Buffer.byteLength(data))
proxyReq.write(data)
},
})
const keyChecker = function (req, res, next) {
if (
config.check &&
config.check.methods.includes(req.body.method) &&
config.check.key === req.body.key
) {
return next()
}
if (config.methods.indexOf(req.body.method) === -1) {
res.status(403).send("method not available") // SET 404 PAGE ??
return
}
if (req.body.key === config.godApiKey) {
return next()
}
if (!isReady) {
res.status(400).send("proxy is not started")
return
}
if (keys.indexOf(req.body.key) === -1) {
res.status(403).send("API key is invalid")
return
}
next()
}
let cacheDurations = undefined
if (config.cache?.length) {
cacheDurations = {}
config.cache.forEach((element) => {
cacheDurations[element.method] = element
})
}
const cache = function (req, res, next) {
if (!cacheDurations) {
return next()
}
if (!cacheDurations[req.body.method]) {
return next()
}
const duration = cacheDurations[req.body.method].duration
let key = "__express__" + req.body.method + JSON.stringify(req.body.params)
let cachedBody = lruCache.get(key)
if (cachedBody) {
res.setHeader("Content-Type", "application/json")
res.setHeader("Cache-Control", "max-age=" + duration / 1000)
res.send(cachedBody)
return
} else {
res.writeResp = res.write
var chunks = [];
res.write = function (chunk) {
chunks.push(chunk);
return res.writeResp.apply(res, arguments);
};
var oldEnd = res.end;
res.end = function (chunk) {
if (chunk)
chunks.push(chunk);
var body = Buffer.concat(chunks).toString('utf8');
const response = JSON.parse(body)
if (!response.error) {
lruCache.set(key, body, { ttl: duration })
}
oldEnd.apply(res, arguments);
};
return next()
}
}
morgan.token("body", (req, res) => JSON.stringify(req.body))
morgan.token("apiKey", (req, res) => (req.body ? req.body.key : null))
app.use(cors())
app.use(bodyParser.json({ limit: "2mb" }))
if (config.logs.output === "file") {
const accessLogStream = fs.createWriteStream(
path.join(__dirname, config.logs.file),
{
flags: "a",
}
)
app.use(
morgan(config.logs.format, {
stream: accessLogStream,
})
)
}
if (config.logs.output === "stdout") {
app.use(morgan(config.logs.format))
}
// WEBSITE -------------------------------------------------------------------------------
// website routes
const websiteDir = path.join(__dirname, 'website');
const websiteResourcesDir = path.join(__dirname, 'website/resources');
app.use(express.static(websiteResourcesDir));
// serve the site
app.get("/", (req, res) => {
res.status(200).sendFile(path.join(websiteDir, 'index.html'));
});
app.get("/faq", (req, res) => {
res.status(200).sendFile(path.join(websiteDir, 'faq.html'));
});
app.get("/contact", (req, res) => {
res.status(200).sendFile(path.join(websiteDir, 'contact.html'));
});
app.get("/about", (req, res) => {
res.status(200).sendFile(path.join(websiteDir, 'about.html'));
});
// old urls
app.get("/faq.html", (req, res) => {
res.redirect(301, "/faq");
});
app.get("/contact.html", (req, res) => {
res.redirect(301, "/contact");
});
// Idena RPC ---------------------
app.use(rateLimiter)
app.use(keyChecker)
app.use(cache)
app.use(proxy)
app.listen(8000)