-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipdiff.js
More file actions
266 lines (203 loc) · 5.76 KB
/
Copy pathipdiff.js
File metadata and controls
266 lines (203 loc) · 5.76 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import express from 'express';
import fetch from 'node-fetch';
import fs from 'fs';
import { execSync } from 'child_process';
// **********
// * Globals.
let us = ''; // ? storage for our IP
let hit = 0; // ? storage for our hit counter
const app = express();
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
const start = Date.now();
console.log(config.ui.hello);
const lut = {}; // ? last update time
const err = {}; // ? errors and such
const url = {}; // ? user rate limit
// ? pre-load our targets last-hit time into the lut
for (const s of config.services) {
lut[s] = start - (config.timeout * 1000);
err[s] = start - (config.retry * 1000);
}
// ********************
// * Some shenannigans.
function applyRateLimit(u, l) {
let limit = false;
if (u !== us)
{
// ? only limit requests that are not from ourselves (we're nice)
const tag = u + config.tagsep + l;
const t = Date.now();
// ? always increment the global hit counter
hit++;
// ? check endpoint, then global rate limits
for (const item of [[tag, config.router[l].limit], [u, config.limit]]) {
const i = item[0];
const j = item[1];
if (i in url) {
url[i].push(t);
if (url[i].length > j) {
// ? keep limit lists fixed length
url[i].splice(0, url[i].length - j);
console.log(config.ui.limit + i);
limit = true;
}
} else {
url[i] = [t];
}
}
}
return limit;
}
function cleanRateLimit() {
const t = Date.now();
for (const tag in url) {
let i = url[tag].length;
while (i--) {
if (url[tag][i] + (config.expire * 1000) < t) {
url[tag].splice(i, 1);
}
}
if (url[tag].length === 0) {
delete url[tag];
}
}
}
// *****
// * core functions
function checkGateway() {
let ret = false;
try {
execSync(`ping -c 1 "${config.gateway}"`, { timeout: 2000 });
ret = true;
}
catch (err) {
console.error(config.ui.gateway + err);
}
return ret;
}
function getIP(r) {
// ? get IP and chop off ::ffff: from IPv4 addresses
return (r.headers['x-forwarded-for'] || r.ip).replace('::ffff:', '');
}
function qShuffle(a) {
// ? ask me no questions, I will tell you no lies
return a.map((value) => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
}
async function refreshMyIP() {
// ? before we start, check if we can ping our remote gateway
if (checkGateway()) {
// ? every refresh period, select a random(ish) site, see if our IP is new
const t = Date.now();
let site = undefined;
for (const s of qShuffle(config.services)) {
if ((err[s] + (config.retry * 1000)) < t && (lut[s] + (config.timeout * 1000)) < t) {
site = s;
break;
}
}
if (typeof site !== 'undefined') {
try {
const res = await fetch(site, { 'headers': { 'User-Agent': config.agent } });
// ! console.debug(config.ui.site + site);
lut[site] = t;
if (res.status === 200) {
const txt = await res.text();
const newUs = txt.replace(/[^\u0020-\u007E]/g, '');
if (us !== newUs) {
us = newUs;
console.log(config.ui.site + site);
console.log(config.ui.update + us);
}
} else {
err[site] = t;
console.log(config.ui.norefresh + site);
}
} catch (e) {
err[site] = t;
console.log(config.ui.nobueno + site);
console.error(e.message);
}
} else {
console.log(config.ui.nosite);
}
}
}
// **********************************
// * Express router entries and such.
app.get(config.router.root.path, (req, res) => {
// ? send as little back as possible on a root request
const them = getIP(req);
if (applyRateLimit(them, "root")) {
res.sendStatus(429);
} else {
console.log(config.ui.request.health + them);
res.send(config.ui.healthy);
}
});
app.get(config.router.health.path, (req, res) => {
// ? send some real health information back
const them = getIP(req);
if (applyRateLimit(them, "health")) {
res.sendStatus(429);
} else {
console.log(config.ui.request.health2 + them);
const t = Date.now();
let count = 0;
for (const s of config.services) {
if ((err[s] + (config.retry * 1000)) < t) {
count++;
}
}
res.json({
'available': count,
'total': config.services.length,
'me': us,
'you': them,
'now': t,
'hit': hit,
'refreshed': Math.max(...Object.keys(lut).map((k) => lut[k])),
'uptime': t - start
});
}
});
app.get(config.router.text.path, (req, res) => {
// ? crappy html response
const them = getIP(req);
if (applyRateLimit(them, "text")) {
res.sendStatus(429);
} else {
console.log(config.ui.request.text + them);
res.send(config.ui.us + us + config.ui.textsep + config.ui.them + them);
}
});
app.get(config.router.json.path, (req, res) => {
// ? cool json response
const them = getIP(req);
if (applyRateLimit(them, "json")) {
res.sendStatus(429);
} else {
console.log(config.ui.request.json + them);
res.json({ 'me': us, 'you': them });
}
});
app.get(config.router.ip.path, (req, res) => {
// ? cool json response
const them = getIP(req);
if (applyRateLimit(them, "ip")) {
res.sendStatus(429);
} else {
console.log(config.ui.request.ip + them);
res.contentType('text/plain');
res.send(them);
}
});
app.listen(config.port, () => {
console.log(config.ui.startup + config.port);
});
// **************************
// * Interval and start call.
setInterval(cleanRateLimit, (config.clean * 1000));
setInterval(refreshMyIP, (config.refresh * 1000));
setTimeout(refreshMyIP, (config.startup * 1000));