@fastify/express 4.0.9 → 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 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 paths with `^` anchors inside
211
- > groups (e.g., `/(?:^\/a|^\/b)/`) are not rewritten correctly. Use array paths
212
- > instead: `fastify.use(['/a', '/b'], middleware)`.
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
- const prefix = this.prefix
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 = prefix + (path === '/' && prefix.length > 0 ? '' : path)
38
+ path = prefixMountPath(path, prefix, ignoreDuplicateSlashes)
31
39
  } else if (Array.isArray(path) && path.length > 0 && typeof path[0] !== 'function') {
32
- path = path.map(p => prefixMountPath(p, prefix))
33
- } else if (path instanceof RegExp && prefix.length > 0) {
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,7 +61,13 @@ 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
- req.raw = new Proxy(req.raw, createProxyHandler(req))
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
@@ -63,7 +85,11 @@ function fastifyExpress (fastify, options, next) {
63
85
  return
64
86
  }
65
87
 
66
- req.raw.url = normalizedUrl
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
67
93
  req.raw.id = req.id
68
94
  req.raw.hostname = req.hostname
69
95
  req.raw.ip = req.ip
@@ -109,20 +135,44 @@ function fastifyExpress (fastify, options, next) {
109
135
  }
110
136
 
111
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
+
112
150
  if (this[kMiddlewares].length > 0) {
113
151
  for (const [headerName, headerValue] of Object.entries(reply.getHeaders())) {
114
152
  reply.raw.setHeader(headerName, headerValue)
115
153
  }
116
154
 
117
- 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()
118
158
  } else {
119
159
  next()
120
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
+ }
121
169
  }
122
170
 
123
171
  function onRegister (instance) {
124
172
  const middlewares = instance[kMiddlewares].slice()
173
+ const dynamicMountMatchers = instance[kDynamicMountMatchers].slice()
125
174
  instance[kMiddlewares] = middlewares.slice()
175
+ instance[kDynamicMountMatchers] = dynamicMountMatchers.slice()
126
176
  instance.decorate('express', Express())
127
177
  instance.express.disable('x-powered-by')
128
178
  instance.decorate('use', use)
@@ -138,6 +188,90 @@ function fastifyExpress (fastify, options, next) {
138
188
  next()
139
189
  }
140
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
+
141
275
  function normalizeUrl (url, options) {
142
276
  const {
143
277
  ignoreDuplicateSlashes,
@@ -145,22 +279,63 @@ function normalizeUrl (url, options) {
145
279
  } = options
146
280
 
147
281
  // Match find-my-way's absolute-form handling before normalizing the path.
148
- const originFormUrl = getPathFromAbsoluteUrl(url)
149
- if (originFormUrl === null) {
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] !== '/') {
150
289
  return null
151
290
  }
152
291
 
153
- let decodedUrl
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
154
300
  try {
155
- decodedUrl = decodeURI(originFormUrl)
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)
156
305
  } catch {
157
306
  return null
158
307
  }
159
308
 
160
- const { path, query } = splitPathAndQuery(decodedUrl, useSemicolonDelimiter)
161
- const normalizedPath = ignoreDuplicateSlashes ? removeDuplicateSlashes(path) : path
309
+ const normalizedPath = ignoreDuplicateSlashes ? removeDuplicateSlashes(decodedPath) : decodedPath
310
+
311
+ return encodeParseurlFallbackChars(normalizedPath + query)
312
+ }
313
+
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
162
319
 
163
- return normalizedPath + query
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) {
335
+ const queryIndex = url.indexOf('?')
336
+ return queryIndex === -1
337
+ ? url.toLowerCase()
338
+ : url.slice(0, queryIndex).toLowerCase() + url.slice(queryIndex)
164
339
  }
165
340
 
