-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
79 lines (59 loc) · 1.79 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
const got = require('got')
const cors = require('@koa/cors')
const Koa = require('koa')
const KoaRouter = require('koa-router')
const globalTunnel = require('global-tunnel-ng')
const { PROXY } = process.env
if (PROXY) {
const [ host, port ] = PROXY.split(':')
console.log(`Proxying all requests through ${host}:${port}`)
globalTunnel.initialize({ host, port })
}
const MIXPANEL_API_URL = 'https://api.mixpanel.com'
const MIXPANEL_JS_LIB_URL = 'http://cdn4.mxpnl.com/libs/mixpanel-2-latest.min.js'
const CODE_CACHE = new Map()
const init = async () => {
console.log(`Downloading JS lib from: ${MIXPANEL_JS_LIB_URL}`)
const { body: mixpanelJs } = await got(MIXPANEL_JS_LIB_URL)
const app = new Koa()
const router = new KoaRouter()
app.use(cors({
credentials: true,
}))
router.get('/client.js', async ctx => {
const { origin } = ctx
if (!CODE_CACHE[origin]) {
CODE_CACHE[origin] = mixpanelJs.replace(MIXPANEL_API_URL, origin.substr(origin.indexOf('://') + 1))
}
ctx.body = CODE_CACHE[origin]
})
router.get('/favicon.ico', async ctx => {
ctx.body = ''
})
router.get('*', async ctx => {
const { origin, href } = ctx
const newUrl = `${MIXPANEL_API_URL}${href.substr(origin.length)}`
const headers = {
...ctx.headers,
'X-Forwarded-For': ctx.ip
}
delete headers.host
const { body, statusCode, rawHeaders } = await got(newUrl, {
headers,
...(PROXY ? { agent: false } : null)
})
ctx.body = body
ctx.status = statusCode
ctx.headers = rawHeaders
})
app.use(router.routes())
app.use(router.allowedMethods())
const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
console.log(`Running on http://127.0.0.1:${PORT}`)
})
}
init().catch(err => {
console.error(err)
process.exit(-1)
})