0
# Utility Functions
1
2
Domain validation, path matching, date parsing, and other RFC 6265-compliant utility functions for cookie processing including public suffix handling and canonicalization.
3
4
## Capabilities
5
6
### Domain Utilities
7
8
Functions for domain validation, canonicalization, and matching per RFC 6265 requirements.
9
10
```typescript { .api }
11
/**
12
* Transforms a domain name into canonical form (trimmed, lowercased, punycode-encoded)
13
* @param domainName - Domain name to canonicalize
14
* @returns Canonical domain string or undefined if invalid
15
*/
16
function canonicalDomain(domainName: string | null): string | undefined;
17
18
/**
19
* Tests if a domain matches a cookie domain per RFC 6265 Section 5.1.3
20
* @param domain - Request domain to test
21
* @param cookieDomain - Cookie's domain attribute
22
* @param canonicalize - Whether to canonicalize domains first (default: true)
23
* @returns True if domain matches cookie domain, undefined if either is invalid
24
*/
25
function domainMatch(
26
domain?: string | null,
27
cookieDomain?: string | null,
28
canonicalize?: boolean
29
): boolean | undefined;
30
31
/**
32
* Generates all possible domain permutations for cookie matching (shortest to longest)
33
* @param domain - Domain to generate permutations for
34
* @param allowSpecialUseDomain - Whether to allow special use domains
35
* @returns Array of domain permutations or undefined if invalid
36
*/
37
function permuteDomain(domain: string, allowSpecialUseDomain?: boolean): string[] | undefined;
38
39
/**
40
* Returns the public suffix (shortest domain for cookie setting) using the Public Suffix List
41
* @param domain - Domain to get public suffix for
42
* @param options - Options controlling suffix resolution
43
* @returns Public suffix or undefined if not found
44
*/
45
function getPublicSuffix(domain: string, options?: GetPublicSuffixOptions): string | undefined;
46
47
interface GetPublicSuffixOptions {
48
allowSpecialUseDomain?: boolean; // Default: false
49
ignoreError?: boolean; // Default: false
50
}
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import {
57
canonicalDomain,
58
domainMatch,
59
permuteDomain,
60
getPublicSuffix
61
} from "tough-cookie";
62
63
// Canonicalize domains
64
const canonical = canonicalDomain(" Example.COM ");
65
console.log(canonical); // "example.com"
66
67
const punycoded = canonicalDomain("münchen.de");
68
console.log(punycoded); // "xn--mnchen-3ya.de"
69
70
// Test domain matching
71
const matches = domainMatch("sub.example.com", "example.com");
72
console.log(matches); // true
73
74
const exactMatch = domainMatch("example.com", "example.com");
75
console.log(exactMatch); // true
76
77
const noMatch = domainMatch("other.com", "example.com");
78
console.log(noMatch); // false
79
80
// Generate domain permutations
81
const permutations = permuteDomain("a.b.c.example.com");
82
console.log(permutations);
83
// ["example.com", "c.example.com", "b.c.example.com", "a.b.c.example.com"]
84
85
// Get public suffix
86
const suffix = getPublicSuffix("subdomain.example.co.uk");
87
console.log(suffix); // "co.uk"
88
89
const comSuffix = getPublicSuffix("example.com");
90
console.log(comSuffix); // "com"
91
```
92
93
### Path Utilities
94
95
Functions for path matching and default path computation according to RFC 6265.
96
97
```typescript { .api }
98
/**
99
* Tests if request path matches cookie path per RFC 6265 Section 5.1.4
100
* @param reqPath - Request path to test
101
* @param cookiePath - Cookie's path attribute
102
* @returns True if paths match according to RFC rules
103
*/
104
function pathMatch(reqPath: string, cookiePath: string): boolean;
105
106
/**
107
* Computes default cookie path from request path per RFC 6265 Section 5.1.4
108
* @param path - Request path to compute default from
109
* @returns Default path for cookies (always starts with '/')
110
*/
111
function defaultPath(path?: string | null): string;
112
113
/**
114
* Generates all possible path permutations for cookie matching (longest to shortest)
115
* @param path - Path to generate permutations for
116
* @returns Array of path permutations
117
*/
118
function permutePath(path: string): string[];
119
```
120
121
**Usage Examples:**
122
123
```typescript
124
import { pathMatch, defaultPath, permutePath } from "tough-cookie";
125
126
// Test path matching
127
console.log(pathMatch("/app/page", "/app")); // true
128
console.log(pathMatch("/app/page", "/app/")); // true
129
console.log(pathMatch("/app", "/app/page")); // false
130
console.log(pathMatch("/app/page", "/")); // true
131
132
// Compute default paths
133
console.log(defaultPath("/app/page.html")); // "/app"
134
console.log(defaultPath("/app/")); // "/app"
135
console.log(defaultPath("/")); // "/"
136
console.log(defaultPath("")); // "/"
137
console.log(defaultPath(null)); // "/"
138
139
// Generate path permutations
140
const pathPermutations = permutePath("/app/admin/users");
141
console.log(pathPermutations);
142
// ["/app/admin/users", "/app/admin", "/app", "/"]
143
144
const rootPermutations = permutePath("/");
145
console.log(rootPermutations); // ["/"]
146
```
147
148
### Date Utilities
149
150
Functions for parsing and formatting cookie dates according to RFC 6265 specifications.
151
152
```typescript { .api }
153
/**
154
* Parses cookie date string per RFC 6265 Section 5.1.1 (not Date.parse())
155
* Uses RFC-compliant parsing algorithm that handles various date formats
156
* @param cookieDate - Date string from cookie expires attribute
157
* @returns Parsed Date object or undefined if invalid
158
*/
159
function parseDate(cookieDate: string | null): Date | undefined;
160
161
/**
162
* Formats Date to RFC 822/1123 format for cookie headers
163
* @param date - Date object to format
164
* @returns RFC-compliant date string
165
*/
166
function formatDate(date: Date): string;
167
```
168
169
**Usage Examples:**
170
171
```typescript
172
import { parseDate, formatDate } from "tough-cookie";
173
174
// Parse various cookie date formats
175
const date1 = parseDate("Tue, 19 Jan 2038 03:14:07 GMT");
176
console.log(date1); // Valid Date object
177
178
const date2 = parseDate("Tuesday, 19-Jan-38 03:14:07 GMT");
179
console.log(date2); // Valid Date object (RFC 850 format)
180
181
const date3 = parseDate("Tue Jan 19 03:14:07 2038");
182
console.log(date3); // Valid Date object (asctime format)
183
184
// Invalid formats return undefined
185
const invalid = parseDate("not a date");
186
console.log(invalid); // undefined
187
188
const nullDate = parseDate(null);
189
console.log(nullDate); // undefined
190
191
// Format dates for cookie headers
192
const now = new Date();
193
const formatted = formatDate(now);
194
console.log(formatted); // "Wed, 07 Sep 2025 12:34:56 GMT"
195
196
// Format specific date
197
const specificDate = new Date("2025-12-25T00:00:00Z");
198
const christmasFormatted = formatDate(specificDate);
199
console.log(christmasFormatted); // "Thu, 25 Dec 2025 00:00:00 GMT"
200
```
201
202
### Validation Functions
203
204
Error class for parameter validation failures in tough-cookie operations.
205
206
```typescript { .api }
207
/**
208
* Error class for parameter validation failures
209
* @public
210
*/
211
class ParameterError extends Error {}
212
```
213
214
**Usage Examples:**
215
216
```typescript
217
import { ParameterError } from "tough-cookie";
218
219
try {
220
// Some operation that might throw ParameterError
221
} catch (error) {
222
if (error instanceof ParameterError) {
223
console.log('Parameter validation failed:', error.message);
224
}
225
}
226
```
227
228
### Constants and Enums
229
230
Cookie-related constants and configuration values.
231
232
```typescript { .api }
233
/**
234
* Cookie prefix security enforcement levels
235
*/
236
const PrefixSecurityEnum = {
237
SILENT: 'silent', // Silently ignore violations (default)
238
STRICT: 'strict', // Throw errors on violations
239
DISABLED: 'unsafe-disabled', // Disable prefix checking
240
} as const;
241
242
/**
243
* The version of tough-cookie library
244
*/
245
const version: string; // Currently "6.0.0"
246
```
247
248
**Usage Examples:**
249
250
```typescript
251
import { PrefixSecurityEnum, version } from "tough-cookie";
252
253
console.log(version); // "6.0.0"
254
255
// Use prefix security constants
256
const jarOptions = {
257
prefixSecurity: PrefixSecurityEnum.STRICT,
258
rejectPublicSuffixes: true
259
};
260
261
console.log(PrefixSecurityEnum.SILENT); // "silent"
262
console.log(PrefixSecurityEnum.STRICT); // "strict"
263
console.log(PrefixSecurityEnum.DISABLED); // "unsafe-disabled"
264
```
265
266
## Advanced Usage Examples
267
268
### Complete Domain Processing Pipeline
269
270
```typescript
271
import {
272
canonicalDomain,
273
domainMatch,
274
permuteDomain,
275
getPublicSuffix
276
} from "tough-cookie";
277
278
function processCookieDomain(requestDomain: string, cookieDomain?: string) {
279
// Canonicalize the request domain
280
const canonical = canonicalDomain(requestDomain);
281
if (!canonical) {
282
throw new Error(`Invalid request domain: ${requestDomain}`);
283
}
284
285
// If no cookie domain specified, use request domain
286
if (!cookieDomain) {
287
return {
288
canonical,
289
isHostOnly: true,
290
permutations: [canonical]
291
};
292
}
293
294
// Canonicalize cookie domain
295
const cookieCanonical = canonicalDomain(cookieDomain);
296
if (!cookieCanonical) {
297
throw new Error(`Invalid cookie domain: ${cookieDomain}`);
298
}
299
300
// Check if request domain matches cookie domain
301
const matches = domainMatch(canonical, cookieCanonical);
302
if (!matches) {
303
throw new Error(`Domain ${canonical} does not match cookie domain ${cookieCanonical}`);
304
}
305
306
// Get public suffix to ensure cookie isn't too broad
307
const publicSuffix = getPublicSuffix(cookieCanonical);
308
if (publicSuffix === cookieCanonical) {
309
throw new Error(`Cannot set cookie on public suffix: ${cookieCanonical}`);
310
}
311
312
// Generate domain permutations for matching
313
const permutations = permuteDomain(cookieCanonical);
314
315
return {
316
canonical: cookieCanonical,
317
isHostOnly: false,
318
permutations: permutations || [cookieCanonical],
319
publicSuffix
320
};
321
}
322
323
// Example usage
324
const result = processCookieDomain("sub.example.com", "example.com");
325
console.log(result);
326
// {
327
// canonical: "example.com",
328
// isHostOnly: false,
329
// permutations: ["example.com"],
330
// publicSuffix: "com"
331
// }
332
```
333
334
### Path Processing with Validation
335
336
```typescript
337
import { pathMatch, defaultPath, permutePath } from "tough-cookie";
338
339
function processRequestPath(requestPath: string, cookiePath?: string) {
340
// Normalize request path
341
const normalizedRequest = requestPath || '/';
342
343
// Determine effective cookie path
344
const effectivePath = cookiePath || defaultPath(normalizedRequest);
345
346
// Validate path match
347
const matches = pathMatch(normalizedRequest, effectivePath);
348
if (!matches) {
349
return null; // Cookie doesn't apply to this request
350
}
351
352
// Generate path permutations for cookie lookup
353
const permutations = permutePath(normalizedRequest);
354
355
return {
356
requestPath: normalizedRequest,
357
cookiePath: effectivePath,
358
pathPermutations: permutations,
359
isDefault: !cookiePath
360
};
361
}
362
363
// Example usage
364
const pathInfo = processRequestPath("/app/admin/users", "/app");
365
console.log(pathInfo);
366
// {
367
// requestPath: "/app/admin/users",
368
// cookiePath: "/app",
369
// pathPermutations: ["/app/admin/users", "/app/admin", "/app", "/"],
370
// isDefault: false
371
// }
372
```
373
374
## Types
375
376
```typescript { .api }
377
interface Callback<T> {
378
(error: Error, result?: never): void;
379
(error: null, result: T): void;
380
}
381
382
type Nullable<T> = T | null | undefined;
383
```