fastify 5.11.2 → 5.12.0
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 +7 -7
- package/SPONSORS.md +1 -0
- package/docs/Guides/Serverless.md +34 -2
- package/docs/Reference/Encapsulation.md +31 -2
- package/docs/Reference/Errors.md +76 -3
- package/docs/Reference/Reply.md +14 -0
- package/docs/Reference/Request.md +18 -6
- package/docs/Reference/Routes.md +13 -0
- package/fastify.js +1 -1
- package/lib/content-type-parser.js +4 -0
- package/lib/content-type.js +4 -1
- package/lib/decorate.js +1 -1
- package/lib/log-controller.js +1 -1
- package/lib/reply.js +18 -4
- package/package.json +2 -3
- package/test/content-parser.test.js +48 -18
- package/test/content-type.test.js +4 -0
- package/test/decorator-instance-properties.test.js +49 -0
- package/test/helper.js +73 -1
- package/test/hooks-async.test.js +1 -2
- package/test/hooks.test.js +1 -2
- package/test/internals/reply.test.js +76 -1
- package/test/listen.1.test.js +17 -52
- package/test/listen.5.test.js +6 -9
- package/test/logger/instantiation.test.js +1 -1
- package/test/logger/logging.test.js +1 -1
- package/test/logger/request.test.js +1 -1
- package/test/logger/response.test.js +1 -1
- package/test/plugin.4.test.js +5 -4
- package/test/reply-media-type.test.js +131 -0
- package/test/reply-trailers.test.js +92 -4
- package/test/route-prefix.test.js +1 -1
- package/test/route.6.test.js +4 -11
- package/test/schema-feature.test.js +36 -65
- package/test/schema-serialization.test.js +1 -1
- package/test/schema-special-usage.test.js +1 -1
- package/test/schema-validation.test.js +1 -1
- package/test/stream.2.test.js +1 -1
- package/types/logger.d.ts +1 -1
- package/.pi/bash-confirm-whitelist.json +0 -180
- package/test/toolkit.js +0 -63
package/README.md
CHANGED
|
@@ -73,7 +73,7 @@ mkdir my-app
|
|
|
73
73
|
cd my-app
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
Generate a
|
|
76
|
+
Generate a Fastify project with `npm init`:
|
|
77
77
|
|
|
78
78
|
```sh
|
|
79
79
|
npm init fastify
|
|
@@ -121,7 +121,7 @@ import Fastify from 'fastify'
|
|
|
121
121
|
const fastify = Fastify({
|
|
122
122
|
logger: true
|
|
123
123
|
})
|
|
124
|
-
//
|
|
124
|
+
// CommonJS
|
|
125
125
|
const fastify = require('fastify')({
|
|
126
126
|
logger: true
|
|
127
127
|
})
|
|
@@ -147,7 +147,7 @@ import Fastify from 'fastify'
|
|
|
147
147
|
const fastify = Fastify({
|
|
148
148
|
logger: true
|
|
149
149
|
})
|
|
150
|
-
//
|
|
150
|
+
// CommonJS
|
|
151
151
|
const fastify = require('fastify')({
|
|
152
152
|
logger: true
|
|
153
153
|
})
|
|
@@ -181,7 +181,7 @@ If you learn best by reading code, explore the official [demo](https://github.co
|
|
|
181
181
|
### Core features
|
|
182
182
|
|
|
183
183
|
- **Highly performant:** as far as we know, Fastify is one of the fastest web
|
|
184
|
-
frameworks in town, depending on the code complexity we can serve
|
|
184
|
+
frameworks in town, depending on the code complexity we can serve more than 76
|
|
185
185
|
thousand requests per second.
|
|
186
186
|
- **Extensible:** Fastify is fully extensible via its hooks, plugins, and
|
|
187
187
|
decorators.
|
|
@@ -189,7 +189,7 @@ If you learn best by reading code, explore the official [demo](https://github.co
|
|
|
189
189
|
Schema](https://json-schema.org/) to validate your routes and serialize your
|
|
190
190
|
outputs. Internally Fastify compiles the schema in a highly performant
|
|
191
191
|
function.
|
|
192
|
-
- **Logging:** logs are extremely important but are costly; we chose the best
|
|
192
|
+
- **Logging:** logs are extremely important, but are costly; we chose the best
|
|
193
193
|
logger to almost remove this cost, [Pino](https://github.com/pinojs/pino)!
|
|
194
194
|
- **Developer friendly:** the framework is built to be very expressive and help
|
|
195
195
|
developers in their daily use without sacrificing performance and
|
|
@@ -212,8 +212,8 @@ second average
|
|
|
212
212
|
| - | | | |
|
|
213
213
|
| `http.Server` | 16.14.2 | ✗ | 74,513 |
|
|
214
214
|
|
|
215
|
-
These benchmarks taken using https://github.com/fastify/benchmarks. This is
|
|
216
|
-
synthetic "hello world" benchmark that aims to evaluate the framework overhead.
|
|
215
|
+
These benchmarks were taken using https://github.com/fastify/benchmarks. This is
|
|
216
|
+
a synthetic "hello world" benchmark that aims to evaluate the framework overhead.
|
|
217
217
|
The overhead that each framework has on your application depends on your
|
|
218
218
|
application. You should __always__ benchmark if performance matters to you.
|
|
219
219
|
|
package/SPONSORS.md
CHANGED
|
@@ -19,6 +19,7 @@ or [GitHub Sponsors](https://github.com/sponsors/fastify)!
|
|
|
19
19
|
- [atagon GmbH](https://github.com/atagon-GmbH)
|
|
20
20
|
- [Photon](https://github.com/photon-hq)
|
|
21
21
|
- [N-iX](https://www.n-ix.com/)
|
|
22
|
+
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=fastify)
|
|
22
23
|
|
|
23
24
|
## Tier 2
|
|
24
25
|
|
|
@@ -256,9 +256,41 @@ curl -X POST https://$GOOGLE_REGION-$GOOGLE_PROJECT.cloudfunctions.net/me \
|
|
|
256
256
|
{"message":"Hello Fastify!"}
|
|
257
257
|
```
|
|
258
258
|
|
|
259
|
+
#### Per-route logging
|
|
260
|
+
|
|
261
|
+
Google Cloud Functions exposes one entry point for your Fastify instance, so
|
|
262
|
+
the dashboard may show all HTTP traffic under that function. Instead of
|
|
263
|
+
deploying one function per endpoint, keep the single Fastify instance and emit
|
|
264
|
+
a structured log line after each request with the matched route:
|
|
265
|
+
|
|
266
|
+
```js
|
|
267
|
+
fastify.addHook('onResponse', async (request, reply) => {
|
|
268
|
+
request.log.info({
|
|
269
|
+
route: request.routeOptions.url,
|
|
270
|
+
method: request.method,
|
|
271
|
+
statusCode: reply.statusCode,
|
|
272
|
+
responseTime: reply.elapsedTime
|
|
273
|
+
}, 'request completed')
|
|
274
|
+
})
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`request.routeOptions.url` is the route pattern, so `/users/123` and
|
|
278
|
+
`/users/456` are grouped under `/users/:id`. With Fastify's logger enabled, the
|
|
279
|
+
fields are emitted as structured log fields, as described in the [Cloud
|
|
280
|
+
Logging structured logging documentation](https://cloud.google.com/logging/docs/structured-logging)
|
|
281
|
+
and the [Cloud Functions logging guide](https://cloud.google.com/functions/docs/monitoring/logging).
|
|
282
|
+
In Cloud Logging, create a [log-based
|
|
283
|
+
metric](https://cloud.google.com/logging/docs/logs-based-metrics) or filter on
|
|
284
|
+
`jsonPayload.route` to get per-route request counts, latency, and error rates.
|
|
285
|
+
|
|
286
|
+
The same hook works when deploying through Firebase Functions with `onRequest`.
|
|
287
|
+
|
|
259
288
|
### References
|
|
260
289
|
- [Google Cloud Functions - Node.js Quickstart
|
|
261
|
-
](https://
|
|
290
|
+
](https://cloud.google.com/run/docs/quickstarts/functions/deploy-functions-gcloud)
|
|
291
|
+
- [Cloud Logging - Structured Logging](https://cloud.google.com/logging/docs/structured-logging)
|
|
292
|
+
- [Cloud Logging - Log-based Metrics](https://cloud.google.com/logging/docs/logs-based-metrics)
|
|
293
|
+
- [Cloud Functions - Logging](https://cloud.google.com/functions/docs/monitoring/logging)
|
|
262
294
|
|
|
263
295
|
## Google Firebase Functions
|
|
264
296
|
|
|
@@ -594,4 +626,4 @@ https://vercel.com/templates/backend/fastify-on-vercel).
|
|
|
594
626
|
[Fluid compute](https://vercel.com/docs/fluid-compute) currently
|
|
595
627
|
requires an explicit opt-in. Learn more about enabling Fluid compute
|
|
596
628
|
[here](
|
|
597
|
-
https://vercel.com/docs/fluid-compute#enabling-fluid-compute).
|
|
629
|
+
https://vercel.com/docs/fluid-compute#enabling-fluid-compute).
|
|
@@ -140,7 +140,7 @@ update the code as follows:
|
|
|
140
140
|
'use strict'
|
|
141
141
|
|
|
142
142
|
const fastify = require('fastify')()
|
|
143
|
-
const
|
|
143
|
+
const fp = require('fastify-plugin')
|
|
144
144
|
|
|
145
145
|
fastify.decorateRequest('answer', 42)
|
|
146
146
|
|
|
@@ -161,7 +161,7 @@ fastify.register(async function publicContext (childServer) {
|
|
|
161
161
|
}
|
|
162
162
|
})
|
|
163
163
|
|
|
164
|
-
childServer.register(
|
|
164
|
+
childServer.register(fp(grandchildContext))
|
|
165
165
|
|
|
166
166
|
async function grandchildContext (grandchildServer) {
|
|
167
167
|
grandchildServer.decorateRequest('bar', 'bar')
|
|
@@ -192,4 +192,33 @@ curl http://127.0.0.1:8000/three
|
|
|
192
192
|
# {"answer":42,"foo":"foo","bar":"bar"}
|
|
193
193
|
```
|
|
194
194
|
|
|
195
|
+
`fastify-plugin` breaks encapsulation only for the plugin it wraps. Plugins
|
|
196
|
+
registered inside it without `fastify-plugin` still create new encapsulated
|
|
197
|
+
contexts:
|
|
198
|
+
|
|
199
|
+
```js
|
|
200
|
+
'use strict'
|
|
201
|
+
|
|
202
|
+
const fastify = require('fastify')()
|
|
203
|
+
const fp = require('fastify-plugin')
|
|
204
|
+
|
|
205
|
+
fastify.register(fp(async function sharedContext (childServer) {
|
|
206
|
+
childServer.decorate('foo', 'foo')
|
|
207
|
+
|
|
208
|
+
childServer.register(async function encapsulatedContext (grandchildServer) {
|
|
209
|
+
grandchildServer.decorate('bar', 'bar')
|
|
210
|
+
})
|
|
211
|
+
}))
|
|
212
|
+
|
|
213
|
+
await fastify.ready()
|
|
214
|
+
|
|
215
|
+
console.log(fastify.foo) // 'foo'
|
|
216
|
+
console.log(fastify.bar) // undefined
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
The `foo` decorator is available in the root context because it is added
|
|
220
|
+
directly by the plugin wrapped with `fastify-plugin`. The nested `register`
|
|
221
|
+
call still creates a grandchild context, so the `bar` decorator remains
|
|
222
|
+
available only in that context and its children.
|
|
223
|
+
|
|
195
224
|
[fastify-plugin]: https://github.com/fastify/fastify-plugin
|
package/docs/Reference/Errors.md
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
- [Errors In Fastify](#errors-in-fastify)
|
|
12
12
|
- [Errors In Input Data](#errors-in-input-data)
|
|
13
13
|
- [Catching Uncaught Errors In Fastify](#catching-uncaught-errors-in-fastify)
|
|
14
|
+
- [What The Default Error Handler Sends](#what-the-default-error-handler-sends)
|
|
14
15
|
- [Errors In Fastify Lifecycle Hooks And A Custom Error Handler](#errors-in-fastify-lifecycle-hooks-and-a-custom-error-handler)
|
|
15
16
|
- [Fastify Error Codes](#fastify-error-codes)
|
|
16
17
|
- [FST_ERR_NOT_FOUND](#fst_err_not_found)
|
|
@@ -142,10 +143,82 @@ performance. This includes:
|
|
|
142
143
|
})`
|
|
143
144
|
|
|
144
145
|
In both cases, the error will be caught safely and routed to Fastify's default
|
|
145
|
-
error handler, resulting in a
|
|
146
|
+
error handler, resulting in a `500 Internal Server Error` response.
|
|
146
147
|
|
|
147
|
-
|
|
148
|
-
|
|
148
|
+
#### What The Default Error Handler Sends
|
|
149
|
+
The default error handler serializes the error into a JSON body with the
|
|
150
|
+
`statusCode`, `error`, and `message` properties, plus `code` when the error
|
|
151
|
+
carries one:
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
app.get('/', async () => { throw new Error('kaboom') })
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
```json
|
|
158
|
+
{
|
|
159
|
+
"statusCode": 500,
|
|
160
|
+
"error": "Internal Server Error",
|
|
161
|
+
"message": "kaboom"
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
The `error` property is the generic HTTP status text, but **`message` is
|
|
166
|
+
`error.message` verbatim**. This applies to every status code, including `500`.
|
|
167
|
+
Fastify's built-in error serializer emits only these four properties, so the
|
|
168
|
+
stack trace is not part of the default payload — but a route-level response
|
|
169
|
+
schema replaces that serializer, and one that declares a `stack` property will
|
|
170
|
+
serialize it.
|
|
171
|
+
|
|
172
|
+
> Security:
|
|
173
|
+
> Because `message` and `code` are forwarded as-is, errors thrown by libraries
|
|
174
|
+
> deeper in your application are exposed to the client. A database driver
|
|
175
|
+
> error, for example, can leak schema details and query text:
|
|
176
|
+
>
|
|
177
|
+
> ```json
|
|
178
|
+
> {
|
|
179
|
+
> "statusCode": 500,
|
|
180
|
+
> "code": "ER_BAD_FIELD_ERROR",
|
|
181
|
+
> "error": "Internal Server Error",
|
|
182
|
+
> "message": "Unknown column 'username' in 'field list'"
|
|
183
|
+
> }
|
|
184
|
+
> ```
|
|
185
|
+
>
|
|
186
|
+
> Fastify does not distinguish between development and production here. If
|
|
187
|
+
> unexpected errors must not reach the client, handle this explicitly.
|
|
188
|
+
|
|
189
|
+
Register a [`setErrorHandler`](./Server.md#seterrorhandler) to replace the
|
|
190
|
+
message for errors you did not raise deliberately, while letting the ones you
|
|
191
|
+
did pass through:
|
|
192
|
+
|
|
193
|
+
```js
|
|
194
|
+
app.setErrorHandler(function (error, request, reply) {
|
|
195
|
+
// Errors with a statusCode below 500 were raised deliberately by this
|
|
196
|
+
// application, as were validation errors. A status code below 500 is not on
|
|
197
|
+
// its own a guarantee that the message is safe to expose — narrow this
|
|
198
|
+
// condition if any of yours are not.
|
|
199
|
+
if (error.validation || (error.statusCode && error.statusCode < 500)) {
|
|
200
|
+
return reply.send(error)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Anything else is unexpected: log it, but do not describe it to the client.
|
|
204
|
+
this.log.error({ err: error }, 'unhandled error')
|
|
205
|
+
reply.status(500).send({
|
|
206
|
+
statusCode: 500,
|
|
207
|
+
error: 'Internal Server Error',
|
|
208
|
+
message: 'Internal Server Error'
|
|
209
|
+
})
|
|
210
|
+
})
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The handler above is registered on the root instance, so it applies to every
|
|
214
|
+
route. Error handlers are encapsulated; for how they resolve across plugin
|
|
215
|
+
contexts, see
|
|
216
|
+
[the next section](#errors-in-fastify-lifecycle-hooks-and-a-custom-error-handler).
|
|
217
|
+
|
|
218
|
+
Note that a route-level response schema is still applied to whatever the error
|
|
219
|
+
handler sends, and will reshape the payload accordingly — including properties
|
|
220
|
+
the built-in error serializer would have omitted, such as `stack`. See
|
|
221
|
+
[Serialization](./Validation-and-Serialization.md#serialization).
|
|
149
222
|
|
|
150
223
|
### Errors In Fastify Lifecycle Hooks And A Custom Error Handler
|
|
151
224
|
|
package/docs/Reference/Reply.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
- [.code(statusCode)](#codestatuscode)
|
|
7
7
|
- [.elapsedTime](#elapsedtime)
|
|
8
8
|
- [.statusCode](#statuscode)
|
|
9
|
+
- [.mediaType](#mediatype)
|
|
9
10
|
- [.server](#server)
|
|
10
11
|
- [.header(key, value)](#headerkey-value)
|
|
11
12
|
- [.headers(object)](#headersobject)
|
|
@@ -51,6 +52,7 @@ object that exposes the following functions and properties:
|
|
|
51
52
|
- `.statusCode` - Read and set the HTTP status code.
|
|
52
53
|
- `.elapsedTime` - Returns the amount of time passed
|
|
53
54
|
since the request was received by Fastify.
|
|
55
|
+
- `.mediaType` - The media type extracted from `Content-Type` header.
|
|
54
56
|
- `.server` - A reference to the fastify instance object.
|
|
55
57
|
- `.header(name, value)` - Sets a response header.
|
|
56
58
|
- `.headers(object)` - Sets all the keys of the object as response headers.
|
|
@@ -129,6 +131,18 @@ if (reply.statusCode >= 299) {
|
|
|
129
131
|
reply.statusCode = 500
|
|
130
132
|
}
|
|
131
133
|
```
|
|
134
|
+
### .mediaType
|
|
135
|
+
<a id="mediatype"></a>
|
|
136
|
+
|
|
137
|
+
Returns the media type extracted from `Content-Type` header. When `Content-Type`
|
|
138
|
+
header is missing, it will return `undefined`.
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
if (reply.mediaType === 'image/gif') {
|
|
142
|
+
const versionBuffer = new Uint8Array(reply.payload, 3, 3)
|
|
143
|
+
reply.header('x-gif-version', new TextDecoder().decode(versionBuffer))
|
|
144
|
+
}
|
|
145
|
+
```
|
|
132
146
|
|
|
133
147
|
### .server
|
|
134
148
|
<a id="server"></a>
|
|
@@ -9,7 +9,11 @@ Request is a core Fastify object containing the following fields:
|
|
|
9
9
|
- `body` - The request payload, see [Content-Type Parser](./ContentTypeParser.md)
|
|
10
10
|
for details on what request payloads Fastify natively parses and how to support
|
|
11
11
|
other content types.
|
|
12
|
-
- `params` - The params matching the URL.
|
|
12
|
+
- `params` - The params matching the URL. Values are percent-decoded
|
|
13
|
+
(for example `%20` becomes a space, and `%2f` becomes `/`). Decoded
|
|
14
|
+
values may contain `.`, `..`, `/`, or other characters; treat them as
|
|
15
|
+
untrusted input. See the security note below and
|
|
16
|
+
[Routes - Url building](./Routes.md#url-building).
|
|
13
17
|
- [`headers`](#headers) - The headers getter and setter.
|
|
14
18
|
- `raw` - The incoming HTTP request from Node core.
|
|
15
19
|
- `server` - The Fastify server instance, scoped to the current
|
|
@@ -35,13 +39,21 @@ Request is a core Fastify object containing the following fields:
|
|
|
35
39
|
[`trustProxy`](./Server.md#factory-trust-proxy) is enabled).
|
|
36
40
|
|
|
37
41
|
> ⚠️ Security:
|
|
42
|
+
> `request.params`, `request.query`, `request.headers`, and `request.body`
|
|
43
|
+
> are untrusted network input. Route parameter values are percent-decoded
|
|
44
|
+
> before your handler runs, so a segment like `..%2ffile` becomes `../file`
|
|
45
|
+
> in `request.params`. Do not use parameter values as filesystem paths,
|
|
46
|
+
> template names, or redirect targets without validating or containing
|
|
47
|
+
> them. Prefer [`@fastify/static`](https://github.com/fastify/fastify-static)
|
|
48
|
+
> (or `reply.sendFile`) when serving files from a root directory.
|
|
49
|
+
>
|
|
38
50
|
> `request.ip`, `request.ips`, `request.host`, `request.hostname`,
|
|
39
51
|
> `request.port`, and `request.protocol` come from request metadata
|
|
40
|
-
> (socket and/or forwarding headers) and should be treated as
|
|
41
|
-
> Fastify does not perform security validation for
|
|
42
|
-
> If these values are used in security-sensitive decisions,
|
|
43
|
-
> be validated explicitly (for example: trusted proxy
|
|
44
|
-
> allow-lists, strict parsing, and normalization).
|
|
52
|
+
> (socket and/or forwarding headers) and should also be treated as
|
|
53
|
+
> untrusted input. Fastify does not perform security validation for
|
|
54
|
+
> business logic. If these values are used in security-sensitive decisions,
|
|
55
|
+
> they must be validated explicitly (for example: trusted proxy
|
|
56
|
+
> configuration, allow-lists, strict parsing, and normalization).
|
|
45
57
|
|
|
46
58
|
- `method` - The method of the incoming request.
|
|
47
59
|
- `url` - The URL of the incoming request.
|
package/docs/Reference/Routes.md
CHANGED
|
@@ -328,6 +328,19 @@ Prefer a single parameter approach, especially on routes that are on the hot
|
|
|
328
328
|
path of your application. For more details, see
|
|
329
329
|
[find-my-way](https://github.com/delvedor/find-my-way).
|
|
330
330
|
|
|
331
|
+
> ⚠️ Security:
|
|
332
|
+
> Fastify (via find-my-way) percent-decodes route parameters and wildcards
|
|
333
|
+
> before they reach your handler. Encoded separators in a segment are
|
|
334
|
+
> decoded in the parameter value: for a route `/download/:file`, a request
|
|
335
|
+
> to `/download/..%2fsecret.txt` yields
|
|
336
|
+
> `request.params.file === '../secret.txt'`. Parameters are untrusted
|
|
337
|
+
> input. Do not pass them to `path.join`, `fs` APIs, template engines, or
|
|
338
|
+
> redirects without validation or path containment. To serve files from a
|
|
339
|
+
> directory root, use
|
|
340
|
+
> [`@fastify/static`](https://github.com/fastify/fastify-static) instead of
|
|
341
|
+
> joining `request.params` into a filesystem path yourself. See also
|
|
342
|
+
> [Request](./Request.md).
|
|
343
|
+
|
|
331
344
|
To include a colon in a path without declaring a parameter, use a double colon.
|
|
332
345
|
For example:
|
|
333
346
|
```js
|
package/fastify.js
CHANGED
|
@@ -145,6 +145,10 @@ ContentTypeParser.prototype.getParser = function (contentType) {
|
|
|
145
145
|
|
|
146
146
|
for (let j = 0; j !== this.parserRegExpList.length; ++j) {
|
|
147
147
|
const parserRegExp = this.parserRegExpList[j]
|
|
148
|
+
// A parser registered with a `g`/`y` flagged RegExp keeps a mutable
|
|
149
|
+
// lastIndex between calls, so a plain `.test()` would skip part of the
|
|
150
|
+
// next content type and match inconsistently. Reset it before testing.
|
|
151
|
+
parserRegExp.lastIndex = 0
|
|
148
152
|
if (parserRegExp.test(ct)) {
|
|
149
153
|
parser = this.customParsers.get(parserRegExp.toString())
|
|
150
154
|
this.cache.set(ct, parser)
|
package/lib/content-type.js
CHANGED
|
@@ -183,7 +183,10 @@ class ContentType {
|
|
|
183
183
|
|
|
184
184
|
get isValid () { return this.#valid }
|
|
185
185
|
|
|
186
|
-
get mediaType () {
|
|
186
|
+
get mediaType () {
|
|
187
|
+
if (this.#valid === false) return undefined
|
|
188
|
+
return `${this.#type}/${this.#subtype}`
|
|
189
|
+
}
|
|
187
190
|
|
|
188
191
|
get type () { return this.#type }
|
|
189
192
|
|
package/lib/decorate.js
CHANGED
|
@@ -121,7 +121,7 @@ function checkDependencies (instance, name, deps) {
|
|
|
121
121
|
}
|
|
122
122
|
|
|
123
123
|
for (let i = 0; i !== deps.length; ++i) {
|
|
124
|
-
if (!checkExistence(instance, deps[i])) {
|
|
124
|
+
if (!checkExistence(instance, deps[i]) && !hasInstanceProperty(instance, deps[i])) {
|
|
125
125
|
throw new FST_ERR_DEC_MISSING_DEPENDENCY(deps[i])
|
|
126
126
|
}
|
|
127
127
|
}
|
package/lib/log-controller.js
CHANGED
|
@@ -54,7 +54,7 @@ class LogController {
|
|
|
54
54
|
* Logs the outcome of a completed request.
|
|
55
55
|
* Uses `error` level when an error is present, `info` otherwise.
|
|
56
56
|
*
|
|
57
|
-
* @param {Error | null} error Error that occurred during the response, if any.
|
|
57
|
+
* @param {Error | null | undefined} error Error that occurred during the response, if any.
|
|
58
58
|
* @param {object} request Fastify request object.
|
|
59
59
|
* @param {object} reply Fastify reply object.
|
|
60
60
|
* @param {object} [metadata] Extra contextual data (unused).
|
package/lib/reply.js
CHANGED
|
@@ -93,6 +93,12 @@ Object.defineProperties(Reply.prototype, {
|
|
|
93
93
|
return (this[kReplyEndTime] || now()) - this[kReplyStartTime]
|
|
94
94
|
}
|
|
95
95
|
},
|
|
96
|
+
mediaType: {
|
|
97
|
+
get () {
|
|
98
|
+
const contentTypeHeader = this[kReplyHeaders]['content-type']
|
|
99
|
+
return ContentType.from(contentTypeHeader).mediaType
|
|
100
|
+
}
|
|
101
|
+
},
|
|
96
102
|
server: {
|
|
97
103
|
get () {
|
|
98
104
|
return this.request[kRouteContext].server
|
|
@@ -254,9 +260,13 @@ Reply.prototype.hasHeader = function (key) {
|
|
|
254
260
|
}
|
|
255
261
|
|
|
256
262
|
Reply.prototype.removeHeader = function (key) {
|
|
263
|
+
key = key.toLowerCase()
|
|
257
264
|
// Node.js does not like headers with keys set to undefined,
|
|
258
265
|
// so we have to delete the key.
|
|
259
|
-
delete this[kReplyHeaders][key
|
|
266
|
+
delete this[kReplyHeaders][key]
|
|
267
|
+
if (!this.raw.headersSent) {
|
|
268
|
+
this.raw.removeHeader(key)
|
|
269
|
+
}
|
|
260
270
|
return this
|
|
261
271
|
}
|
|
262
272
|
|
|
@@ -595,9 +605,13 @@ function onSendEnd (reply, payload) {
|
|
|
595
605
|
header += ' '
|
|
596
606
|
header += trailerName
|
|
597
607
|
}
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
608
|
+
if (header !== '') {
|
|
609
|
+
// it must be chunked for trailer to work
|
|
610
|
+
reply.header('Transfer-Encoding', 'chunked')
|
|
611
|
+
reply.header('Trailer', header.trim())
|
|
612
|
+
} else {
|
|
613
|
+
reply[kReplyTrailers] = null
|
|
614
|
+
}
|
|
601
615
|
}
|
|
602
616
|
|
|
603
617
|
// since Response contain status code, headers and body,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fastify",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.12.0",
|
|
4
4
|
"description": "Fast and low overhead web framework, for Node.js",
|
|
5
5
|
"main": "fastify.js",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -167,7 +167,6 @@
|
|
|
167
167
|
],
|
|
168
168
|
"devDependencies": {
|
|
169
169
|
"@jsumners/line-reporter": "^1.0.1",
|
|
170
|
-
"@sinonjs/fake-timers": "^11.2.2",
|
|
171
170
|
"@stylistic/eslint-plugin": "^5.1.0",
|
|
172
171
|
"@stylistic/eslint-plugin-js": "^4.1.0",
|
|
173
172
|
"@types/node": "^26.0.1",
|
|
@@ -214,7 +213,7 @@
|
|
|
214
213
|
"find-my-way": "^9.6.0",
|
|
215
214
|
"light-my-request": "^6.0.0",
|
|
216
215
|
"pino": "^9.14.0 || ^10.1.0",
|
|
217
|
-
"process-warning": "^5.
|
|
216
|
+
"process-warning": "^5.1.0",
|
|
218
217
|
"rfdc": "^1.3.1",
|
|
219
218
|
"secure-json-parse": "^4.0.0",
|
|
220
219
|
"semver": "^7.6.0",
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
'use strict'
|
|
2
2
|
|
|
3
3
|
const { test } = require('node:test')
|
|
4
|
+
const { spyWarning } = require('process-warning')
|
|
4
5
|
const Fastify = require('..')
|
|
5
6
|
const keys = require('../lib/symbols')
|
|
6
7
|
const { FST_ERR_CTP_ALREADY_PRESENT, FST_ERR_CTP_INVALID_TYPE, FST_ERR_CTP_INVALID_MEDIA_TYPE } = require('../lib/errors')
|
|
8
|
+
const { FSTSEC001 } = require('../lib/warnings')
|
|
7
9
|
|
|
8
10
|
const first = function (req, payload, done) {}
|
|
9
11
|
const second = function (req, payload, done) {}
|
|
@@ -488,41 +490,37 @@ test('Safeguard against content-type spoofing - string', async t => {
|
|
|
488
490
|
})
|
|
489
491
|
|
|
490
492
|
test('Warning against improper content-type - regexp', async t => {
|
|
491
|
-
await t.test('improper regex - text plain', (t
|
|
493
|
+
await t.test('improper regex - text plain', async (t) => {
|
|
492
494
|
t.plan(2)
|
|
493
|
-
const
|
|
495
|
+
const spyData = spyWarning(FSTSEC001)
|
|
496
|
+
t.after(spyData.restore)
|
|
494
497
|
|
|
495
|
-
|
|
496
|
-
function onWarning (warning) {
|
|
497
|
-
t.assert.strictEqual(warning.name, 'FastifySecurity')
|
|
498
|
-
t.assert.strictEqual(warning.code, 'FSTSEC001')
|
|
499
|
-
done()
|
|
500
|
-
}
|
|
501
|
-
t.after(() => process.removeListener('warning', onWarning))
|
|
498
|
+
const fastify = Fastify()
|
|
502
499
|
|
|
503
500
|
fastify.removeAllContentTypeParsers()
|
|
504
501
|
fastify.addContentTypeParser(/text\/plain/, function (request, body, done) {
|
|
505
502
|
done(null, body)
|
|
506
503
|
})
|
|
504
|
+
|
|
505
|
+
await fastify.ready()
|
|
506
|
+
t.assert.deepStrictEqual(spyData.calls, [{ arguments: ['text\\/plain'], result: true }])
|
|
507
|
+
t.assert.strictEqual(spyData.callCount(), 1)
|
|
507
508
|
})
|
|
508
509
|
|
|
509
|
-
await t.test('improper regex - application json', (t
|
|
510
|
+
await t.test('improper regex - application json', async (t) => {
|
|
510
511
|
t.plan(2)
|
|
512
|
+
const spyData = spyWarning(FSTSEC001)
|
|
513
|
+
t.after(spyData.restore)
|
|
511
514
|
const fastify = Fastify()
|
|
512
515
|
|
|
513
|
-
process.on('warning', onWarning)
|
|
514
|
-
function onWarning (warning) {
|
|
515
|
-
t.assert.strictEqual(warning.name, 'FastifySecurity')
|
|
516
|
-
t.assert.strictEqual(warning.code, 'FSTSEC001')
|
|
517
|
-
done()
|
|
518
|
-
}
|
|
519
|
-
t.after(() => process.removeListener('warning', onWarning))
|
|
520
|
-
|
|
521
516
|
fastify.removeAllContentTypeParsers()
|
|
522
517
|
|
|
523
518
|
fastify.addContentTypeParser(/application\/json/, function (request, body, done) {
|
|
524
519
|
done(null, body)
|
|
525
520
|
})
|
|
521
|
+
|
|
522
|
+
t.assert.deepStrictEqual(spyData.calls, [{ arguments: ['application\\/json'], result: true }])
|
|
523
|
+
t.assert.deepEqual(spyData.callCount(), 1)
|
|
526
524
|
})
|
|
527
525
|
})
|
|
528
526
|
|
|
@@ -578,6 +576,38 @@ test('content-type match parameters - regexp', async t => {
|
|
|
578
576
|
})
|
|
579
577
|
})
|
|
580
578
|
|
|
579
|
+
test('content-type match - RegExp with global flag', async t => {
|
|
580
|
+
t.plan(4)
|
|
581
|
+
|
|
582
|
+
const fastify = Fastify()
|
|
583
|
+
fastify.addContentTypeParser(/^application\/.+\+xml$/g, { parseAs: 'string' }, function (request, body, done) {
|
|
584
|
+
done(null, body)
|
|
585
|
+
})
|
|
586
|
+
|
|
587
|
+
fastify.post('/', async (request) => request.body)
|
|
588
|
+
|
|
589
|
+
// Two distinct content types that both match the parser. A RegExp with the
|
|
590
|
+
// `g` flag keeps a mutable lastIndex between test() calls, so the second
|
|
591
|
+
// content type must still match rather than fall through to 415.
|
|
592
|
+
const first = await fastify.inject({
|
|
593
|
+
method: 'POST',
|
|
594
|
+
path: '/',
|
|
595
|
+
headers: { 'content-type': 'application/vnd.a+xml' },
|
|
596
|
+
body: '<a/>'
|
|
597
|
+
})
|
|
598
|
+
const second = await fastify.inject({
|
|
599
|
+
method: 'POST',
|
|
600
|
+
path: '/',
|
|
601
|
+
headers: { 'content-type': 'application/vnd.b+xml' },
|
|
602
|
+
body: '<b/>'
|
|
603
|
+
})
|
|
604
|
+
|
|
605
|
+
t.assert.strictEqual(first.statusCode, 200)
|
|
606
|
+
t.assert.strictEqual(first.payload, '<a/>')
|
|
607
|
+
t.assert.strictEqual(second.statusCode, 200)
|
|
608
|
+
t.assert.strictEqual(second.payload, '<b/>')
|
|
609
|
+
})
|
|
610
|
+
|
|
581
611
|
test('content-type fail when parameters not match - string 1', async t => {
|
|
582
612
|
t.plan(1)
|
|
583
613
|
|
|
@@ -46,18 +46,22 @@ describe('ContentType class', () => {
|
|
|
46
46
|
test('returns empty instance for empty value', (t) => {
|
|
47
47
|
let found = new ContentType('')
|
|
48
48
|
t.assert.equal(found.isEmpty, true)
|
|
49
|
+
t.assert.equal(found.mediaType, undefined)
|
|
49
50
|
|
|
50
51
|
found = new ContentType('undefined')
|
|
51
52
|
t.assert.equal(found.isEmpty, true)
|
|
53
|
+
t.assert.equal(found.mediaType, undefined)
|
|
52
54
|
|
|
53
55
|
found = new ContentType()
|
|
54
56
|
t.assert.equal(found.isEmpty, true)
|
|
57
|
+
t.assert.equal(found.mediaType, undefined)
|
|
55
58
|
})
|
|
56
59
|
|
|
57
60
|
test('indicates media type is not correct format', (t) => {
|
|
58
61
|
let found = new ContentType('foo')
|
|
59
62
|
t.assert.equal(found.isEmpty, true)
|
|
60
63
|
t.assert.equal(found.isValid, false)
|
|
64
|
+
t.assert.equal(found.mediaType, undefined)
|
|
61
65
|
|
|
62
66
|
found = new ContentType('foo /bar')
|
|
63
67
|
t.assert.equal(found.isEmpty, true)
|
|
@@ -61,3 +61,52 @@ test('decorateRequest still works for non-built-in names', (t, done) => {
|
|
|
61
61
|
done()
|
|
62
62
|
})
|
|
63
63
|
})
|
|
64
|
+
|
|
65
|
+
test('decorateRequest accepts built-in request properties as dependencies', t => {
|
|
66
|
+
t.plan(6)
|
|
67
|
+
const fastify = Fastify()
|
|
68
|
+
for (const name of ['id', 'params', 'raw', 'query', 'log', 'body']) {
|
|
69
|
+
t.assert.doesNotThrow(() => fastify.decorateRequest(`uses_${name}`, null, [name]))
|
|
70
|
+
}
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
test('decorateReply accepts built-in reply properties as dependencies', t => {
|
|
74
|
+
t.plan(3)
|
|
75
|
+
const fastify = Fastify()
|
|
76
|
+
for (const name of ['raw', 'request', 'log']) {
|
|
77
|
+
t.assert.doesNotThrow(() => fastify.decorateReply(`uses_${name}`, null, [name]))
|
|
78
|
+
}
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
test('decorateRequest accepts built-in properties as dependencies inside a plugin', (t, done) => {
|
|
82
|
+
t.plan(2)
|
|
83
|
+
const fastify = Fastify()
|
|
84
|
+
fastify.register(async (instance) => {
|
|
85
|
+
instance.decorateRequest('scopedExtra', null, ['body'])
|
|
86
|
+
t.assert.equal(instance.hasRequestDecorator('scopedExtra'), true)
|
|
87
|
+
})
|
|
88
|
+
fastify.ready((err) => {
|
|
89
|
+
t.assert.ifError(err)
|
|
90
|
+
done()
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
test('decorateRequest accepts built-in properties mixed with user decorators as dependencies', t => {
|
|
95
|
+
t.plan(1)
|
|
96
|
+
const fastify = Fastify()
|
|
97
|
+
fastify.decorateRequest('userProp', null)
|
|
98
|
+
t.assert.doesNotThrow(() => fastify.decorateRequest('mixed', null, ['userProp', 'body']))
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
test('decorateRequest still throws FST_ERR_DEC_MISSING_DEPENDENCY for unknown dependencies', t => {
|
|
102
|
+
t.plan(2)
|
|
103
|
+
const fastify = Fastify()
|
|
104
|
+
t.assert.throws(
|
|
105
|
+
() => fastify.decorateRequest('withUnknown', null, ['nonExistent']),
|
|
106
|
+
(err) => err.code === 'FST_ERR_DEC_MISSING_DEPENDENCY'
|
|
107
|
+
)
|
|
108
|
+
t.assert.throws(
|
|
109
|
+
() => fastify.decorateReply('withUnknown', null, ['body']),
|
|
110
|
+
(err) => err.code === 'FST_ERR_DEC_MISSING_DEPENDENCY'
|
|
111
|
+
)
|
|
112
|
+
})
|