@fastify/express 4.0.9 → 4.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -3
- package/index.js +391 -53
- package/package.json +4 -2
- package/test/absolute-form-url.test.js +52 -4
- package/test/enhance-request.test.js +57 -6
- package/test/form-data.test.js +3 -3
- package/test/middleware.test.js +1100 -36
- package/test/path-normalization.test.js +158 -0
- package/test/url-encoding.test.js +144 -0
- package/test/use-after-register.test.js +108 -0
package/README.md
CHANGED
|
@@ -128,6 +128,8 @@ me@computer ~ % curl -X PATCH -H 'content-type:application/json' -d '{"foo2":"ba
|
|
|
128
128
|
|
|
129
129
|
The encapsulation works as usual with Fastify, you can register the plugin in a subsystem and your express code will work only inside there, or you can declare the express plugin top level and register a middleware in a nested plugin, and the middleware will be executed only for the nested routes of the specific plugin.
|
|
130
130
|
|
|
131
|
+
As with Fastify hooks, a middleware also runs for the routes of the plugins already registered in the instance where `use()` is called, for example after `await fastify.register(plugin)`.
|
|
132
|
+
|
|
131
133
|
*Register the plugin in its own subsystem:*
|
|
132
134
|
```js
|
|
133
135
|
const fastify = require('fastify')()
|
|
@@ -207,9 +209,21 @@ async function subsystem (fastify, opts) {
|
|
|
207
209
|
```
|
|
208
210
|
|
|
209
211
|
> **Note:** In prefixed plugins, `@fastify/express` rewrites string, array, and
|
|
210
|
-
> RegExp mount paths to include the prefix. RegExp
|
|
211
|
-
>
|
|
212
|
-
>
|
|
212
|
+
> RegExp mount paths to include the prefix. A RegExp path is matched against
|
|
213
|
+
> the rest of the URL after the prefix, as Express does for a mounted router:
|
|
214
|
+
> Express only runs a RegExp mount whose match starts the path, so the pattern
|
|
215
|
+
> must match from the end of the prefix, whether or not it starts with `^`, and
|
|
216
|
+
> a `^` inside a group (e.g., `/(?:^\/a|^\/b)/`) also anchors there. The `g` and
|
|
217
|
+
> `y` flags are dropped from RegExp mount paths, since they make matching stateful.
|
|
218
|
+
|
|
219
|
+
> **Note:** With case-insensitive routing (`routerOptions.caseSensitive: false`),
|
|
220
|
+
> the request path is lowercased while Express matches path-scoped middleware,
|
|
221
|
+
> to mirror the router. Two consequences: middleware sees the lowercased path in
|
|
222
|
+
> `req.url` and in Express `req.params` (the original is kept on
|
|
223
|
+
> `req.originalUrl`, and route handlers see the original spelling), so avoid
|
|
224
|
+
> relying on case-sensitive path data in middleware in this mode, for example
|
|
225
|
+
> `serveStatic` on a case-sensitive filesystem; and `RegExp` mount paths are
|
|
226
|
+
> matched case-insensitively (the `i` flag is added), as string mount paths are.
|
|
213
227
|
|
|
214
228
|
### Wrap Express req in Proxy
|
|
215
229
|
|
package/index.js
CHANGED
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
const fp = require('fastify-plugin')
|
|
4
4
|
const Express = require('express')
|
|
5
|
+
const parseUrl = require('parseurl')
|
|
6
|
+
const { parse, pathToRegexp } = require('path-to-regexp')
|
|
5
7
|
const kMiddlewares = Symbol('fastify-express-middlewares')
|
|
8
|
+
const kDynamicMountMatchers = Symbol('fastify-express-dynamic-mount-matchers')
|
|
9
|
+
const kChildren = Symbol('fastify-express-children')
|
|
6
10
|
|
|
7
11
|
function fastifyExpress (fastify, options, next) {
|
|
8
12
|
const {
|
|
@@ -13,9 +17,12 @@ function fastifyExpress (fastify, options, next) {
|
|
|
13
17
|
const routerOptions = fastify.initialConfig.routerOptions || {}
|
|
14
18
|
const ignoreDuplicateSlashes = routerOptions.ignoreDuplicateSlashes ?? fastify.initialConfig.ignoreDuplicateSlashes
|
|
15
19
|
const useSemicolonDelimiter = routerOptions.useSemicolonDelimiter ?? fastify.initialConfig.useSemicolonDelimiter
|
|
20
|
+
const caseSensitive = routerOptions.caseSensitive ?? fastify.initialConfig.caseSensitive
|
|
16
21
|
|
|
17
22
|
fastify.decorate('use', use)
|
|
18
23
|
fastify[kMiddlewares] = []
|
|
24
|
+
fastify[kDynamicMountMatchers] = []
|
|
25
|
+
fastify[kChildren] = []
|
|
19
26
|
fastify.decorate('express', Express())
|
|
20
27
|
fastify.express.disable('x-powered-by')
|
|
21
28
|
|
|
@@ -25,27 +32,53 @@ function fastifyExpress (fastify, options, next) {
|
|
|
25
32
|
.addHook('onRegister', onRegister)
|
|
26
33
|
|
|
27
34
|
function use (path, fn) {
|
|
28
|
-
|
|
35
|
+
// With ignoreDuplicateSlashes the router collapses repeated slashes in the
|
|
36
|
+
// routes it registers and in the request URL (see normalizeUrl), so mount
|
|
37
|
+
// paths must be collapsed too or they can never match.
|
|
38
|
+
const prefix = encodeMountPath(ignoreDuplicateSlashes ? removeDuplicateSlashes(this.prefix) : this.prefix)
|
|
29
39
|
if (typeof path === 'string') {
|
|
30
|
-
path =
|
|
40
|
+
path = prefixMountPath(path, prefix, ignoreDuplicateSlashes)
|
|
31
41
|
} else if (Array.isArray(path) && path.length > 0 && typeof path[0] !== 'function') {
|
|
32
|
-
path = path.
|
|
33
|
-
} else if (path instanceof RegExp
|
|
42
|
+
path = path.flatMap(p => prefixMountPath(p, prefix, ignoreDuplicateSlashes))
|
|
43
|
+
} else if (path instanceof RegExp) {
|
|
34
44
|
path = prefixRegExp(path, prefix)
|
|
35
45
|
}
|
|
36
|
-
|
|
46
|
+
|
|
47
|
+
if (caseSensitive === false) {
|
|
48
|
+
// The request path is lowercased to mirror the router (see normalizeUrl),
|
|
49
|
+
// so a RegExp mount path, and the plugin prefix rewritten into it, must
|
|
50
|
+
// match case-insensitively or it would never match an uppercase spelling.
|
|
51
|
+
path = Array.isArray(path) ? path.map(foldRegExp) : foldRegExp(path)
|
|
52
|
+
}
|
|
53
|
+
addMiddleware(this, path, fn)
|
|
54
|
+
return this
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Like a Fastify hook, a middleware also runs for the plugins that were
|
|
58
|
+
// already registered in the instance, so it is added to them as well.
|
|
59
|
+
function addMiddleware (instance, path, fn) {
|
|
60
|
+
instance[kMiddlewares].push([path, fn])
|
|
61
|
+
instance[kDynamicMountMatchers].push(...compileDynamicMountMatchers(path))
|
|
37
62
|
if (fn == null) {
|
|
38
|
-
|
|
63
|
+
instance.express.use(path)
|
|
39
64
|
} else {
|
|
40
|
-
|
|
65
|
+
instance.express.use(path, fn)
|
|
66
|
+
}
|
|
67
|
+
for (const child of instance[kChildren]) {
|
|
68
|
+
addMiddleware(child, path, fn)
|
|
41
69
|
}
|
|
42
|
-
return this
|
|
43
70
|
}
|
|
44
71
|
|
|
45
72
|
function enhanceRequest (req, reply, next) {
|
|
46
73
|
// Allow attaching custom Proxy handlers to Express req
|
|
47
74
|
if (typeof createProxyHandler === 'function') {
|
|
48
|
-
|
|
75
|
+
const rawRequest = req.raw
|
|
76
|
+
req.raw = new Proxy(rawRequest, createProxyHandler(req))
|
|
77
|
+
// Express sets `res.req` to the Proxy, but Node.js expects the request
|
|
78
|
+
// it created there when the response finishes
|
|
79
|
+
reply.raw.prependOnceListener('finish', () => {
|
|
80
|
+
reply.raw.req = rawRequest
|
|
81
|
+
})
|
|
49
82
|
}
|
|
50
83
|
|
|
51
84
|
const { url } = req.raw
|
|
@@ -63,7 +96,11 @@ function fastifyExpress (fastify, options, next) {
|
|
|
63
96
|
return
|
|
64
97
|
}
|
|
65
98
|
|
|
66
|
-
|
|
99
|
+
// With case-insensitive routing, Express matches path-scoped middleware on
|
|
100
|
+
// a path folded the way find-my-way folds it. Route handlers get the
|
|
101
|
+
// original spelling back once Express is done (see runConnect).
|
|
102
|
+
req[kNormalizedUrl] = normalizedUrl
|
|
103
|
+
req.raw.url = caseSensitive === false ? foldPath(normalizedUrl) : normalizedUrl
|
|
67
104
|
req.raw.id = req.id
|
|
68
105
|
req.raw.hostname = req.hostname
|
|
69
106
|
req.raw.ip = req.ip
|
|
@@ -109,20 +146,48 @@ function fastifyExpress (fastify, options, next) {
|
|
|
109
146
|
}
|
|
110
147
|
|
|
111
148
|
function runConnect (req, reply, next) {
|
|
149
|
+
// An empty segment can match a Fastify route while the Express mount on the
|
|
150
|
+
// same dynamic pattern is skipped, bypassing its middleware. Reject such
|
|
151
|
+
// ambiguous requests. Only a route with parameters or a wildcard can take
|
|
152
|
+
// the empty segment: a static route (e.g. `/users/` next to a
|
|
153
|
+
// `/users/:id` mount) is not covered by the mount, as in Express.
|
|
154
|
+
if (isDynamicRoute(req.routeOptions.url) && hasAmbiguousDynamicMount(this[kDynamicMountMatchers], req.raw)) {
|
|
155
|
+
const error = new Error('Invalid route parameter')
|
|
156
|
+
error.statusCode = 400
|
|
157
|
+
next(error)
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
|
|
112
161
|
if (this[kMiddlewares].length > 0) {
|
|
113
162
|
for (const [headerName, headerValue] of Object.entries(reply.getHeaders())) {
|
|
114
163
|
reply.raw.setHeader(headerName, headerValue)
|
|
115
164
|
}
|
|
116
165
|
|
|
117
|
-
this.express(req.raw, reply.raw, next)
|
|
166
|
+
this.express(req.raw, reply.raw, caseSensitive === false ? restoreUrl : next)
|
|
167
|
+
} else if (caseSensitive === false) {
|
|
168
|
+
restoreUrl()
|
|
118
169
|
} else {
|
|
119
170
|
next()
|
|
120
171
|
}
|
|
172
|
+
|
|
173
|
+
// Hand route handlers the URL in its original spelling (see enhanceRequest).
|
|
174
|
+
function restoreUrl (err) {
|
|
175
|
+
if (req.raw.url === foldPath(req[kNormalizedUrl])) {
|
|
176
|
+
req.raw.url = req[kNormalizedUrl]
|
|
177
|
+
}
|
|
178
|
+
next(err)
|
|
179
|
+
}
|
|
121
180
|
}
|
|
122
181
|
|
|
123
182
|
function onRegister (instance) {
|
|
124
183
|
const middlewares = instance[kMiddlewares].slice()
|
|
184
|
+
const dynamicMountMatchers = instance[kDynamicMountMatchers].slice()
|
|
125
185
|
instance[kMiddlewares] = middlewares.slice()
|
|
186
|
+
instance[kDynamicMountMatchers] = dynamicMountMatchers.slice()
|
|
187
|
+
// Until it is replaced, the list is the one of the instance the plugin is
|
|
188
|
+
// registered in, as is the list of middlewares.
|
|
189
|
+
instance[kChildren].push(instance)
|
|
190
|
+
instance[kChildren] = []
|
|
126
191
|
instance.decorate('express', Express())
|
|
127
192
|
instance.express.disable('x-powered-by')
|
|
128
193
|
instance.decorate('use', use)
|
|
@@ -138,6 +203,90 @@ function fastifyExpress (fastify, options, next) {
|
|
|
138
203
|
next()
|
|
139
204
|
}
|
|
140
205
|
|
|
206
|
+
function compileDynamicMountMatchers (path) {
|
|
207
|
+
const paths = Array.isArray(path) ? path : [path]
|
|
208
|
+
const matchers = []
|
|
209
|
+
|
|
210
|
+
for (const mountPath of paths) {
|
|
211
|
+
if (mountPath instanceof RegExp) {
|
|
212
|
+
// A RegExp mount cannot be modelled as a string, so keep the pattern and
|
|
213
|
+
// detect ambiguity by filling empty segments (see hasAmbiguousDynamicMount).
|
|
214
|
+
matchers.push({
|
|
215
|
+
express: new RegExp(mountPath.source, mountPath.flags.replace(/[gy]/g, '')),
|
|
216
|
+
permissive: null
|
|
217
|
+
})
|
|
218
|
+
continue
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (typeof mountPath !== 'string') {
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Express strips trailing slashes from string mounts before matching.
|
|
226
|
+
const loosened = mountPath === '/' ? mountPath : mountPath.replace(/\/+$/, '')
|
|
227
|
+
const compiled = compileTokens(parse(loosened).tokens)
|
|
228
|
+
if (compiled.dynamic) {
|
|
229
|
+
matchers.push({
|
|
230
|
+
express: pathToRegexp(loosened, { end: false }).regexp,
|
|
231
|
+
permissive: new RegExp(`^(?:${compiled.source})(?:\\/$)?(?=\\/|$)`, 'i')
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return matchers
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function compileTokens (tokens) {
|
|
240
|
+
let source = ''
|
|
241
|
+
let dynamic = false
|
|
242
|
+
|
|
243
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
244
|
+
const token = tokens[i]
|
|
245
|
+
if (token.type === 'text') {
|
|
246
|
+
source += token.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
247
|
+
} else if (token.type === 'param' || token.type === 'wildcard') {
|
|
248
|
+
// Exclude the following literal's delimiter so adjacent parameters in a
|
|
249
|
+
// single segment cannot overlap and cause catastrophic backtracking.
|
|
250
|
+
const next = tokens[i + 1]
|
|
251
|
+
const delimiter = next && next.type === 'text' ? next.value[0] : ''
|
|
252
|
+
const excluded = delimiter && delimiter !== '/' ? delimiter.replace(/[-\]\\^]/g, '\\$&') : ''
|
|
253
|
+
source += token.type === 'wildcard'
|
|
254
|
+
? (excluded ? `[^${excluded}]*` : '.*')
|
|
255
|
+
: `[^${excluded}/]*`
|
|
256
|
+
dynamic = true
|
|
257
|
+
} else if (token.type === 'group') {
|
|
258
|
+
const group = compileTokens(token.tokens)
|
|
259
|
+
source += `(?:${group.source})?`
|
|
260
|
+
dynamic ||= group.dynamic
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return { source, dynamic }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function isDynamicRoute (url) {
|
|
268
|
+
return url !== undefined && /[:*]/.test(url)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function hasAmbiguousDynamicMount (matchers, rawRequest) {
|
|
272
|
+
const path = parseUrl(rawRequest).pathname
|
|
273
|
+
return matchers.some(matcher => {
|
|
274
|
+
if (matcher.permissive === null) {
|
|
275
|
+
// RegExp mount: ambiguous when the pattern misses only because a segment
|
|
276
|
+
// is empty, i.e. it matches once the empty segments are filled.
|
|
277
|
+
return !matcher.express.test(path) && matcher.express.test(fillEmptySegments(path))
|
|
278
|
+
}
|
|
279
|
+
return !matcher.express.test(path) && matcher.permissive.test(path)
|
|
280
|
+
})
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function fillEmptySegments (path) {
|
|
284
|
+
return path
|
|
285
|
+
.split('/')
|
|
286
|
+
.map((segment, index) => index > 0 && segment.trim().length === 0 ? 'a' : segment)
|
|
287
|
+
.join('/')
|
|
288
|
+
}
|
|
289
|
+
|
|
141
290
|
function normalizeUrl (url, options) {
|
|
142
291
|
const {
|
|
143
292
|
ignoreDuplicateSlashes,
|
|
@@ -145,22 +294,63 @@ function normalizeUrl (url, options) {
|
|
|
145
294
|
} = options
|
|
146
295
|
|
|
147
296
|
// Match find-my-way's absolute-form handling before normalizing the path.
|
|
148
|
-
|
|
149
|
-
|
|
297
|
+
// find-my-way routes the asterisk-form (`OPTIONS *`) as `/`, so Express is
|
|
298
|
+
// handed `/` too. Any other target must start with `/` once an absolute-form
|
|
299
|
+
// URL is resolved: find-my-way skips the first character of the path, so
|
|
300
|
+
// Fastify routes `*admin` as `/admin`, while Express would not match it
|
|
301
|
+
// against a mount on `/admin`.
|
|
302
|
+
const originFormUrl = url === '*' ? '/' : getPathFromAbsoluteUrl(url)
|
|
303
|
+
if (originFormUrl === null || originFormUrl[0] !== '/') {
|
|
150
304
|
return null
|
|
151
305
|
}
|
|
152
306
|
|
|
153
|
-
|
|
307
|
+
// Split off the query string before decoding, as find-my-way does, so that
|
|
308
|
+
// Express decodes it only once, as Fastify does.
|
|
309
|
+
const { path, query } = splitPathAndQuery(originFormUrl, useSemicolonDelimiter)
|
|
310
|
+
|
|
311
|
+
// Decode the path the way find-my-way does before routing: `%25` stays
|
|
312
|
+
// encoded, so a literal `%` is not decoded a second time when Express
|
|
313
|
+
// decodes route parameters.
|
|
314
|
+
let decodedPath
|
|
154
315
|
try {
|
|
155
|
-
|
|
316
|
+
decodedPath = decodeURI(path.replaceAll('%25', '%2525'))
|
|
317
|
+
// The query string is passed on undecoded, but malformed percent-encoding
|
|
318
|
+
// in it is still rejected, as it was when the whole URL was decoded.
|
|
319
|
+
decodeURI(query)
|
|
156
320
|
} catch {
|
|
157
321
|
return null
|
|
158
322
|
}
|
|
159
323
|
|
|
160
|
-
const
|
|
161
|
-
|
|
324
|
+
const normalizedPath = ignoreDuplicateSlashes ? removeDuplicateSlashes(decodedPath) : decodedPath
|
|
325
|
+
|
|
326
|
+
return encodeParseurlFallbackChars(normalizedPath + query)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Express reads req.url with parseurl, which hands a URL containing any of
|
|
330
|
+
// these characters to the legacy url.parse(). That parser rewrites `\` to `/`,
|
|
331
|
+
// so Express would match mount paths against a different path from the one
|
|
332
|
+
// Fastify routed. Percent-encoding them keeps parseurl on its fast path.
|
|
333
|
+
const PARSEURL_FALLBACK_CHARS = /[\t\n\f\r #\u00a0\ufeff]/g
|
|
334
|
+
|
|
335
|
+
function encodeParseurlFallbackChars (url) {
|
|
336
|
+
return url.replace(PARSEURL_FALLBACK_CHARS, encodeURIComponent)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Spell a mount path the way normalizeUrl() spells the request path, so that
|
|
340
|
+
// it means what the same string means as a Fastify route: find-my-way also
|
|
341
|
+
// stores a literal `%` in a route as `%25`.
|
|
342
|
+
function encodeMountPath (path) {
|
|
343
|
+
return encodeParseurlFallbackChars(path.replaceAll('%', '%25'))
|
|
344
|
+
}
|
|
162
345
|
|
|
163
|
-
|
|
346
|
+
const kNormalizedUrl = Symbol('fastify-express-normalized-url')
|
|
347
|
+
|
|
348
|
+
// Lowercase the path, not the query, as find-my-way does with caseSensitive: false.
|
|
349
|
+
function foldPath (url) {
|
|
350
|
+
const queryIndex = url.indexOf('?')
|
|
351
|
+
return queryIndex === -1
|
|
352
|
+
? url.toLowerCase()
|
|
353
|
+
: url.slice(0, queryIndex).toLowerCase() + url.slice(queryIndex)
|
|
164
354
|
}
|
|
165
355
|
|
|
166
356
|
function getPathFromAbsoluteUrl (url) {
|
|
@@ -196,61 +386,209 @@ function getPathFromAbsoluteUrl (url) {
|
|
|
196
386
|
}
|
|
197
387
|
|
|
198
388
|
function splitPathAndQuery (url, useSemicolonDelimiter) {
|
|
199
|
-
|
|
389
|
+
// Like find-my-way, end the path at the first `?` or `#`, or at the first
|
|
390
|
+
// `;` when useSemicolonDelimiter is set.
|
|
391
|
+
const queryIndex = url.search(useSemicolonDelimiter ? /[?#;]/ : /[?#]/)
|
|
200
392
|
|
|
201
|
-
if (
|
|
202
|
-
|
|
203
|
-
return { path: url, query: '' }
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
return {
|
|
207
|
-
path: url.slice(0, queryIndex),
|
|
208
|
-
query: url.slice(queryIndex)
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
const semicolonIndex = url.indexOf(';')
|
|
213
|
-
|
|
214
|
-
if (semicolonIndex === -1 || (queryIndex !== -1 && queryIndex < semicolonIndex)) {
|
|
215
|
-
if (queryIndex === -1) {
|
|
216
|
-
return { path: url, query: '' }
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
return {
|
|
220
|
-
path: url.slice(0, queryIndex),
|
|
221
|
-
query: url.slice(queryIndex)
|
|
222
|
-
}
|
|
393
|
+
if (queryIndex === -1) {
|
|
394
|
+
return { path: url, query: '' }
|
|
223
395
|
}
|
|
224
396
|
|
|
225
397
|
return {
|
|
226
|
-
path: url.slice(0,
|
|
227
|
-
query: `?${url.slice(
|
|
398
|
+
path: url.slice(0, queryIndex),
|
|
399
|
+
query: `?${url.slice(queryIndex + 1)}`
|
|
228
400
|
}
|
|
229
401
|
}
|
|
230
402
|
|
|
403
|
+
function foldRegExp (p) {
|
|
404
|
+
return p instanceof RegExp && !p.flags.includes('i') ? new RegExp(p.source, p.flags + 'i') : p
|
|
405
|
+
}
|
|
406
|
+
|
|
231
407
|
function removeDuplicateSlashes (path) {
|
|
232
408
|
return path.replace(/\/{2,}/g, '/')
|
|
233
409
|
}
|
|
234
410
|
|
|
235
|
-
function
|
|
411
|
+
function joinPrefix (prefix, path) {
|
|
412
|
+
// Match Fastify's own route-prefix join so the Express mount path always
|
|
413
|
+
// lines up with the path find-my-way serves. Both `prefix` and `path` may
|
|
414
|
+
// or may not carry a leading/trailing slash; naively concatenating them
|
|
415
|
+
// yields a mount path that can never match (e.g. `/api//secret` from
|
|
416
|
+
// `/api/` + `/secret`, or `/apisecret` from `/api` + `secret`), letting
|
|
417
|
+
// auth middlewares be silently skipped.
|
|
418
|
+
if ((path === '/' && prefix.length > 0) || (path[0] === '/' && prefix.endsWith('/'))) {
|
|
419
|
+
// The prefix already supplies the separator; drop the path's leading slash.
|
|
420
|
+
path = path.slice(1)
|
|
421
|
+
} else if (path[0] !== '/' && !prefix.endsWith('/')) {
|
|
422
|
+
// A mount path with no leading slash would otherwise glue onto the prefix
|
|
423
|
+
// (`/api` + `secret` => `/apisecret`) and never match a slash-led route.
|
|
424
|
+
// Fastify serves a slashless route at exactly that glued path, though, so
|
|
425
|
+
// mount both spellings.
|
|
426
|
+
return prefix.length > 0 ? [prefix + '/' + path, prefix + path] : '/' + path
|
|
427
|
+
}
|
|
428
|
+
return prefix + path
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function prefixMountPath (p, prefix, ignoreDuplicateSlashes) {
|
|
236
432
|
if (typeof p === 'string') {
|
|
237
|
-
|
|
433
|
+
const joined = joinPrefix(prefix, encodeMountPath(p))
|
|
434
|
+
if (!ignoreDuplicateSlashes) {
|
|
435
|
+
return joined
|
|
436
|
+
}
|
|
437
|
+
return Array.isArray(joined) ? joined.map(removeDuplicateSlashes) : removeDuplicateSlashes(joined)
|
|
238
438
|
}
|
|
239
|
-
if (p instanceof RegExp
|
|
439
|
+
if (p instanceof RegExp) {
|
|
240
440
|
return prefixRegExp(p, prefix)
|
|
241
441
|
}
|
|
242
442
|
/* c8 ignore next */
|
|
243
443
|
return p
|
|
244
444
|
}
|
|
245
445
|
|
|
446
|
+
const ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g
|
|
447
|
+
|
|
448
|
+
// Translate a Fastify route prefix (e.g. `/tenant/:tenantId`, `/a::b`,
|
|
449
|
+
// `/user/:id(\\d+)`) into a RegExp source that matches the concrete URLs
|
|
450
|
+
// Fastify routes to the plugin. Escaping the prefix wholesale treated `:param`
|
|
451
|
+
// as literal text, so RegExp-mounted middleware was skipped for ordinary URLs,
|
|
452
|
+
// bypassing auth (GHSA-84w6-xrf3-f8q8).
|
|
453
|
+
//
|
|
454
|
+
// find-my-way has already routed the request into this plugin, so a prefix
|
|
455
|
+
// segment holding a parameter (`:id`, `:id(\\d+)`, `:from-:to`) only needs to
|
|
456
|
+
// match one whole segment. Copying a parameter regex into the pattern instead
|
|
457
|
+
// would change what its `^` and `$` mean (find-my-way tests it against one
|
|
458
|
+
// segment), could make the pattern invalid under the `u` or `v` flag, and lets
|
|
459
|
+
// several parameters in one segment backtrack.
|
|
460
|
+
function prefixToRegExpSource (prefix) {
|
|
461
|
+
let result = ''
|
|
462
|
+
let segment = ''
|
|
463
|
+
let dynamic = false
|
|
464
|
+
let depth = 0
|
|
465
|
+
|
|
466
|
+
const flush = () => {
|
|
467
|
+
const source = dynamic ? '[^\\/]*' : segment.replace(ESCAPE_REGEXP, '\\$&')
|
|
468
|
+
segment = ''
|
|
469
|
+
dynamic = false
|
|
470
|
+
return source
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
for (let i = 0; i < prefix.length; i++) {
|
|
474
|
+
const char = prefix[i]
|
|
475
|
+
|
|
476
|
+
if (depth > 0) {
|
|
477
|
+
// Skip a parameter regex; find-my-way keeps it within one segment.
|
|
478
|
+
if (char === '\\') {
|
|
479
|
+
i++
|
|
480
|
+
} else if (char === '(') {
|
|
481
|
+
depth++
|
|
482
|
+
} else if (char === ')') {
|
|
483
|
+
depth--
|
|
484
|
+
}
|
|
485
|
+
} else if (char === '/') {
|
|
486
|
+
result += flush() + '\\/'
|
|
487
|
+
} else if (char === ':' && prefix[i + 1] === ':') {
|
|
488
|
+
// `::` is an escaped literal colon in find-my-way.
|
|
489
|
+
segment += ':'
|
|
490
|
+
i++
|
|
491
|
+
} else if (char === ':') {
|
|
492
|
+
dynamic = true
|
|
493
|
+
} else if (char === '(' && dynamic) {
|
|
494
|
+
depth = 1
|
|
495
|
+
} else {
|
|
496
|
+
segment += char
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
return result + flush()
|
|
501
|
+
}
|
|
502
|
+
|
|
246
503
|
function prefixRegExp (re, prefix) {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
504
|
+
// Express calls exec() on the mount RegExp directly. With `g` or `y` the
|
|
505
|
+
// match state carries over in lastIndex, so every other request would skip
|
|
506
|
+
// the middleware.
|
|
507
|
+
const flags = re.flags.replace(/[gy]/g, '')
|
|
508
|
+
if (prefix.length === 0) {
|
|
509
|
+
return flags === re.flags ? re : new RegExp(re.source, flags)
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// Join the prefix to the pattern with an optional single slash, so there is
|
|
513
|
+
// exactly one slash at the boundary whether or not the prefix ends with one
|
|
514
|
+
// and whether or not the pattern (or one of its alternatives) starts with
|
|
515
|
+
// one, however that slash is spelled (`\/`, `[/]`, `\x2f`, inside a group).
|
|
516
|
+
// The slash is optional and lazy: a pattern that can match the empty string
|
|
517
|
+
// (`/^(?!\/public)/`) must stop right after the prefix, since Express skips
|
|
518
|
+
// a mount whose match ends in the middle of a path segment. As for a mounted
|
|
519
|
+
// Express router, the prefix ends at a slash or at the end of the path.
|
|
520
|
+
const mountPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix
|
|
521
|
+
const escapedPrefix = prefixToRegExpSource(mountPrefix)
|
|
522
|
+
const boundary = escapedPrefix + '(?=\\/|$)\\/??'
|
|
523
|
+
|
|
524
|
+
// Every route of a prefixed plugin starts with the prefix, so the pattern is
|
|
525
|
+
// matched against the rest of the path, as Express does for a mounted
|
|
526
|
+
// router. Express only runs a RegExp mount whose match starts the path, so
|
|
527
|
+
// every alternative is matched from the end of the prefix, whether or not it
|
|
528
|
+
// starts with `^`; any other `^` (e.g. inside a group) becomes a lookbehind
|
|
529
|
+
// for the same position. Searching for an unanchored alternative anywhere
|
|
530
|
+
// after the prefix would also take time quadratic in the length of the path.
|
|
531
|
+
const pattern = rewriteAnchors(re.source, flags.includes('v'), '(?<=^' + boundary + ')')
|
|
532
|
+
let source = '^' + boundary + '(?:' + pattern + ')'
|
|
533
|
+
|
|
534
|
+
// A route at the prefix itself (`/api` for `get('/')`) leaves nothing after
|
|
535
|
+
// the prefix, where a mounted Express router would test the pattern against
|
|
536
|
+
// '/'. Match the bare prefix when the pattern matches '/'.
|
|
537
|
+
const root = new RegExp(re.source, flags).exec('/')
|
|
538
|
+
if (root !== null && root[0].length <= 1) {
|
|
539
|
+
source = '^' + escapedPrefix + '(?=\\/?$)|' + source
|
|
540
|
+
}
|
|
541
|
+
return new RegExp(source, flags)
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// Rewrite the `^` assertions of a RegExp source matched from the end of the
|
|
545
|
+
// prefix: the `^` that leads a top-level alternative is dropped, and every
|
|
546
|
+
// other `^` is replaced with `anchor`. Escapes and character classes are
|
|
547
|
+
// skipped, so `\^`, `[^/]` and `[|]` are left alone.
|
|
548
|
+
function rewriteAnchors (source, unicodeSets, anchor) {
|
|
549
|
+
let result = ''
|
|
550
|
+
let leading = true
|
|
551
|
+
let depth = 0
|
|
552
|
+
let classDepth = 0
|
|
553
|
+
|
|
554
|
+
for (let i = 0; i < source.length; i++) {
|
|
555
|
+
const char = source[i]
|
|
556
|
+
let startsAlternative = false
|
|
557
|
+
|
|
558
|
+
if (char === '\\') {
|
|
559
|
+
result += char + source[i + 1]
|
|
560
|
+
i++
|
|
561
|
+
} else if (classDepth > 0) {
|
|
562
|
+
// With the `v` flag, classes nest (`[[a-z]--[aeiou]]`).
|
|
563
|
+
if (char === '[' && unicodeSets) {
|
|
564
|
+
classDepth++
|
|
565
|
+
} else if (char === ']') {
|
|
566
|
+
classDepth--
|
|
567
|
+
}
|
|
568
|
+
result += char
|
|
569
|
+
} else if (char === '[') {
|
|
570
|
+
classDepth = 1
|
|
571
|
+
result += char
|
|
572
|
+
} else if (char === '(') {
|
|
573
|
+
depth++
|
|
574
|
+
result += char
|
|
575
|
+
} else if (char === ')') {
|
|
576
|
+
depth--
|
|
577
|
+
result += char
|
|
578
|
+
} else if (char === '|' && depth === 0) {
|
|
579
|
+
result += char
|
|
580
|
+
startsAlternative = true
|
|
581
|
+
} else if (char === '^') {
|
|
582
|
+
if (!leading) {
|
|
583
|
+
result += anchor
|
|
584
|
+
}
|
|
585
|
+
} else {
|
|
586
|
+
result += char
|
|
587
|
+
}
|
|
588
|
+
leading = startsAlternative
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
return result
|
|
254
592
|
}
|
|
255
593
|
|
|
256
594
|
module.exports = fp(fastifyExpress, {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fastify/express",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.11",
|
|
4
4
|
"description": "Express compatibility layer for Fastify",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -76,7 +76,9 @@
|
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
78
|
"express": "^5.2.1",
|
|
79
|
-
"fastify-plugin": "^6.0.0"
|
|
79
|
+
"fastify-plugin": "^6.0.0",
|
|
80
|
+
"parseurl": "^1.3.3",
|
|
81
|
+
"path-to-regexp": "^8.4.2"
|
|
80
82
|
},
|
|
81
83
|
"publishConfig": {
|
|
82
84
|
"access": "public"
|