diff --git a/lib/web/cookies/util.js b/lib/web/cookies/util.js index 9ed048be874..055337a5e5a 100644 --- a/lib/web/cookies/util.js +++ b/lib/web/cookies/util.js @@ -324,19 +324,27 @@ function stringify (cookie) { } for (const part of cookie.unparsed) { - if (!part.includes('=')) { - throw new Error('Invalid unparsed') - } - - const [key, ...value] = part.split('=') + if (part.includes('=')) { + const [key, ...value] = part.split('=') - const trimmedKey = key.trim() - const joinedValue = value.join('=') + const trimmedKey = key.trim() + if (trimmedKey.length === 0) { + throw new Error('Invalid unparsed') + } + const joinedValue = value.join('=') - validateCookieName(trimmedKey) - validateCookieValue(joinedValue) + validateCookieName(trimmedKey) + validateCookieValue(joinedValue) - out.push(`${trimmedKey}=${joinedValue}`) + out.push(`${trimmedKey}=${joinedValue}`) + } else { + const trimmedKey = part.trim() + if (trimmedKey.length === 0) { + throw new Error('Invalid unparsed') + } + validateCookieName(trimmedKey) + out.push(trimmedKey) + } } return out.join('; ') diff --git a/test/cookie/cookies.js b/test/cookie/cookies.js index 549627cf97a..841f4626aa2 100644 --- a/test/cookie/cookies.js +++ b/test/cookie/cookies.js @@ -782,3 +782,27 @@ test('Set-Cookie parser ignores an unparseable Expires', () => { value: 'a3fWa' }]) }) + +test('Cookie setCookie supports valueless unparsed attributes (e.g. Partitioned)', () => { + const headers = new Headers() + setCookie(headers, { + name: 'session', + value: 'abc', + secure: true, + path: '/', + unparsed: ['Partitioned'] + }) + assert.equal(headers.get('Set-Cookie'), 'session=abc; Secure; Path=/; Partitioned') + + assert.throws(() => { + setCookie(headers, { name: 'session', value: 'abc', unparsed: [''] }) + }, /Invalid unparsed/) + + assert.throws(() => { + setCookie(headers, { name: 'session', value: 'abc', unparsed: [' '] }) + }, /Invalid unparsed/) + + assert.throws(() => { + setCookie(headers, { name: 'session', value: 'abc', unparsed: ['=val'] }) + }, /Invalid unparsed/) +})