tough-cookie 4.1.2 → 5.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,31 +9,31 @@
9
9
  ## Synopsis
10
10
 
11
11
  ```javascript
12
- var tough = require("tough-cookie");
13
- var Cookie = tough.Cookie;
14
- var cookie = Cookie.parse(header);
15
- cookie.value = "somethingdifferent";
16
- header = cookie.toString();
17
- var cookiejar = new tough.CookieJar();
12
+ var tough = require('tough-cookie')
13
+ var Cookie = tough.Cookie
14
+ var cookie = Cookie.parse(header)
15
+ cookie.value = 'somethingdifferent'
16
+ header = cookie.toString()
17
+ var cookiejar = new tough.CookieJar()
18
18
 
19
19
  // Asynchronous!
20
20
  var cookie = await cookiejar.setCookie(
21
21
  cookie,
22
- "https://currentdomain.example.com/path"
23
- );
24
- var cookies = await cookiejar.getCookies("https://example.com/otherpath");
22
+ 'https://currentdomain.example.com/path',
23
+ )
24
+ var cookies = await cookiejar.getCookies('https://example.com/otherpath')
25
25
 
26
26
  // Or with callbacks!
27
27
  cookiejar.setCookie(
28
28
  cookie,
29
- "https://currentdomain.example.com/path",
29
+ 'https://currentdomain.example.com/path',
30
30
  function (err, cookie) {
31
31
  /* ... */
32
- }
33
- );
34
- cookiejar.getCookies("http://example.com/otherpath", function (err, cookies) {
32
+ },
33
+ )
34
+ cookiejar.getCookies('http://example.com/otherpath', function (err, cookies) {
35
35
  /* ... */
36
- });
36
+ })
37
37
  ```
38
38
 
39
39
  Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken.
@@ -113,8 +113,8 @@ For use with `.sort()`, sorts a list of cookies into the recommended order given
113
113
  ```javascript
114
114
  var cookies = [
115
115
  /* unsorted array of Cookie objects */
116
- ];
117
- cookies = cookies.sort(cookieCompare);
116
+ ]
117
+ cookies = cookies.sort(cookieCompare)
118
118
  ```
119
119
 
120
120
  > **Note**: 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 `.setCookie()`. The `.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 `MemoryCookieStore` since `Set-Cookie` headers are parsed in order, but is not so great for distributed systems. Sophisticated `Store`s 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`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`.
@@ -144,9 +144,9 @@ If options is not an object it is ignored, which means it can be used with [`Arr
144
144
  To process the Set-Cookie header(s) on a node HTTP/HTTPS response:
145
145
 
146
146
  ```javascript
147
- if (Array.isArray(res.headers["set-cookie"]))
148
- cookies = res.headers["set-cookie"].map(Cookie.parse);
149
- else cookies = [Cookie.parse(res.headers["set-cookie"])];
147
+ if (Array.isArray(res.headers['set-cookie']))
148
+ cookies = res.headers['set-cookie'].map(Cookie.parse)
149
+ else cookies = [Cookie.parse(res.headers['set-cookie'])]
150
150
  ```
151
151
 
152
152
  _Note:_ In version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation was removed in version 2.3.4.
@@ -406,7 +406,7 @@ Retrieve a cookie with the given domain, path, and key (name). The RFC maintains
406
406
 
407
407
  Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (that is, not an error).
408
408
 
409
- #### `store.findCookies(domain, path, callback(err, cookies))`
409
+ #### `store.findCookies(domain, path, allowSpecialUseDomain, callback(err, cookies))`
410
410
 
