diff --git a/lib/index.js b/lib/index.js index f0f4bb6..28be59a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,6 +15,24 @@ const { getNodeRequestOptions } = Request const FetchError = require('./fetch-error.js') const AbortError = require('./abort-error.js') +const acceptsEncoding = (headers, encoding) => { + const encodings = new Headers(headers).get('Accept-Encoding') + .toLowerCase() + .split(',') + .map(value => value.trim().split(/\s*;\s*/)) + // An explicit encoding preference takes precedence over a wildcard. + const preference = encodings.find(([name]) => name === encoding) || + encodings.find(([name]) => name === '*') + if (!preference) { + return false + } + + const [, weight = 'q=1'] = preference + return preference.length <= 2 && + /^q=(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(weight) && + Number(weight.slice(2)) > 0 +} + // XXX this should really be split up and unit-ized for easier testing // and better DRY implementation of data/http request aborting const fetch = async (url, opts) => { @@ -333,7 +351,7 @@ const fetch = async (url, opts) => { } // for br - if (codings === 'br') { + if (codings === 'br' && acceptsEncoding(options.headers, 'br')) { // ignoring coverage so tests don't have to fake support (or lack of) for brotli // istanbul ignore next try { diff --git a/test/decompress-async.js b/test/decompress-async.js index 4472d2a..381d278 100644 --- a/test/decompress-async.js +++ b/test/decompress-async.js @@ -68,7 +68,9 @@ t.test('decompress response when using async pipe', async t => { 'Content-Encoding': 'br', }) - const res = await fetch('http://a.b/brotli') + const res = await fetch('http://a.b/brotli', { + headers: { 'Accept-Encoding': 'br' }, + }) const result = await res.text() t.equal(result, input, 'brotli response processed correctly when using async pipe') t.end() diff --git a/test/index.js b/test/index.js index e0aa4f2..fb253c6 100644 --- a/test/index.js +++ b/test/index.js @@ -554,21 +554,77 @@ t.test('decompress deflate raw response from old apache server', async t => { }) t.test('decompress brotli response', async t => { + const options = { headers: { 'Accept-Encoding': 'br' } } // if the node core zlib doesn't export brotli functions, we'll end up // rejecting the request with an error that comes from minizlib, assert // that here if (typeof realZlib.BrotliCompress !== 'function') { - return t.rejects(fetch(`${base}brotli`), { + return t.rejects(fetch(`${base}brotli`, options), { message: 'Brotli is not supported in this version of Node.js', }, 'rejects the promise') } - const res = await fetch(`${base}brotli`) + const res = await fetch(`${base}brotli`, options) t.equal(res.headers.get('content-type'), 'text/plain') const result = await res.text() t.equal(result, 'hello world') }) +t.test('only decompress brotli when accepted by the request', async t => { + const zlib = require('minizlib') + let decoderCalls = 0 + const mockedFetch = t.mock('../lib/index.js', { + minizlib: { + ...zlib, + BrotliDecompress: class extends zlib.BrotliDecompress { + constructor (...args) { + super(...args) + decoderCalls++ + } + }, + }, + }) + const input = Buffer.from('hello world') + const compressed = realZlib.brotliCompressSync(input) + + for (const [acceptEncoding, accepted] of [ + [undefined, false], + ['', false], + ['gzip', false], + ['br', true], + ['gzip, BR ; Q=0.500', true], + ['br;q=0', false], + ['br;q=0.000', false], + ['br;q=0.001', true], + ['*', true], + ['*;q=0', false], + ['*;q=0.5', true], + ['*, br;q=0', false], + ['br;q=0, *', false], + ['*;q=0, br;q=1', true], + ['br;q=invalid', false], + ['br;q=1.1', false], + ['br;q=1;extra=1', false], + ]) { + await t.test(acceptEncoding === undefined ? 'default' : acceptEncoding || 'empty', async t => { + const before = decoderCalls + const scope = nock('http://brotli.test', { + reqheaders: { + 'accept-encoding': acceptEncoding === undefined ? 'gzip,deflate' : acceptEncoding, + }, + }) + .get('/') + .reply(200, compressed, { 'Content-Encoding': 'br' }) + const headers = acceptEncoding === undefined ? {} : { 'Accept-Encoding': acceptEncoding } + const res = await mockedFetch('http://brotli.test/', { headers }) + + t.same(await res.buffer(), accepted ? input : compressed) + t.equal(decoderCalls - before, accepted ? 1 : 0, 'only constructs an accepted decoder') + scope.done() + }) + } +}) + t.test('handle no content response with brotli encoding', async t => { const res = await fetch(`${base}no-content/brotli`) t.equal(res.status, 204)