CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tough-cookie

RFC6265 Cookies and Cookie Jar for node.js

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Tough Cookie

Tough Cookie is a comprehensive RFC 6265-compliant HTTP cookie library for JavaScript and Node.js that provides parsing, storage, and retrieval of cookies. It offers a complete implementation of cookie handling including domain matching, path matching, secure cookies, SameSite attributes, and cookie prefixes, with both synchronous and asynchronous APIs.

Package Information

  • Package Name: tough-cookie
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install tough-cookie

Core Imports

import { Cookie, CookieJar, MemoryCookieStore, Store } from "tough-cookie";

For CommonJS:

const { Cookie, CookieJar, MemoryCookieStore, Store } = require("tough-cookie");

Utility functions:

import { 
  parse, 
  fromJSON, 
  canonicalDomain, 
  domainMatch, 
  pathMatch, 
  parseDate,
  formatDate 
} from "tough-cookie";

Basic Usage

import { Cookie, CookieJar } from "tough-cookie";

// Parse a cookie string
const cookie = Cookie.parse('name=value; Domain=example.com; Path=/; Secure');

// Create a cookie jar with default memory store
const jar = new CookieJar();

// Set a cookie from a Set-Cookie header
await jar.setCookie('session=abc123; HttpOnly; Secure', 'https://example.com/');

// Get cookies for a URL as Cookie objects
const cookies = await jar.getCookies('https://example.com/');

// Get cookies as a Cookie header string
const cookieHeader = await jar.getCookieString('https://example.com/');

// Create a cookie programmatically
const newCookie = new Cookie({
  key: 'user_pref',
  value: 'dark_mode',
  domain: 'example.com',
  path: '/',
  secure: true,
  httpOnly: false,
  maxAge: 86400 // 1 day in seconds
});

Architecture

Tough Cookie is built around several key components:

  • Cookie Class: Individual cookie representation with RFC 6265 compliance, attribute validation, and serialization
  • CookieJar Class: Main cookie management with RFC-compliant storage, retrieval, and domain/path matching
  • Store Interface: Pluggable storage backend system with async/sync operation support
  • MemoryCookieStore: Default in-memory store implementation with efficient indexing
  • Utility Functions: Domain validation, path matching, date parsing, and cookie comparison functions
  • RFC 6265bis Support: SameSite attributes, cookie prefixes (__Secure-, __Host-), and secure context handling

Capabilities

Cookie Operations

Core cookie parsing, creation, and manipulation functionality. Handle individual cookies with full RFC 6265 compliance including validation, serialization, and attribute management.

// Parse cookie from string
function parse(str: string, options?: ParseCookieOptions): Cookie | undefined;

// Create cookie from JSON
function fromJSON(str: unknown): Cookie | undefined;

// Cookie comparison for sorting
function cookieCompare(a: Cookie, b: Cookie): number;

Cookie Operations

Cookie Jar Management

Comprehensive cookie storage and retrieval with RFC-compliant domain and path matching, expiration handling, and security validation.

// Set cookies with validation
setCookie(
  cookie: string | Cookie, 
  url: string | URL, 
  options?: SetCookieOptions
): Promise<Cookie | undefined>;

// Get cookies for URL
getCookies(
  url: string | URL, 
  options?: GetCookiesOptions
): Promise<Cookie[]>;

// Get cookie header string
getCookieString(
  url: string | URL, 
  options?: GetCookiesOptions
): Promise<string>;

Cookie Jar Management

Store Implementations

Pluggable storage system supporting both synchronous and asynchronous operations with complete CRUD functionality for cookie persistence.

// Store base class
abstract class Store {
  abstract findCookie(
    domain: string | null, 
    path: string | null, 
    key: string | null
  ): Promise<Cookie | undefined>;
  
  abstract putCookie(cookie: Cookie): Promise<void>;
  abstract getAllCookies(): Promise<Cookie[]>;
}

// Memory store implementation
class MemoryCookieStore extends Store {
  synchronous: boolean; // Always true
}

Store Implementations

Utility Functions

Domain validation, path matching, date parsing, and other RFC-compliant utility functions for cookie processing.

// Domain utilities
function canonicalDomain(domainName: string | null): string | undefined;
function domainMatch(domain?: string | null, cookieDomain?: string | null): boolean | undefined;
function getPublicSuffix(domain: string, options?: GetPublicSuffixOptions): string | undefined;

// Path utilities  
function pathMatch(reqPath: string, cookiePath: string): boolean;
function defaultPath(path?: string | null): string;

// Date utilities
function parseDate(cookieDate: string | null): Date | undefined;
function formatDate(date: Date): string;

Utility Functions

Core Types

// Cookie constructor options
interface CreateCookieOptions {
  key?: string;
  value?: string;
  expires?: Date | 'Infinity' | null;
  maxAge?: number | 'Infinity' | '-Infinity' | null;
  domain?: string | null;
  path?: string | null;
  secure?: boolean;
  httpOnly?: boolean;
  extensions?: string[] | null;
  creation?: Date | 'Infinity' | null;
  hostOnly?: boolean | null;
  pathIsDefault?: boolean | null;
  lastAccessed?: Date | 'Infinity' | null;
  sameSite?: string | undefined;
}

// Cookie parsing options
interface ParseCookieOptions {
  loose?: boolean; // Allow keyless cookies like =abc
}

// CookieJar configuration
interface CreateCookieJarOptions {
  rejectPublicSuffixes?: boolean; // Default: true
  looseMode?: boolean; // Default: false  
  prefixSecurity?: 'strict' | 'silent' | 'unsafe-disabled'; // Default: 'silent'
  allowSpecialUseDomain?: boolean; // Default: true
  allowSecureOnLocal?: boolean; // Default: true
}

// Cookie setting options
interface SetCookieOptions {
  loose?: boolean;
  sameSiteContext?: 'strict' | 'lax' | 'none';
  ignoreError?: boolean;
  http?: boolean; // Default: true
  now?: Date;
}

// Cookie retrieval options
interface GetCookiesOptions {
  http?: boolean; // Default: true
  expire?: boolean; // Default: true
  allPaths?: boolean; // Default: false
  sameSiteContext?: 'none' | 'lax' | 'strict';
  sort?: boolean;
}

// Public suffix options
interface GetPublicSuffixOptions {
  allowSpecialUseDomain?: boolean; // Default: false
  ignoreError?: boolean; // Default: false
}

// Callback types
interface Callback<T> {
  (error: Error, result?: never): void;
  (error: null, result: T): void;
}

interface ErrorCallback {
  (error: Error | null): void;
}

// Serialization types
type SerializedCookie = {
  key?: string;
  value?: string;
  [key: string]: unknown;
}

interface SerializedCookieJar {
  version: string;
  storeType: string | null;
  rejectPublicSuffixes: boolean;
  [key: string]: unknown;
  cookies: SerializedCookie[];
}

docs

cookie-jar.md

cookie-operations.md

index.md

stores.md

utilities.md

tile.json