@fastify/express 4.0.5 → 4.0.7

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.
@@ -2,12 +2,52 @@ version: 2
2
2
  updates:
3
3
  - package-ecosystem: "github-actions"
4
4
  directory: "/"
5
+ commit-message:
6
+ # Prefix all commit messages with "chore: "
7
+ prefix: "chore"
5
8
  schedule:
6
- interval: "monthly"
9
+ interval: "weekly"
10
+ cooldown:
11
+ default-days: 7
12
+ allow:
13
+ - dependency-name: "*"
14
+ update-types:
15
+ - "version-update:semver-major"
7
16
  open-pull-requests-limit: 10
8
17
 
9
18
  - package-ecosystem: "npm"
10
19
  directory: "/"
20
+ commit-message:
21
+ # Prefix all commit messages with "chore: "
22
+ prefix: "chore"
11
23
  schedule:
12
- interval: "monthly"
24
+ interval: "weekly"
25
+ cooldown:
26
+ default-days: 7
27
+ versioning-strategy: "increase-if-necessary"
28
+ allow:
29
+ - dependency-name: "*"
30
+ update-types:
31
+ - "version-update:semver-major"
32
+ ignore:
33
+ # TODO: remove ignore until neostandard support ESLint 10
34
+ - dependency-name: "eslint"
35
+ - dependency-name: "neostandard"
36
+ - dependency-name: "@stylistic/*"
13
37
  open-pull-requests-limit: 10
