-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (57 loc) · 1.47 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
const http = require('http')
function main() {
const port = process.env.PORT ?? 8123
const intervalSecs = process.env.INTERVAL_SECS ?? 60
const allowedOrigins =
process.env.ALLOWED_ORIGINS &&
new Set(process.env.ALLOWED_ORIGINS.split(','))
const intervalMs = intervalSecs * 1000
const clients = new Map()
const server = http.createServer((req, res) => {
if (req.method !== 'POST') {
res.writeHead(404)
res.write('not found')
res.end()
return
}
const id = req.url.substr(1)
if (id.length < 8) {
res.writeHead(400)
res.write('identifier too short')
res.end()
return
} else if (id.length > 32) {
res.writeHead(400)
res.write('identifier too long')
res.end()
return
}
const origin = req.headers['origin']
if (allowedOrigins && !allowedOrigins.has(origin)) {
res.writeHead(403)
res.write('invalid origin')
res.end()
return
}
clients.set(id, Date.now())
const headers = {
'Cache-Control': `max-age=${intervalSecs}`,
}
if (allowedOrigins) {
headers['Access-Control-Allow-Origin'] = origin
}
res.writeHead(200, headers)
res.write(String(clients.size))
res.end()
})
setInterval(() => {
const now = Date.now()
for (const [id, lastSeen] of clients.entries()) {
if (lastSeen < now - intervalMs * 1.5) {
clients.delete(id)
}
}
}, intervalMs)
server.listen(port)
}
main()