Set up comprehensive frontend testing infrastructure

- Install Jest for unit testing with React Testing Library
- Install Playwright for end-to-end testing
- Configure Jest with proper TypeScript support and module mapping
- Create test setup files and utilities for both unit and e2e tests

Components:
* Jest configuration with coverage thresholds
* Playwright configuration with browser automation
* Unit tests for LoginForm, AuthContext, and useSocketIO hook
* E2E tests for authentication, dashboard, and agents workflows
* GitHub Actions workflow for automated testing
* Mock data and API utilities for consistent testing
* Test documentation with best practices

Testing features:
- Unit tests with 70% coverage threshold
- E2E tests with API mocking and user journey testing
- CI/CD integration for automated test runs
- Cross-browser testing support with Playwright
- Authentication system testing end-to-end

🚀 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-07-11 14:06:34 +10:00
parent c6d69695a8
commit aacb45156b
6109 changed files with 777927 additions and 1 deletions

View File

@@ -0,0 +1,33 @@
import type { Nullable } from '../utils';
/**
* Transforms a domain name into a canonical domain name. The canonical domain name is a domain name
* that has been trimmed, lowercased, stripped of leading dot, and optionally punycode-encoded
* ({@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.2 | Section 5.1.2 of RFC 6265}). For
* the most part, this function is idempotent (calling the function with the output from a previous call
* returns the same output).
*
* @remarks
* A canonicalized host name is the string generated by the following
* algorithm:
*
* 1. Convert the host name to a sequence of individual domain name
* labels.
*
* 2. Convert each label that is not a Non-Reserved LDH (NR-LDH) label,
* to an A-label (see Section 2.3.2.1 of [RFC5890] for the former
* and latter), or to a "punycode label" (a label resulting from the
* "ToASCII" conversion in Section 4 of [RFC3490]), as appropriate
* (see Section 6.3 of this specification).
*
* 3. Concatenate the resulting labels, separated by a %x2E (".")
* character.
*
* @example
* ```
* canonicalDomain('.EXAMPLE.com') === 'example.com'
* ```
*
* @param domainName - the domain name to generate the canonical domain from
* @public
*/
export declare function canonicalDomain(domainName: Nullable<string>): string | undefined;

View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canonicalDomain = canonicalDomain;
const constants_1 = require("./constants");
/**
* Normalizes a domain to lowercase and punycode-encoded.
* Runtime-agnostic equivalent to node's `domainToASCII`.
* @see https://nodejs.org/docs/latest-v22.x/api/url.html#urldomaintoasciidomain
*/
function domainToASCII(domain) {
return new URL(`http://${domain}`).hostname;
}
/**
* Transforms a domain name into a canonical domain name. The canonical domain name is a domain name
* that has been trimmed, lowercased, stripped of leading dot, and optionally punycode-encoded
* ({@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.2 | Section 5.1.2 of RFC 6265}). For
* the most part, this function is idempotent (calling the function with the output from a previous call
* returns the same output).
*
* @remarks
* A canonicalized host name is the string generated by the following
* algorithm:
*
* 1. Convert the host name to a sequence of individual domain name
* labels.
*
* 2. Convert each label that is not a Non-Reserved LDH (NR-LDH) label,
* to an A-label (see Section 2.3.2.1 of [RFC5890] for the former
* and latter), or to a "punycode label" (a label resulting from the
* "ToASCII" conversion in Section 4 of [RFC3490]), as appropriate
* (see Section 6.3 of this specification).
*
* 3. Concatenate the resulting labels, separated by a %x2E (".")
* character.
*
* @example
* ```
* canonicalDomain('.EXAMPLE.com') === 'example.com'
* ```
*
* @param domainName - the domain name to generate the canonical domain from
* @public
*/
function canonicalDomain(domainName) {
if (domainName == null) {
return undefined;
}
let str = domainName.trim().replace(/^\./, ''); // S4.1.2.3 & S5.2.3: ignore leading .
if (constants_1.IP_V6_REGEX_OBJECT.test(str)) {
if (!str.startsWith('[')) {
str = '[' + str;
}
if (!str.endsWith(']')) {
str = str + ']';
}
return domainToASCII(str).slice(1, -1); // remove [ and ]
}
// convert to IDN if any non-ASCII characters
// eslint-disable-next-line no-control-regex
if (/[^\u0001-\u007f]/.test(str)) {
return domainToASCII(str);
}
// ASCII-only domain - not canonicalized with new URL() because it may be a malformed URL
return str.toLowerCase();
}

View File

@@ -0,0 +1,54 @@
/**
* Cookie prefixes are a way to indicate that a given cookie was set with a set of attributes simply by inspecting the
* first few characters of the cookie's name. These are defined in {@link https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3 | RFC6265bis - Section 4.1.3}.
*
* The following values can be used to configure how a {@link CookieJar} enforces attribute restrictions for Cookie prefixes:
*
* - `silent` - Enable cookie prefix checking but silently ignores the cookie if conditions are not met. This is the default configuration for a {@link CookieJar}.
*
* - `strict` - Enables cookie prefix checking and will raise an error if conditions are not met.
*
* - `unsafe-disabled` - Disables cookie prefix checking.
* @public
*/
export declare const PrefixSecurityEnum: {
readonly SILENT: "silent";
readonly STRICT: "strict";
readonly DISABLED: "unsafe-disabled";
};
export declare const IP_V6_REGEX_OBJECT: RegExp;
/**
* A JSON representation of a {@link CookieJar}.
* @public
*/
export interface SerializedCookieJar {
/**
* The version of `tough-cookie` used during serialization.
*/
version: string;
/**
* The name of the store used during serialization.
*/
storeType: string | null;
/**
* The value of {@link CreateCookieJarOptions.rejectPublicSuffixes} configured on the {@link CookieJar}.
*/
rejectPublicSuffixes: boolean;
/**
* Other configuration settings on the {@link CookieJar}.
*/
[key: string]: unknown;
/**
* The list of {@link Cookie} values serialized as JSON objects.
*/
cookies: SerializedCookie[];
}
/**
* A JSON object that is created when {@link Cookie.toJSON} is called. This object will contain the properties defined in {@link Cookie.serializableProperties}.
* @public
*/
export type SerializedCookie = {
key?: string;
value?: string;
[key: string]: unknown;
};

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IP_V6_REGEX_OBJECT = exports.PrefixSecurityEnum = void 0;
/**
* Cookie prefixes are a way to indicate that a given cookie was set with a set of attributes simply by inspecting the
* first few characters of the cookie's name. These are defined in {@link https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3 | RFC6265bis - Section 4.1.3}.
*
* The following values can be used to configure how a {@link CookieJar} enforces attribute restrictions for Cookie prefixes:
*
* - `silent` - Enable cookie prefix checking but silently ignores the cookie if conditions are not met. This is the default configuration for a {@link CookieJar}.
*
* - `strict` - Enables cookie prefix checking and will raise an error if conditions are not met.
*
* - `unsafe-disabled` - Disables cookie prefix checking.
* @public
*/
exports.PrefixSecurityEnum = {
SILENT: 'silent',
STRICT: 'strict',
DISABLED: 'unsafe-disabled',
};
Object.freeze(exports.PrefixSecurityEnum);
const IP_V6_REGEX = `
\\[?(?:
(?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)|
(?:[a-fA-F\\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|:[a-fA-F\\d]{1,4}|:)|
(?:[a-fA-F\\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,2}|:)|
(?:[a-fA-F\\d]{1,4}:){4}(?:(?::[a-fA-F\\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,3}|:)|
(?:[a-fA-F\\d]{1,4}:){3}(?:(?::[a-fA-F\\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,4}|:)|
(?:[a-fA-F\\d]{1,4}:){2}(?:(?::[a-fA-F\\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,5}|:)|
(?:[a-fA-F\\d]{1,4}:){1}(?:(?::[a-fA-F\\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,6}|:)|
(?::(?:(?::[a-fA-F\\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,7}|:))
)(?:%[0-9a-zA-Z]{1,})?\\]?
`
.replace(/\s*\/\/.*$/gm, '')
.replace(/\n/g, '')
.trim();
exports.IP_V6_REGEX_OBJECT = new RegExp(`^${IP_V6_REGEX}$`);

View File

