-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
80 lines (60 loc) · 2.31 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
const { readFileSync, appendFileSync, mkdirSync, writeFileSync, existsSync } = require('fs')
const moment = require('moment')
if (!existsSync('./log')) mkdirSync('./log')
if (!existsSync('./log/log-' + moment().format('YYYY-MM-DD') + '.log')) writeFileSync('./log/log-' + moment().format('YYYY-MM-DD') + '.log', '')
// ---
let settings
const { parse } = require('yaml')
const bouncy = require('bouncy')
const uuid = require('uuid').v4
getSetting()
setInterval(getSetting, 1000)
const gpio = settings.gpio ? require('gpio') : { DIRECTION: { OUT: 0 }, export: () => ({ set: () => {} }) }
const pin2 = gpio.export(27, { direction: gpio.DIRECTION.OUT })
const s1 = bouncy(mtx)
const s2 = settings.ssl ? bouncy({ cert: readFileSync('./cert/cert.pem').toString('utf-8'), key: readFileSync('./cert/key.pem').toString('utf-8') }, mtx) : null
s1.listen(80)
if (s2) s2.listen(443)
// ---
function mtx (req, res, bounce) {
pin2.set()
setTimeout(() => pin2.set(0), 100)
const code = uuid().slice(0, 10)
const ip =
req.headers['x-forwarded-for']
|| req.connection.remoteAddress
|| req.socket.remoteAddress
|| (req.connection.socket ? req.connection.socket.remoteAddress : null)
const host = req.headers.host
const rstr = settings.locale[req.socket.localPort !== 443 ? 'log' : 'slog'].replace('$ip', ip).replace('$host', host).replace('$code', code)
if (settings.blacklist.find((str) => ip.match(new RegExp(str)))) {
res.end(settings.locale.blocked.replace('$ip', ip).replace('$host', host).replace('$code', code))
log(rstr.replace('$togo', '[!blocked]'))
return
}
const target = settings.bounce[host]
if (!target) {
res.end(settings.locale.notpermitted.replace('$ip', ip).replace('$host', host).replace('$code', code))
log(rstr.replace('$togo', '[!no-permit]'))
return
}
if (Number.isNaN(Number(target))) {
res.end(target)
log(rstr.replace('$togo', '[pre-written]'))
return
}
bounce(target)
log(rstr.replace('$togo', target))
}
// ---
function getSetting () {
const raw = readFileSync('./settings.yaml', 'utf-8')
settings = parse(raw)
if (!settings.bounce) settings.bounce = {}
if (!settings.blacklist) settings.blacklist = []
}
// ---
function log (str) {
console.log(str)
appendFileSync('./log/log-' + moment().format('YYYY-MM-DD') + '.log', str + '\n')
}