@fastify/express 4.0.4 → 4.0.6

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.
@@ -27,7 +27,7 @@ jobs:
27
27
  permissions:
28
28
  contents: write
29
29
  pull-requests: write
30
- uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
30
+ uses: fastify/workflows/.github/workflows/plugins-ci.yml@v6
31
31
  with:
32
32
  license-check: true
33
33
  lint: true
@@ -0,0 +1,19 @@
1
+ name: Lock Threads
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 0 1 * *'
6
+ workflow_dispatch:
7
+
8
+ concurrency:
9
+ group: lock
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ lock-threads:
16
+ permissions:
17
+ issues: write
18
+ pull-requests: write
19
+ uses: fastify/workflows/.github/workflows/lock-threads.yml@v6
package/LICENSE CHANGED
@@ -1,8 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2019-present The Fastify team
4
-
5
- The Fastify team members are listed at https://github.com/fastify/fastify#team.
3
+ Copyright (c) 2019-present The Fastify team <https://github.com/fastify/fastify#team>
6
4
 
7
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
8
6
  of this software and associated documentation files (the "Software"), to deal
package/index.js CHANGED
@@ -10,6 +10,10 @@ function fastifyExpress (fastify, options, next) {
10
10
  createProxyHandler
11
11
  } = options
12
12
 
13
+ const routerOptions = fastify.initialConfig.routerOptions || {}
14
+ const ignoreDuplicateSlashes = routerOptions.ignoreDuplicateSlashes ?? fastify.initialConfig.ignoreDuplicateSlashes
15
+ const useSemicolonDelimiter = routerOptions.useSemicolonDelimiter ?? fastify.initialConfig.useSemicolonDelimiter
16
+
13
17
  fastify.decorate('use', use)
14
18
  fastify[kMiddlewares] = []
15
19
  fastify.decorate('express', Express())
