import { createHmac, timingSafeEqual } from 'crypto'; import { CookieGetOptions, Cookies, CookieSetOptions } from './cookies-protocol'; /** RFC 7230 field-content: what a cookie name or value may hold. */ const FIELD_CONTENT = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; const SAME_SITE = /^(?:lax|none|strict)$/i; const PRIORITY = /^(?:low|medium|high)$/i; /** `(?:^|;) *=([^;]*)` per cookie name; names come from code, so there are few. */ const PATTERNS = new Map(); /** Same signatures as keygrip (HMAC-SHA1, base64url): cookies signed by Cell 4.1 stay valid. */ function sign(data: string, key: string): string { return createHmac('sha1', key).update(data).digest('base64url'); } function equals(a: string, b: string): boolean { const x = Buffer.from(a); const y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); } function escape(name: string): string { return name.replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&'); } /** * Cookies of the current request and response. Signed cookies (when `web.cookies.keys` are set) carry a * `.sig` cookie made with the first key; any of the keys verifies it, and a cookie signed with an * older key is signed again with the first. */ export class CookiesImpl implements Cookies { constructor(protected readonly request: any, protected readonly response: any, protected readonly keys?: string[], protected readonly secure?: boolean) { } get(name: string, opts?: CookieGetOptions): string | undefined { const header = this.request.headers.cookie as string | undefined; if (!header) { return; } const value = this.read(header, name); // As the cookies package: the signature is only checked when options are passed. const signed = opts?.signed ?? !!this.keys?.length; if (value === undefined || !opts || !signed) { return value; } const sigName = `${name}.sig`; const signature = this.read(header, sigName); if (!signature) { return; } const index = this.keys ? this.keys.findIndex(key => equals(sign(`${name}=${value}`, key), signature)) : -1; if (index < 0) { this.set(sigName, null, { path: '/', signed: false }); return; } if (index > 0) { this.set(sigName, sign(`${name}=${value}`, this.keys![0]), { signed: false }); } return value; } set(name: string, value?: string | null, opts: CookieSetOptions = {}): this { const secure = this.secure !== undefined ? this.secure : this.request.protocol === 'https' || !!this.request.connection?.encrypted; if (!secure && opts.secure) { throw new Error('Cannot send secure cookie over unencrypted connection'); } const signed = opts.signed ?? !!this.keys?.length; if (signed && !this.keys?.length) { throw new Error('.keys required for signed cookies'); } // An empty value deletes the cookie, and its signature with it. const expires = !value ? new Date(0) : opts.maxAge ? new Date(Date.now() + opts.maxAge) : opts.expires; const cookies = [this.serialize(name, value || '', expires, opts)]; if (signed) { cookies.push(this.serialize(`${name}.sig`, sign(`${name}=${value || ''}`, this.keys![0]), expires, opts)); } const existing = this.response.getHeader('Set-Cookie'); let headers: string[] = existing === undefined ? [] : Array.isArray(existing) ? existing : [String(existing)]; if (opts.overwrite) { const prefixes = [`${name}=`, `${name}.sig=`]; headers = headers.filter(header => !prefixes.some(prefix => header.startsWith(prefix))); } this.response.setHeader('Set-Cookie', [...headers, ...cookies]); return this; } protected read(header: string, name: string): string | undefined { let pattern = PATTERNS.get(name); if (!pattern) { pattern = new RegExp(`(?:^|;) *${escape(name)}=([^;]*)`); if (PATTERNS.size < 1000) { PATTERNS.set(name, pattern); } } return pattern.exec(header)?.[1]; } protected serialize(name: string, value: string, expires: Date | undefined, opts: CookieSetOptions): string { if (!FIELD_CONTENT.test(name) || /[=;]/.test(name)) { throw new TypeError('argument name is invalid'); } if (value && !FIELD_CONTENT.test(value)) { throw new TypeError('argument value is invalid'); } let header = `${name}=${value}; path=${opts.path ?? '/'}`; if (expires) { header += `; expires=${expires.toUTCString()}`; } if (opts.domain) { header += `; domain=${opts.domain}`; } if (opts.priority) { if (!PRIORITY.test(opts.priority)) { throw new TypeError('option priority is invalid'); } header += `; priority=${opts.priority.toLowerCase()}`; } if (opts.sameSite) { const sameSite = opts.sameSite === true ? 'strict' : String(opts.sameSite); if (!SAME_SITE.test(sameSite)) { throw new TypeError('option sameSite is invalid'); } header += `; samesite=${sameSite.toLowerCase()}`; } if (opts.secure) { header += '; secure'; } if (opts.httpOnly !== false) { header += '; httponly'; } if (opts.partitioned) { header += '; partitioned'; } return header; } }