38
+ groups:
39
+ # Production dependencies with breaking changes
40
+ dependencies:
41
+ dependency-type: "production"
42
+ # ESLint related dependencies
43
+ dev-dependencies-eslint:
44
+ patterns:
45
+ - "eslint"
46
+ - "neostandard"
47
+ - "@stylistic/*"
48
+ # TypeScript related dependencies
49
+ dev-dependencies-typescript:
50
+ patterns:
51
+ - "@types/*"
52
+ - "tstyche"
53
+ - "typescript"
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![NPM version](https://img.shields.io/npm/v/@fastify/express.svg?style=flat)](https://www.npmjs.com/package/@fastify/express)
5
5
  [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
6
6
 
7
- This plugin adds full [Express](http://expressjs.com) compatibility to Fastify, it exposes the same `use` function of Express, and it allows you to use any Express middleware or application.<br/>
7
+ This plugin adds full [Express](https://expressjs.com) compatibility to Fastify, it exposes the same `use` function of Express, and it allows you to use any Express middleware or application.<br/>
8
8
 
9
9
  <table>
10
10
  <tbody>
@@ -206,6 +206,11 @@ async function subsystem (fastify, opts) {
206
206
  }
207
207
  ```
208
208
 
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)`.
213
+
209
214
  ### Wrap Express req in Proxy
210
215
 
211
216
  It is possible to wrap the Express request object in a Proxy by passing `createProxyHandler` function to generate the Proxy handler. The function will receive the Fastify request object as the first parameter.
package/index.js CHANGED
@@ -25,9 +25,13 @@ function fastifyExpress (fastify, options, next) {
25
25
  .addHook('onRegister', onRegister)
26
26
 
27
27
  function use (path, fn) {
28
+ const prefix = this.prefix
28
29
  if (typeof path === 'string') {
29
- const prefix = this.prefix
30
30
  path = prefix + (path === '/' && prefix.length > 0 ? '' : path)
31
+ } 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) {
34
+ path = prefixRegExp(path, prefix)
31
35
  }
32
36
  this[kMiddlewares].push([path, fn])
33
37
  if (fn == null) {
@@ -60,7 +64,14 @@ function fastifyExpress (fastify, options, next) {
60
64
  req.raw.ips = req.ips
61
65
  req.raw.log = req.log
62
66
  reply.raw.log = req.log
67
+
68
+ let replySent = false
63
69
  reply.raw.send = function send (...args) {
70
+ if (replySent) {
71
+ return
72
+ }
73
+
74
+ replySent = true
64
75
  // Restore req.raw.url to its original value https://github.com/fastify/fastify-express/issues/11
65
76
  req.raw.url = normalizedUrl
66
77
  return reply.send.apply(reply, args)
@@ -76,13 +87,19 @@ function fastifyExpress (fastify, options, next) {
76
87
  req.raw.cookies = req.cookies
77
88
  }
78
89
 
79
- // Make it lazy as it does a bit of work
90
+ // ** Request **
80
91
  Object.defineProperty(req.raw, 'protocol', {
81
92
  get () {
82
93
  return req.protocol
83
94
  }
84
95
  })
85
96
 
97
+ // ** Response **
98
+ Object.defineProperty(reply.raw, 'headersSent', {
99
+ get () { return replySent },
100
+ configurable: true
101
+ })
102
+
86
103
  next()
87
104
  }
88
105
 
@@ -165,6 +182,27 @@ function removeDuplicateSlashes (path) {
165
182
  return path.replace(/\/{2,}/g, '/')
166
183
  }
167
184
 
185
+ function prefixMountPath (p, prefix) {
186
+ if (typeof p === 'string') {
187
+ return prefix + (p === '/' && prefix.length > 0 ? '' : p)
188
+ }
189
+ if (p instanceof RegExp && prefix.length > 0) {
190
+ return prefixRegExp(p, prefix)
191
+ }
192
+ /* c8 ignore next */
193
+ return p
194
+ }
195
+
196
+ function prefixRegExp (re, prefix) {
197
+ const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
198
+ const inner = re.source.replace(/(?:^|(?<=\|))\^/g, '')
199
+ const hasAnchor = inner !== re.source
200
+ const source = hasAnchor
201
+ ? '^' + escapedPrefix + '(?:' + inner + ')'
202
+ : escapedPrefix + '(?:' + re.source + ')'
203
+ return new RegExp(source, re.flags)
204
+ }
205
+
168
206
  module.exports = fp(fastifyExpress, {
169
207
  fastify: '5.x',
170
208
  name: '@fastify/express'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/express",
3
- "version": "4.0.5",
3
+ "version": "4.0.7",
4
4
  "description": "Express compatibility layer for Fastify",
5
5
  "main": "index.js",
6
6
  "type": "commonjs",
@@ -10,7 +10,7 @@
10
10
  "lint:fix": "eslint --fix",
11
11
  "test": "npm run test:unit && npm run test:typescript",
12
12
  "test:unit": "c8 --100 --reporter html node --test",
13
- "test:typescript": "tsd"
13
+ "test:typescript": "tstyche"
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
@@ -23,7 +23,7 @@
23
23
  "use",
24
24
  "compatibility"
25
25
  ],
26
- "author": "Tomas Della Vedova - @delvedor (http://delved.org)",
26
+ "author": "Tomas Della Vedova - @delvedor (https://delvedor.dev)",
27
27
  "contributors": [
28
28
  {
29
29
  "name": "Matteo Collina",
@@ -72,14 +72,11 @@
72
72
  "passport": "^0.7.0",
73
73
  "passport-http-bearer": "^1.0.1",
74
74
  "serve-static": "^2.2.0",
75
- "tsd": "^0.33.0"
75
+ "tstyche": "^7.0.0"
76
76
  },
77
77
  "dependencies": {
78
78
  "express": "^5.2.1",
79
- "fastify-plugin": "^5.0.0"
80
- },
81
- "tsd": {
82
- "directory": "test/types"
79
+ "fastify-plugin": "^6.0.0"
83
80
  },
84
81
  "publishConfig": {
85
82
  "access": "public"
@@ -5,6 +5,72 @@ const Fastify = require('fastify')
5
5
  const express = require('express')
6
6
  const expressPlugin = require('../index')
7
7
 
8
+ test('express error middlewares chained via next(err) must not crash the process when the first middleware already sent a response', async t => {
9
+ t.plan(2)
10
+ const fastify = Fastify()
11
+ t.after(() => fastify.close())
12
+
13
+ await fastify.register(expressPlugin)
14
+
15
+ const app = express()
16
+
17
+ app.get('/foo', (_req, _res, next) => {
18
+ next(new Error('route error'))
19
+ })
20
+
21
+ // First error middleware: send a response, then pass the error along.
22
+ app.use((err, _req, res, next) => {
23
+ res.status(500).json({ error: err.message })
24
+ next(err)
25
+ })
26
+
27
+ // Second error middleware: should skip sending because headersSent is true.
28
+ app.use((_err, _req, res, _next) => {
29
+ if (!res.headersSent) {
30
+ res.status(500).json({ error: 'fallback' })
31
+ }
32
+ })
33
+
34
+ fastify.use(app)
35
+
36
+ const address = await fastify.listen({ port: 0 })
37
+ const result = await fetch(`${address}/foo`)
38
+ t.assert.deepStrictEqual(result.status, 500)
39
+ t.assert.deepStrictEqual(await result.json(), { error: 'route error' })
40
+ })
41
+
42
+ test('express error middleware that sends unconditionally must not crash the process after the first send', async t => {
43
+ t.plan(2)
44
+ const fastify = Fastify()
45
+ t.after(() => fastify.close())
46
+
47
+ await fastify.register(expressPlugin)
48
+
49
+ const app = express()
50
+
51
+ app.get('/bar', (_req, _res, next) => {
52
+ next(new Error('route error'))
53
+ })
54
+
55
+ // First error middleware sends and forwards the error.
56
+ app.use((err, _req, res, next) => {
57
+ res.status(500).json({ error: err.message })
58
+ next(err)
59
+ })
60
+
61
+ // Second error middleware sends unconditionally — exercises the replySent guard.
62
+ app.use((_err, _req, res, _next) => {
63
+ res.status(500).json({ error: 'should be blocked by replySent guard' })
64
+ })
65
+
66
+ fastify.use(app)
67
+
68
+ const address = await fastify.listen({ port: 0 })
69
+ const result = await fetch(`${address}/bar`)
70
+ t.assert.deepStrictEqual(result.status, 500)
71
+ t.assert.deepStrictEqual(await result.json(), { error: 'route error' })
72
+ })
73
+
8
74
  test('onSend hook should receive valid request and reply objects if middleware fails', async t => {
9
75
  t.plan(3)
10
76
  const fastify = Fastify()
@@ -267,6 +267,296 @@ test('should not double-prefix inherited middleware paths in child scopes', asyn
267
267
  t.assert.deepStrictEqual(await childWithAuth.json(), { data: 'child-secret' })
268
268
  })
269
269
 
270
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
271
+ test('array mount paths are rewritten with prefix', async t => {
272
+ t.plan(4)
273
+
274
+ const instance = fastify()
275
+ t.after(() => instance.close())
276
+
277
+ await instance.register(expressPlugin)
278
+
279
+ await instance.register(async function (admin) {
280
+ admin.use(['/private', '/settings'], function (req, res, next) {
281
+ if (req.headers.authorization !== 'Bearer secret') {
282
+ res.statusCode = 403
283
+ res.end('blocked by middleware')
284
+ return
285
+ }
286
+ next()
287
+ })
288
+
289
+ admin.get('/private', async () => {
290
+ return { secret: 'admin-data' }
291
+ })
292
+
293
+ admin.get('/settings', async () => {
294
+ return { settings: true }
295
+ })
296
+ }, { prefix: '/admin' })
297
+
298
+ const address = await instance.listen({ port: 0 })
299
+
300
+ const privateNoAuth = await fetch(address + '/admin/private')
301
+ t.assert.deepStrictEqual(privateNoAuth.status, 403)
302
+
303
+ const settingsNoAuth = await fetch(address + '/admin/settings')
304
+ t.assert.deepStrictEqual(settingsNoAuth.status, 403)
305
+
306
+ const privateWithAuth = await fetch(address + '/admin/private', {
307
+ headers: { authorization: 'Bearer secret' }
308
+ })
309
+ t.assert.deepStrictEqual(privateWithAuth.status, 200)
310
+ t.assert.deepStrictEqual(await privateWithAuth.json(), { secret: 'admin-data' })
311
+ })
312
+
313
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
314
+ test('regex mount paths are rewritten with prefix', async t => {
315
+ t.plan(3)
316
+
317
+ const instance = fastify()
318
+ t.after(() => instance.close())
319
+
320
+ await instance.register(expressPlugin)
321
+
322
+ await instance.register(async function (admin) {
323
+ admin.use(/^\/private/, function (req, res, next) {
324
+ if (req.headers.authorization !== 'Bearer secret') {
325
+ res.statusCode = 403
326
+ res.end('blocked by middleware')
327
+ return
328
+ }
329
+ next()
330
+ })
331
+
332
+ admin.get('/private', async () => {
333
+ return { secret: 'admin-data' }
334
+ })
335
+ }, { prefix: '/admin' })
336
+
337
+ const address = await instance.listen({ port: 0 })
338
+
339
+ const noAuth = await fetch(address + '/admin/private')
340
+ t.assert.deepStrictEqual(noAuth.status, 403)
341
+
342
+ const withAuth = await fetch(address + '/admin/private', {
343
+ headers: { authorization: 'Bearer secret' }
344
+ })
345
+ t.assert.deepStrictEqual(withAuth.status, 200)
346
+ t.assert.deepStrictEqual(await withAuth.json(), { secret: 'admin-data' })
347
+ })
348
+
349
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
350
+ test('regex without anchor is rewritten with prefix', async t => {
351
+ t.plan(3)
352
+
353
+ const instance = fastify()
354
+ t.after(() => instance.close())
355
+
356
+ await instance.register(expressPlugin)
357
+
358
+ await instance.register(async function (admin) {
359
+ admin.use(/\/private/, function (req, res, next) {
360
+ if (req.headers.authorization !== 'Bearer secret') {
361
+ res.statusCode = 403
362
+ res.end('blocked by middleware')
363
+ return
364
+ }
365
+ next()
366
+ })
367
+
368
+ admin.get('/private', async () => {
369
+ return { secret: 'admin-data' }
370
+ })
371
+ }, { prefix: '/admin' })
372
+
373
+ const address = await instance.listen({ port: 0 })
374
+
375
+ const noAuth = await fetch(address + '/admin/private')
376
+ t.assert.deepStrictEqual(noAuth.status, 403)
377
+
378
+ const withAuth = await fetch(address + '/admin/private', {
379
+ headers: { authorization: 'Bearer secret' }
380
+ })
381
+ t.assert.deepStrictEqual(withAuth.status, 200)
382
+ t.assert.deepStrictEqual(await withAuth.json(), { secret: 'admin-data' })
383
+ })
384
+
385
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
386
+ test('array with root slash is handled correctly with prefix', async t => {
387
+ t.plan(2)
388
+
389
+ const instance = fastify()
390
+ t.after(() => instance.close())
391
+
392
+ await instance.register(expressPlugin)
393
+
394
+ let middlewareCalled = false
395
+
396
+ await instance.register(async function (child) {
397
+ child.use(['/', '/health'], function (_req, _res, next) {
398
+ middlewareCalled = true
399
+ next()
400
+ })
401
+
402
+ child.get('/health', async () => {
403
+ return { ok: true }
404
+ })
405
+ }, { prefix: '/api' })
406
+
407
+ const address = await instance.listen({ port: 0 })
408
+
409
+ const result = await fetch(address + '/api/health')
410
+ t.assert.deepStrictEqual(result.status, 200)
411
+ t.assert.ok(middlewareCalled)
412
+ })
413
+
414
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
415
+ test('array of middleware functions (no path) works in prefixed plugin', async t => {
416
+ t.plan(2)
417
+
418
+ const instance = fastify()
419
+ t.after(() => instance.close())
420
+
421
+ await instance.register(expressPlugin)
422
+
423
+ let middlewareCalled = false
424
+
425
+ await instance.register(async function (child) {
426
+ child.use([function (_req, _res, next) {
427
+ middlewareCalled = true
428
+ next()
429
+ }])
430
+
431
+ child.get('/data', async () => {
432
+ return { ok: true }
433
+ })
434
+ }, { prefix: '/api' })
435
+
436
+ const address = await instance.listen({ port: 0 })
437
+
438
+ const result = await fetch(address + '/api/data')
439
+ t.assert.deepStrictEqual(result.status, 200)
440
+ t.assert.ok(middlewareCalled)
441
+ })
442
+
443
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
444
+ test('regex with alternation is fully rewritten with prefix', async t => {
445
+ t.plan(4)
446
+
447
+ const instance = fastify()
448
+ t.after(() => instance.close())
449
+
450
+ await instance.register(expressPlugin)
451
+
452
+ await instance.register(async function (admin) {
453
+ admin.use(/^\/private|^\/settings/, function (req, res, next) {
454
+ if (req.headers.authorization !== 'Bearer secret') {
455
+ res.statusCode = 403
456
+ res.end('blocked by middleware')
457
+ return
458
+ }
459
+ next()
460
+ })
461
+
462
+ admin.get('/private', async () => {
463
+ return { secret: 'admin-data' }
464
+ })
465
+
466
+ admin.get('/settings', async () => {
467
+ return { settings: true }
468
+ })
469
+ }, { prefix: '/admin' })
470
+
471
+ const address = await instance.listen({ port: 0 })
472
+
473
+ const privateNoAuth = await fetch(address + '/admin/private')
474
+ t.assert.deepStrictEqual(privateNoAuth.status, 403)
475
+
476
+ const settingsNoAuth = await fetch(address + '/admin/settings')
477
+ t.assert.deepStrictEqual(settingsNoAuth.status, 403)
478
+
479
+ const privateWithAuth = await fetch(address + '/admin/private', {
480
+ headers: { authorization: 'Bearer secret' }
481
+ })
482
+ t.assert.deepStrictEqual(privateWithAuth.status, 200)
483
+ t.assert.deepStrictEqual(await privateWithAuth.json(), { secret: 'admin-data' })
484
+ })
485
+
486
+ // @see https://github.com/fastify/fastify-express/security/advisories/GHSA-3wf5-7852-vcfq
487
+ test('mixed array of strings and regexes is rewritten with prefix', async t => {
488
+ t.plan(4)
489
+
490
+ const instance = fastify()
491
+ t.after(() => instance.close())
492
+
493
+ await instance.register(expressPlugin)
494
+
495
+ await instance.register(async function (admin) {
496
+ admin.use(['/private', /^\/settings/], function (req, res, next) {
497
+ if (req.headers.authorization !== 'Bearer secret') {
498
+ res.statusCode = 403
499
+ res.end('blocked by middleware')
500
+ return
501
+ }
502
+ next()
503
+ })
504
+
505
+ admin.get('/private', async () => {
506
+ return { secret: 'admin-data' }
507
+ })
508
+
509
+ admin.get('/settings', async () => {
510
+ return { settings: true }
511
+ })
512
+ }, { prefix: '/admin' })
513
+
514
+ const address = await instance.listen({ port: 0 })
515
+
516
+ const privateNoAuth = await fetch(address + '/admin/private')
517
+ t.assert.deepStrictEqual(privateNoAuth.status, 403)
518
+
519
+ const settingsNoAuth = await fetch(address + '/admin/settings')
520
+ t.assert.deepStrictEqual(settingsNoAuth.status, 403)
521
+
522
+ const privateWithAuth = await fetch(address + '/admin/private', {
523
+ headers: { authorization: 'Bearer secret' }
524
+ })
525
+ t.assert.deepStrictEqual(privateWithAuth.status, 200)
526
+ t.assert.deepStrictEqual(await privateWithAuth.json(), { secret: 'admin-data' })
527
+ })
528
+
529
+ test('regex with grouped anchors does not match in prefixed plugins (known limitation)', async t => {
530
+ t.plan(1)
531
+
532
+ const instance = fastify()
533
+ t.after(() => instance.close())
534
+
535
+ await instance.register(expressPlugin)
536
+
537
+ let middlewareCalled = false
538
+
539
+ await instance.register(async function (child) {
540
+ // (?:^\/private|^\/settings) -- the ^ inside the group is not stripped
541
+ // by prefixRegExp, so the rewritten regex still anchors to position 0
542
+ // of the full URL and fails to match /admin/private
543
+ child.use(/(?:^\/private|^\/settings)/, function (_req, _res, next) {
544
+ middlewareCalled = true
545
+ next()
546
+ })
547
+
548
+ child.get('/private', async () => {
549
+ return { ok: true }
550
+ })
551
+ }, { prefix: '/admin' })
552
+
553
+ const address = await instance.listen({ port: 0 })
554
+
555
+ await fetch(address + '/admin/private')
556
+ // Middleware is NOT called -- this is expected behavior, not a bug
557
+ t.assert.ok(!middlewareCalled)
558
+ })
559
+
270
560
  test('res.end should block middleware execution', async t => {
271
561
  t.plan(4)
272
562
 
@@ -1,6 +1,6 @@
1
1
  import Fastify, { FastifyRequest } from 'fastify'
2
2
  import fastifyExpress from '..'
3
- import { expectType } from 'tsd'
3
+ import { expect } from 'tstyche'
4
4
  import { Application } from 'express'
5
5
 
6
6
  const app = Fastify()
@@ -10,13 +10,13 @@ app.register(fastifyExpress, {
10
10
  expressHook: 'onRequest',
11
11
  createProxyHandler: (fastifyReq) => ({
12
12
  set (target, prop, value) {
13
- expectType<FastifyRequest>(fastifyReq)
13
+ expect(fastifyReq).type.toBe<FastifyRequest>()
14
14
  return Reflect.set(target, prop, value)
15
15
  }
16
16
  })
17
17
  })
18
18
 
19
- expectType<Application>(app.express)
19
+ expect(app.express).type.toBe<Application>()
20
20
 
21
21
  app.express.disable('x-powered-by')
22
22