@@ -43,7 +47,12 @@ function fastifyExpress (fastify, options, next) {
43
47
  const { url } = req.raw
44
48
 
45
49
  const decodedUrl = decodeURI(url)
46
- req.raw.url = decodedUrl
50
+ const normalizedUrl = normalizeUrl(decodedUrl, {
51
+ ignoreDuplicateSlashes,
52
+ useSemicolonDelimiter
53
+ })
54
+
55
+ req.raw.url = normalizedUrl
47
56
  req.raw.originalUrl = url
48
57
  req.raw.id = req.id
49
58
  req.raw.hostname = req.hostname
@@ -51,9 +60,16 @@ function fastifyExpress (fastify, options, next) {
51
60
  req.raw.ips = req.ips
52
61
  req.raw.log = req.log
53
62
  reply.raw.log = req.log
63
+
64
+ let replySent = false
54
65
  reply.raw.send = function send (...args) {
66
+ if (replySent) {
67
+ return
68
+ }
69
+
70
+ replySent = true
55
71
  // Restore req.raw.url to its original value https://github.com/fastify/fastify-express/issues/11
56
- req.raw.url = decodedUrl
72
+ req.raw.url = normalizedUrl
57
73
  return reply.send.apply(reply, args)
58
74
  }
59
75
 
@@ -67,13 +83,19 @@ function fastifyExpress (fastify, options, next) {
67
83
  req.raw.cookies = req.cookies
68
84
  }
69
85
 
70
- // Make it lazy as it does a bit of work
86
+ // ** Request **
71
87
  Object.defineProperty(req.raw, 'protocol', {
72
88
  get () {
73
89
  return req.protocol
74
90
  }
75
91
  })
76
92
 
93
+ // ** Response **
94
+ Object.defineProperty(reply.raw, 'headersSent', {
95
+ get () { return replySent },
96
+ configurable: true
97
+ })
98
+
77
99
  next()
78
100
  }
79
101
 
@@ -91,18 +113,71 @@ function fastifyExpress (fastify, options, next) {
91
113
 
92
114
  function onRegister (instance) {
93
115
  const middlewares = instance[kMiddlewares].slice()
94
- instance[kMiddlewares] = []
116
+ instance[kMiddlewares] = middlewares.slice()
95
117
  instance.decorate('express', Express())
96
118
  instance.express.disable('x-powered-by')
97
119
  instance.decorate('use', use)
98
- for (const middleware of middlewares) {
99
- instance.use(...middleware)
120
+ for (const [path, fn] of middlewares) {
121
+ if (fn == null) {
122
+ instance.express.use(path)
123
+ } else {
124
+ instance.express.use(path, fn)
125
+ }
100
126
  }
101
127
  }
102
128
 
103
129
  next()
104
130
  }
105
131
 
132
+ function normalizeUrl (url, options) {
133
+ const {
134
+ ignoreDuplicateSlashes,
135
+ useSemicolonDelimiter
136
+ } = options
137
+
138
+ const { path, query } = splitPathAndQuery(url, useSemicolonDelimiter)
139
+ const normalizedPath = ignoreDuplicateSlashes ? removeDuplicateSlashes(path) : path
140
+
141
+ return normalizedPath + query
142
+ }
143
+
144
+ function splitPathAndQuery (url, useSemicolonDelimiter) {
145
+ const queryIndex = url.indexOf('?')
146
+
147
+ if (!useSemicolonDelimiter) {
148
+ if (queryIndex === -1) {
149
+ return { path: url, query: '' }
150
+ }
151
+
152
+ return {
153
+ path: url.slice(0, queryIndex),
154
+ query: url.slice(queryIndex)
155
+ }
156
+ }
157
+
158
+ const semicolonIndex = url.indexOf(';')
159
+
160
+ if (semicolonIndex === -1 || (queryIndex !== -1 && queryIndex < semicolonIndex)) {
161
+ if (queryIndex === -1) {
162
+ return { path: url, query: '' }
163
+ }
164
+
165
+ return {
166
+ path: url.slice(0, queryIndex),
167
+ query: url.slice(queryIndex)
168
+ }
169
+ }
170
+
171
+ return {
172
+ path: url.slice(0, semicolonIndex),
173
+ query: `?${url.slice(semicolonIndex + 1)}`
174
+ }
175
+ }
176
+
177
+ function removeDuplicateSlashes (path) {
178
+ return path.replace(/\/{2,}/g, '/')
179
+ }
180
+
106
181
  module.exports = fp(fastifyExpress, {
107
182
  fastify: '5.x',
108
183
  name: '@fastify/express'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastify/express",
3
- "version": "4.0.4",
3
+ "version": "4.0.6",
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",
@@ -63,24 +63,21 @@
63
63
  "@types/express": "^5.0.0",
64
64
  "@types/node": "*",
65
65
  "body-parser": "^1.20.2",
66
- "c8": "^10.1.3",
66
+ "c8": "^11.0.0",
67
67
  "cors": "^2.8.5",
68
68
  "eslint": "^9.17.0",
69
69
  "fastify": "^5.0.0",
70
70
  "helmet": "^8.0.0",
71
- "neostandard": "^0.12.0",
71
+ "neostandard": "^0.13.0",
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
- "express": "^4.18.3",
78
+ "express": "^5.2.1",
79
79
  "fastify-plugin": "^5.0.0"
80
80
  },
81
- "tsd": {
82
- "directory": "test/types"
83
- },
84
81
  "publishConfig": {
85
82
  "access": "public"
86
83
  }
@@ -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()
@@ -221,6 +221,52 @@ test('middlewares with prefix', async t => {
221
221
  })
222
222
  })
223
223
 
224
+ test('should not double-prefix inherited middleware paths in child scopes', async t => {
225
+ t.plan(4)
226
+
227
+ const instance = fastify()
228
+ t.after(() => instance.close())
229
+
230
+ await instance.register(expressPlugin)
231
+
232
+ instance.use('/admin', function (req, res, next) {
233
+ if (req.headers.authorization == null) {
234
+ res.statusCode = 403
235
+ res.end('forbidden')
236
+ return
237
+ }
238
+
239
+ next()
240
+ })
241
+
242
+ instance.get('/admin/root-data', async function () {
243
+ return { data: 'root-secret' }
244
+ })
245
+
246
+ await instance.register(async function (child) {
247
+ child.get('/secret', async function () {
248
+ return { data: 'child-secret' }
249
+ })
250
+ }, { prefix: '/admin' })
251
+
252
+ const address = await instance.listen({ port: 0 })
253
+
254
+ const rootNoAuth = await fetch(address + '/admin/root-data')
255
+ t.assert.deepStrictEqual(rootNoAuth.status, 403)
256
+
257
+ const childNoAuth = await fetch(address + '/admin/secret')
258
+ t.assert.deepStrictEqual(childNoAuth.status, 403)
259
+
260
+ const childWithAuth = await fetch(address + '/admin/secret', {
261
+ headers: {
262
+ authorization: 'Bearer test'
263
+ }
264
+ })
265
+
266
+ t.assert.deepStrictEqual(childWithAuth.status, 200)
267
+ t.assert.deepStrictEqual(await childWithAuth.json(), { data: 'child-secret' })
268
+ })
269
+
224
270
  test('res.end should block middleware execution', async t => {
225
271
  t.plan(4)
226
272
 
@@ -0,0 +1,98 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('node:test')
4
+ const fastify = require('fastify')
5
+
6
+ const expressPlugin = require('../index')
7
+
8
+ test('ignoreDuplicateSlashes does not bypass path-scoped middleware', async t => {
9
+ t.plan(3)
10
+
11
+ const instance = fastify({
12
+ routerOptions: {
13
+ ignoreDuplicateSlashes: true
14
+ }
15
+ })
16
+
17
+ t.after(() => instance.close())
18
+
19
+ await instance.register(expressPlugin)
20
+
21
+ let middlewareCalls = 0
22
+
23
+ instance.use('/admin', function (req, res, next) {
24
+ middlewareCalls++
25
+
26
+ if (req.headers.authorization !== 'Bearer admin-secret-token') {
27
+ res.statusCode = 403
28
+ res.setHeader('content-type', 'application/json')
29
+ res.end(JSON.stringify({ error: 'Forbidden by Express middleware' }))
30
+ return
31
+ }
32
+
33
+ next()
34
+ })
35
+
36
+ instance.get('/admin/dashboard', async () => {
37
+ return { secret: 'classified' }
38
+ })
39
+
40
+ const address = await instance.listen({ port: 0 })
41
+
42
+ const normalRequest = await fetch(address + '/admin/dashboard')
43
+ t.assert.deepStrictEqual(normalRequest.status, 403)
44
+
45
+ const bypassAttempt = await fetch(address + '//admin/dashboard')
46
+ t.assert.deepStrictEqual(bypassAttempt.status, 403)
47
+
48
+ t.assert.deepStrictEqual(middlewareCalls, 2)
49
+ })
50
+
51
+ test('useSemicolonDelimiter does not bypass path-scoped middleware', async t => {
52
+ t.plan(5)
53
+
54
+ const instance = fastify({
55
+ routerOptions: {
56
+ useSemicolonDelimiter: true
57
+ }
58
+ })
59
+
60
+ t.after(() => instance.close())
61
+
62
+ await instance.register(expressPlugin)
63
+
64
+ let middlewareCalls = 0
65
+
66
+ instance.use('/admin', function (req, res, next) {
67
+ middlewareCalls++
68
+
69
+ if (req.headers.authorization !== 'Bearer admin-secret-token') {
70
+ res.statusCode = 403
71
+ res.setHeader('content-type', 'application/json')
72
+ res.end(JSON.stringify({ error: 'Forbidden by Express middleware' }))
73
+ return
74
+ }
75
+
76
+ next()
77
+ })
78
+
79
+ instance.get('/admin', async () => {
80
+ return { secret: 'classified' }
81
+ })
82
+
83
+ const address = await instance.listen({ port: 0 })
84
+
85
+ const normalRequest = await fetch(address + '/admin')
86
+ t.assert.deepStrictEqual(normalRequest.status, 403)
87
+
88
+ const withQueryString = await fetch(address + '/admin?foo=bar')
89
+ t.assert.deepStrictEqual(withQueryString.status, 403)
90
+
91
+ const withSemicolonInQuery = await fetch(address + '/admin?foo=bar;baz=1')
92
+ t.assert.deepStrictEqual(withSemicolonInQuery.status, 403)
93
+
94
+ const bypassAttempt = await fetch(address + '/admin;bypass')
95
+ t.assert.deepStrictEqual(bypassAttempt.status, 403)
96
+
97
+ t.assert.deepStrictEqual(middlewareCalls, 4)
98
+ })
@@ -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
 
package/.github/stale.yml DELETED
@@ -1,21 +0,0 @@
1
- # Number of days of inactivity before an issue becomes stale
2
- daysUntilStale: 15
3
- # Number of days of inactivity before a stale issue is closed
4
- daysUntilClose: 7
5
- # Issues with these labels will never be considered stale
6
- exemptLabels:
7
- - "discussion"
8
- - "feature request"
9
- - "bug"
10
- - "help wanted"
11
- - "plugin suggestion"
12
- - "good first issue"
13
- # Label to use when marking an issue as stale
14
- staleLabel: stale
15
- # Comment to post when marking an issue as stale. Set to `false` to disable
16
- markComment: >
17
- This issue has been automatically marked as stale because it has not had
18
- recent activity. It will be closed if no further activity occurs. Thank you
19
- for your contributions.
20
- # Comment to post when closing a stale issue. Set to `false` to disable
21
- closeComment: false