Debian Codegraph @

lib/web/cookies/parse.js

raw
1 'use strict'
2
3 const { collectASequenceOfCodePointsFast } = require('../infra')
4 const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants')
5 const { isCTLExcludingHtab } = require('./util')
6 const assert = require('node:assert')
7
8 /**
9 * @description Parses the field-value attributes of a set-cookie header string.
10 * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
11 * @param {string} header
12 * @returns {import('./index').Cookie|null} if the header is invalid, null will be returned
13 */
14 function parseSetCookie (header) {
15 // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
16 // character (CTL characters excluding HTAB): Abort these steps and
17 // ignore the set-cookie-string entirely.
18 if (isCTLExcludingHtab(header)) {
19 return null
20 }
21
22 let nameValuePair = ''
23 let unparsedAttributes = ''
24 let name = ''
25 let value = ''
26
27 // 2. If the set-cookie-string contains a %x3B (";") character:
28 if (header.includes(';')) {
29 // 1. The name-value-pair string consists of the characters up to,
30 // but not including, the first %x3B (";"), and the unparsed-
31 // attributes consist of the remainder of the set-cookie-string
32 // (including the %x3B (";") in question).
33 const position = { position: 0 }
34
35 nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
36 unparsedAttributes = header.slice(position.position)
37 } else {
38 // Otherwise:
39
40 // 1. The name-value-pair string consists of all the characters
41 // contained in the set-cookie-string, and the unparsed-
42 // attributes is the empty string.
43 nameValuePair = header
44 }
45
46 // 3. If the name-value-pair string lacks a %x3D ("=") character, then
47 // the name string is empty, and the value string is the value of
48 // name-value-pair.
49 if (!nameValuePair.includes('=')) {
50 value = nameValuePair
51 } else {
52 // Otherwise, the name string consists of the characters up to, but
53 // not including, the first %x3D ("=") character, and the (possibly
54 // empty) value string consists of the characters after the first
55 // %x3D ("=") character.
56 const position = { position: 0 }
57 name = collectASequenceOfCodePointsFast(
58 '=',
59 nameValuePair,
60 position
61 )
62 value = nameValuePair.slice(position.position + 1)
63 }
64
65 // 4. Remove any leading or trailing WSP characters from the name
66 // string and the value string.
67 name = name.trim()
68 value = value.trim()
69
70 // 5. If the sum of the lengths of the name string and the value string
71 // is more than 4096 octets, abort these steps and ignore the set-
72 // cookie-string entirely.
73 if (name.length + value.length > maxNameValuePairSize) {
74 return null
75 }
76
77 // 6. The cookie-name is the name string, and the cookie-value is the
78 // value string.
79 // https://datatracker.ietf.org/doc/html/rfc6265
80 // To maximize compatibility with user agents, servers that wish to
81 // store arbitrary data in a cookie-value SHOULD encode that data, for
82 // example, using Base64 [RFC4648].
83 return {
84 name, value, ...parseUnparsedAttributes(unparsedAttributes)
85 }
86 }
87
88 /**
89 * Parses the remaining attributes of a set-cookie header
90 * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
91 * @param {string} unparsedAttributes
92 * @param {Object.<string, unknown>} [cookieAttributeList={}]
93 */
94 function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
95 // 1. If the unparsed-attributes string is empty, skip the rest of
96 // these steps.
97 if (unparsedAttributes.length === 0) {
98 return cookieAttributeList
99 }
100
101 // 2. Discard the first character of the unparsed-attributes (which
102 // will be a %x3B (";") character).
103 assert(unparsedAttributes[0] === ';')
104 unparsedAttributes = unparsedAttributes.slice(1)
105
106 let cookieAv = ''
107
108 // 3. If the remaining unparsed-attributes contains a %x3B (";")
109 // character:
110 if (unparsedAttributes.includes(';')) {
111 // 1. Consume the characters of the unparsed-attributes up to, but
112 // not including, the first %x3B (";") character.
113 cookieAv = collectASequenceOfCodePointsFast(
114 ';',
115 unparsedAttributes,
116 { position: 0 }
117 )
118 unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
119 } else {
120 // Otherwise:
121
122 // 1. Consume the remainder of the unparsed-attributes.
123 cookieAv = unparsedAttributes
124 unparsedAttributes = ''
125 }
126
127 // Let the cookie-av string be the characters consumed in this step.
128
129 let attributeName = ''
130 let attributeValue = ''
131
132 // 4. If the cookie-av string contains a %x3D ("=") character:
133 if (cookieAv.includes('=')) {
134 // 1. The (possibly empty) attribute-name string consists of the
135 // characters up to, but not including, the first %x3D ("=")
136 // character, and the (possibly empty) attribute-value string
137 // consists of the characters after the first %x3D ("=")
138 // character.
139 const position = { position: 0 }
140
141 attributeName = collectASequenceOfCodePointsFast(
142 '=',
143 cookieAv,
144 position
145 )
146 attributeValue = cookieAv.slice(position.position + 1)
147 } else {
148 // Otherwise:
149
150 // 1. The attribute-name string consists of the entire cookie-av
151 // string, and the attribute-value string is empty.
152 attributeName = cookieAv
153 }
154
155 // 5. Remove any leading or trailing WSP characters from the attribute-
156 // name string and the attribute-value string.
157 attributeName = attributeName.trim()
158 attributeValue = attributeValue.trim()
159
160 // 6. If the attribute-value is longer than 1024 octets, ignore the
161 // cookie-av string and return to Step 1 of this algorithm.
162 if (attributeValue.length > maxAttributeValueSize) {
163 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
164 }
165
166 // 7. Process the attribute-name and attribute-value according to the
167 // requirements in the following subsections. (Notice that
168 // attributes with unrecognized attribute-names are ignored.)
169 const attributeNameLowercase = attributeName.toLowerCase()
170
171 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
172 // If the attribute-name case-insensitively matches the string
173 // "Expires", the user agent MUST process the cookie-av as follows.
174 if (attributeNameLowercase === 'expires') {
175 // 1. Let the expiry-time be the result of parsing the attribute-value
176 // as cookie-date (see Section 5.1.1).
177 const expiryTime = new Date(attributeValue)
178
179 // 2. If the attribute-value failed to parse as a cookie date, ignore
180 // the cookie-av.
181
182 cookieAttributeList.expires = expiryTime
183 } else if (attributeNameLowercase === 'max-age') {
184 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
185 // If the attribute-name case-insensitively matches the string "Max-
186 // Age", the user agent MUST process the cookie-av as follows.
187
188 // 1. If the first character of the attribute-value is not a DIGIT or a
189 // "-" character, ignore the cookie-av.
190 const charCode = attributeValue.charCodeAt(0)
191
192 if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
193 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
194 }
195
196 // 2. If the remainder of attribute-value contains a non-DIGIT
197 // character, ignore the cookie-av.
198 if (!/^\d+$/.test(attributeValue)) {
199 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
200 }
201
202 // 3. Let delta-seconds be the attribute-value converted to an integer.
203 const deltaSeconds = Number(attributeValue)
204
205 // 4. Let cookie-age-limit be the maximum age of the cookie (which
206 // SHOULD be 400 days or less, see Section 4.1.2.2).
207
208 // 5. Set delta-seconds to the smaller of its present value and cookie-
209 // age-limit.
210 // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
211
212 // 6. If delta-seconds is less than or equal to zero (0), let expiry-
213 // time be the earliest representable date and time. Otherwise, let
214 // the expiry-time be the current date and time plus delta-seconds
215 // seconds.
216 // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
217
218 // 7. Append an attribute to the cookie-attribute-list with an
219 // attribute-name of Max-Age and an attribute-value of expiry-time.
220 cookieAttributeList.maxAge = deltaSeconds
221 } else if (attributeNameLowercase === 'domain') {
222 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
223 // If the attribute-name case-insensitively matches the string "Domain",
224 // the user agent MUST process the cookie-av as follows.
225
226 // 1. Let cookie-domain be the attribute-value.
227 let cookieDomain = attributeValue
228
229 // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
230 // cookie-domain without its leading %x2E (".").
231 if (cookieDomain[0] === '.') {
232 cookieDomain = cookieDomain.slice(1)
233 }
234
235 // 3. Convert the cookie-domain to lower case.
236 cookieDomain = cookieDomain.toLowerCase()
237
238 // 4. Append an attribute to the cookie-attribute-list with an
239 // attribute-name of Domain and an attribute-value of cookie-domain.
240 cookieAttributeList.domain = cookieDomain
241 } else if (attributeNameLowercase === 'path') {
242 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
243 // If the attribute-name case-insensitively matches the string "Path",
244 // the user agent MUST process the cookie-av as follows.
245
246 // 1. If the attribute-value is empty or if the first character of the
247 // attribute-value is not %x2F ("/"):
248 let cookiePath = ''
249 if (attributeValue.length === 0 || attributeValue[0] !== '/') {
250 // 1. Let cookie-path be the default-path.
251 cookiePath = '/'
252 } else {
253 // Otherwise:
254
255 // 1. Let cookie-path be the attribute-value.
256 cookiePath = attributeValue
257 }
258
259 // 2. Append an attribute to the cookie-attribute-list with an
260 // attribute-name of Path and an attribute-value of cookie-path.
261 cookieAttributeList.path = cookiePath
262 } else if (attributeNameLowercase === 'secure') {
263 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
264 // If the attribute-name case-insensitively matches the string "Secure",
265 // the user agent MUST append an attribute to the cookie-attribute-list
266 // with an attribute-name of Secure and an empty attribute-value.
267
268 cookieAttributeList.secure = true
269 } else if (attributeNameLowercase === 'httponly') {
270 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
271 // If the attribute-name case-insensitively matches the string
272 // "HttpOnly", the user agent MUST append an attribute to the cookie-
273 // attribute-list with an attribute-name of HttpOnly and an empty
274 // attribute-value.
275
276 cookieAttributeList.httpOnly = true
277 } else if (attributeNameLowercase === 'samesite') {
278 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
279 // If the attribute-name case-insensitively matches the string
280 // "SameSite", the user agent MUST process the cookie-av as follows:
281
282 const attributeValueLowercase = attributeValue.toLowerCase()
283
284 // 1. If cookie-av's attribute-value is a case-insensitive match for
285 // "None", append an attribute to the cookie-attribute-list with an
286 // attribute-name of "SameSite" and an attribute-value of "None".
287 if (attributeValueLowercase === 'none') {
288 cookieAttributeList.sameSite = 'None'
289 } else if (attributeValueLowercase === 'strict') {
290 // 2. If cookie-av's attribute-value is a case-insensitive match for
291 // "Strict", append an attribute to the cookie-attribute-list with
292 // an attribute-name of "SameSite" and an attribute-value of
293 // "Strict".
294 cookieAttributeList.sameSite = 'Strict'
295 } else if (attributeValueLowercase === 'lax') {
296 // 3. If cookie-av's attribute-value is a case-insensitive match for
297 // "Lax", append an attribute to the cookie-attribute-list with an
298 // attribute-name of "SameSite" and an attribute-value of "Lax".
299 cookieAttributeList.sameSite = 'Lax'
300 }
301 } else {
302 cookieAttributeList.unparsed ??= []
303
304 cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
305 }
306
307 // 8. Return to Step 1 of this algorithm.
308 return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
309 }
310
311 module.exports = {
312 parseSetCookie,
313 parseUnparsedAttributes
314 }