166
341
  function getPathFromAbsoluteUrl (url) {
@@ -196,61 +371,209 @@ function getPathFromAbsoluteUrl (url) {
196
371
  }
197
372
 
198
373
  function splitPathAndQuery (url, useSemicolonDelimiter) {
199
- const queryIndex = url.indexOf('?')
200
-
201
- if (!useSemicolonDelimiter) {
202
- if (queryIndex === -1) {
203
- return { path: url, query: '' }
204
- }
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 ? /[?#;]/ : /[?#]/)
205
377
 
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
- }
378
+ if (queryIndex === -1) {
379
+ return { path: url, query: '' }
223
380
  }
224
381
 
225
382
  return {
226
- path: url.slice(0, semicolonIndex),
227
- query: `?${url.slice(semicolonIndex + 1)}`
383
+ path: url.slice(0, queryIndex),
384
+ query: `?${url.slice(queryIndex + 1)}`
228
385
  }
229
386
  }
230
387
 
388
+ function foldRegExp (p) {
389
+ return p instanceof RegExp && !p.flags.includes('i') ? new RegExp(p.source, p.flags + 'i') : p
390
+ }
391
+
231
392
  function removeDuplicateSlashes (path) {
232
393
  return path.replace(/\/{2,}/g, '/')
233
394
  }
234
395
 
235
- function prefixMountPath (p, prefix) {
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) {
236
417
  if (typeof p === 'string') {
237
- return prefix + (p === '/' && prefix.length > 0 ? '' : p)
418
+ const joined = joinPrefix(prefix, encodeMountPath(p))
419
+ if (!ignoreDuplicateSlashes) {
420
+ return joined
421
+ }
422
+ return Array.isArray(joined) ? joined.map(removeDuplicateSlashes) : removeDuplicateSlashes(joined)
238
423
  }
239
- if (p instanceof RegExp && prefix.length > 0) {
424
+ if (p instanceof RegExp) {
240
425
  return prefixRegExp(p, prefix)
241
426
  }
242
427
  /* c8 ignore next */
243
428
  return p
244
429
  }
245
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
+
246
488
  function prefixRegExp (re, prefix) {
247
- const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
248
- const inner = re.source.replace(/(?:^|(?<=\|))\^/g, '')
249
- const hasAnchor = inner !== re.source
250
- const source = hasAnchor
251
- ? '^' + escapedPrefix + '(?:' + inner + ')'
252
- : escapedPrefix + '(?:' + re.source + ')'
253
- return new RegExp(source, re.flags)
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
254
577
  }
255
578
 
256
579
  module.exports = fp(fastifyExpress, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/express",
3
- "version": "4.0.9",
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"
@@ -11,7 +11,10 @@ function requestTarget (address, target, method = 'GET') {
11
11
 
12
12
  return new Promise((resolve, reject) => {
13
13
  const socket = net.createConnection({ host: hostname, port }, () => {
14
- socket.end(`${method} ${target} HTTP/1.1\r\nHost: ${hostname}:${port}\r\nConnection: close\r\n\r\n`)
14
+ // Do not half-close the connection: Node.js aborts a request still in
15
+ // flight when the client ends its side, so its response would be lost.
16
+ // The server closes the connection after responding (Connection: close).
17
+ socket.write(`${method} ${target} HTTP/1.1\r\nHost: ${hostname}:${port}\r\nConnection: close\r\n\r\n`)
15
18
  })
16
19
 
17
20
  let response = ''
@@ -71,7 +74,7 @@ test('absolute-form targets do not bypass path-scoped middleware', async t => {
71
74
  t.assert.deepStrictEqual(seen, [
72
75
  { url: '/admin/dashboard', originalUrl: targets[0] },
73
76
  { url: '/admin/dashboard', originalUrl: targets[1] },
74
- { url: '/admin/dashboard?test=value', originalUrl: targets[2] },
77
+ { url: '/admin/dashboard?test=%76alue', originalUrl: targets[2] },
75
78
  { url: '/admin/dashboard', originalUrl: targets[3] },
76
79
  { url: '/admin/dashboard?bypass', originalUrl: targets[4] }
77
80
  ])
@@ -137,7 +140,52 @@ test('absolute-form targets without a path resolve to root and preserve the quer
137
140
  t.assert.strictEqual((await requestTarget(address, 'http://example.test')).statusCode, 200)
138
141
  t.assert.strictEqual((await requestTarget(address, 'http://example.test?next=/admin&x=%76alue')).statusCode, 200)
139
142
  t.assert.strictEqual((await requestTarget(address, '*', 'OPTIONS')).statusCode, 200)
140
- t.assert.deepStrictEqual(seen, ['/', '/?next=/admin&x=value', '*'])
143
+ t.assert.deepStrictEqual(seen, ['/', '/?next=/admin&x=%76alue', '/'])
144
+ })
145
+
146
+ test('request targets that do not start with a slash do not bypass path-scoped middleware', async t => {
147
+ const instance = Fastify()
148
+ t.after(() => instance.close())
149
+
150
+ await instance.register(expressPlugin)
151
+
152
+ const deny = (req, res) => {
153
+ res.statusCode = 403
154
+ res.end('blocked')
155
+ }
156
+ instance.use('/admin', deny)
157
+ instance.use('/tenant/:id/admin', deny)
158
+ instance.get('/admin', async () => ({ secret: 'classified' }))
159
+ instance.get('/admin/:id', async () => ({ secret: 'classified' }))
160
+ instance.get('/tenant/:id/admin', async () => ({ secret: 'classified' }))
161
+
162
+ const address = await instance.listen({ port: 0, host: '127.0.0.1' })
163
+
164
+ for (const target of ['*admin', '*admin/42', '*tenant/x/admin']) {
165
+ const response = await requestTarget(address, target)
166
+ t.assert.strictEqual(response.statusCode, 400, target)
167
+ }
168
+ })
169
+
170
+ test('the asterisk-form request target is matched as the root path', async t => {
171
+ const instance = Fastify()
172
+ t.after(() => instance.close())
173
+
174
+ await instance.register(expressPlugin)
175
+
176
+ instance.use(/^\/$/, (req, res) => {
177
+ res.statusCode = 403
178
+ res.end('blocked')
179
+ })
180
+ instance.get('/', async () => ({ secret: 'classified' }))
181
+ instance.options('/', async () => ({ secret: 'classified' }))
182
+
183
+ const address = await instance.listen({ port: 0, host: '127.0.0.1' })
184
+
185
+ for (const method of ['GET', 'OPTIONS']) {
186
+ const response = await requestTarget(address, '*', method)
187
+ t.assert.strictEqual(response.statusCode, 403, method)
188
+ }
141
189
  })
142
190
 
143
191
  test('malformed request targets are rejected without affecting later requests', async t => {
@@ -175,7 +223,7 @@ test('malformed request targets are rejected without affecting later requests',
175
223
  t.assert.strictEqual(response.statusCode, 400, target)
176
224
  }
177
225
 
178
- for (const target of ['http:///admin', '/admin?value=%zz']) {
226
+ for (const target of ['http:///admin', '/admin?value=%zz', '*admin']) {
179
227
  const response = await instance.inject({
180
228
  method: 'GET',
181
229
  url: '/admin',