fastify / fastify/fastify-compress
buildRoute(De)Compress doesn't handle non-compressible content if a custom onUnsupported handler is defined
- Dominant language
- JavaScript
- Stars
- 230
- Forks
- 70
- Avg merge
- 4d 8h
- Merged PRs (30d)
- 2
Description
### Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
### Fastify version
4.28.1
### Plugin version
7.0.3
### Node.js version
22.2
### Operating system
Windows
### Operating system version (i.e. 20.04, 11.3, 10)
10 22H2
### Description
Hi!
I think I found a bug in these functions.
```javascript
let stream, encoding
const noCompress =
// don't compress on x-no-compression header
(req.headers['x-no-compression'] !== undefined) ||
// don't compress if not one of the indicated compressible types
(shouldCompress(reply.getHeader('Content-Type') || 'application/json', params.compressibleTypes) === false) ||
// don't compress on missing or identity `accept-encoding` header
((encoding = getEncodingHeader(params.encodings, req)) == null || encoding === 'identity')
if (encoding == null && params.onUnsupportedEncoding != null) {
const encodingHeader = req.headers['accept-encoding']
try {
const errorPayload = params.onUnsupportedEncoding(encodingHeader, reply.request, reply)
return next(null, errorPayload)
} catch (err) {
return next(err)
}
}
```
The problem seems to be that the 'x-no-compression' header or the 'Content-Type' could resolve to true value and preempt (short-circuit) assigning a value to the encoding variable. In this case the `encoding == null` evaluates to true and if any custom `onUnsupportedEncoding` function was defined it gets called regardless whether the client and server has a common negotiable compression method.
Evaluating `encoding = getEncodingHeader(params.encodings, req)` before the `noCompress` variable should solve this in both functions.
### Link to code that reproduces the bug
_No response_
### Expected Behavior
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.