forked from fastify/fastify-cors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
222 lines (190 loc) · 6.65 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
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
'use strict'
const fp = require('fastify-plugin')
const vary = require('./vary')
const defaultOptions = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: false,
exposedHeaders: null,
allowedHeaders: null,
maxAge: null,
preflight: true,
strictPreflight: true
}
function fastifyCors (fastify, opts, next) {
fastify.decorateRequest('corsPreflightEnabled', false)
let hideOptionsRoute = true
if (typeof opts === 'function') {
handleCorsOptionsDelegator(opts, fastify)
} else {
if (opts.hideOptionsRoute !== undefined) hideOptionsRoute = opts.hideOptionsRoute
const corsOptions = Object.assign({}, defaultOptions, opts)
fastify.addHook('onRequest', (req, reply, next) => {
onRequest(fastify, corsOptions, req, reply, next)
})
}
// The preflight reply must occur in the hook. This allows fastify-cors to reply to
// preflight requests BEFORE possible authentication plugins. If the preflight reply
// occurred in this handler, other plugins may deny the request since the browser will
// remove most headers (such as the Authentication header).
//
// This route simply enables fastify to accept preflight requests.
fastify.options('*', { schema: { hide: hideOptionsRoute } }, (req, reply) => {
if (!req.corsPreflightEnabled) {
// Do not handle preflight requests if the origin option disabled CORS
reply.callNotFound()
return
}
reply.send()
})
next()
}
function handleCorsOptionsDelegator (optionsResolver, fastify) {
fastify.addHook('onRequest', (req, reply, next) => {
if (optionsResolver.length === 2) {
handleCorsOptionsCallbackDelegator(optionsResolver, fastify, req, reply, next)
return
} else {
// handle delegator based on Promise
const ret = optionsResolver(req)
if (ret && typeof ret.then === 'function') {
ret.then(options => Object.assign({}, defaultOptions, options))
.then(corsOptions => onRequest(fastify, corsOptions, req, reply, next)).catch(next)
return
}
}
next(new Error('Invalid CORS origin option'))
})
}
function handleCorsOptionsCallbackDelegator (optionsResolver, fastify, req, reply, next) {
optionsResolver(req, (err, options) => {
if (err) {
next(err)
} else {
const corsOptions = Object.assign({}, defaultOptions, options)
onRequest(fastify, corsOptions, req, reply, next)
}
})
}
function onRequest (fastify, options, req, reply, next) {
// Always set Vary header
// https://github.com/rs/cors/issues/10
vary(reply, 'Origin')
const resolveOriginOption = typeof options.origin === 'function' ? resolveOriginWrapper(fastify, options.origin) : (_, cb) => cb(null, options.origin)
resolveOriginOption(req, (error, resolvedOriginOption) => {
if (error !== null) {
return next(error)
}
// Disable CORS and preflight if false
if (resolvedOriginOption === false) {
return next()
}
// Falsy values are invalid
if (!resolvedOriginOption) {
return next(new Error('Invalid CORS origin option'))
}
addCorsHeaders(req, reply, resolvedOriginOption, options)
if (req.raw.method === 'OPTIONS' && options.preflight === true) {
// Strict mode enforces the required headers for preflight
if (options.strictPreflight === true && (!req.headers.origin || !req.headers['access-control-request-method'])) {
reply.status(400).type('text/plain').send('Invalid Preflight Request')
return
}
req.corsPreflightEnabled = true
addPreflightHeaders(req, reply, options)
if (!options.preflightContinue) {
// Do not call the hook callback and terminate the request
// Safari (and potentially other browsers) need content-length 0,
// for 204 or they just hang waiting for a body
reply
.code(options.optionsSuccessStatus)
.header('Content-Length', '0')
.send()
return
}
}
return next()
})
}
function addCorsHeaders (req, reply, originOption, corsOptions) {
const origin = getAccessControlAllowOriginHeader(req.headers.origin, originOption)
// In the case of origin not allowed the header is not
// written in the response.
// https://github.com/fastify/fastify-cors/issues/127
if (origin) {
reply.header('Access-Control-Allow-Origin', origin)
}
if (corsOptions.credentials) {
reply.header('Access-Control-Allow-Credentials', 'true')
}
if (corsOptions.exposedHeaders !== null) {
reply.header(
'Access-Control-Expose-Headers',
Array.isArray(corsOptions.exposedHeaders) ? corsOptions.exposedHeaders.join(', ') : corsOptions.exposedHeaders
)
}
}
function addPreflightHeaders (req, reply, corsOptions) {
reply.header(
'Access-Control-Allow-Methods',
Array.isArray(corsOptions.methods) ? corsOptions.methods.join(', ') : corsOptions.methods
)
if (corsOptions.allowedHeaders === null) {
vary(reply, 'Access-Control-Request-Headers')
const reqAllowedHeaders = req.headers['access-control-request-headers']
if (reqAllowedHeaders !== undefined) {
reply.header('Access-Control-Allow-Headers', reqAllowedHeaders)
}
} else {
reply.header(
'Access-Control-Allow-Headers',
Array.isArray(corsOptions.allowedHeaders) ? corsOptions.allowedHeaders.join(', ') : corsOptions.allowedHeaders
)
}
if (corsOptions.maxAge !== null) {
reply.header('Access-Control-Max-Age', String(corsOptions.maxAge))
}
}
function resolveOriginWrapper (fastify, origin) {
return function (req, cb) {
const result = origin.call(fastify, req.headers.origin, cb)
// Allow for promises
if (result && typeof result.then === 'function') {
result.then(res => cb(null, res), cb)
}
}
}
function getAccessControlAllowOriginHeader (reqOrigin, originOption) {
if (originOption === '*') {
// allow any origin
return '*'
}
if (typeof originOption === 'string') {
// fixed origin
return originOption
}
// reflect origin
return isRequestOriginAllowed(reqOrigin, originOption) ? reqOrigin : false
}
function isRequestOriginAllowed (reqOrigin, allowedOrigin) {
if (Array.isArray(allowedOrigin)) {
for (let i = 0; i < allowedOrigin.length; ++i) {
if (isRequestOriginAllowed(reqOrigin, allowedOrigin[i])) {
return true
}
}
return false
} else if (typeof allowedOrigin === 'string') {
return reqOrigin === allowedOrigin
} else if (allowedOrigin instanceof RegExp) {
return allowedOrigin.test(reqOrigin)
} else {
return !!allowedOrigin
}
}
module.exports = fp(fastifyCors, {
fastify: '>=4.0.0-alpha.1',
name: 'fastify-cors'
})