Skip to content

Commit

Permalink
fix(kit): handle whitespace in HTTP Accept header (#12292)
Browse files Browse the repository at this point in the history
According to [RFC 9110][1], in the HTTP Accept header, there can be OWS (optional whitespace, e.g. zero to unlimited SP (space) or HTAB (horizontal tab)) between the `;` and `,` characters.

[1]: https://www.rfc-editor.org/rfc/rfc9110
  • Loading branch information
aloisklink committed Jun 7, 2024
1 parent 84f03cc commit 0a0e9aa
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/witty-bees-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/kit": patch
---

fix: handle whitespace in HTTP Accept header
2 changes: 1 addition & 1 deletion packages/kit/src/utils/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function negotiate(accept, types) {
const parts = [];

accept.split(',').forEach((str, i) => {
const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
const match = /([^/ \t]+)\/([^; \t]+)[ \t]*(?:;[ \t]*q=([0-9.]+))?/.exec(str);

// no match equals invalid header — ignore
if (match) {
Expand Down
7 changes: 7 additions & 0 deletions packages/kit/src/utils/http.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ test('handle valid accept header value', () => {
assert.equal(negotiate(accept, ['text/html']), 'text/html');
});

test('handle accept values with optional whitespace', () => {
// according to RFC 9110, OWS (optional whitespace, aka a space or horizontal tab)
// can occur before/after the `,` and the `;`.
const accept = 'application/some-thing-else, \tapplication/json \t; q=0.9 ,text/plain;q=0.1';
assert.equal(negotiate(accept, ['application/json', 'text/plain']), 'application/json');
});

test('handle invalid accept header value', () => {
const accept = 'text/html,*';
assert.equal(negotiate(accept, ['text/html']), 'text/html');
Expand Down

0 comments on commit 0a0e9aa

Please sign in to comment.