You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/src/http/kernel/HTTPCookieJar.ts

141 lines
3.4 KiB

import {Request} from "../lifecycle/Request";
import {uninfer, infer, uuid_v4} from "@extollo/util";
/**
* Base type representing a parsed cookie.
*/
export interface HTTPCookie {
key: string,
originalValue: string,
value: any,
exists: boolean,
options?: HTTPCookieOptions,
}
export type MaybeHTTPCookie = HTTPCookie | undefined;
export interface HTTPCookieOptions {
domain?: string,
expires?: Date, // encodeURIComponent
httpOnly?: boolean,
maxAge?: number,
path?: string,
secure?: boolean,
signed?: boolean,
sameSite?: 'strict' | 'lax' | 'none-secure',
}
export class HTTPCookieJar {
protected parsed: {[key: string]: HTTPCookie} = {}
constructor(
protected request: Request,
) {
this.parseCookies()
}
get(name: string): MaybeHTTPCookie {
if ( name in this.parsed ) {
return this.parsed[name]
}
}
set(name: string, value: any, options?: HTTPCookieOptions) {
this.parsed[name] = {
key: name,
value,
originalValue: uninfer(value),
exists: false,
options,
}
}
has(name: string) {
return !!this.parsed[name]
}
clear(name: string, options?: HTTPCookieOptions) {
if ( !options ) options = {}
options.expires = new Date(0)
this.parsed[name] = {
key: name,
value: undefined,
originalValue: uuid_v4(),
exists: false,
options,
}
}
getSetCookieHeaders(): string[] {
const headers: string[] = []
for ( const key in this.parsed ) {
if ( !this.parsed.hasOwnProperty(key) ) continue
const cookie = this.parsed[key]
if ( cookie.exists ) continue
const parts = []
parts.push(`${key}=${encodeURIComponent(cookie.originalValue)}`)
if ( cookie.options?.expires ) {
parts.push(`Expires=${cookie.options.expires.toUTCString()}`)
}
if ( cookie.options?.maxAge ) {
parts.push(`Max-Age=${Math.floor(cookie.options.maxAge)}`)
}
if ( cookie.options?.domain ) {
parts.push(`Domain=${cookie.options.domain}`)
}
if ( cookie.options?.path ) {
parts.push(`Path=${cookie.options.path}`)
}
if ( cookie.options?.secure ) {
parts.push('Secure')
}
if ( cookie.options?.httpOnly ) {
parts.push('HttpOnly')
}
if ( cookie.options?.sameSite ) {
const map = {
strict: 'Strict',
lax: 'Lax',
'none-secure': 'None; Secure'
}
parts.push(map[cookie.options.sameSite])
}
headers.push(parts.join('; '))
}
return headers
}
private parseCookies() {
const cookies = String(this.request.getHeader('cookie'))
cookies.split(';').forEach(cookie => {
const parts = cookie.split('=')
const key = parts.shift()?.trim()
if ( !key ) return;
const value = decodeURI(parts.join('='))
this.parsed[key] = {
key,
originalValue: value,
value: infer(value),
exists: true,
}
})
}
}