Skip to content
Myr

cookie.ts

This file

Path

src/utils/cookie.ts

244 lines · 7.7 KiB · TypeScript

Last changed by

Merge commit from forkTaku Amanobefore adoption44ae0c8

History of this file

Take it

The walk stopped after 200 commits: lines older than 82bdc4d point at it.

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 1–33why, one step back
1/**
2 * @module3 * Cookie utility.4 */56import { decodeURIComponent_, tryDecode } from './url'78export 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}`

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

lines 34–35why, one step back
34 ? CookieOptions & HostCookieConstraint
35 : CookieOptions

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 36–144why, one step back
36
37const 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)70const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/7172// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)73// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)74//75// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world76// (see: https://github.com/golang/go/issues/7243)77const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/7879export const parse = (cookie: string, name?: string): Cookie => {80 if (name && cookie.indexOf(name) === -1) {81 // Fast-path: return immediately if the demanded-key is not in the cookie string82 return {}83 }84 const pairs = cookie.trim().split(';')85 const parsedCookie: Cookie = {}86 for (let pairStr of pairs) {87 pairStr = pairStr.trim()88 const valueStartPos = pairStr.indexOf('=')89 if (valueStartPos === -1) {90 continue91 }9293 const cookieName = pairStr.substring(0, valueStartPos).trim()94 if ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {95 continue96 }9798 let cookieValue = pairStr.substring(valueStartPos + 1).trim()99 if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {100 cookieValue = cookieValue.slice(1, -1)101 }102 if (validCookieValueRegEx.test(cookieValue)) {103 parsedCookie[cookieName] =104 cookieValue.indexOf('%') !== -1 ? tryDecode(cookieValue, decodeURIComponent_) : cookieValue105 if (name) {106 // Fast-path: return only the demanded-key immediately. Other keys are not needed.107 break108 }109 }110 }111 return parsedCookie112}113114export const parseSigned = async (115 cookie: string,116 secret: string | BufferSource,117 name?: string118): Promise<SignedCookie> => {119 const parsedCookie: SignedCookie = {}120 const secretKey = await getCryptoKey(secret)121122 for (const [key, value] of Object.entries(parse(cookie, name))) {123 const signatureStartPos = value.lastIndexOf('.')124 if (signatureStartPos < 1) {125 continue126 }127128 const signedValue = value.substring(0, signatureStartPos)129 const signature = value.substring(signatureStartPos + 1)130 if (signature.length !== 44 || !signature.endsWith('=')) {131 continue132 }133134 const isVerified = await verifySignature(signature, signedValue, secretKey)135 parsedCookie[key] = isVerified ? signedValue : false136 }137138 return parsedCookie139}140141const _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {142 let cookie = `${name}=${value}`143144 if (name.startsWith('__Secure-') && !opt.secure) {

docs(cookie): update outdated RFC links (#4557)Ayush Kumar Singhbefore adoptionf8c5a79

line 145why, one step back
145 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-4.1.3.1

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 146–149why, one step back
146 throw new Error('__Secure- Cookie must have Secure attributes')
147 }148149 if (name.startsWith('__Host-')) {

docs(cookie): update outdated RFC links (#4557)Ayush Kumar Singhbefore adoptionf8c5a79

line 150why, one step back
150 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-4.1.3.2

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 151–163why, one step back
151 if (!opt.secure) {
152 throw new Error('__Host- Cookie must have Secure attributes')153 }154155 if (opt.path !== '/') {156 throw new Error('__Host- Cookie must have Path attributes with "/"')157 }158159 if (opt.domain) {160 throw new Error('__Host- Cookie must not have Domain attributes')161 }162 }163

Merge commit from forkTaku Amanobefore adoption44ae0c8

lines 164–169why, one step back
164 for (const key of ['domain', 'path'] as (keyof CookieOptions)[]) {
165 if (opt[key] && /[;\r\n]/.test(opt[key] as string)) {166 throw new Error(`${key} must not contain ";", "\\r", or "\\n"`)167 }168 }169

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 170–171why, one step back
170 if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {
171 if (opt.maxAge > 34560000) {

docs(cookie): update outdated RFC links (#4557)Ayush Kumar Singhbefore adoptionf8c5a79

line 172why, one step back
172 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.6.2

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 173–189why, one step back
173 throw new Error(
174 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'175 )176 }177 cookie += `; Max-Age=${opt.maxAge | 0}`178 }179180 if (opt.domain && opt.prefix !== 'host') {181 cookie += `; Domain=${opt.domain}`182 }183184 if (opt.path) {185 cookie += `; Path=${opt.path}`186 }187188 if (opt.expires) {189 if (opt.expires.getTime() - Date.now() > 34560000_000) {

docs(cookie): update outdated RFC links (#4557)Ayush Kumar Singhbefore adoptionf8c5a79

line 190why, one step back
190 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-22#section-5.5

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 191–214why, one step back
191 throw new Error(
192 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'193 )194 }195 cookie += `; Expires=${opt.expires.toUTCString()}`196 }197198 if (opt.httpOnly) {199 cookie += '; HttpOnly'200 }201202 if (opt.secure) {203 cookie += '; Secure'204 }205206 if (opt.sameSite) {207 cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`208 }209210 if (opt.priority) {211 cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`212 }213214 if (opt.partitioned) {

docs(cookie): update outdated RFC links (#4557)Ayush Kumar Singhbefore adoptionf8c5a79

line 215why, one step back
215 // https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.1

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 216–244why, one step back
216 if (!opt.secure) {
217 throw new Error('Partitioned Cookie must have Secure attributes')218 }219 cookie += '; Partitioned'220 }221222 return cookie223}224225export const serialize = <Name extends string>(226 name: Name,227 value: string,228 opt?: CookieConstraint<Name>229): string => {230 value = encodeURIComponent(value)231 return _serialize(name, value, opt)232}233234export const serializeSigned = async (235 name: string,236 value: string,237 secret: string | BufferSource,238 opt: CookieOptions = {}239): Promise<string> => {240 const signature = await makeSignature(value, secret)241 value = `${value}.${signature}`242 value = encodeURIComponent(value)243 return _serialize(name, value, opt)244}