Debian Codegraph @

lib/web/cookies/util.js

raw
1 'use strict'
2
3 /**
4 * @param {string} value
5 * @returns {boolean}
6 */
7 function isCTLExcludingHtab (value) {
8 for (let i = 0; i < value.length; ++i) {
9 const code = value.charCodeAt(i)
10
11 if (
12 (code >= 0x00 && code <= 0x08) ||
13 (code >= 0x0A && code <= 0x1F) ||
14 code === 0x7F
15 ) {
16 return true
17 }
18 }
19 return false
20 }
21
22 /**
23 CHAR = <any US-ASCII character (octets 0 - 127)>
24 token = 1*<any CHAR except CTLs or separators>
25 separators = "(" | ")" | "<" | ">" | "@"
26 | "," | ";" | ":" | "\" | <">
27 | "/" | "[" | "]" | "?" | "="
28 | "{" | "}" | SP | HT
29 * @param {string} name
30 */
31 function validateCookieName (name) {
32 for (let i = 0; i < name.length; ++i) {
33 const code = name.charCodeAt(i)
34
35 if (
36 code < 0x21 || // exclude CTLs (0-31), SP and HT
37 code > 0x7E || // exclude non-ascii and DEL
38 code === 0x22 || // "
39 code === 0x28 || // (
40 code === 0x29 || // )
41 code === 0x3C || // <
42 code === 0x3E || // >
43 code === 0x40 || // @
44 code === 0x2C || // ,
45 code === 0x3B || // ;
46 code === 0x3A || // :
47 code === 0x5C || // \
48 code === 0x2F || // /
49 code === 0x5B || // [
50 code === 0x5D || // ]
51 code === 0x3F || // ?
52 code === 0x3D || // =
53 code === 0x7B || // {
54 code === 0x7D // }
55 ) {
56 throw new Error('Invalid cookie name')
57 }
58 }
59 }
60
61 /**
62 cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
63 cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
64 ; US-ASCII characters excluding CTLs,
65 ; whitespace DQUOTE, comma, semicolon,
66 ; and backslash
67 * @param {string} value
68 */
69 function validateCookieValue (value) {
70 let len = value.length
71 let i = 0
72
73 // if the value is wrapped in DQUOTE
74 if (value[0] === '"') {
75 if (len === 1 || value[len - 1] !== '"') {
76 throw new Error('Invalid cookie value')
77 }
78 --len
79 ++i
80 }
81
82 while (i < len) {
83 const code = value.charCodeAt(i++)
84
85 if (
86 code < 0x21 || // exclude CTLs (0-31)
87 code > 0x7E || // non-ascii and DEL (127)
88 code === 0x22 || // "
89 code === 0x2C || // ,
90 code === 0x3B || // ;
91 code === 0x5C // \
92 ) {
93 throw new Error('Invalid cookie value')
94 }
95 }
96 }
97
98 /**
99 * path-value = <any CHAR except CTLs or ";">
100 * @param {string} path
101 */
102 function validateCookiePath (path) {
103 for (let i = 0; i < path.length; ++i) {
104 const code = path.charCodeAt(i)
105
106 if (
107 code < 0x20 || // exclude CTLs (0-31)
108 code === 0x7F || // DEL
109 code === 0x3B // ;
110 ) {
111 throw new Error('Invalid cookie path')
112 }
113 }
114 }
115
116 /**
117 * I have no idea why these values aren't allowed to be honest,
118 * but Deno tests these. - Khafra
119 * @param {string} domain
120 */
121 function validateCookieDomain (domain) {
122 if (
123 domain.startsWith('-') ||
124 domain.endsWith('.') ||
125 domain.endsWith('-')
126 ) {
127 throw new Error('Invalid cookie domain')
128 }
129 }
130
131 const IMFDays = [
132 'Sun', 'Mon', 'Tue', 'Wed',
133 'Thu', 'Fri', 'Sat'
134 ]
135
136 const IMFMonths = [
137 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
138 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
139 ]
140
141 const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0'))
142
143 /**
144 * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
145 * @param {number|Date} date
146 IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
147 ; fixed length/zone/capitalization subset of the format
148 ; see Section 3.3 of [RFC5322]
149
150 day-name = %x4D.6F.6E ; "Mon", case-sensitive
151 / %x54.75.65 ; "Tue", case-sensitive
152 / %x57.65.64 ; "Wed", case-sensitive
153 / %x54.68.75 ; "Thu", case-sensitive
154 / %x46.72.69 ; "Fri", case-sensitive
155 / %x53.61.74 ; "Sat", case-sensitive
156 / %x53.75.6E ; "Sun", case-sensitive
157 date1 = day SP month SP year
158 ; e.g., 02 Jun 1982
159
160 day = 2DIGIT
161 month = %x4A.61.6E ; "Jan", case-sensitive
162 / %x46.65.62 ; "Feb", case-sensitive
163 / %x4D.61.72 ; "Mar", case-sensitive
164 / %x41.70.72 ; "Apr", case-sensitive
165 / %x4D.61.79 ; "May", case-sensitive
166 / %x4A.75.6E ; "Jun", case-sensitive
167 / %x4A.75.6C ; "Jul", case-sensitive
168 / %x41.75.67 ; "Aug", case-sensitive
169 / %x53.65.70 ; "Sep", case-sensitive
170 / %x4F.63.74 ; "Oct", case-sensitive
171 / %x4E.6F.76 ; "Nov", case-sensitive
172 / %x44.65.63 ; "Dec", case-sensitive
173 year = 4DIGIT
174
175 GMT = %x47.4D.54 ; "GMT", case-sensitive
176
177 time-of-day = hour ":" minute ":" second
178 ; 00:00:00 - 23:59:60 (leap second)
179
180 hour = 2DIGIT
181 minute = 2DIGIT
182 second = 2DIGIT
183 */
184 function toIMFDate (date) {
185 if (typeof date === 'number') {
186 date = new Date(date)
187 }
188
189 return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`
190 }
191
192 /**
193 max-age-av = "Max-Age=" non-zero-digit *DIGIT
194 ; In practice, both expires-av and max-age-av
195 ; are limited to dates representable by the
196 ; user agent.
197 * @param {number} maxAge
198 */
199 function validateCookieMaxAge (maxAge) {
200 if (maxAge < 0) {
201 throw new Error('Invalid cookie max-age')
202 }
203 }
204
205 /**
206 * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
207 * @param {import('./index').Cookie} cookie
208 */
209 function stringify (cookie) {
210 if (cookie.name.length === 0) {
211 return null
212 }
213
214 validateCookieName(cookie.name)
215 validateCookieValue(cookie.value)
216
217 const out = [`${cookie.name}=${cookie.value}`]
218
219 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
220 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
221 if (cookie.name.startsWith('__Secure-')) {
222 cookie.secure = true
223 }
224
225 if (cookie.name.startsWith('__Host-')) {
226 cookie.secure = true
227 cookie.domain = null
228 cookie.path = '/'
229 }
230
231 if (cookie.secure) {
232 out.push('Secure')
233 }
234
235 if (cookie.httpOnly) {
236 out.push('HttpOnly')
237 }
238
239 if (typeof cookie.maxAge === 'number') {
240 validateCookieMaxAge(cookie.maxAge)
241 out.push(`Max-Age=${cookie.maxAge}`)
242 }
243
244 if (cookie.domain) {
245 validateCookieDomain(cookie.domain)
246 out.push(`Domain=${cookie.domain}`)
247 }
248
249 if (cookie.path) {
250 validateCookiePath(cookie.path)
251 out.push(`Path=${cookie.path}`)
252 }
253
254 if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
255 out.push(`Expires=${toIMFDate(cookie.expires)}`)
256 }
257
258 if (cookie.sameSite) {
259 out.push(`SameSite=${cookie.sameSite}`)
260 }
261
262 for (const part of cookie.unparsed) {
263 if (!part.includes('=')) {
264 throw new Error('Invalid unparsed')
265 }
266
267 const [key, ...value] = part.split('=')
268
269 out.push(`${key.trim()}=${value.join('=')}`)
270 }
271
272 return out.join('; ')
273 }
274
275 module.exports = {
276 isCTLExcludingHtab,
277 validateCookieName,
278 validateCookiePath,
279 validateCookieValue,
280 toIMFDate,
281 stringify
282 }