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