cookie.ts
This file
Path
src/utils/cookie.ts
280 lines · 8.9 KiB · TypeScript
Last changed by
fix(cookie): allow parsing signed cookies with empty string values (#5246)Nanasibefore adoption241ae4c
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–5why, one step back1/**2 * @module3 * Cookie utility.4 */5Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 6why, one step back6import { tryDecodeURIComponent } from './url'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 7–69why, one step back78export type Cookie = Record<string, string>9export type SignedCookie = Record<string, string | false>1011type PartitionedCookieConstraint =12 | { partitioned: true; secure: true }13 | { partitioned?: boolean; secure?: boolean } // reset to default14type SecureCookieConstraint = { secure: true }15type HostCookieConstraint = { secure: true; path: '/'; domain?: undefined }1617export type CookieOptions = {18 domain?: string19 expires?: Date20 httpOnly?: boolean21 maxAge?: number22 path?: string23 secure?: boolean24 sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none'25 partitioned?: boolean26 priority?: 'Low' | 'Medium' | 'High' | 'low' | 'medium' | 'high'27 prefix?: CookiePrefixOptions28} & PartitionedCookieConstraint29export type CookiePrefixOptions = 'host' | 'secure'3031export type CookieConstraint<Name> = Name extends `__Secure-${string}`32 ? CookieOptions & SecureCookieConstraint33 : Name extends `__Host-${string}`34 ? CookieOptions & HostCookieConstraint35 : CookieOptions3637const algorithm = { name: 'HMAC', hash: 'SHA-256' }3839const getCryptoKey = async (secret: string | BufferSource): Promise<CryptoKey> => {40 const secretBuf = typeof secret === 'string' ? new TextEncoder().encode(secret) : secret41 return await crypto.subtle.importKey('raw', secretBuf, algorithm, false, ['sign', 'verify'])42}4344const makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {45 const key = await getCryptoKey(secret)46 const signature = await crypto.subtle.sign(algorithm.name, key, new TextEncoder().encode(value))47 // the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs48 return btoa(String.fromCharCode(...new Uint8Array(signature)))49}5051const verifySignature = async (52 base64Signature: string,53 value: string,54 secret: CryptoKey55): Promise<boolean> => {56 try {57 const signatureBinStr = atob(base64Signature)58 const signature = new Uint8Array(signatureBinStr.length)59 for (let i = 0, len = signatureBinStr.length; i < len; i++) {60 signature[i] = signatureBinStr.charCodeAt(i)61 }62 return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value))63 } catch {64 return false65 }66}6768// all alphanumeric chars and all of _!#$%&'*.^`|~+-69// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)fix(cookie): relax name validation when parsing Cookie header (#5164)Yusuke Wadabefore adoption09cf01c
line 70why, one step back70// used only when producing cookies via serialize(); parsing uses the relaxed regex belowMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 71–72why, one step back71const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/72fix(cookie): relax name validation when parsing Cookie header (#5164)Yusuke Wadabefore adoption09cf01c
lines 73–78why, one step back73// all ASCII chars 33-126 except 34, 59, 61, and 92 (i.e. "!" to "~" but not double quote, semicolon, equals, or backslash)74// the strict RFC 6265 token rule above is a requirement for cookie producers; when consuming75// the Cookie header we accept the names other producers emit in the wild, e.g. "paraglide:lang"76// (see: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.6 and https://github.com/honojs/hono/issues/3189)77const relaxedCookieNameRegEx = /^[!#-:<>-[\]-~]+$/78Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 79–124why, one step back79// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)80// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)81//82// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world83// (see: https://github.com/golang/go/issues/7243)84const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/8586const trimCookieWhitespace = (value: string): string => {87 let start = 088 let end = value.length8990 while (start < end) {91 const charCode = value.charCodeAt(start)92 if (charCode !== 0x20 && charCode !== 0x09) {93 break94 }95 start++96 }9798 while (end > start) {99 const charCode = value.charCodeAt(end - 1)100 if (charCode !== 0x20 && charCode !== 0x09) {101 break102 }103 end--104 }105106 return start === 0 && end === value.length ? value : value.slice(start, end)107}108109export const parse = (cookie: string, name?: string): Cookie => {110 if (name && cookie.indexOf(name) === -1) {111 // Fast-path: return immediately if the demanded-key is not in the cookie string112 return {}113 }114 const pairs = cookie.split(';')115 const parsedCookie: Cookie = Object.create(null)116 for (const pairStr of pairs) {117 const valueStartPos = pairStr.indexOf('=')118 if (valueStartPos === -1) {119 continue120 }121122 const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos))123 if (124 (name && name !== cookieName) ||fix(cookie): relax name validation when parsing Cookie header (#5164)Yusuke Wadabefore adoption09cf01c
line 125why, one step back125 !relaxedCookieNameRegEx.test(cookieName) ||Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 126–135why, one step back126 cookieName in parsedCookie127 ) {128 continue129 }130131 let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1))132 if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {133 cookieValue = cookieValue.slice(1, -1)134 }135 if (validCookieValueRegEx.test(cookieValue)) {Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 136why, one step back136 parsedCookie[cookieName] = tryDecodeURIComponent(cookieValue)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 137–155why, one step back137 if (name) {138 // Fast-path: return only the demanded-key immediately. Other keys are not needed.139 break140 }141 }142 }143 return parsedCookie144}145146export const parseSigned = async (147 cookie: string,148 secret: string | BufferSource,149 name?: string150): Promise<SignedCookie> => {151 const parsedCookie: SignedCookie = Object.create(null)152 const secretKey = await getCryptoKey(secret)153154 for (const [key, value] of Object.entries(parse(cookie, name))) {155 const signatureStartPos = value.lastIndexOf('.')fix(cookie): allow parsing signed cookies with empty string values (#5246)Nanasibefore adoption241ae4c
line 156why, one step back156 if (signatureStartPos < 0) {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 157–280why, one step back157 continue158 }159160 const signedValue = value.substring(0, signatureStartPos)161 const signature = value.substring(signatureStartPos + 1)162 if (signature.length !== 44 || !signature.endsWith('=')) {163 continue164 }165166 const isVerified = await verifySignature(signature, signedValue, secretKey)167 parsedCookie[key] = isVerified ? signedValue : false168 }169170 return parsedCookie171}172173const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {174 if (!validCookieNameRegEx.test(name)) {175 throw new Error('Invalid cookie name')176 }177178 let cookie = `${name}=${value}`179180 if (name.startsWith('__Secure-') && !opt.secure) {181 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-4.1.3.1182 throw new Error('__Secure- Cookie must have Secure attributes')183 }184185 if (name.startsWith('__Host-')) {186 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-4.1.3.2187 if (!opt.secure) {188 throw new Error('__Host- Cookie must have Secure attributes')189 }190191 if (opt.path !== '/') {192 throw new Error('__Host- Cookie must have Path attributes with "/"')193 }194195 if (opt.domain) {196 throw new Error('__Host- Cookie must not have Domain attributes')197 }198 }199200 for (const key of ['domain', 'path', 'sameSite', 'priority'] as (keyof CookieOptions)[]) {201 if (opt[key] && /[;\r\n]/.test(opt[key] as string)) {202 throw new Error(`${key} must not contain ";", "\\r", or "\\n"`)203 }204 }205206 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {207 if (opt.maxAge > 34560000) {208 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.6.2209 throw new Error(210 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'211 )212 }213 cookie += `; Max-Age=${opt.maxAge | 0}`214 }215216 if (opt.domain && opt.prefix !== 'host') {217 cookie += `; Domain=${opt.domain}`218 }219220 if (opt.path) {221 cookie += `; Path=${opt.path}`222 }223224 if (opt.expires) {225 if (opt.expires.getTime() - Date.now() > 34560000_000) {226 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.5227 throw new Error(228 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'229 )230 }231 cookie += `; Expires=${opt.expires.toUTCString()}`232 }233234 if (opt.httpOnly) {235 cookie += '; HttpOnly'236 }237238 if (opt.secure) {239 cookie += '; Secure'240 }241242 if (opt.sameSite) {243 cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`244 }245246 if (opt.priority) {247 cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`248 }249250 if (opt.partitioned) {251 // https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.1252 if (!opt.secure) {253 throw new Error('Partitioned Cookie must have Secure attributes')254 }255 cookie += '; Partitioned'256 }257258 return cookie259}260261export const serialize = <Name extends string>(262 name: Name,263 value: string,264 opt?: CookieConstraint<Name>265): string => {266 value = encodeURIComponent(value)267 return _serialize(name, value, opt)268}269270export const serializeSigned = async (271 name: string,272 value: string,273 secret: string | BufferSource,274 opt: CookieOptions = {}275): Promise<string> => {276 const signature = await makeSignature(value, secret)277 value = `${value}.${signature}`278 value = encodeURIComponent(value)279 return _serialize(name, value, opt)280}