@@ -0,0 +1,326 @@
import type { SerializedCookie } from './constants';
/**
* Optional configuration to be used when parsing cookies.
* @public
*/
export interface ParseCookieOptions {
/**
* If `true` then keyless cookies like `=abc` and `=` which are not RFC-compliant will be parsed.
*/
loose?: boolean | undefined;
}
/**
* Configurable values that can be set when creating a {@link Cookie}.
* @public
*/
export interface CreateCookieOptions {
/** {@inheritDoc Cookie.key} */
key?: string;
/** {@inheritDoc Cookie.value} */
value?: string;
/** {@inheritDoc Cookie.expires} */
expires?: Date | 'Infinity' | null;
/** {@inheritDoc Cookie.maxAge} */
maxAge?: number | 'Infinity' | '-Infinity' | null;
/** {@inheritDoc Cookie.domain} */
domain?: string | null;
/** {@inheritDoc Cookie.path} */
path?: string | null;
/** {@inheritDoc Cookie.secure} */
secure?: boolean;
/** {@inheritDoc Cookie.httpOnly} */
httpOnly?: boolean;
/** {@inheritDoc Cookie.extensions} */
extensions?: string[] | null;
/** {@inheritDoc Cookie.creation} */
creation?: Date | 'Infinity' | null;
/** {@inheritDoc Cookie.hostOnly} */
hostOnly?: boolean | null;
/** {@inheritDoc Cookie.pathIsDefault} */
pathIsDefault?: boolean | null;
/** {@inheritDoc Cookie.lastAccessed} */
lastAccessed?: Date | 'Infinity' | null;
/** {@inheritDoc Cookie.sameSite} */
sameSite?: string | undefined;
}
/**
* An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser.
* It is defined in {@link https://www.rfc-editor.org/rfc/rfc6265.html | RFC6265}.
* @public
*/
export declare class Cookie {
/**
* The name or key of the cookie
*/
key: string;
/**
* The value of the cookie
*/
value: string;
/**
* The 'Expires' attribute of the cookie
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.1 | RFC6265 Section 5.2.1}).
*/
expires: Date | 'Infinity' | null;
/**
* The 'Max-Age' attribute of the cookie
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.2 | RFC6265 Section 5.2.2}).
*/
maxAge: number | 'Infinity' | '-Infinity' | null;
/**
* The 'Domain' attribute of the cookie represents the domain the cookie belongs to
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.3 | RFC6265 Section 5.2.3}).
*/
domain: string | null;
/**
* The 'Path' attribute of the cookie represents the path of the cookie
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.4 | RFC6265 Section 5.2.4}).
*/
path: string | null;
/**
* The 'Secure' flag of the cookie indicates if the scope of the cookie is
* limited to secure channels (e.g.; HTTPS) or not
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.5 | RFC6265 Section 5.2.5}).
*/
secure: boolean;
/**
* The 'HttpOnly' flag of the cookie indicates if the cookie is inaccessible to
* client scripts or not
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.6 | RFC6265 Section 5.2.6}).
*/
httpOnly: boolean;
/**
* Contains attributes which are not part of the defined spec but match the `extension-av` syntax
* defined in Section 4.1.1 of RFC6265
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-4.1.1 | RFC6265 Section 4.1.1}).
*/
extensions: string[] | null;
/**
* Set to the date and time when a Cookie is initially stored or a matching cookie is
* received that replaces an existing cookie
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 Section 5.3}).
*
* Also used to maintain ordering among cookies. Among cookies that have equal-length path fields,
* cookies with earlier creation-times are listed before cookies with later creation-times
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 Section 5.4}).
*/
creation: Date | 'Infinity' | null;
/**
* A global counter used to break ordering ties between two cookies that have equal-length path fields
* and the same creation-time.
*/
creationIndex: number;
/**
* A boolean flag indicating if a cookie is a host-only cookie (i.e.; when the request's host exactly
* matches the domain of the cookie) or not
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 Section 5.3}).
*/
hostOnly: boolean | null;
/**
* A boolean flag indicating if a cookie had no 'Path' attribute and the default path
* was used
* (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.4 | RFC6265 Section 5.2.4}).
*/
pathIsDefault: boolean | null;
/**
* Set to the date and time when a cookie was initially stored ({@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 Section 5.3}) and updated whenever
* the cookie is retrieved from the {@link CookieJar} ({@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 Section 5.4}).
*/
lastAccessed: Date | 'Infinity' | null;
/**
* The 'SameSite' attribute of a cookie as defined in RFC6265bis
* (See {@link https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-13.html#section-5.2 | RFC6265bis (v13) Section 5.2 }).
*/
sameSite: string | undefined;
/**
* Create a new Cookie instance.
* @public
* @param options - The attributes to set on the cookie
*/
constructor(options?: CreateCookieOptions);
/**
* For convenience in using `JSON.stringify(cookie)`. Returns a plain-old Object that can be JSON-serialized.
*
* @remarks
* - Any `Date` properties (such as {@link Cookie.expires}, {@link Cookie.creation}, and {@link Cookie.lastAccessed}) are exported in ISO format (`Date.toISOString()`).
*
* - Custom Cookie properties are discarded. In tough-cookie 1.x, since there was no {@link Cookie.toJSON} method explicitly defined, all enumerable properties were captured.
* If you want a property to be serialized, add the property name to {@link Cookie.serializableProperties}.
*/
toJSON(): SerializedCookie;
/**
* Does a deep clone of this cookie, implemented exactly as `Cookie.fromJSON(cookie.toJSON())`.
* @public
*/
clone(): Cookie | undefined;
/**
* Validates cookie attributes for semantic correctness. Useful for "lint" checking any `Set-Cookie` headers you generate.
* For now, it returns a boolean, but eventually could return a reason string.
*
* @remarks
* Works for a few things, but is by no means comprehensive.
*
* @beta
*/
validate(): boolean;
/**
* Sets the 'Expires' attribute on a cookie.
*
* @remarks
* When given a `string` value it will be parsed with {@link parseDate}. If the value can't be parsed as a cookie date
* then the 'Expires' attribute will be set to `"Infinity"`.
*
* @param exp - the new value for the 'Expires' attribute of the cookie.
*/
setExpires(exp: string | Date): void;
/**
* Sets the 'Max-Age' attribute (in seconds) on a cookie.
*
* @remarks
* Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it can be serialized to JSON.
*
* @param age - the new value for the 'Max-Age' attribute (in seconds).
*/
setMaxAge(age: number): void;
/**
* Encodes to a `Cookie` header value (specifically, the {@link Cookie.key} and {@link Cookie.value} properties joined with "=").
* @public
*/
cookieString(): string;
/**
* Encodes to a `Set-Cookie header` value.
* @public
*/
toString(): string;
/**
* Computes the TTL relative to now (milliseconds).
*
* @remarks
* - `Infinity` is returned for cookies without an explicit expiry
*
* - `0` is returned if the cookie is expired.
*
* - Otherwise a time-to-live in milliseconds is returned.
*
* @param now - passing an explicit value is mostly used for testing purposes since this defaults to the `Date.now()`
* @public
*/
TTL(now?: number): number;
/**
* Computes the absolute unix-epoch milliseconds that this cookie expires.
*
* The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
* (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
*
* If Expires ({@link Cookie.expires}) is set, that's returned.
*
* @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
*/
expiryTime(now?: Date): number | undefined;
/**
* Similar to {@link Cookie.expiryTime}, computes the absolute unix-epoch milliseconds that this cookie expires and returns it as a Date.
*
* The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
* (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
*
* If Expires ({@link Cookie.expires}) is set, that's returned.
*
* @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
*/
expiryDate(now?: Date): Date | undefined;
/**
* Indicates if the cookie has been persisted to a store or not.
* @public
*/
isPersistent(): boolean;
/**
* Calls {@link canonicalDomain} with the {@link Cookie.domain} property.
* @public
*/
canonicalizedDomain(): string | undefined;
/**
* Alias for {@link Cookie.canonicalizedDomain}
* @public
*/
cdomain(): string | undefined;
/**
* Parses a string into a Cookie object.
*
* @remarks
* Note: when parsing a `Cookie` header it must be split by ';' before each Cookie string can be parsed.
*
* @example
* ```
* // parse a `Set-Cookie` header
* const setCookieHeader = 'a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT'
* const cookie = Cookie.parse(setCookieHeader)
* cookie.key === 'a'
* cookie.value === 'bcd'
* cookie.expires === new Date(Date.parse('Tue, 18 Oct 2011 07:05:03 GMT'))
* ```
*
* @example
* ```
* // parse a `Cookie` header
* const cookieHeader = 'name=value; name2=value2; name3=value3'
* const cookies = cookieHeader.split(';').map(Cookie.parse)
* cookies[0].name === 'name'
* cookies[0].value === 'value'
* cookies[1].name === 'name2'
* cookies[1].value === 'value2'
* cookies[2].name === 'name3'
* cookies[2].value === 'value3'
* ```
*
* @param str - The `Set-Cookie` header or a Cookie string to parse.
* @param options - Configures `strict` or `loose` mode for cookie parsing
*/
static parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
/**
* Does the reverse of {@link Cookie.toJSON}.
*
* @remarks
* Any Date properties (such as .expires, .creation, and .lastAccessed) are parsed via Date.parse, not tough-cookie's parseDate, since ISO timestamps are being handled at this layer.
*
* @example
* ```
* const json = JSON.stringify({
* key: 'alpha',
* value: 'beta',
* domain: 'example.com',
* path: '/foo',
* expires: '2038-01-19T03:14:07.000Z',
* })
* const cookie = Cookie.fromJSON(json)
* cookie.key === 'alpha'
* cookie.value === 'beta'
* cookie.domain === 'example.com'
* cookie.path === '/foo'
* cookie.expires === new Date(Date.parse('2038-01-19T03:14:07.000Z'))
* ```
*
* @param str - An unparsed JSON string or a value that has already been parsed as JSON
*/
static fromJSON(str: unknown): Cookie | undefined;
private static cookiesCreated;
/**
* @internal
*/
static sameSiteLevel: {
readonly strict: 3;
readonly lax: 2;
readonly none: 1;
};
/**
* @internal
*/
static sameSiteCanonical: {
readonly strict: "Strict";
readonly lax: "Lax";
};
/**
* Cookie properties that will be serialized when using {@link Cookie.fromJSON} and {@link Cookie.toJSON}.
* @public
*/
static serializableProperties: readonly ["key", "value", "expires", "maxAge", "domain", "path", "secure", "httpOnly", "extensions", "hostOnly", "pathIsDefault", "creation", "lastAccessed", "sameSite"];
}

View File