411
411
  Locates cookies matching the given domain and path. This is most often called in the context of [`cookiejar.getCookies()`](#getcookiescurrenturl-options-callbackerr-cookies).
412
412
 
@@ -0,0 +1,313 @@
1
+ /*!
2
+ * Copyright (c) 2015, Salesforce.com, Inc.
3
+ * All rights reserved.
4
+ *
5
+ * Redistribution and use in source and binary forms, with or without
6
+ * modification, are permitted provided that the following conditions are met:
7
+ *
8
+ * 1. Redistributions of source code must retain the above copyright notice,
9
+ * this list of conditions and the following disclaimer.
10
+ *
11
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ * this list of conditions and the following disclaimer in the documentation
13
+ * and/or other materials provided with the distribution.
14
+ *
15
+ * 3. Neither the name of Salesforce.com nor the names of its contributors may
16
+ * be used to endorse or promote products derived from this software without
17
+ * specific prior written permission.
18
+ *
19
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ * POSSIBILITY OF SUCH DAMAGE.
30
+ */
31
+ 'use strict';
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.inspectFallback = exports.MemoryCookieStore = void 0;
34
+ const pathMatch_1 = require("./pathMatch");
35
+ const permuteDomain_1 = require("./permuteDomain");
36
+ const store_1 = require("./store");
37
+ const utilHelper_1 = require("./utilHelper");
38
+ const utils_1 = require("./utils");
39
+ class MemoryCookieStore extends store_1.Store {
40
+ constructor() {
41
+ super();
42
+ this.synchronous = true;
43
+ this.idx = Object.create(null);
44
+ const customInspectSymbol = (0, utilHelper_1.getCustomInspectSymbol)();
45
+ if (customInspectSymbol) {
46
+ Object.defineProperty(this, customInspectSymbol, {
47
+ value: this.inspect.bind(this),
48
+ enumerable: false,
49
+ writable: false,
50
+ configurable: false,
51
+ });
52
+ }
53
+ }
54
+ inspect() {
55
+ const util = { inspect: (0, utilHelper_1.getUtilInspect)(inspectFallback) };
56
+ return `{ idx: ${util.inspect(this.idx, false, 2)} }`;
57
+ }
58
+ findCookie(domain, path, key,
59
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
60
+ _callback) {
61
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
62
+ const cb = promiseCallback.callback;
63
+ if (domain == null || path == null) {
64
+ return promiseCallback.resolve(undefined);
65
+ }
66
+ const domainEntry = this.idx[domain];
67
+ if (!domainEntry) {
68
+ return promiseCallback.resolve(undefined);
69
+ }
70
+ const pathEntry = domainEntry[path];
71
+ if (!pathEntry) {
72
+ return promiseCallback.resolve(undefined);
73
+ }
74
+ if (key == null) {
75
+ return promiseCallback.resolve(null);
76
+ }
77
+ cb(null, pathEntry[key] || null);
78
+ return promiseCallback.promise;
79
+ }
80
+ findCookies(domain, path, allowSpecialUseDomain = false,
81
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
82
+ _callback) {
83
+ if (typeof allowSpecialUseDomain === 'function') {
84
+ allowSpecialUseDomain = true;
85
+ }
86
+ const results = [];
87
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
88
+ const cb = promiseCallback.callback;
89
+ if (!domain) {
90
+ return promiseCallback.resolve([]);
91
+ }
92
+ let pathMatcher;
93
+ if (!path) {
94
+ // null means "all paths"
95
+ pathMatcher = function matchAll(domainIndex) {
96
+ for (const curPath in domainIndex) {
97
+ const pathIndex = domainIndex[curPath];
98
+ for (const key in pathIndex) {
99
+ const value = pathIndex[key];
100
+ if (value) {
101
+ results.push(value);
102
+ }
103
+ }
104
+ }
105
+ };
106
+ }
107
+ else {
108
+ pathMatcher = function matchRFC(domainIndex) {
109
+ //NOTE: we should use path-match algorithm from S5.1.4 here
110
+ //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
111
+ for (const cookiePath in domainIndex) {
112
+ if ((0, pathMatch_1.pathMatch)(path, cookiePath)) {
113
+ const pathIndex = domainIndex[cookiePath];
114
+ for (const key in pathIndex) {
115
+ const value = pathIndex[key];
116
+ if (value) {
117
+ results.push(value);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ };
123
+ }
124
+ const domains = (0, permuteDomain_1.permuteDomain)(domain, allowSpecialUseDomain) || [domain];
125
+ const idx = this.idx;
126
+ domains.forEach((curDomain) => {
127
+ const domainIndex = idx[curDomain];
128
+ if (!domainIndex) {
129
+ return;
130
+ }
131
+ pathMatcher(domainIndex);
132
+ });
133
+ cb(null, results);
134
+ return promiseCallback.promise;
135
+ }
136
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
137
+ putCookie(cookie, _callback) {
138
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
139
+ const cb = promiseCallback.callback;
140
+ const { domain, path, key } = cookie;
141
+ if (domain == null || path == null || key == null) {
142
+ cb(null, undefined);
143
+ return promiseCallback.promise;
144
+ }
145
+ const domainEntry = this.idx[domain] ??
146
+ Object.create(null);
147
+ this.idx[domain] = domainEntry;
148
+ const pathEntry = domainEntry[path] ??
149
+ Object.create(null);
150
+ domainEntry[path] = pathEntry;
151
+ pathEntry[key] = cookie;
152
+ cb(null, undefined);
153
+ return promiseCallback.promise;
154
+ }
155
+ updateCookie(_oldCookie, newCookie, callback) {
156
+ // this seems wrong but it stops typescript from complaining and all the test pass...
157
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
158
+ callback = callback ?? function () { };
159
+ // updateCookie() may avoid updating cookies that are identical. For example,
160
+ // lastAccessed may not be important to some stores and an equality
161
+ // comparison could exclude that field.
162
+ return this.putCookie(newCookie, callback);
163
+ }
164
+ removeCookie(domain, path, key,
165
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
166
+ _callback) {
167
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
168
+ const cb = promiseCallback.callback;
169
+ const domainEntry = this.idx[domain];
170
+ if (domainEntry) {
171
+ const pathEntry = domainEntry[path];
172
+ if (pathEntry) {
173
+ const keyEntry = pathEntry[key];
174
+ if (keyEntry) {
175
+ delete pathEntry[key];
176
+ }
177
+ }
178
+ }
179
+ cb(null, undefined);
180
+ return promiseCallback.promise;
181
+ }
182
+ removeCookies(domain, path,
183
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
184
+ _callback) {
185
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
186
+ const cb = promiseCallback.callback;
187
+ const domainEntry = this.idx[domain];
188
+ if (domainEntry) {
189
+ if (path) {
190
+ delete domainEntry[path];
191
+ }
192
+ else {
193
+ delete this.idx[domain];
194
+ }
195
+ }
196
+ cb(null);
197
+ return promiseCallback.promise;
198
+ }
199
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
200
+ removeAllCookies(_callback) {
201
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
202
+ const cb = promiseCallback.callback;
203
+ this.idx = Object.create(null);
204
+ cb(null);
205
+ return promiseCallback.promise;
206
+ }
207
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
208
+ getAllCookies(_callback) {
209
+ const promiseCallback = (0, utils_1.createPromiseCallback)(arguments);
210
+ const cb = promiseCallback.callback;
211
+ const cookies = [];
212
+ const idx = this.idx;
213
+ const domains = Object.keys(idx);
214
+ domains.forEach((domain) => {
215
+ const domainEntry = idx[domain] ?? {};
216
+ const paths = Object.keys(domainEntry);
217
+ paths.forEach((path) => {
218
+ const pathEntry = domainEntry[path] ?? {};
219
+ const keys = Object.keys(pathEntry);
220
+ keys.forEach((key) => {
221
+ const keyEntry = pathEntry[key];
222
+ if (keyEntry != null) {
223
+ cookies.push(keyEntry);
224
+ }
225
+ });
226
+ });
227
+ });
228
+ // Sort by creationIndex so deserializing retains the creation order.
229
+ // When implementing your own store, this SHOULD retain the order too
230
+ cookies.sort((a, b) => {
231
+ return (a.creationIndex || 0) - (b.creationIndex || 0);
232
+ });
233
+ cb(null, cookies);
234
+ return promiseCallback.promise;
235
+ }
236
+ }
237
+ exports.MemoryCookieStore = MemoryCookieStore;
238
+ function inspectFallback(val) {
239
+ if (typeof val === 'string') {
240
+ return `'${val}'`;
241
+ }
242
+ if (val && typeof val === 'object') {
243
+ const domains = Object.keys(val);
244
+ if (domains.length === 0) {
245
+ return '[Object: null prototype] {}';
246
+ }
247
+ let result = '[Object: null prototype] {\n';
248
+ Object.keys(val).forEach((domain, i) => {
249
+ if ((0, utils_1.inOperator)(domain, val)) {
250
+ result += formatDomain(domain, val[domain]);
251
+ if (i < domains.length - 1) {
252
+ result += ',';
253
+ }
254
+ result += '\n';
255
+ }
256
+ });
257
+ result += '}';
258
+ return result;
259
+ }
260
+ return String(val);
261
+ }
262
+ exports.inspectFallback = inspectFallback;
263
+ function formatDomain(domainName, domainValue) {
264
+ if (typeof domainValue === 'string') {
265
+ return `'${domainValue}'`;
266
+ }
267
+ if (domainValue && typeof domainValue === 'object') {
268
+ const indent = ' ';
269
+ let result = `${indent}'${domainName}': [Object: null prototype] {\n`;
270
+ Object.keys(domainValue).forEach((path, i, paths) => {
271
+ if ((0, utils_1.inOperator)(path, domainValue)) {
272
+ result += formatPath(path, domainValue[path]);
273
+ if (i < paths.length - 1) {
274
+ result += ',';
275
+ }
276
+ result += '\n';
277
+ }
278
+ });
279
+ result += `${indent}}`;
280
+ return result;
281
+ }
282
+ return String(domainValue);
283
+ }
284
+ function formatPath(pathName, pathValue) {
285
+ if (typeof pathValue === 'string') {
286
+ return `'${pathValue}'`;
287
+ }
288
+ if (pathValue && typeof pathValue === 'object') {
289
+ const indent = ' ';
290
+ let result = `${indent}'${pathName}': [Object: null prototype] {\n`;
291
+ Object.keys(pathValue).forEach((cookieName, i, cookieNames) => {
292
+ if ((0, utils_1.inOperator)(cookieName, pathValue)) {
293
+ const cookie = pathValue[cookieName];
294
+ if (cookie != null &&
295
+ typeof cookie === 'object' &&
296
+ (0, utils_1.inOperator)('inspect', cookie) &&
297
+ typeof cookie.inspect === 'function') {
298
+ const inspectedValue = cookie.inspect();
299
+ if (typeof inspectedValue === 'string') {
300
+ result += ` ${cookieName}: ${inspectedValue}`;
301
+ if (i < cookieNames.length - 1) {
302
+ result += ',';
303
+ }
304
+ result += '\n';
305
+ }
306
+ }
307
+ }
308
+ });
309
+ result += `${indent}}`;
310
+ return result;
311
+ }
312
+ return String(pathValue);
313
+ }
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  /*!
2
3
  * Copyright (c) 2015, Salesforce.com, Inc.
3
4
  * All rights reserved.
@@ -28,34 +29,32 @@
28
29
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
30
  * POSSIBILITY OF SUCH DAMAGE.
30
31
  */
31
- "use strict";
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.pathMatch = void 0;
32
34
  /*
33
35
  * "A request-path path-matches a given cookie-path if at least one of the
34
36
  * following conditions holds:"
35
37
  */
36
38
  function pathMatch(reqPath, cookiePath) {
37
- // "o The cookie-path and the request-path are identical."
38
- if (cookiePath === reqPath) {
39
- return true;
40
- }
41
-
42
- const idx = reqPath.indexOf(cookiePath);
43
- if (idx === 0) {
44
- // "o The cookie-path is a prefix of the request-path, and the last
45
- // character of the cookie-path is %x2F ("/")."
46
- if (cookiePath.substr(-1) === "/") {
47
- return true;
39
+ // "o The cookie-path and the request-path are identical."
40
+ if (cookiePath === reqPath) {
41
+ return true;
48
42
  }
49
-
50
- // " o The cookie-path is a prefix of the request-path, and the first
51
- // character of the request-path that is not included in the cookie- path
52
- // is a %x2F ("/") character."
53
- if (reqPath.substr(cookiePath.length, 1) === "/") {
54
- return true;
43
+ const idx = reqPath.indexOf(cookiePath);
44
+ if (idx === 0) {
45
+ // "o The cookie-path is a prefix of the request-path, and the last
46
+ // character of the cookie-path is %x2F ("/")."
47
+ if (cookiePath[cookiePath.length - 1] === '/') {
48
+ return true;
49
+ }
50
+ // " o The cookie-path is a prefix of the request-path, and the first
51
+ // character of the request-path that is not included in the cookie- path
52
+ // is a %x2F ("/") character."
53
+ if (new RegExp(`^${cookiePath}`).test(reqPath) &&
54
+ reqPath[cookiePath.length] === '/') {
55
+ return true;
56
+ }
55
57
  }
56
- }
57
-
58
- return false;
58
+ return false;
59
59
  }
60
-
61
60
  exports.pathMatch = pathMatch;
@@ -28,38 +28,36 @@
28
28
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
29
  * POSSIBILITY OF SUCH DAMAGE.
30
30
  */
31
- "use strict";
32
- const pubsuffix = require("./pubsuffix-psl");
33
-
31
+ 'use strict';
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.permuteDomain = void 0;
34
+ const pubsuffix_psl_1 = require("./pubsuffix-psl");
34
35
  // Gives the permutation of all possible domainMatch()es of a given domain. The
35
36
  // array is in shortest-to-longest order. Handy for indexing.
36
-
37
37
  function permuteDomain(domain, allowSpecialUseDomain) {
38
- const pubSuf = pubsuffix.getPublicSuffix(domain, {
39
- allowSpecialUseDomain: allowSpecialUseDomain
40
- });
41
-
42
- if (!pubSuf) {
43
- return null;
44
- }
45
- if (pubSuf == domain) {
46
- return [domain];
47
- }
48
-
49
- // Nuke trailing dot
50
- if (domain.slice(-1) == ".") {
51
- domain = domain.slice(0, -1);
52
- }
53
-
54
- const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
55
- const parts = prefix.split(".").reverse();
56
- let cur = pubSuf;
57
- const permutations = [cur];
58
- while (parts.length) {
59
- cur = `${parts.shift()}.${cur}`;
60
- permutations.push(cur);
61
- }
62
- return permutations;
38
+ const pubSuf = (0, pubsuffix_psl_1.getPublicSuffix)(domain, {
39
+ allowSpecialUseDomain: allowSpecialUseDomain,
40
+ });
41
+ if (!pubSuf) {
42
+ return null;
43
+ }
44
+ if (pubSuf == domain) {
45
+ return [domain];
46
+ }
47
+ // Nuke trailing dot
48
+ if (domain.slice(-1) == '.') {
49
+ domain = domain.slice(0, -1);
50
+ }
51
+ const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
52
+ const parts = prefix.split('.').reverse();
53
+ let cur = pubSuf;
54
+ const permutations = [cur];
55
+ while (parts.length) {
56
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
57
+ const part = parts.shift();
58
+ cur = `${part}.${cur}`;
59
+ permutations.push(cur);
60
+ }
61
+ return permutations;
63
62
  }
64
-
65
63
  exports.permuteDomain = permuteDomain;
@@ -0,0 +1,94 @@
1
+ /*!
2
+ * Copyright (c) 2018, Salesforce.com, Inc.
3
+ * All rights reserved.
4
+ *
5
+ * Redistribution and use in source and binary forms, with or without
6
+ * modification, are permitted provided that the following conditions are met:
7
+ *
8
+ * 1. Redistributions of source code must retain the above copyright notice,
9
+ * this list of conditions and the following disclaimer.
10
+ *
11
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ * this list of conditions and the following disclaimer in the documentation
13
+ * and/or other materials provided with the distribution.
14
+ *
15
+ * 3. Neither the name of Salesforce.com nor the names of its contributors may
16
+ * be used to endorse or promote products derived from this software without
17
+ * specific prior written permission.
18
+ *
19
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ * POSSIBILITY OF SUCH DAMAGE.
30
+ */
31
+ 'use strict';
32
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
33
+ if (k2 === undefined) k2 = k;
34
+ var desc = Object.getOwnPropertyDescriptor(m, k);
35
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
36
+ desc = { enumerable: true, get: function() { return m[k]; } };
37
+ }
38
+ Object.defineProperty(o, k2, desc);
39
+ }) : (function(o, m, k, k2) {
40
+ if (k2 === undefined) k2 = k;
41
+ o[k2] = m[k];
42
+ }));
43
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
44
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
45
+ }) : function(o, v) {
46
+ o["default"] = v;
47
+ });
48
+ var __importStar = (this && this.__importStar) || function (mod) {
49
+ if (mod && mod.__esModule) return mod;
50
+ var result = {};
51
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
52
+ __setModuleDefault(result, mod);
53
+ return result;
54
+ };
55
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.getPublicSuffix = void 0;
57
+ const psl = __importStar(require("psl"));
58
+ // RFC 6761
59
+ const SPECIAL_USE_DOMAINS = ['local', 'example', 'invalid', 'localhost', 'test'];
60
+ const SPECIAL_TREATMENT_DOMAINS = ['localhost', 'invalid'];
61
+ const defaultGetPublicSuffixOptions = {
62
+ allowSpecialUseDomain: false,
63
+ ignoreError: false,
64
+ };
65
+ function getPublicSuffix(domain, options = {}) {
66
+ options = { ...defaultGetPublicSuffixOptions, ...options };
67
+ const domainParts = domain.split('.');
68
+ const topLevelDomain = domainParts[domainParts.length - 1];
69
+ const allowSpecialUseDomain = !!options.allowSpecialUseDomain;
70
+ const ignoreError = !!options.ignoreError;
71
+ if (allowSpecialUseDomain &&
72
+ topLevelDomain !== undefined &&
73
+ SPECIAL_USE_DOMAINS.includes(topLevelDomain)) {
74
+ if (domainParts.length > 1) {
75
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
76
+ const secondLevelDomain = domainParts[domainParts.length - 2];
77
+ // In aforementioned example, the eTLD/pubSuf will be apple.localhost
78
+ return `${secondLevelDomain}.${topLevelDomain}`;
79
+ }
80
+ else if (SPECIAL_TREATMENT_DOMAINS.includes(topLevelDomain)) {
81
+ // For a single word special use domain, e.g. 'localhost' or 'invalid', per RFC 6761,
82
+ // "Application software MAY recognize {localhost/invalid} names as special, or
83
+ // MAY pass them to name resolution APIs as they would for other domain names."
84
+ return `${topLevelDomain}`;
85
+ }
86
+ }
87
+ if (!ignoreError &&
88
+ topLevelDomain !== undefined &&
89
+ SPECIAL_USE_DOMAINS.includes(topLevelDomain)) {
90
+ throw new Error(`Cookie has domain set to the public suffix "${topLevelDomain}" which is a special use domain. To allow this, configure your CookieJar with {allowSpecialUseDomain:true, rejectPublicSuffixes: false}.`);
91
+ }
92
+ return psl.get(domain);
93
+ }
94
+ exports.getPublicSuffix = getPublicSuffix;