forked from billiegoose/cors-buster
-
Notifications
You must be signed in to change notification settings - Fork 35
/
middleware.js
163 lines (152 loc) · 3.67 KB
/
middleware.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
'use strict'
const url = require('url')
const {send} = require('micro')
const microCors = require('micro-cors')
const fetch = require('node-fetch')
const allowHeaders = [
'accept-encoding',
'accept-language',
'accept',
'access-control-allow-origin',
'authorization',
'cache-control',
'connection',
'content-length',
'content-type',
'dnt',
'git-protocol',
'pragma',
'range',
'referer',
'user-agent',
'x-authorization',
'x-http-method-override',
'x-requested-with',
]
const exposeHeaders = [
'accept-ranges',
'age',
'cache-control',
'content-length',
'content-language',
'content-type',
'date',
'etag',
'expires',
'last-modified',
'location',
'pragma',
'server',
'transfer-encoding',
'vary',
'x-github-request-id',
'x-redirected-url',
]
const allowMethods = [
'POST',
'GET',
'OPTIONS'
]
const allow = require('./allow-request.js')
const filter = (predicate, middleware) => {
function corsProxyMiddleware (req, res, next) {
if (predicate(req, res)) {
middleware(req, res, next)
} else {
next()
}
}
return corsProxyMiddleware
}
const compose = (...handlers) => {
const composeTwo = (handler1, handler2) => {
function composed (req, res, next) {
handler1(req, res, (err) => {
if (err) {
return next(err)
} else {
return handler2(req, res, next)
}
})
}
return composed
}
let result = handlers.pop()
while(handlers.length) {
result = composeTwo(handlers.pop(), result)
}
return result
}
function noop (_req, _res, next) {
next()
}
module.exports = ({ origin, insecure_origins = [], authorization = noop } = {}) => {
function predicate (req) {
let u = url.parse(req.url, true)
// Not a git request, skip
return allow(req, u)
}
function sendCorsOK (req, res, next) {
// Handle CORS preflight request
if (req.method === 'OPTIONS') {
return send(res, 200, '')
} else {
next()
}
}
function middleware (req, res, next) {
let u = url.parse(req.url, true)
let headers = {}
for (let h of allowHeaders) {
if (req.headers[h]) {
headers[h] = req.headers[h]
}
}
// GitHub uses user-agent sniffing for git/* and changes its behavior which is frustrating
if (!headers['user-agent'] || !headers['user-agent'].startsWith('git/')) {
headers['user-agent'] = 'git/@isomorphic-git/cors-proxy'
}
let p = u.path
let parts = p.match(/\/([^\/]*)\/(.*)/)
let pathdomain = parts[1]
let remainingpath = parts[2]
let protocol = insecure_origins.includes(pathdomain) ? 'http' : 'https'
fetch(
`${protocol}://${pathdomain}/${remainingpath}`,
{
method: req.method,
redirect: 'manual',
headers,
body: (req.method !== 'GET' && req.method !== 'HEAD') ? req : undefined
}
).then(f => {
if (f.headers.has('location')) {
// Modify the location so the client continues to use the proxy
let newUrl = f.headers.get('location').replace(/^https?:\//, '')
f.headers.set('location', newUrl)
}
res.statusCode = f.status
for (let h of exposeHeaders) {
if (h === 'content-length') continue
if (f.headers.has(h)) {
res.setHeader(h, f.headers.get(h))
}
}
if (f.redirected) {
res.setHeader('x-redirected-url', f.url)
}
f.body.pipe(res)
}).catch(e => {
console.error(e);
next();
});
}
const cors = microCors({
allowHeaders,
exposeHeaders,
allowMethods,
allowCredentials: false,
origin
})
return filter(predicate, cors(compose(sendCorsOK, authorization, middleware)))
}