@@ -0,0 +1,831 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cookie = void 0;
/*!
* Copyright (c) 2015-2020, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
const getPublicSuffix_1 = require("../getPublicSuffix");
const validators = __importStar(require("../validators"));
const utils_1 = require("../utils");
const formatDate_1 = require("./formatDate");
const parseDate_1 = require("./parseDate");
const canonicalDomain_1 = require("./canonicalDomain");
// From RFC6265 S4.1.1
// note that it excludes \x3B ";"
const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
// Note ';' is \x3B
const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
// eslint-disable-next-line no-control-regex
const CONTROL_CHARS = /[\x00-\x1F]/;
// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
// the "relaxed" mode, see:
// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
const TERMINATORS = ['\n', '\r', '\0'];
function trimTerminator(str) {
if (validators.isEmptyString(str))
return str;
for (let t = 0; t < TERMINATORS.length; t++) {
const terminator = TERMINATORS[t];
const terminatorIdx = terminator ? str.indexOf(terminator) : -1;
if (terminatorIdx !== -1) {
str = str.slice(0, terminatorIdx);
}
}
return str;
}
function parseCookiePair(cookiePair, looseMode) {
cookiePair = trimTerminator(cookiePair);
let firstEq = cookiePair.indexOf('=');
if (looseMode) {
if (firstEq === 0) {
// '=' is immediately at start
cookiePair = cookiePair.substring(1);
firstEq = cookiePair.indexOf('='); // might still need to split on '='
}
}
else {
// non-loose mode
if (firstEq <= 0) {
// no '=' or is at start
return undefined; // needs to have non-empty "cookie-name"
}
}
let cookieName, cookieValue;
if (firstEq <= 0) {
cookieName = '';
cookieValue = cookiePair.trim();
}
else {
cookieName = cookiePair.slice(0, firstEq).trim();
cookieValue = cookiePair.slice(firstEq + 1).trim();
}
if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
return undefined;
}
const c = new Cookie();
c.key = cookieName;
c.value = cookieValue;
return c;
}
function parse(str, options) {
if (validators.isEmptyString(str) || !validators.isString(str)) {
return undefined;
}
str = str.trim();
// We use a regex to parse the "name-value-pair" part of S5.2
const firstSemi = str.indexOf(';'); // S5.2 step 1
const cookiePair = firstSemi === -1 ? str : str.slice(0, firstSemi);
const c = parseCookiePair(cookiePair, options?.loose ?? false);
if (!c) {
return undefined;
}
if (firstSemi === -1) {
return c;
}
// S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
// (including the %x3B (";") in question)." plus later on in the same section
// "discard the first ";" and trim".
const unparsed = str.slice(firstSemi + 1).trim();
// "If the unparsed-attributes string is empty, skip the rest of these
// steps."
if (unparsed.length === 0) {
return c;
}
/*
* S5.2 says that when looping over the items "[p]rocess the attribute-name
* and attribute-value according to the requirements in the following
* subsections" for every item. Plus, for many of the individual attributes
* in S5.3 it says to use the "attribute-value of the last attribute in the
* cookie-attribute-list". Therefore, in this implementation, we overwrite
* the previous value.
*/
const cookie_avs = unparsed.split(';');
while (cookie_avs.length) {
const av = (cookie_avs.shift() ?? '').trim();
if (av.length === 0) {
// happens if ";;" appears
continue;
}
const av_sep = av.indexOf('=');
let av_key, av_value;
if (av_sep === -1) {
av_key = av;
av_value = null;
}
else {
av_key = av.slice(0, av_sep);
av_value = av.slice(av_sep + 1);
}
av_key = av_key.trim().toLowerCase();
if (av_value) {
av_value = av_value.trim();
}
switch (av_key) {
case 'expires': // S5.2.1
if (av_value) {
const exp = (0, parseDate_1.parseDate)(av_value);
// "If the attribute-value failed to parse as a cookie date, ignore the
// cookie-av."
if (exp) {
// over and underflow not realistically a concern: V8's getTime() seems to
// store something larger than a 32-bit time_t (even with 32-bit node)
c.expires = exp;
}
}
break;
case 'max-age': // S5.2.2
if (av_value) {
// "If the first character of the attribute-value is not a DIGIT or a "-"
// character ...[or]... If the remainder of attribute-value contains a
// non-DIGIT character, ignore the cookie-av."
if (/^-?[0-9]+$/.test(av_value)) {
const delta = parseInt(av_value, 10);
// "If delta-seconds is less than or equal to zero (0), let expiry-time
// be the earliest representable date and time."
c.setMaxAge(delta);
}
}
break;
case 'domain': // S5.2.3
// "If the attribute-value is empty, the behavior is undefined. However,
// the user agent SHOULD ignore the cookie-av entirely."
if (av_value) {
// S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
// (".") character."
const domain = av_value.trim().replace(/^\./, '');
if (domain) {
// "Convert the cookie-domain to lower case."
c.domain = domain.toLowerCase();
}
}
break;
case 'path': // S5.2.4
/*
* "If the attribute-value is empty or if the first character of the
* attribute-value is not %x2F ("/"):
* Let cookie-path be the default-path.
* Otherwise:
* Let cookie-path be the attribute-value."
*
* We'll represent the default-path as null since it depends on the
* context of the parsing.
*/
c.path = av_value && av_value[0] === '/' ? av_value : null;
break;
case 'secure': // S5.2.5
/*
* "If the attribute-name case-insensitively matches the string "Secure",
* the user agent MUST append an attribute to the cookie-attribute-list
* with an attribute-name of Secure and an empty attribute-value."
*/
c.secure = true;
break;
case 'httponly': // S5.2.6 -- effectively the same as 'secure'
c.httpOnly = true;
break;
case 'samesite': // RFC6265bis-02 S5.3.7
switch (av_value ? av_value.toLowerCase() : '') {
case 'strict':
c.sameSite = 'strict';
break;
case 'lax':
c.sameSite = 'lax';
break;
case 'none':
c.sameSite = 'none';
break;
default:
c.sameSite = undefined;
break;
}
break;
default:
c.extensions = c.extensions || [];
c.extensions.push(av);
break;
}
}
return c;
}
function fromJSON(str) {
if (!str || validators.isEmptyString(str)) {
return undefined;
}
let obj;
if (typeof str === 'string') {
try {
obj = JSON.parse(str);
}
catch {
return undefined;
}
}
else {
// assume it's an Object
obj = str;
}
const c = new Cookie();
Cookie.serializableProperties.forEach((prop) => {
if (obj && typeof obj === 'object' && (0, utils_1.inOperator)(prop, obj)) {
const val = obj[prop];
if (val === undefined) {
return;
}
if ((0, utils_1.inOperator)(prop, cookieDefaults) && val === cookieDefaults[prop]) {
return;
}
switch (prop) {
case 'key':
case 'value':
case 'sameSite':
if (typeof val === 'string') {
c[prop] = val;
}
break;
case 'expires':
case 'creation':
case 'lastAccessed':
if (typeof val === 'number' ||
typeof val === 'string' ||
val instanceof Date) {
c[prop] = obj[prop] == 'Infinity' ? 'Infinity' : new Date(val);
}
else if (val === null) {
c[prop] = null;
}
break;
case 'maxAge':
if (typeof val === 'number' ||
val === 'Infinity' ||
val === '-Infinity') {
c[prop] = val;
}
break;
case 'domain':
case 'path':
if (typeof val === 'string' || val === null) {
c[prop] = val;
}
break;
case 'secure':
case 'httpOnly':
if (typeof val === 'boolean') {
c[prop] = val;
}
break;
case 'extensions':
if (Array.isArray(val) &&
val.every((item) => typeof item === 'string')) {
c[prop] = val;
}
break;
case 'hostOnly':
case 'pathIsDefault':
if (typeof val === 'boolean' || val === null) {
c[prop] = val;
}
break;
}
}
});
return c;
}
const cookieDefaults = {
// the order in which the RFC has them:
key: '',
value: '',
expires: 'Infinity',
maxAge: null,
domain: null,
path: null,
secure: false,
httpOnly: false,
extensions: null,
// set by the CookieJar:
hostOnly: null,
pathIsDefault: null,
creation: null,
lastAccessed: null,
sameSite: undefined,
};
/**
* An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser.
* It is defined in {@link https://www.rfc-editor.org/rfc/rfc6265.html | RFC6265}.
* @public
*/
class Cookie {
/**
* Create a new Cookie instance.
* @public
* @param options - The attributes to set on the cookie
*/
constructor(options = {}) {
this.key = options.key ?? cookieDefaults.key;
this.value = options.value ?? cookieDefaults.value;
this.expires = options.expires ?? cookieDefaults.expires;
this.maxAge = options.maxAge ?? cookieDefaults.maxAge;
this.domain = options.domain ?? cookieDefaults.domain;
this.path = options.path ?? cookieDefaults.path;
this.secure = options.secure ?? cookieDefaults.secure;
this.httpOnly = options.httpOnly ?? cookieDefaults.httpOnly;
this.extensions = options.extensions ?? cookieDefaults.extensions;
this.creation = options.creation ?? cookieDefaults.creation;
this.hostOnly = options.hostOnly ?? cookieDefaults.hostOnly;
this.pathIsDefault = options.pathIsDefault ?? cookieDefaults.pathIsDefault;
this.lastAccessed = options.lastAccessed ?? cookieDefaults.lastAccessed;
this.sameSite = options.sameSite ?? cookieDefaults.sameSite;
this.creation = options.creation ?? new Date();
// used to break creation ties in cookieCompare():
Object.defineProperty(this, 'creationIndex', {
configurable: false,
enumerable: false, // important for assert.deepEqual checks
writable: true,
value: ++Cookie.cookiesCreated,
});
// Duplicate operation, but it makes TypeScript happy...
this.creationIndex = Cookie.cookiesCreated;
}
[Symbol.for('nodejs.util.inspect.custom')]() {
const now = Date.now();
const hostOnly = this.hostOnly != null ? this.hostOnly.toString() : '?';
const createAge = this.creation && this.creation !== 'Infinity'
? `${String(now - this.creation.getTime())}ms`
: '?';
const accessAge = this.lastAccessed && this.lastAccessed !== 'Infinity'
? `${String(now - this.lastAccessed.getTime())}ms`
: '?';
return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`;
}
/**
* For convenience in using `JSON.stringify(cookie)`. Returns a plain-old Object that can be JSON-serialized.
*
* @remarks
* - Any `Date` properties (such as {@link Cookie.expires}, {@link Cookie.creation}, and {@link Cookie.lastAccessed}) are exported in ISO format (`Date.toISOString()`).
*
* - Custom Cookie properties are discarded. In tough-cookie 1.x, since there was no {@link Cookie.toJSON} method explicitly defined, all enumerable properties were captured.
* If you want a property to be serialized, add the property name to {@link Cookie.serializableProperties}.
*/
toJSON() {
const obj = {};
for (const prop of Cookie.serializableProperties) {
const val = this[prop];
if (val === cookieDefaults[prop]) {
continue; // leave as prototype default
}
switch (prop) {
case 'key':
case 'value':
case 'sameSite':
if (typeof val === 'string') {
obj[prop] = val;
}
break;
case 'expires':
case 'creation':
case 'lastAccessed':
if (typeof val === 'number' ||
typeof val === 'string' ||
val instanceof Date) {
obj[prop] =
val == 'Infinity' ? 'Infinity' : new Date(val).toISOString();
}
else if (val === null) {
obj[prop] = null;
}
break;
case 'maxAge':
if (typeof val === 'number' ||
val === 'Infinity' ||
val === '-Infinity') {
obj[prop] = val;
}
break;
case 'domain':
case 'path':
if (typeof val === 'string' || val === null) {
obj[prop] = val;
}
break;
case 'secure':
case 'httpOnly':
if (typeof val === 'boolean') {
obj[prop] = val;
}
break;
case 'extensions':
if (Array.isArray(val)) {
obj[prop] = val;
}
break;
case 'hostOnly':
case 'pathIsDefault':
if (typeof val === 'boolean' || val === null) {
obj[prop] = val;
}
break;
}
}
return obj;
}
/**
* Does a deep clone of this cookie, implemented exactly as `Cookie.fromJSON(cookie.toJSON())`.
* @public
*/
clone() {
return fromJSON(this.toJSON());
}
/**
* Validates cookie attributes for semantic correctness. Useful for "lint" checking any `Set-Cookie` headers you generate.
* For now, it returns a boolean, but eventually could return a reason string.
*
* @remarks
* Works for a few things, but is by no means comprehensive.
*
* @beta
*/
validate() {
if (!this.value || !COOKIE_OCTETS.test(this.value)) {
return false;
}
if (this.expires != 'Infinity' &&
!(this.expires instanceof Date) &&
!(0, parseDate_1.parseDate)(this.expires)) {
return false;
}
if (this.maxAge != null &&
this.maxAge !== 'Infinity' &&
(this.maxAge === '-Infinity' || this.maxAge <= 0)) {
return false; // "Max-Age=" non-zero-digit *DIGIT
}
if (this.path != null && !PATH_VALUE.test(this.path)) {
return false;
}
const cdomain = this.cdomain();
if (cdomain) {
if (cdomain.match(/\.$/)) {
return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
}
const suffix = (0, getPublicSuffix_1.getPublicSuffix)(cdomain);
if (suffix == null) {
// it's a public suffix
return false;
}
}
return true;
}
/**
* Sets the 'Expires' attribute on a cookie.
*
* @remarks
* When given a `string` value it will be parsed with {@link parseDate}. If the value can't be parsed as a cookie date
* then the 'Expires' attribute will be set to `"Infinity"`.
*
* @param exp - the new value for the 'Expires' attribute of the cookie.
*/
setExpires(exp) {
if (exp instanceof Date) {
this.expires = exp;
}
else {
this.expires = (0, parseDate_1.parseDate)(exp) || 'Infinity';
}
}
/**
* Sets the 'Max-Age' attribute (in seconds) on a cookie.
*
* @remarks
* Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it can be serialized to JSON.
*
* @param age - the new value for the 'Max-Age' attribute (in seconds).
*/
setMaxAge(age) {
if (age === Infinity) {
this.maxAge = 'Infinity';
}
else if (age === -Infinity) {
this.maxAge = '-Infinity';
}
else {
this.maxAge = age;
}
}
/**
* Encodes to a `Cookie` header value (specifically, the {@link Cookie.key} and {@link Cookie.value} properties joined with "=").
* @public
*/
cookieString() {
const val = this.value || '';
if (this.key) {
return `${this.key}=${val}`;
}
return val;
}
/**
* Encodes to a `Set-Cookie header` value.
* @public
*/
toString() {
let str = this.cookieString();
if (this.expires != 'Infinity') {
if (this.expires instanceof Date) {
str += `; Expires=${(0, formatDate_1.formatDate)(this.expires)}`;
}
}
if (this.maxAge != null && this.maxAge != Infinity) {
str += `; Max-Age=${String(this.maxAge)}`;
}
if (this.domain && !this.hostOnly) {
str += `; Domain=${this.domain}`;
}
if (this.path) {
str += `; Path=${this.path}`;
}
if (this.secure) {
str += '; Secure';
}
if (this.httpOnly) {
str += '; HttpOnly';
}
if (this.sameSite && this.sameSite !== 'none') {
if (this.sameSite.toLowerCase() ===
Cookie.sameSiteCanonical.lax.toLowerCase()) {
str += `; SameSite=${Cookie.sameSiteCanonical.lax}`;
}
else if (this.sameSite.toLowerCase() ===
Cookie.sameSiteCanonical.strict.toLowerCase()) {
str += `; SameSite=${Cookie.sameSiteCanonical.strict}`;
}
else {
str += `; SameSite=${this.sameSite}`;
}
}
if (this.extensions) {
this.extensions.forEach((ext) => {
str += `; ${ext}`;
});
}
return str;
}
/**
* Computes the TTL relative to now (milliseconds).
*
* @remarks
* - `Infinity` is returned for cookies without an explicit expiry
*
* - `0` is returned if the cookie is expired.
*
* - Otherwise a time-to-live in milliseconds is returned.
*
* @param now - passing an explicit value is mostly used for testing purposes since this defaults to the `Date.now()`
* @public
*/
TTL(now = Date.now()) {
// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere)
// S5.3 says to give the "latest representable date" for which we use Infinity
// For "expired" we use 0
// -----
// RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
// attribute, the Max-Age attribute has precedence and controls the
// expiration date of the cookie.
// (Concurs with S5.3 step 3)
if (this.maxAge != null && typeof this.maxAge === 'number') {
return this.maxAge <= 0 ? 0 : this.maxAge * 1000;
}
const expires = this.expires;
if (expires === 'Infinity') {
return Infinity;
}
return (expires?.getTime() ?? now) - (now || Date.now());
}
/**
* Computes the absolute unix-epoch milliseconds that this cookie expires.
*
* The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
* (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
*
* If Expires ({@link Cookie.expires}) is set, that's returned.
*
* @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
*/
expiryTime(now) {
// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() elsewhere)
if (this.maxAge != null) {
const relativeTo = now || this.lastAccessed || new Date();
const maxAge = typeof this.maxAge === 'number' ? this.maxAge : -Infinity;
const age = maxAge <= 0 ? -Infinity : maxAge * 1000;
if (relativeTo === 'Infinity') {
return Infinity;
}
return relativeTo.getTime() + age;
}
if (this.expires == 'Infinity') {
return Infinity;
}
return this.expires ? this.expires.getTime() : undefined;
}
/**
* Similar to {@link Cookie.expiryTime}, computes the absolute unix-epoch milliseconds that this cookie expires and returns it as a Date.
*
* The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
* (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
*
* If Expires ({@link Cookie.expires}) is set, that's returned.
*
* @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
*/
expiryDate(now) {
const millisec = this.expiryTime(now);
if (millisec == Infinity) {
// The 31-bit value of 2147483647000 was chosen to be the MAX_TIME representable
// in tough-cookie though MDN states that the actual maximum value for a Date is 8.64e15.
// I'm guessing this is due to the Y2038 problem that would affect systems that store
// unix time as 32-bit integers.
// See:
// - https://github.com/salesforce/tough-cookie/commit/0616f70bf725e00c63d442544ad230c4f8b23357
// - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// - https://en.wikipedia.org/wiki/Year_2038_problem
return new Date(2147483647000);
}
else if (millisec == -Infinity) {
return new Date(0);
}
else {
return millisec == undefined ? undefined : new Date(millisec);
}
}
/**
* Indicates if the cookie has been persisted to a store or not.
* @public
*/
isPersistent() {
// This replaces the "persistent-flag" parts of S5.3 step 3
return this.maxAge != null || this.expires != 'Infinity';
}
/**
* Calls {@link canonicalDomain} with the {@link Cookie.domain} property.
* @public
*/
canonicalizedDomain() {
// Mostly S5.1.2 and S5.2.3:
return (0, canonicalDomain_1.canonicalDomain)(this.domain);
}
/**
* Alias for {@link Cookie.canonicalizedDomain}
* @public
*/
cdomain() {
return (0, canonicalDomain_1.canonicalDomain)(this.domain);
}
/**
* Parses a string into a Cookie object.
*
* @remarks
* Note: when parsing a `Cookie` header it must be split by ';' before each Cookie string can be parsed.
*
* @example
* ```
* // parse a `Set-Cookie` header
* const setCookieHeader = 'a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT'
* const cookie = Cookie.parse(setCookieHeader)
* cookie.key === 'a'
* cookie.value === 'bcd'
* cookie.expires === new Date(Date.parse('Tue, 18 Oct 2011 07:05:03 GMT'))
* ```
*
* @example
* ```
* // parse a `Cookie` header
* const cookieHeader = 'name=value; name2=value2; name3=value3'
* const cookies = cookieHeader.split(';').map(Cookie.parse)
* cookies[0].name === 'name'
* cookies[0].value === 'value'
* cookies[1].name === 'name2'
* cookies[1].value === 'value2'
* cookies[2].name === 'name3'
* cookies[2].value === 'value3'
* ```
*
* @param str - The `Set-Cookie` header or a Cookie string to parse.
* @param options - Configures `strict` or `loose` mode for cookie parsing
*/
static parse(str, options) {
return parse(str, options);
}
/**
* Does the reverse of {@link Cookie.toJSON}.
*
* @remarks
* Any Date properties (such as .expires, .creation, and .lastAccessed) are parsed via Date.parse, not tough-cookie's parseDate, since ISO timestamps are being handled at this layer.
*
* @example
* ```
* const json = JSON.stringify({
* key: 'alpha',
* value: 'beta',
* domain: 'example.com',
* path: '/foo',
* expires: '2038-01-19T03:14:07.000Z',
* })
* const cookie = Cookie.fromJSON(json)
* cookie.key === 'alpha'
* cookie.value === 'beta'
* cookie.domain === 'example.com'
* cookie.path === '/foo'
* cookie.expires === new Date(Date.parse('2038-01-19T03:14:07.000Z'))
* ```
*
* @param str - An unparsed JSON string or a value that has already been parsed as JSON
*/
static fromJSON(str) {
return fromJSON(str);
}
}
exports.Cookie = Cookie;
Cookie.cookiesCreated = 0;
/**
* @internal
*/
Cookie.sameSiteLevel = {
strict: 3,
lax: 2,
none: 1,
};
/**
* @internal
*/
Cookie.sameSiteCanonical = {
strict: 'Strict',
lax: 'Lax',
};
/**
* Cookie properties that will be serialized when using {@link Cookie.fromJSON} and {@link Cookie.toJSON}.
* @public
*/
Cookie.serializableProperties = [
'key',
'value',
'expires',
'maxAge',
'domain',
'path',
'secure',
'httpOnly',
'extensions',
'hostOnly',
'pathIsDefault',
'creation',
'lastAccessed',
'sameSite',
];

View File

@@ -0,0 +1,58 @@
import type { Cookie } from './cookie';
/**
* A comparison function that can be used with {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort | Array.sort()},
* which orders a list of cookies into the recommended order given in Step 2 of {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 - Section 5.4}.
*
* The sort algorithm is, in order of precedence:
*
* - Longest {@link Cookie.path}
*
* - Oldest {@link Cookie.creation} (which has a 1-ms precision, same as Date)
*
* - Lowest {@link Cookie.creationIndex} (to get beyond the 1-ms precision)
*
* @remarks
* ### RFC6265 - Section 5.4 - Step 2
*
* The user agent SHOULD sort the cookie-list in the following order:
*
* - Cookies with longer paths are listed before cookies with shorter paths.
*
* - Among cookies that have equal-length path fields, cookies with
* earlier creation-times are listed before cookies with later
* creation-times.
*
* NOTE: Not all user agents sort the cookie-list in this order, but
* this order reflects common practice when this document was
* written, and, historically, there have been servers that
* (erroneously) depended on this order.
*
* ### Custom Store Implementors
*
* Since the JavaScript Date is limited to a 1-ms precision, cookies within the same millisecond are entirely possible.
* This is especially true when using the `now` option to `CookieJar.setCookie(...)`. The {@link Cookie.creationIndex}
* property is a per-process global counter, assigned during construction with `new Cookie()`, which preserves the spirit
* of the RFC sorting: older cookies go first. This works great for {@link MemoryCookieStore} since `Set-Cookie` headers
* are parsed in order, but is not so great for distributed systems.
*
* Sophisticated Stores may wish to set this to some other
* logical clock so that if cookies `A` and `B` are created in the same millisecond, but cookie `A` is created before
* cookie `B`, then `A.creationIndex < B.creationIndex`.
*
* @example
* ```
* const cookies = [
* new Cookie({ key: 'a', value: '' }),
* new Cookie({ key: 'b', value: '' }),
* new Cookie({ key: 'c', value: '', path: '/path' }),
* new Cookie({ key: 'd', value: '', path: '/path' }),
* ]
* cookies.sort(cookieCompare)
* // cookie sort order would be ['c', 'd', 'a', 'b']
* ```
*
* @param a - the first Cookie for comparison
* @param b - the second Cookie for comparison
* @public
*/
export declare function cookieCompare(a: Cookie, b: Cookie): number;

View File

@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cookieCompare = cookieCompare;
/**
* The maximum timestamp a cookie, in milliseconds. The value is (2^31 - 1) seconds since the Unix
* epoch, corresponding to 2038-01-19.
*/
const MAX_TIME = 2147483647000;
/**
* A comparison function that can be used with {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort | Array.sort()},
* which orders a list of cookies into the recommended order given in Step 2 of {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 - Section 5.4}.
*
* The sort algorithm is, in order of precedence:
*
* - Longest {@link Cookie.path}
*
* - Oldest {@link Cookie.creation} (which has a 1-ms precision, same as Date)
*
* - Lowest {@link Cookie.creationIndex} (to get beyond the 1-ms precision)
*
* @remarks
* ### RFC6265 - Section 5.4 - Step 2
*
* The user agent SHOULD sort the cookie-list in the following order:
*
* - Cookies with longer paths are listed before cookies with shorter paths.
*
* - Among cookies that have equal-length path fields, cookies with
* earlier creation-times are listed before cookies with later
* creation-times.
*
* NOTE: Not all user agents sort the cookie-list in this order, but
* this order reflects common practice when this document was
* written, and, historically, there have been servers that
* (erroneously) depended on this order.
*
* ### Custom Store Implementors
*
* Since the JavaScript Date is limited to a 1-ms precision, cookies within the same millisecond are entirely possible.
* This is especially true when using the `now` option to `CookieJar.setCookie(...)`. The {@link Cookie.creationIndex}
* property is a per-process global counter, assigned during construction with `new Cookie()`, which preserves the spirit
* of the RFC sorting: older cookies go first. This works great for {@link MemoryCookieStore} since `Set-Cookie` headers
* are parsed in order, but is not so great for distributed systems.
*
* Sophisticated Stores may wish to set this to some other
* logical clock so that if cookies `A` and `B` are created in the same millisecond, but cookie `A` is created before
* cookie `B`, then `A.creationIndex < B.creationIndex`.
*
* @example
* ```
* const cookies = [
* new Cookie({ key: 'a', value: '' }),
* new Cookie({ key: 'b', value: '' }),
* new Cookie({ key: 'c', value: '', path: '/path' }),
* new Cookie({ key: 'd', value: '', path: '/path' }),
* ]
* cookies.sort(cookieCompare)
* // cookie sort order would be ['c', 'd', 'a', 'b']
* ```
*
* @param a - the first Cookie for comparison
* @param b - the second Cookie for comparison
* @public
*/
function cookieCompare(a, b) {
let cmp;
// descending for length: b CMP a
const aPathLen = a.path ? a.path.length : 0;
const bPathLen = b.path ? b.path.length : 0;
cmp = bPathLen - aPathLen;
if (cmp !== 0) {
return cmp;
}
// ascending for time: a CMP b
const aTime = a.creation && a.creation instanceof Date ? a.creation.getTime() : MAX_TIME;
const bTime = b.creation && b.creation instanceof Date ? b.creation.getTime() : MAX_TIME;
cmp = aTime - bTime;
if (cmp !== 0) {
return cmp;
}
// break ties for the same millisecond (precision of JavaScript's clock)
cmp = (a.creationIndex || 0) - (b.creationIndex || 0);
return cmp;
}

View File

@@ -0,0 +1,621 @@
import { Store } from '../store';
import { Cookie } from './cookie';
import { Callback, ErrorCallback, Nullable } from '../utils';
import { SerializedCookieJar } from './constants';
/**
* Configuration options used when calling `CookieJar.setCookie(...)`
* @public
*/
export interface SetCookieOptions {
/**
* Controls if a cookie string should be parsed using `loose` mode or not.
* See {@link Cookie.parse} and {@link ParseCookieOptions} for more details.
*
* Defaults to `false` if not provided.
*/
loose?: boolean | undefined;
/**
* Set this to 'none', 'lax', or 'strict' to enforce SameSite cookies upon storage.
*
* - `'strict'` - If the request is on the same "site for cookies" (see the RFC draft
* for more information), pass this option to add a layer of defense against CSRF.
*
* - `'lax'` - If the request is from another site, but is directly because of navigation
* by the user, such as, `<link type=prefetch>` or `<a href="...">`, then use `lax`.
*
* - `'none'` - This indicates a cross-origin request.
*
* - `undefined` - SameSite is not be enforced! This can be a valid use-case for when
* CSRF isn't in the threat model of the system being built.
*
* Defaults to `undefined` if not provided.
*
* @remarks
* - It is highly recommended that you read {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02##section-8.8 | RFC6265bis - Section 8.8}
* which discusses security considerations and defence on SameSite cookies in depth.
*/
sameSiteContext?: 'strict' | 'lax' | 'none' | undefined;
/**
* Silently ignore things like parse errors and invalid domains. Store errors aren't ignored by this option.
*
* Defaults to `false` if not provided.
*/
ignoreError?: boolean | undefined;
/**
* Indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.
*
* Defaults to `true` if not provided.
*/
http?: boolean | undefined;
/**
* Forces the cookie creation and access time of cookies to this value when stored.
*
* Defaults to `Date.now()` if not provided.
*/
now?: Date | undefined;
}
/**
* Configuration options used when calling `CookieJar.getCookies(...)`.
* @public
*/
export interface GetCookiesOptions {
/**
* Indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.
*
* Defaults to `true` if not provided.
*/
http?: boolean | undefined;
/**
* Perform `expiry-time` checking of cookies and asynchronously remove expired
* cookies from the store.
*
* @remarks
* - Using `false` returns expired cookies and does not remove them from the
* store which is potentially useful for replaying `Set-Cookie` headers.
*
* Defaults to `true` if not provided.
*/
expire?: boolean | undefined;
/**
* If `true`, do not scope cookies by path. If `false`, then RFC-compliant path scoping will be used.
*
* @remarks
* - May not be supported by the underlying store (the default {@link MemoryCookieStore} supports it).
*
* Defaults to `false` if not provided.
*/
allPaths?: boolean | undefined;
/**
* Set this to 'none', 'lax', or 'strict' to enforce SameSite cookies upon retrieval.
*
* - `'strict'` - If the request is on the same "site for cookies" (see the RFC draft
* for more information), pass this option to add a layer of defense against CSRF.
*
* - `'lax'` - If the request is from another site, but is directly because of navigation
* by the user, such as, `<link type=prefetch>` or `<a href="...">`, then use `lax`.
*
* - `'none'` - This indicates a cross-origin request.
*
* - `undefined` - SameSite is not be enforced! This can be a valid use-case for when
* CSRF isn't in the threat model of the system being built.
*
* Defaults to `undefined` if not provided.
*
* @remarks
* - It is highly recommended that you read {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02##section-8.8 | RFC6265bis - Section 8.8}
* which discusses security considerations and defence on SameSite cookies in depth.
*/
sameSiteContext?: 'none' | 'lax' | 'strict' | undefined;
/**
* Flag to indicate if the returned cookies should be sorted or not.
*
* Defaults to `undefined` if not provided.
*/
sort?: boolean | undefined;
}
/**
* Configuration settings to be used with a {@link CookieJar}.
* @public
*/
export interface CreateCookieJarOptions {
/**
* Reject cookies that match those defined in the {@link https://publicsuffix.org/ | Public Suffix List} (e.g.; domains like "com" and "co.uk").
*
* Defaults to `true` if not specified.
*/
rejectPublicSuffixes?: boolean | undefined;
/**
* Accept malformed cookies like `bar` and `=bar`, which have an implied empty name but are not RFC-compliant.
*
* Defaults to `false` if not specified.
*/
looseMode?: boolean | undefined;
/**
* Controls how cookie prefixes are handled. See {@link PrefixSecurityEnum}.
*
* Defaults to `silent` if not specified.
*/
prefixSecurity?: 'strict' | 'silent' | 'unsafe-disabled' | undefined;
/**
* Accepts {@link https://datatracker.ietf.org/doc/html/rfc6761 | special-use domains } such as `local`.
* This is not in the standard, but is used sometimes on the web and is accepted by most browsers. It is
* also useful for testing purposes.
*
* Defaults to `true` if not specified.
*/
allowSpecialUseDomain?: boolean | undefined;
}
/**
* A CookieJar is for storage and retrieval of {@link Cookie} objects as defined in
* {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 - Section 5.3}.
*
* It also supports a pluggable persistence layer via {@link Store}.
* @public
*/
export declare class CookieJar {
private readonly rejectPublicSuffixes;
private readonly enableLooseMode;
private readonly allowSpecialUseDomain;
/**
* The configured {@link Store} for the {@link CookieJar}.
*/
readonly store: Store;
/**
* The configured {@link PrefixSecurityEnum} value for the {@link CookieJar}.
*/
readonly prefixSecurity: string;
/**
* Creates a new `CookieJar` instance.
*
* @remarks
* - If a custom store is not passed to the constructor, an in-memory store ({@link MemoryCookieStore} will be created and used.
* - If a boolean value is passed as the `options` parameter, this is equivalent to passing `{ rejectPublicSuffixes: <value> }`
*
* @param store - a custom {@link Store} implementation (defaults to {@link MemoryCookieStore})
* @param options - configures how cookies are processed by the cookie jar
*/
constructor(store?: Nullable<Store>, options?: CreateCookieJarOptions | boolean);
private callSync;
/**
* Attempt to set the {@link Cookie} in the {@link CookieJar}.
*
* @remarks
* - If successfully persisted, the {@link Cookie} will have updated
* {@link Cookie.creation}, {@link Cookie.lastAccessed} and {@link Cookie.hostOnly}
* properties.
*
* - As per the RFC, the {@link Cookie.hostOnly} flag is set if there was no `Domain={value}`
* atttribute on the cookie string. The {@link Cookie.domain} property is set to the
* fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an
* exact hostname match (not a {@link domainMatch} as per usual)
*
* @param cookie - The cookie object or cookie string to store. A string value will be parsed into a cookie using {@link Cookie.parse}.
* @param url - The domain to store the cookie with.
* @param callback - A function to call after a cookie has been successfully stored.
* @public
*/
setCookie(cookie: string | Cookie, url: string | URL, callback: Callback<Cookie | undefined>): void;
/**
* Attempt to set the {@link Cookie} in the {@link CookieJar}.
*
* @remarks
* - If successfully persisted, the {@link Cookie} will have updated
* {@link Cookie.creation}, {@link Cookie.lastAccessed} and {@link Cookie.hostOnly}
* properties.
*
* - As per the RFC, the {@link Cookie.hostOnly} flag is set if there was no `Domain={value}`
* atttribute on the cookie string. The {@link Cookie.domain} property is set to the
* fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an
* exact hostname match (not a {@link domainMatch} as per usual)
*
* @param cookie - The cookie object or cookie string to store. A string value will be parsed into a cookie using {@link Cookie.parse}.
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when storing the cookie.
* @param callback - A function to call after a cookie has been successfully stored.
* @public
*/
setCookie(cookie: string | Cookie, url: string | URL, options: SetCookieOptions, callback: Callback<Cookie | undefined>): void;
/**
* Attempt to set the {@link Cookie} in the {@link CookieJar}.
*
* @remarks
* - If successfully persisted, the {@link Cookie} will have updated
* {@link Cookie.creation}, {@link Cookie.lastAccessed} and {@link Cookie.hostOnly}
* properties.
*
* - As per the RFC, the {@link Cookie.hostOnly} flag is set if there was no `Domain={value}`
* atttribute on the cookie string. The {@link Cookie.domain} property is set to the
* fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an
* exact hostname match (not a {@link domainMatch} as per usual)
*
* @param cookie - The cookie object or cookie string to store. A string value will be parsed into a cookie using {@link Cookie.parse}.
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when storing the cookie.
* @public
*/
setCookie(cookie: string | Cookie, url: string | URL, options?: SetCookieOptions): Promise<Cookie | undefined>;
/**
* @internal No doc because this is an overload that supports the implementation
*/
setCookie(cookie: string | Cookie, url: string | URL, options: SetCookieOptions | Callback<Cookie | undefined>, callback?: Callback<Cookie | undefined>): unknown;
/**
* Synchronously attempt to set the {@link Cookie} in the {@link CookieJar}.
*
* <strong>Note:</strong> Only works if the configured {@link Store} is also synchronous.
*
* @remarks
* - If successfully persisted, the {@link Cookie} will have updated
* {@link Cookie.creation}, {@link Cookie.lastAccessed} and {@link Cookie.hostOnly}
* properties.
*
* - As per the RFC, the {@link Cookie.hostOnly} flag is set if there was no `Domain={value}`
* atttribute on the cookie string. The {@link Cookie.domain} property is set to the
* fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an
* exact hostname match (not a {@link domainMatch} as per usual)
*
* @param cookie - The cookie object or cookie string to store. A string value will be parsed into a cookie using {@link Cookie.parse}.
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when storing the cookie.
* @public
*/
setCookieSync(cookie: string | Cookie, url: string, options?: SetCookieOptions): Cookie | undefined;
/**
* Retrieve the list of cookies that can be sent in a Cookie header for the
* current URL.
*
* @remarks
* - The array of cookies returned will be sorted according to {@link cookieCompare}.
*
* - The {@link Cookie.lastAccessed} property will be updated on all returned cookies.
*
* @param url - The domain to store the cookie with.
*/
getCookies(url: string): Promise<Cookie[]>;
/**
* Retrieve the list of cookies that can be sent in a Cookie header for the
* current URL.
*
* @remarks
* - The array of cookies returned will be sorted according to {@link cookieCompare}.
*
* - The {@link Cookie.lastAccessed} property will be updated on all returned cookies.
*
* @param url - The domain to store the cookie with.
* @param callback - A function to call after a cookie has been successfully retrieved.
*/
getCookies(url: string, callback: Callback<Cookie[]>): void;
/**
* Retrieve the list of cookies that can be sent in a Cookie header for the
* current URL.
*
* @remarks
* - The array of cookies returned will be sorted according to {@link cookieCompare}.
*
* - The {@link Cookie.lastAccessed} property will be updated on all returned cookies.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
* @param callback - A function to call after a cookie has been successfully retrieved.
*/
getCookies(url: string | URL, options: GetCookiesOptions | undefined, callback: Callback<Cookie[]>): void;
/**
* Retrieve the list of cookies that can be sent in a Cookie header for the
* current URL.
*
* @remarks
* - The array of cookies returned will be sorted according to {@link cookieCompare}.
*
* - The {@link Cookie.lastAccessed} property will be updated on all returned cookies.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
*/
getCookies(url: string | URL, options?: GetCookiesOptions): Promise<Cookie[]>;
/**
* @internal No doc because this is an overload that supports the implementation
*/
getCookies(url: string | URL, options: GetCookiesOptions | undefined | Callback<Cookie[]>, callback?: Callback<Cookie[]>): unknown;
/**
* Synchronously retrieve the list of cookies that can be sent in a Cookie header for the
* current URL.
*
* <strong>Note</strong>: Only works if the configured Store is also synchronous.
*
* @remarks
* - The array of cookies returned will be sorted according to {@link cookieCompare}.
*
* - The {@link Cookie.lastAccessed} property will be updated on all returned cookies.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
*/
getCookiesSync(url: string, options?: GetCookiesOptions): Cookie[];
/**
* Accepts the same options as `.getCookies()` but returns a string suitable for a
* `Cookie` header rather than an Array.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
* @param callback - A function to call after the `Cookie` header string has been created.
*/
getCookieString(url: string, options: GetCookiesOptions, callback: Callback<string | undefined>): void;
/**
* Accepts the same options as `.getCookies()` but returns a string suitable for a
* `Cookie` header rather than an Array.
*
* @param url - The domain to store the cookie with.
* @param callback - A function to call after the `Cookie` header string has been created.
*/
getCookieString(url: string, callback: Callback<string | undefined>): void;
/**
* Accepts the same options as `.getCookies()` but returns a string suitable for a
* `Cookie` header rather than an Array.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
*/
getCookieString(url: string, options?: GetCookiesOptions): Promise<string>;
/**
* @internal No doc because this is an overload that supports the implementation
*/
getCookieString(url: string, options: GetCookiesOptions | Callback<string | undefined>, callback?: Callback<string | undefined>): unknown;
/**
* Synchronous version of `.getCookieString()`. Accepts the same options as `.getCookies()` but returns a string suitable for a
* `Cookie` header rather than an Array.
*
* <strong>Note</strong>: Only works if the configured Store is also synchronous.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
*/
getCookieStringSync(url: string, options?: GetCookiesOptions): string;
/**
* Returns an array of strings suitable for `Set-Cookie` headers. Accepts the same options
* as `.getCookies()`.
*
* @param url - The domain to store the cookie with.
* @param callback - A function to call after the `Set-Cookie` header strings have been created.
*/
getSetCookieStrings(url: string, callback: Callback<string[] | undefined>): void;
/**
* Returns an array of strings suitable for `Set-Cookie` headers. Accepts the same options
* as `.getCookies()`.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
* @param callback - A function to call after the `Set-Cookie` header strings have been created.
*/
getSetCookieStrings(url: string, options: GetCookiesOptions, callback: Callback<string[] | undefined>): void;
/**
* Returns an array of strings suitable for `Set-Cookie` headers. Accepts the same options
* as `.getCookies()`.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
*/
getSetCookieStrings(url: string, options?: GetCookiesOptions): Promise<string[] | undefined>;
/**
* @internal No doc because this is an overload that supports the implementation
*/
getSetCookieStrings(url: string, options: GetCookiesOptions, callback?: Callback<string[] | undefined>): unknown;
/**
* Synchronous version of `.getSetCookieStrings()`. Returns an array of strings suitable for `Set-Cookie` headers.
* Accepts the same options as `.getCookies()`.
*
* <strong>Note</strong>: Only works if the configured Store is also synchronous.
*
* @param url - The domain to store the cookie with.
* @param options - Configuration settings to use when retrieving the cookies.
*/
getSetCookieStringsSync(url: string, options?: GetCookiesOptions): string[];
/**
* Serialize the CookieJar if the underlying store supports `.getAllCookies`.
* @param callback - A function to call after the CookieJar has been serialized
*/
serialize(callback: Callback<SerializedCookieJar>): void;
/**
* Serialize the CookieJar if the underlying store supports `.getAllCookies`.
*/
serialize(): Promise<SerializedCookieJar>;
/**
* Serialize the CookieJar if the underlying store supports `.getAllCookies`.
*
* <strong>Note</strong>: Only works if the configured Store is also synchronous.
*/
serializeSync(): SerializedCookieJar | undefined;
/**
* Alias of {@link CookieJar.serializeSync}. Allows the cookie to be serialized
* with `JSON.stringify(cookieJar)`.
*/
toJSON(): SerializedCookieJar | undefined;
/**
* Use the class method CookieJar.deserialize instead of calling this directly
* @internal
*/
_importCookies(serialized: unknown, callback: Callback<CookieJar>): void;
/**
* @internal
*/
_importCookiesSync(serialized: unknown): void;
/**
* Produces a deep clone of this CookieJar. Modifications to the original do
* not affect the clone, and vice versa.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - Transferring between store types is supported so long as the source
* implements `.getAllCookies()` and the destination implements `.putCookie()`.
*
* @param callback - A function to call when the CookieJar is cloned.
*/
clone(callback: Callback<CookieJar>): void;
/**
* Produces a deep clone of this CookieJar. Modifications to the original do
* not affect the clone, and vice versa.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - Transferring between store types is supported so long as the source
* implements `.getAllCookies()` and the destination implements `.putCookie()`.
*
* @param newStore - The target {@link Store} to clone cookies into.
* @param callback - A function to call when the CookieJar is cloned.
*/
clone(newStore: Store, callback: Callback<CookieJar>): void;
/**
* Produces a deep clone of this CookieJar. Modifications to the original do
* not affect the clone, and vice versa.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - Transferring between store types is supported so long as the source
* implements `.getAllCookies()` and the destination implements `.putCookie()`.
*
* @param newStore - The target {@link Store} to clone cookies into.
*/
clone(newStore?: Store): Promise<CookieJar>;
/**
* @internal
*/
_cloneSync(newStore?: Store): CookieJar | undefined;
/**
* Produces a deep clone of this CookieJar. Modifications to the original do
* not affect the clone, and vice versa.
*
* <strong>Note</strong>: Only works if both the configured Store and destination
* Store are synchronous.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - Transferring between store types is supported so long as the source
* implements `.getAllCookies()` and the destination implements `.putCookie()`.
*
* @param newStore - The target {@link Store} to clone cookies into.
*/
cloneSync(newStore?: Store): CookieJar | undefined;
/**
* Removes all cookies from the CookieJar.
*
* @remarks
* - This is a new backwards-compatible feature of tough-cookie version 2.5,
* so not all Stores will implement it efficiently. For Stores that do not
* implement `removeAllCookies`, the fallback is to call `removeCookie` after
* `getAllCookies`.
*
* - If `getAllCookies` fails or isn't implemented in the Store, an error is returned.
*
* - If one or more of the `removeCookie` calls fail, only the first error is returned.
*
* @param callback - A function to call when all the cookies have been removed.
*/
removeAllCookies(callback: ErrorCallback): void;
/**
* Removes all cookies from the CookieJar.
*
* @remarks
* - This is a new backwards-compatible feature of tough-cookie version 2.5,
* so not all Stores will implement it efficiently. For Stores that do not
* implement `removeAllCookies`, the fallback is to call `removeCookie` after
* `getAllCookies`.
*
* - If `getAllCookies` fails or isn't implemented in the Store, an error is returned.
*
* - If one or more of the `removeCookie` calls fail, only the first error is returned.
*/
removeAllCookies(): Promise<void>;
/**
* Removes all cookies from the CookieJar.
*
* <strong>Note</strong>: Only works if the configured Store is also synchronous.
*
* @remarks
* - This is a new backwards-compatible feature of tough-cookie version 2.5,
* so not all Stores will implement it efficiently. For Stores that do not
* implement `removeAllCookies`, the fallback is to call `removeCookie` after
* `getAllCookies`.
*
* - If `getAllCookies` fails or isn't implemented in the Store, an error is returned.
*
* - If one or more of the `removeCookie` calls fail, only the first error is returned.
*/
removeAllCookiesSync(): void;
/**
* A new CookieJar is created and the serialized {@link Cookie} values are added to
* the underlying store. Each {@link Cookie} is added via `store.putCookie(...)` in
* the order in which they appear in the serialization.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
*
* @param strOrObj - A JSON string or object representing the deserialized cookies.
* @param callback - A function to call after the {@link CookieJar} has been deserialized.
*/
static deserialize(strOrObj: string | object, callback: Callback<CookieJar>): void;
/**
* A new CookieJar is created and the serialized {@link Cookie} values are added to
* the underlying store. Each {@link Cookie} is added via `store.putCookie(...)` in
* the order in which they appear in the serialization.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
*
* @param strOrObj - A JSON string or object representing the deserialized cookies.
* @param store - The underlying store to persist the deserialized cookies into.
* @param callback - A function to call after the {@link CookieJar} has been deserialized.
*/
static deserialize(strOrObj: string | object, store: Store, callback: Callback<CookieJar>): void;
/**
* A new CookieJar is created and the serialized {@link Cookie} values are added to
* the underlying store. Each {@link Cookie} is added via `store.putCookie(...)` in
* the order in which they appear in the serialization.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
*
* @param strOrObj - A JSON string or object representing the deserialized cookies.
* @param store - The underlying store to persist the deserialized cookies into.
*/
static deserialize(strOrObj: string | object, store?: Store): Promise<CookieJar>;
/**
* @internal No doc because this is an overload that supports the implementation
*/
static deserialize(strOrObj: string | object, store?: Store | Callback<CookieJar>, callback?: Callback<CookieJar>): unknown;
/**
* A new CookieJar is created and the serialized {@link Cookie} values are added to
* the underlying store. Each {@link Cookie} is added via `store.putCookie(...)` in
* the order in which they appear in the serialization.
*
* <strong>Note</strong>: Only works if the configured Store is also synchronous.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
*
* @param strOrObj - A JSON string or object representing the deserialized cookies.
* @param store - The underlying store to persist the deserialized cookies into.
*/
static deserializeSync(strOrObj: string | SerializedCookieJar, store?: Store): CookieJar;
/**
* Alias of {@link CookieJar.deserializeSync}.
*
* @remarks
* - When no {@link Store} is provided, a new {@link MemoryCookieStore} will be used.
*
* - As a convenience, if `strOrObj` is a string, it is passed through `JSON.parse` first.
*
* @param jsonString - A JSON string or object representing the deserialized cookies.
* @param store - The underlying store to persist the deserialized cookies into.
*/
static fromJSON(jsonString: string | SerializedCookieJar, store?: Store): CookieJar;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
import type { Nullable } from '../utils';
/**
* Given a current request/response path, gives the path appropriate for storing
* in a cookie. This is basically the "directory" of a "file" in the path, but
* is specified by {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.4 | RFC6265 - Section 5.1.4}.
*
* @remarks
* ### RFC6265 - Section 5.1.4
*
* The user agent MUST use an algorithm equivalent to the following algorithm to compute the default-path of a cookie:
*
* 1. Let uri-path be the path portion of the request-uri if such a
* portion exists (and empty otherwise). For example, if the
* request-uri contains just a path (and optional query string),
* then the uri-path is that path (without the %x3F ("?") character
* or query string), and if the request-uri contains a full
* absoluteURI, the uri-path is the path component of that URI.
*
* 2. If the uri-path is empty or if the first character of the uri-
* path is not a %x2F ("/") character, output %x2F ("/") and skip
* the remaining steps.
*
* 3. If the uri-path contains no more than one %x2F ("/") character,
* output %x2F ("/") and skip the remaining step.
*
* 4. Output the characters of the uri-path from the first character up
* to, but not including, the right-most %x2F ("/").
*
* @example
* ```
* defaultPath('') === '/'
* defaultPath('/some-path') === '/'
* defaultPath('/some-parent-path/some-path') === '/some-parent-path'
* defaultPath('relative-path') === '/'
* ```
*
* @param path - the path portion of the request-uri (excluding the hostname, query, fragment, and so on)
* @public
*/
export declare function defaultPath(path?: Nullable<string>): string;

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultPath = defaultPath;
/**
* Given a current request/response path, gives the path appropriate for storing
* in a cookie. This is basically the "directory" of a "file" in the path, but
* is specified by {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.4 | RFC6265 - Section 5.1.4}.
*
* @remarks
* ### RFC6265 - Section 5.1.4
*
* The user agent MUST use an algorithm equivalent to the following algorithm to compute the default-path of a cookie:
*
* 1. Let uri-path be the path portion of the request-uri if such a
* portion exists (and empty otherwise). For example, if the
* request-uri contains just a path (and optional query string),
* then the uri-path is that path (without the %x3F ("?") character
* or query string), and if the request-uri contains a full
* absoluteURI, the uri-path is the path component of that URI.
*
* 2. If the uri-path is empty or if the first character of the uri-
* path is not a %x2F ("/") character, output %x2F ("/") and skip
* the remaining steps.
*
* 3. If the uri-path contains no more than one %x2F ("/") character,
* output %x2F ("/") and skip the remaining step.
*
* 4. Output the characters of the uri-path from the first character up
* to, but not including, the right-most %x2F ("/").
*
* @example
* ```
* defaultPath('') === '/'
* defaultPath('/some-path') === '/'
* defaultPath('/some-parent-path/some-path') === '/some-parent-path'
* defaultPath('relative-path') === '/'
* ```
*
* @param path - the path portion of the request-uri (excluding the hostname, query, fragment, and so on)
* @public
*/
function defaultPath(path) {
// "2. If the uri-path is empty or if the first character of the uri-path is not
// a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
if (!path || path.slice(0, 1) !== '/') {
return '/';
}
// "3. If the uri-path contains no more than one %x2F ("/") character, output
// %x2F ("/") and skip the remaining step."
if (path === '/') {
return path;
}
const rightSlash = path.lastIndexOf('/');
if (rightSlash === 0) {
return '/';
}
// "4. Output the characters of the uri-path from the first character up to,
// but not including, the right-most %x2F ("/")."
return path.slice(0, rightSlash);
}

View File

@@ -0,0 +1,38 @@
import type { Nullable } from '../utils';
/**
* Answers "does this real domain match the domain in a cookie?". The `domain` is the "current" domain name and the
* `cookieDomain` is the "cookie" domain name. Matches according to {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.3 | RFC6265 - Section 5.1.3},
* but it helps to think of it as a "suffix match".
*
* @remarks
* ### 5.1.3. Domain Matching
*
* A string domain-matches a given domain string if at least one of the
* following conditions hold:
*
* - The domain string and the string are identical. (Note that both
* the domain string and the string will have been canonicalized to
* lower case at this point.)
*
* - All of the following conditions hold:
*
* - The domain string is a suffix of the string.
*
* - The last character of the string that is not included in the
* domain string is a %x2E (".") character.
*
* - The string is a host name (i.e., not an IP address).
*
* @example
* ```
* domainMatch('example.com', 'example.com') === true
* domainMatch('eXaMpLe.cOm', 'ExAmPlE.CoM') === true
* domainMatch('no.ca', 'yes.ca') === false
* ```
*
* @param domain - The domain string to test
* @param cookieDomain - The cookie domain string to match against
* @param canonicalize - The canonicalize parameter toggles whether the domain parameters get normalized with canonicalDomain or not
* @public
*/
export declare function domainMatch(domain?: Nullable<string>, cookieDomain?: Nullable<string>, canonicalize?: boolean): boolean | undefined;

View File

@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.domainMatch = domainMatch;
const canonicalDomain_1 = require("./canonicalDomain");
// Dumped from ip-regex@4.0.0, with the following changes:
// * all capturing groups converted to non-capturing -- "(?:)"
// * support for IPv6 Scoped Literal ("%eth1") removed
// * lowercase hexadecimal only
const IP_REGEX_LOWERCASE = /(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/;
/**
* Answers "does this real domain match the domain in a cookie?". The `domain` is the "current" domain name and the
* `cookieDomain` is the "cookie" domain name. Matches according to {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.3 | RFC6265 - Section 5.1.3},
* but it helps to think of it as a "suffix match".
*
* @remarks
* ### 5.1.3. Domain Matching
*
* A string domain-matches a given domain string if at least one of the
* following conditions hold:
*
* - The domain string and the string are identical. (Note that both
* the domain string and the string will have been canonicalized to
* lower case at this point.)
*
* - All of the following conditions hold:
*
* - The domain string is a suffix of the string.
*
* - The last character of the string that is not included in the
* domain string is a %x2E (".") character.
*
* - The string is a host name (i.e., not an IP address).
*
* @example
* ```
* domainMatch('example.com', 'example.com') === true
* domainMatch('eXaMpLe.cOm', 'ExAmPlE.CoM') === true
* domainMatch('no.ca', 'yes.ca') === false
* ```
*
* @param domain - The domain string to test
* @param cookieDomain - The cookie domain string to match against
* @param canonicalize - The canonicalize parameter toggles whether the domain parameters get normalized with canonicalDomain or not
* @public
*/
function domainMatch(domain, cookieDomain, canonicalize) {
if (domain == null || cookieDomain == null) {
return undefined;
}
let _str;
let _domStr;
if (canonicalize !== false) {
_str = (0, canonicalDomain_1.canonicalDomain)(domain);
_domStr = (0, canonicalDomain_1.canonicalDomain)(cookieDomain);
}
else {
_str = domain;
_domStr = cookieDomain;
}
if (_str == null || _domStr == null) {
return undefined;
}
/*
* S5.1.3:
* "A string domain-matches a given domain string if at least one of the
* following conditions hold:"
*
* " o The domain string and the string are identical. (Note that both the
* domain string and the string will have been canonicalized to lower case at
* this point)"
*/
if (_str == _domStr) {
return true;
}
/* " o All of the following [three] conditions hold:" */
/* "* The domain string is a suffix of the string" */
const idx = _str.lastIndexOf(_domStr);
if (idx <= 0) {
return false; // it's a non-match (-1) or prefix (0)
}
// next, check it's a proper suffix
// e.g., "a.b.c".indexOf("b.c") === 2
// 5 === 3+2
if (_str.length !== _domStr.length + idx) {
return false; // it's not a suffix
}
/* " * The last character of the string that is not included in the
* domain string is a %x2E (".") character." */
if (_str.substring(idx - 1, idx) !== '.') {
return false; // doesn't align on "."
}
/* " * The string is a host name (i.e., not an IP address)." */
return !IP_REGEX_LOWERCASE.test(_str);
}

View File

@@ -0,0 +1,15 @@
/**
* Format a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date} into
* the {@link https://www.rfc-editor.org/rfc/rfc2616#section-3.3.1 | preferred Internet standard format}
* defined in {@link https://www.rfc-editor.org/rfc/rfc822#section-5 | RFC822} and
* updated in {@link https://www.rfc-editor.org/rfc/rfc1123#page-55 | RFC1123}.
*
* @example
* ```
* formatDate(new Date(0)) === 'Thu, 01 Jan 1970 00:00:00 GMT`
* ```
*
* @param date - the date value to format
* @public
*/
export declare function formatDate(date: Date): string;

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatDate = formatDate;
/**
* Format a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date} into
* the {@link https://www.rfc-editor.org/rfc/rfc2616#section-3.3.1 | preferred Internet standard format}
* defined in {@link https://www.rfc-editor.org/rfc/rfc822#section-5 | RFC822} and
* updated in {@link https://www.rfc-editor.org/rfc/rfc1123#page-55 | RFC1123}.
*
* @example
* ```
* formatDate(new Date(0)) === 'Thu, 01 Jan 1970 00:00:00 GMT`
* ```
*
* @param date - the date value to format
* @public
*/
function formatDate(date) {
return date.toUTCString();
}

View File

@@ -0,0 +1,29 @@
export { MemoryCookieStore, type MemoryCookieStoreIndex } from '../memstore';
export { pathMatch } from '../pathMatch';
export { permuteDomain } from '../permuteDomain';
export { getPublicSuffix, type GetPublicSuffixOptions, } from '../getPublicSuffix';
export { Store } from '../store';
export { ParameterError } from '../validators';
export { version } from '../version';
export { type Callback, type ErrorCallback, type Nullable } from '../utils';
export { canonicalDomain } from './canonicalDomain';
export { PrefixSecurityEnum, type SerializedCookie, type SerializedCookieJar, } from './constants';
export { Cookie, type CreateCookieOptions, type ParseCookieOptions, } from './cookie';
export { cookieCompare } from './cookieCompare';
export { CookieJar, type CreateCookieJarOptions, type GetCookiesOptions, type SetCookieOptions, } from './cookieJar';
export { defaultPath } from './defaultPath';
export { domainMatch } from './domainMatch';
export { formatDate } from './formatDate';
export { parseDate } from './parseDate';
export { permutePath } from './permutePath';
import { Cookie, ParseCookieOptions } from './cookie';
/**
* {@inheritDoc Cookie.parse}
* @public
*/
export declare function parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
/**
* {@inheritDoc Cookie.fromJSON}
* @public
*/
export declare function fromJSON(str: unknown): Cookie | undefined;

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.permutePath = exports.parseDate = exports.formatDate = exports.domainMatch = exports.defaultPath = exports.CookieJar = exports.cookieCompare = exports.Cookie = exports.PrefixSecurityEnum = exports.canonicalDomain = exports.version = exports.ParameterError = exports.Store = exports.getPublicSuffix = exports.permuteDomain = exports.pathMatch = exports.MemoryCookieStore = void 0;
exports.parse = parse;
exports.fromJSON = fromJSON;
var memstore_1 = require("../memstore");
Object.defineProperty(exports, "MemoryCookieStore", { enumerable: true, get: function () { return memstore_1.MemoryCookieStore; } });
var pathMatch_1 = require("../pathMatch");
Object.defineProperty(exports, "pathMatch", { enumerable: true, get: function () { return pathMatch_1.pathMatch; } });
var permuteDomain_1 = require("../permuteDomain");
Object.defineProperty(exports, "permuteDomain", { enumerable: true, get: function () { return permuteDomain_1.permuteDomain; } });
var getPublicSuffix_1 = require("../getPublicSuffix");
Object.defineProperty(exports, "getPublicSuffix", { enumerable: true, get: function () { return getPublicSuffix_1.getPublicSuffix; } });
var store_1 = require("../store");
Object.defineProperty(exports, "Store", { enumerable: true, get: function () { return store_1.Store; } });
var validators_1 = require("../validators");
Object.defineProperty(exports, "ParameterError", { enumerable: true, get: function () { return validators_1.ParameterError; } });
var version_1 = require("../version");
Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_1.version; } });
var canonicalDomain_1 = require("./canonicalDomain");
Object.defineProperty(exports, "canonicalDomain", { enumerable: true, get: function () { return canonicalDomain_1.canonicalDomain; } });
var constants_1 = require("./constants");
Object.defineProperty(exports, "PrefixSecurityEnum", { enumerable: true, get: function () { return constants_1.PrefixSecurityEnum; } });
var cookie_1 = require("./cookie");
Object.defineProperty(exports, "Cookie", { enumerable: true, get: function () { return cookie_1.Cookie; } });
var cookieCompare_1 = require("./cookieCompare");
Object.defineProperty(exports, "cookieCompare", { enumerable: true, get: function () { return cookieCompare_1.cookieCompare; } });
var cookieJar_1 = require("./cookieJar");
Object.defineProperty(exports, "CookieJar", { enumerable: true, get: function () { return cookieJar_1.CookieJar; } });
var defaultPath_1 = require("./defaultPath");
Object.defineProperty(exports, "defaultPath", { enumerable: true, get: function () { return defaultPath_1.defaultPath; } });
var domainMatch_1 = require("./domainMatch");
Object.defineProperty(exports, "domainMatch", { enumerable: true, get: function () { return domainMatch_1.domainMatch; } });
var formatDate_1 = require("./formatDate");
Object.defineProperty(exports, "formatDate", { enumerable: true, get: function () { return formatDate_1.formatDate; } });
var parseDate_1 = require("./parseDate");
Object.defineProperty(exports, "parseDate", { enumerable: true, get: function () { return parseDate_1.parseDate; } });
var permutePath_1 = require("./permutePath");
Object.defineProperty(exports, "permutePath", { enumerable: true, get: function () { return permutePath_1.permutePath; } });
const cookie_2 = require("./cookie");
/**
* {@inheritDoc Cookie.parse}
* @public
*/
function parse(str, options) {
return cookie_2.Cookie.parse(str, options);
}
/**
* {@inheritDoc Cookie.fromJSON}
* @public
*/
function fromJSON(str) {
return cookie_2.Cookie.fromJSON(str);
}

View File

@@ -0,0 +1,103 @@
import type { Nullable } from '../utils';
/**
* Parse a cookie date string into a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date}. Parses according to
* {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.1 | RFC6265 - Section 5.1.1}, not
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse | Date.parse()}.
*
* @remarks
*
* ### RFC6265 - 5.1.1. Dates
*
* The user agent MUST use an algorithm equivalent to the following
* algorithm to parse a cookie-date. Note that the various boolean
* flags defined as a part of the algorithm (i.e., found-time, found-
* day-of-month, found-month, found-year) are initially "not set".
*
* 1. Using the grammar below, divide the cookie-date into date-tokens.
*
* ```
* cookie-date = *delimiter date-token-list *delimiter
* date-token-list = date-token *( 1*delimiter date-token )
* date-token = 1*non-delimiter
*
* delimiter = %x09 / %x20-2F / %x3B-40 / %x5B-60 / %x7B-7E
* non-delimiter = %x00-08 / %x0A-1F / DIGIT / ":" / ALPHA / %x7F-FF
* non-digit = %x00-2F / %x3A-FF
*
* day-of-month = 1*2DIGIT ( non-digit *OCTET )
* month = ( "jan" / "feb" / "mar" / "apr" /
* "may" / "jun" / "jul" / "aug" /
* "sep" / "oct" / "nov" / "dec" ) *OCTET
* year = 2*4DIGIT ( non-digit *OCTET )
* time = hms-time ( non-digit *OCTET )
* hms-time = time-field ":" time-field ":" time-field
* time-field = 1*2DIGIT
* ```
*
* 2. Process each date-token sequentially in the order the date-tokens
* appear in the cookie-date:
*
* 1. If the found-time flag is not set and the token matches the
* time production, set the found-time flag and set the hour-
* value, minute-value, and second-value to the numbers denoted
* by the digits in the date-token, respectively. Skip the
* remaining sub-steps and continue to the next date-token.
*
* 2. If the found-day-of-month flag is not set and the date-token
* matches the day-of-month production, set the found-day-of-
* month flag and set the day-of-month-value to the number
* denoted by the date-token. Skip the remaining sub-steps and
* continue to the next date-token.
*
* 3. If the found-month flag is not set and the date-token matches
* the month production, set the found-month flag and set the
* month-value to the month denoted by the date-token. Skip the
* remaining sub-steps and continue to the next date-token.
*
* 4. If the found-year flag is not set and the date-token matches
* the year production, set the found-year flag and set the
* year-value to the number denoted by the date-token. Skip the
* remaining sub-steps and continue to the next date-token.
*
* 3. If the year-value is greater than or equal to 70 and less than or
* equal to 99, increment the year-value by 1900.
*
* 4. If the year-value is greater than or equal to 0 and less than or
* equal to 69, increment the year-value by 2000.
*
* 1. NOTE: Some existing user agents interpret two-digit years differently.
*
* 5. Abort these steps and fail to parse the cookie-date if:
*
* - at least one of the found-day-of-month, found-month, found-
* year, or found-time flags is not set,
*
* - the day-of-month-value is less than 1 or greater than 31,
*
* - the year-value is less than 1601,
*
* - the hour-value is greater than 23,
*
* - the minute-value is greater than 59, or
*
* - the second-value is greater than 59.
*
* (Note that leap seconds cannot be represented in this syntax.)
*
* 6. Let the parsed-cookie-date be the date whose day-of-month, month,
* year, hour, minute, and second (in UTC) are the day-of-month-
* value, the month-value, the year-value, the hour-value, the
* minute-value, and the second-value, respectively. If no such
* date exists, abort these steps and fail to parse the cookie-date.
*
* 7. Return the parsed-cookie-date as the result of this algorithm.
*
* @example
* ```
* parseDate('Wed, 09 Jun 2021 10:18:14 GMT')
* ```
*
* @param cookieDate - the cookie date string
* @public
*/
export declare function parseDate(cookieDate: Nullable<string>): Date | undefined;

View File

@@ -0,0 +1,323 @@
"use strict";
// date-time parsing constants (RFC6265 S5.1.1)
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseDate = parseDate;
// eslint-disable-next-line no-control-regex
const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
const MONTH_TO_NUM = {
jan: 0,
feb: 1,
mar: 2,
apr: 3,
may: 4,
jun: 5,
jul: 6,
aug: 7,
sep: 8,
oct: 9,
nov: 10,
dec: 11,
};
/*
* Parses a Natural number (i.e., non-negative integer) with either the
* <min>*<max>DIGIT ( non-digit *OCTET )
* or
* <min>*<max>DIGIT
* grammar (RFC6265 S5.1.1).
*
* The "trailingOK" boolean controls if the grammar accepts a
* "( non-digit *OCTET )" trailer.
*/
function parseDigits(token, minDigits, maxDigits, trailingOK) {
let count = 0;
while (count < token.length) {
const c = token.charCodeAt(count);
// "non-digit = %x00-2F / %x3A-FF"
if (c <= 0x2f || c >= 0x3a) {
break;
}
count++;
}
// constrain to a minimum and maximum number of digits.
if (count < minDigits || count > maxDigits) {
return;
}
if (!trailingOK && count != token.length) {
return;
}
return parseInt(token.slice(0, count), 10);
}
function parseTime(token) {
const parts = token.split(':');
const result = [0, 0, 0];
/* RF6256 S5.1.1:
* time = hms-time ( non-digit *OCTET )
* hms-time = time-field ":" time-field ":" time-field
* time-field = 1*2DIGIT
*/
if (parts.length !== 3) {
return;
}
for (let i = 0; i < 3; i++) {
// "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
// followed by "( non-digit *OCTET )" therefore the last time-field can
// have a trailer
const trailingOK = i == 2;
const numPart = parts[i];
if (numPart === undefined) {
return;
}
const num = parseDigits(numPart, 1, 2, trailingOK);
if (num === undefined) {
return;
}
result[i] = num;
}
return result;
}
function parseMonth(token) {
token = String(token).slice(0, 3).toLowerCase();
switch (token) {
case 'jan':
return MONTH_TO_NUM.jan;
case 'feb':
return MONTH_TO_NUM.feb;
case 'mar':
return MONTH_TO_NUM.mar;
case 'apr':
return MONTH_TO_NUM.apr;
case 'may':
return MONTH_TO_NUM.may;
case 'jun':
return MONTH_TO_NUM.jun;
case 'jul':
return MONTH_TO_NUM.jul;
case 'aug':
return MONTH_TO_NUM.aug;
case 'sep':
return MONTH_TO_NUM.sep;
case 'oct':
return MONTH_TO_NUM.oct;
case 'nov':
return MONTH_TO_NUM.nov;
case 'dec':
return MONTH_TO_NUM.dec;
default:
return;
}
}
/**
* Parse a cookie date string into a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date}. Parses according to
* {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.1.1 | RFC6265 - Section 5.1.1}, not
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse | Date.parse()}.
*
* @remarks
*
* ### RFC6265 - 5.1.1. Dates
*
* The user agent MUST use an algorithm equivalent to the following
* algorithm to parse a cookie-date. Note that the various boolean
* flags defined as a part of the algorithm (i.e., found-time, found-
* day-of-month, found-month, found-year) are initially "not set".
*
* 1. Using the grammar below, divide the cookie-date into date-tokens.
*
* ```
* cookie-date = *delimiter date-token-list *delimiter
* date-token-list = date-token *( 1*delimiter date-token )
* date-token = 1*non-delimiter
*
* delimiter = %x09 / %x20-2F / %x3B-40 / %x5B-60 / %x7B-7E
* non-delimiter = %x00-08 / %x0A-1F / DIGIT / ":" / ALPHA / %x7F-FF
* non-digit = %x00-2F / %x3A-FF
*
* day-of-month = 1*2DIGIT ( non-digit *OCTET )
* month = ( "jan" / "feb" / "mar" / "apr" /
* "may" / "jun" / "jul" / "aug" /
* "sep" / "oct" / "nov" / "dec" ) *OCTET
* year = 2*4DIGIT ( non-digit *OCTET )
* time = hms-time ( non-digit *OCTET )
* hms-time = time-field ":" time-field ":" time-field
* time-field = 1*2DIGIT
* ```
*
* 2. Process each date-token sequentially in the order the date-tokens
* appear in the cookie-date:
*
* 1. If the found-time flag is not set and the token matches the
* time production, set the found-time flag and set the hour-
* value, minute-value, and second-value to the numbers denoted
* by the digits in the date-token, respectively. Skip the
* remaining sub-steps and continue to the next date-token.
*
* 2. If the found-day-of-month flag is not set and the date-token
* matches the day-of-month production, set the found-day-of-
* month flag and set the day-of-month-value to the number
* denoted by the date-token. Skip the remaining sub-steps and
* continue to the next date-token.
*
* 3. If the found-month flag is not set and the date-token matches
* the month production, set the found-month flag and set the
* month-value to the month denoted by the date-token. Skip the
* remaining sub-steps and continue to the next date-token.
*
* 4. If the found-year flag is not set and the date-token matches
* the year production, set the found-year flag and set the
* year-value to the number denoted by the date-token. Skip the
* remaining sub-steps and continue to the next date-token.
*
* 3. If the year-value is greater than or equal to 70 and less than or
* equal to 99, increment the year-value by 1900.
*
* 4. If the year-value is greater than or equal to 0 and less than or
* equal to 69, increment the year-value by 2000.
*
* 1. NOTE: Some existing user agents interpret two-digit years differently.
*
* 5. Abort these steps and fail to parse the cookie-date if:
*
* - at least one of the found-day-of-month, found-month, found-
* year, or found-time flags is not set,
*
* - the day-of-month-value is less than 1 or greater than 31,
*
* - the year-value is less than 1601,
*
* - the hour-value is greater than 23,
*
* - the minute-value is greater than 59, or
*
* - the second-value is greater than 59.
*
* (Note that leap seconds cannot be represented in this syntax.)
*
* 6. Let the parsed-cookie-date be the date whose day-of-month, month,
* year, hour, minute, and second (in UTC) are the day-of-month-
* value, the month-value, the year-value, the hour-value, the
* minute-value, and the second-value, respectively. If no such
* date exists, abort these steps and fail to parse the cookie-date.
*
* 7. Return the parsed-cookie-date as the result of this algorithm.
*
* @example
* ```
* parseDate('Wed, 09 Jun 2021 10:18:14 GMT')
* ```
*
* @param cookieDate - the cookie date string
* @public
*/
function parseDate(cookieDate) {
if (!cookieDate) {
return;
}
/* RFC6265 S5.1.1:
* 2. Process each date-token sequentially in the order the date-tokens
* appear in the cookie-date
*/
const tokens = cookieDate.split(DATE_DELIM);
let hour;
let minute;
let second;
let dayOfMonth;
let month;
let year;
for (let i = 0; i < tokens.length; i++) {
const token = (tokens[i] ?? '').trim();
if (!token.length) {
continue;
}
/* 2.1. If the found-time flag is not set and the token matches the time
* production, set the found-time flag and set the hour- value,
* minute-value, and second-value to the numbers denoted by the digits in
* the date-token, respectively. Skip the remaining sub-steps and continue
* to the next date-token.
*/
if (second === undefined) {
const result = parseTime(token);
if (result) {
hour = result[0];
minute = result[1];
second = result[2];
continue;
}
}
/* 2.2. If the found-day-of-month flag is not set and the date-token matches
* the day-of-month production, set the found-day-of- month flag and set
* the day-of-month-value to the number denoted by the date-token. Skip
* the remaining sub-steps and continue to the next date-token.
*/
if (dayOfMonth === undefined) {
// "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
const result = parseDigits(token, 1, 2, true);
if (result !== undefined) {
dayOfMonth = result;
continue;
}
}
/* 2.3. If the found-month flag is not set and the date-token matches the
* month production, set the found-month flag and set the month-value to
* the month denoted by the date-token. Skip the remaining sub-steps and
* continue to the next date-token.
*/
if (month === undefined) {
const result = parseMonth(token);
if (result !== undefined) {
month = result;
continue;
}
}
/* 2.4. If the found-year flag is not set and the date-token matches the
* year production, set the found-year flag and set the year-value to the
* number denoted by the date-token. Skip the remaining sub-steps and
* continue to the next date-token.
*/
if (year === undefined) {
// "year = 2*4DIGIT ( non-digit *OCTET )"
const result = parseDigits(token, 2, 4, true);
if (result !== undefined) {
year = result;
/* From S5.1.1:
* 3. If the year-value is greater than or equal to 70 and less
* than or equal to 99, increment the year-value by 1900.
* 4. If the year-value is greater than or equal to 0 and less
* than or equal to 69, increment the year-value by 2000.
*/
if (year >= 70 && year <= 99) {
year += 1900;
}
else if (year >= 0 && year <= 69) {
year += 2000;
}
}
}
}
/* RFC 6265 S5.1.1
* "5. Abort these steps and fail to parse the cookie-date if:
* * at least one of the found-day-of-month, found-month, found-
* year, or found-time flags is not set,
* * the day-of-month-value is less than 1 or greater than 31,
* * the year-value is less than 1601,
* * the hour-value is greater than 23,
* * the minute-value is greater than 59, or
* * the second-value is greater than 59.
* (Note that leap seconds cannot be represented in this syntax.)"
*
* So, in order as above:
*/
if (dayOfMonth === undefined ||
month === undefined ||
year === undefined ||
hour === undefined ||
minute === undefined ||
second === undefined ||
dayOfMonth < 1 ||
dayOfMonth > 31 ||
year < 1601 ||
hour > 23 ||
minute > 59 ||
second > 59) {
return;
}
return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
}

View File

@@ -0,0 +1,14 @@
/**
* Generates the permutation of all possible values that {@link pathMatch} the `path` parameter.
* The array is in longest-to-shortest order. Useful when building custom {@link Store} implementations.
*
* @example
* ```
* permutePath('/foo/bar/')
* // ['/foo/bar/', '/foo/bar', '/foo', '/']
* ```
*
* @param path - the path to generate permutations for
* @public
*/
export declare function permutePath(path: string): string[];

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.permutePath = permutePath;
/**
* Generates the permutation of all possible values that {@link pathMatch} the `path` parameter.
* The array is in longest-to-shortest order. Useful when building custom {@link Store} implementations.
*
* @example
* ```
* permutePath('/foo/bar/')
* // ['/foo/bar/', '/foo/bar', '/foo', '/']
* ```
*
* @param path - the path to generate permutations for
* @public
*/
function permutePath(path) {
if (path === '/') {
return ['/'];
}
const permutations = [path];
while (path.length > 1) {
const lindex = path.lastIndexOf('/');
if (lindex === 0) {
break;
}
path = path.slice(0, lindex);
permutations.push(path);
}
permutations.push('/');
return permutations;
}