Timo Hocker
cc8762e4ec
All checks were successful
continuous-integration/drone/push Build is passing
79 lines
2.0 KiB
TypeScript
79 lines
2.0 KiB
TypeScript
import { run_regex } from '@sapphirecode/utilities';
|
|
import { debug } from './debug';
|
|
|
|
const logger = debug ('cookies');
|
|
|
|
type SameSiteValue = 'Lax' | 'None' | 'Strict';
|
|
|
|
interface CookieSettings {
|
|
name: string;
|
|
secure?: boolean;
|
|
http_only?: boolean;
|
|
same_site?: SameSiteValue|null;
|
|
expires?: string;
|
|
max_age?: number;
|
|
domain?: string;
|
|
path?: string;
|
|
}
|
|
|
|
const default_settings: Omit<CookieSettings, 'name'> = {
|
|
secure: true,
|
|
http_only: true,
|
|
same_site: 'Strict'
|
|
};
|
|
|
|
function build_cookie (
|
|
settings: CookieSettings,
|
|
value: string
|
|
): string {
|
|
const local_settings = { ...default_settings, ...settings };
|
|
const sections = [ `${local_settings.name}=${value}` ];
|
|
|
|
if (local_settings.secure)
|
|
sections.push ('Secure');
|
|
if (local_settings.http_only)
|
|
sections.push ('HttpOnly');
|
|
if (
|
|
typeof local_settings.same_site !== 'undefined'
|
|
&& local_settings.same_site !== null
|
|
)
|
|
sections.push (`SameSite=${local_settings.same_site}`);
|
|
if (typeof local_settings.expires !== 'undefined')
|
|
sections.push (`Expires=${local_settings.expires}`);
|
|
if (typeof local_settings.max_age !== 'undefined')
|
|
sections.push (`Max-Age=${local_settings.max_age}`);
|
|
if (typeof local_settings.domain !== 'undefined')
|
|
sections.push (`Domain=${local_settings.domain}`);
|
|
if (typeof local_settings.path !== 'undefined')
|
|
sections.push (`Path=${local_settings.path}`);
|
|
|
|
return sections.join ('; ');
|
|
}
|
|
|
|
function extract_cookie (
|
|
name: string|undefined,
|
|
header: string|undefined
|
|
): string| null {
|
|
logger (`extracting cookie ${name}`);
|
|
|
|
const cookie_regex = /(?:^|;)\s*(?<name>[^;=]+)=(?<value>[^;]+)/gu;
|
|
|
|
let result = null;
|
|
|
|
run_regex (
|
|
cookie_regex,
|
|
header,
|
|
(res: RegExpMatchArray) => {
|
|
logger ('parsing cookie %s', res.groups?.name);
|
|
if (res.groups?.name === name) {
|
|
logger ('found cookie');
|
|
result = res.groups?.value as string;
|
|
}
|
|
}
|
|
);
|
|
|
|
return result;
|
|
}
|
|
|
|
export { build_cookie, extract_cookie, SameSiteValue, CookieSettings };
|