tough-cookie 3.0.0 → 4.1.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
@@ -1,190 +1,204 @@
1
- [RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js
1
+ # tough-cookie
2
+
3
+ [RFC 6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js
2
4
 
3
5
  [![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/)
4
6
 
5
- [![Build Status](https://travis-ci.org/salesforce/tough-cookie.png?branch=master)](https://travis-ci.org/salesforce/tough-cookie)
7
+ [![Build Status](https://travis-ci.org/salesforce/tough-cookie.svg?branch=master)](https://travis-ci.org/salesforce/tough-cookie)
6
8
 
7
- # Synopsis
9
+ ## Synopsis
8
10
 
9
- ``` javascript
10
- var tough = require('tough-cookie');
11
+ ```javascript
12
+ var tough = require("tough-cookie");
11
13
  var Cookie = tough.Cookie;
12
14
  var cookie = Cookie.parse(header);
13
- cookie.value = 'somethingdifferent';
15
+ cookie.value = "somethingdifferent";
14
16
  header = cookie.toString();
15
-
16
17
  var cookiejar = new tough.CookieJar();
17
- cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb);
18
- // ...
19
- cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) {
20
- res.headers['cookie'] = cookies.join('; ');
18
+
19
+ // Asynchronous!
20
+ var cookie = await cookiejar.setCookie(
21
+ cookie,
22
+ "https://currentdomain.example.com/path"
23
+ );
24
+ var cookies = await cookiejar.getCookies("https://example.com/otherpath");
25
+
26
+ // Or with callbacks!
27
+ cookiejar.setCookie(
28
+ cookie,
29
+ "https://currentdomain.example.com/path",
30
+ function (err, cookie) {
31
+ /* ... */
32
+ }
33
+ );
34
+ cookiejar.getCookies("http://example.com/otherpath", function (err, cookies) {
35
+ /* ... */
21
36
  });
22
37
  ```
23
38
 
24
- # Installation
25
-
26
- It's _so_ easy!
39
+ Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken.
27
40
 
28
- `npm install tough-cookie`
41
+ ## Installation
29
42
 
30
- Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken.
43
+ It's _so_ easy! Install with `npm` or your preferred package manager.
31
44
 
32
- ## Version Support
45
+ ```sh
46
+ npm install tough-cookie
47
+ ```
33
48
 
34
- Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module.
49
+ ## Node.js Version Support
35
50
 
36
- # API
51
+ We follow the [node.js release schedule](https://github.com/nodejs/Release#release-schedule) and support all versions that are in Active LTS or Maintenance. We will always do a major release when dropping support for older versions of node, and we will do so in consultation with our community.
37
52
 
38
- ## tough
53
+ ## API
39
54
 
40
- Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound".
55
+ ### tough
41
56
 
42
- **Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary.
57
+ The top-level exports from `require('tough-cookie')` can all be used as pure functions and don't need to be bound.
43
58
 
44
- ### `parseDate(string)`
59
+ #### `parseDate(string)`
45
60
 
46
- Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`.
61
+ Parse a cookie date string into a `Date`. Parses according to [RFC 6265 Section 5.1.1](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.1), not `Date.parse()`.
47
62
 
48
- ### `formatDate(date)`
63
+ #### `formatDate(date)`
49
64
 
50
- Format a Date into a RFC1123 string (the RFC6265-recommended format).
65
+ Format a `Date` into an [RFC 822](https://datatracker.ietf.org/doc/html/rfc822#section-5) string (the RFC 6265 recommended format).
51
66
 
52
- ### `canonicalDomain(str)`
67
+ #### `canonicalDomain(str)`
53
68
 
54
- Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects).
69
+ 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 ([Section 5.1.2 of RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.2)). For the most part, this function is idempotent (calling the function with the output from a previous call returns the same output).
55
70
 
56
- ### `domainMatch(str,domStr[,canonicalize=true])`
71
+ #### `domainMatch(str, domStr[, canonicalize=true])`
57
72
 
58
- Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match".
73
+ Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain name and the `domStr` is the "cookie" domain name. Matches according to [RFC 6265 Section 5.1.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3), but it helps to think of it as a "suffix match".
59
74
 
60
- The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not.
75
+ The `canonicalize` parameter toggles whether the domain parameters get normalized with `canonicalDomain` or not.
61
76
 
62
- ### `defaultPath(path)`
77
+ #### `defaultPath(path)`
63
78
 
64
- Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC.
79
+ 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 [Section 5.1.4 of the RFC](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4).
65
80
 
66
- The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output.
81
+ The `path` parameter MUST be _only_ the pathname part of a URI (excluding the hostname, query, fragment, and so on). This is the `.pathname` property of node's `uri.parse()` output.
67
82
 
68
- ### `pathMatch(reqPath,cookiePath)`
83
+ #### `pathMatch(reqPath, cookiePath)`
69
84
 
70
- Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean.
85
+ Answers "does the request-path path-match a given cookie-path?" as per [RFC 6265 Section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4). Returns a boolean.
71
86
 
72
87
  This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`.
73
88
 
74
- ### `parse(cookieString[, options])`
89
+ #### `parse(cookieString[, options])`
75
90
 
76
- alias for `Cookie.parse(cookieString[, options])`
91
+ Alias for [`Cookie.parse(cookieString[, options])`](#cookieparsecookiestring-options).
77
92
 
78
- ### `fromJSON(string)`
93
+ #### `fromJSON(string)`
79
94
 
80
- alias for `Cookie.fromJSON(string)`
95
+ Alias for [`Cookie.fromJSON(string)`](#cookiefromjsonstrorobj).
81
96
 
82
- ### `getPublicSuffix(hostname)`
97
+ #### `getPublicSuffix(hostname)`
83
98
 
84
- Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it.
99
+ Returns the public suffix of this hostname. The public suffix is the shortest domain name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it.
85
100
 
86
101
  For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`.
87
102
 
88
- For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain).
103
+ For further information, see the [Public Suffix List](http://publicsuffix.org/). This module derives its list from that site. This call is a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [`get` method](https://www.npmjs.com/package/psl##pslgetdomain).
89
104
 
90
- ### `cookieCompare(a,b)`
105
+ #### `cookieCompare(a, b)`
91
106
 
92
- For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence:
107
+ For use with `.sort()`, sorts a list of cookies into the recommended order given in step 2 of ([RFC 6265 Section 5.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.4)). The sort algorithm is, in order of precedence:
93
108
 
94
- * Longest `.path`
95
- * oldest `.creation` (which has a 1ms precision, same as `Date`)
96
- * lowest `.creationIndex` (to get beyond the 1ms precision)
109
+ - Longest `.path`
110
+ - oldest `.creation` (which has a 1-ms precision, same as `Date`)
111
+ - lowest `.creationIndex` (to get beyond the 1-ms precision)
97
112
 
98
- ``` javascript
99
- var cookies = [ /* unsorted array of Cookie objects */ ];
113
+ ```javascript
114
+ var cookies = [
115
+ /* unsorted array of Cookie objects */
116
+ ];
100
117
  cookies = cookies.sort(cookieCompare);
101
118
  ```
102
119
 
103
- **Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond 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()`. This 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 may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such 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`.
104
-
105
- ### `permuteDomain(domain)`
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`.
106
121
 
107
- Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores.
122
+ #### `permuteDomain(domain)`
108
123
 
109
- ### `permutePath(path)`
124
+ Generates a list of all possible domains that `domainMatch()` the parameter. Can be handy for implementing cookie stores.
110
125
 
111
- Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores.
126
+ #### `permutePath(path)`
112
127
 
128
+ Generates a list of all possible paths that `pathMatch()` the parameter. Can be handy for implementing cookie stores.
113
129
 
114
- ## Cookie
130
+ ### Cookie
115
131
 
116
132
  Exported via `tough.Cookie`.
117
133
 
118
- ### `Cookie.parse(cookieString[, options])`
134
+ #### `Cookie.parse(cookieString[, options])`
119
135
 
120
- Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed.
136
+ Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed.
121
137
 
122
138
  The options parameter is not required and currently has only one property:
123
139
 
124
- * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant.
140
+ - _loose_ - boolean - if `true` enable parsing of keyless cookies like `=abc` and `=`, which are not RFC-compliant.
125
141
 
126
- If options is not an object, it is ignored, which means you can use `Array#map` with it.
142
+ If options is not an object it is ignored, which means it can be used with [`Array#map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
127
143
 
128
- Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response:
144
+ To process the Set-Cookie header(s) on a node HTTP/HTTPS response:
129
145
 
130
- ``` javascript
131
- if (res.headers['set-cookie'] instanceof Array)
132
- cookies = res.headers['set-cookie'].map(Cookie.parse);
133
- else
134
- cookies = [Cookie.parse(res.headers['set-cookie'])];
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"])];
135
150
  ```
136
151
 
137
- _Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed.
138
- See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92)
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.
153
+ For more details, see [issue #92](https://github.com/salesforce/tough-cookie/issues/92).
139
154
 
140
- ### Properties
155
+ #### Properties
141
156
 
142
157
  Cookie object properties:
143
158
 
144
- * _key_ - string - the name or key of the cookie (default "")
145
- * _value_ - string - the value of the cookie (default "")
146
- * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()`
147
- * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()`
148
- * _domain_ - string - the `Domain=` attribute of the cookie
149
- * _path_ - string - the `Path=` of the cookie
150
- * _secure_ - boolean - the `Secure` cookie flag
151
- * _httpOnly_ - boolean - the `HttpOnly` cookie flag
152
- * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside)
153
- * _creation_ - `Date` - when this cookie was constructed
154
- * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation)
155
-
156
- After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes:
159
+ - _key_ - string - the name or key of the cookie (default `""`)
160
+ - _value_ - string - the value of the cookie (default `""`)
161
+ - _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()`
162
+ - _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. Can also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()`
163
+ - _domain_ - string - the `Domain=` attribute of the cookie
164
+ - _path_ - string - the `Path=` of the cookie
165
+ - _secure_ - boolean - the `Secure` cookie flag
166
+ - _httpOnly_ - boolean - the `HttpOnly` cookie flag
167
+ - _sameSite_ - string - the `SameSite` cookie attribute (from [RFC 6265bis](#rfc-6265bis)); must be one of `none`, `lax`, or `strict`
168
+ - _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside)
169
+ - _creation_ - `Date` - when this cookie was constructed
170
+ - _creationIndex_ - number - set at construction, used to provide greater sort precision (see `cookieCompare(a,b)` for a full explanation)
157
171
 
158
- * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied)
159
- * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one.
160
- * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar
161
- * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute.
172
+ After a cookie has been passed through `CookieJar.setCookie()` it has the following additional attributes:
162
173
 
163
- ### `Cookie([{properties}])`
174
+ - _hostOnly_ - boolean - is this a host-only cookie (that is, no Domain field was set, but was instead implied).
175
+ - _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one.
176
+ - _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar.
177
+ - _lastAccessed_ - `Date` - last time the cookie got accessed. Affects cookie cleaning after it is implemented. Using `cookiejar.getCookies(...)` updates this attribute.
164
178
 
165
- Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties.
179
+ #### `new Cookie([properties])`
166
180
 
167
- ### `.toString()`
181
+ Receives an options object that can contain any of the above Cookie properties. Uses the default for unspecified properties.
168
182
 
169
- encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`.
183
+ #### `.toString()`
170
184
 
171
- ### `.cookieString()`
185
+ Encodes to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`.
172
186
 
173
- encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '=').
187
+ #### `.cookieString()`
174
188
 
175
- ### `.setExpires(String)`
189
+ Encodes to a Cookie header value (specifically, the `.key` and `.value` properties joined with `"="`).
176
190
 
177
- sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set.
191
+ #### `.setExpires(string)`
178
192
 
179
- ### `.setMaxAge(number)`
193
+ Sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (that is, can't parse this date string), `.expires` is set to `"Infinity"` (a string).
180
194
 
181
- sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly.
195
+ #### `.setMaxAge(number)`
182
196
 
183
- ### `.expiryTime([now=Date.now()])`
197
+ Sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it correctly serializes to JSON.
184
198
 
185
- ### `.expiryDate([now=Date.now()])`
199
+ #### `.expiryDate([now=Date.now()])`
186
200
 
187
- expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds.
201
+ `expiryTime()` computes the absolute unix-epoch milliseconds that this cookie expires. `expiryDate()` works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds.
188
202
 
189
203
  Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute.
190
204
 
@@ -192,45 +206,45 @@ If Expires (`.expires`) is set, that's returned.
192
206
 
193
207
  Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents).
194
208
 
195
- ### `.TTL([now=Date.now()])`
209
+ #### `.TTL([now=Date.now()])`
196
210
 
197
- compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply.
211
+ Computes the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply.
198
212
 
199
- The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned.
213
+ `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned.
200
214
 
201
- ### `.canonicalizedDomain()`
215
+ #### `.canonicalizedDomain()`
202
216
 
203
- ### `.cdomain()`
217
+ #### `.cdomain()`
204
218
 
205
- return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters.
219
+ Returns the canonicalized `.domain` field. This is lower-cased and punycode ([RFC 3490](https://datatracker.ietf.org/doc/html/rfc3490)) encoded if the domain has any non-ASCII characters.
206
220
 
207
- ### `.toJSON()`
221
+ #### `.toJSON()`
208
222
 
209
223
  For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized.
210
224
 
211
- Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`).
225
+ Any `Date` properties (such as `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`).
212
226
 
213
- **NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array.
227
+ > **NOTE**: Custom `Cookie` properties are discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array.
214
228
 
215
- ### `Cookie.fromJSON(strOrObj)`
229
+ #### `Cookie.fromJSON(strOrObj)`
216
230
 
217
231
  Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first.
218
232
 
219
- Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer.
233
+ Any `Date` properties (such as `.expires`, `.creation`, and `.lastAccessed`) are parsed via [`Date.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse), not tough-cookie's `parseDate`, since ISO timestamps are being handled at this layer.
220
234
 
221
- Returns `null` upon JSON parsing error.
235
+ Returns `null` upon a JSON parsing error.
222
236
 
223
- ### `.clone()`
237
+ #### `.clone()`
224
238
 
225
- Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`.
239
+ Does a deep clone of this cookie, implemented exactly as `Cookie.fromJSON(cookie.toJSON())`.
226
240
 
227
- ### `.validate()`
241
+ #### `.validate()`
228
242
 
229
- Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive.
243
+ Status: _IN PROGRESS_. Works for a few things, but is by no means comprehensive.
230
244
 
231
- 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 -- you can future-proof with this construct:
245
+ 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. Future-proof with this construct:
232
246
 
233
- ``` javascript
247
+ ```javascript
234
248
  if (cookie.validate() === true) {
235
249
  // it's tasty
236
250
  } else {
@@ -238,221 +252,225 @@ if (cookie.validate() === true) {
238
252
  }
239
253
  ```
240
254
 
241
-
242
- ## CookieJar
255
+ ### CookieJar
243
256
 
244
257
  Exported via `tough.CookieJar`.
245
258
 
246
- ### `CookieJar([store],[options])`
259
+ #### `CookieJar([store][, options])`
247
260
 
248
- Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used.
261
+ Simply use `new CookieJar()`. If a custom store is not passed to the constructor, a [`MemoryCookieStore`](#memorycookiestore) is created and used.
249
262
 
250
263
  The `options` object can be omitted and can have the following properties:
251
264
 
252
- * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk"
253
- * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name.
254
- This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers.
255
-
256
- Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods.
265
+ - _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk"
266
+ - _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name.
267
+ - _prefixSecurity_ - string - default `silent` - set to `'unsafe-disabled'`, `'silent'`, or `'strict'`. See [Cookie Prefixes](#cookie-prefixes) below.
268
+ - _allowSpecialUseDomain_ - boolean - default `false` - accepts special-use domain suffixes, such as `local`. Useful for testing purposes.
269
+ This is not in the standard, but is used sometimes on the web and is accepted by most browsers.
257
270
 
258
- ### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))`
271
+ #### `.setCookie(cookieOrString, currentUrl[, options][, callback(err, cookie)])`
259
272
 
260
- Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties.
273
+ Attempt to set the cookie in the cookie jar. The cookie has updated `.creation`, `.lastAccessed` and `.hostOnly` properties. And returns a promise if a callback is not provided.
261
274
 
262
275
  The `options` object can be omitted and can have the following properties:
263
276
 
264
- * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.
265
- * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`.
266
- * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies
267
- * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option.
277
+ - _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects `HttpOnly` cookies.
278
+ - _secure_ - boolean - autodetect from URL - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` this defaults to `true`, otherwise `false`.
279
+ - _now_ - Date - default `new Date()` - what to use for the creation or access time of cookies.
280
+ - _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option.
281
+ - _sameSiteContext_ - string - default unset - set to `'none'`, `'lax'`, or `'strict'` See [SameSite Cookies](#samesite-cookies) below.
268
282
 
269
- As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual).
283
+ As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual).
270
284
 
271
- ### `.setCookieSync(cookieOrString, currentUrl, [{options}])`
285
+ #### `.setCookieSync(cookieOrString, currentUrl[, options])`
272
286
 
273
- Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
287
+ Synchronous version of [`setCookie`](#setcookiecookieorstring-currenturl-options-callbackerr-cookie); only works with synchronous stores (that is, the default `MemoryCookieStore`).
274
288
 
275
- ### `.getCookies(currentUrl, [{options},] cb(err,cookies))`
289
+ #### `.getCookies(currentUrl[, options][, callback(err, cookies)])`
276
290
 
277
- Retrieve the list of cookies that can be sent in a Cookie header for the current url.
291
+ Retrieve the list of cookies that can be sent in a Cookie header for the current URL. Returns a promise if a callback is not provided.
278
292
 
279
- If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given.
293
+ Returns an array of `Cookie` objects, sorted by default using [`cookieCompare`](#cookiecomparea-b).
294
+
295
+ If an error is encountered it's passed as `err` to the callback, otherwise an array of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given.
280
296
 
281
297
  The `options` object can be omitted and can have the following properties:
282
298
 
283
- * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.
284
- * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`.
285
- * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies
286
- * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially).
287
- * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it).
299
+ - _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects `HttpOnly` cookies.
300
+ - _secure_ - boolean - autodetect from URL - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`.
301
+ - _now_ - Date - default `new Date()` - what to use for the creation or access time of cookies
302
+ - _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` returns expired cookies and does **not** remove them from the store (which is potentially useful for replaying Set-Cookie headers).
303
+ - _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it).
304
+ - _sameSiteContext_ - string - default unset - Set this to `'none'`, `'lax'`, or `'strict'` to enforce SameSite cookies upon retrieval. See [SameSite Cookies](#samesite-cookies) below.
305
+ - _sort_ - boolean - whether to sort the list of cookies.
288
306
 
289
307
  The `.lastAccessed` property of the returned cookies will have been updated.
290
308
 
291
- ### `.getCookiesSync(currentUrl, [{options}])`
309
+ #### `.getCookiesSync(currentUrl, [{options}])`
310
+
311
+ Synchronous version of [`getCookies`](#getcookiescurrenturl-options-callbackerr-cookies); only works with synchronous stores (for example, the default `MemoryCookieStore`).
292
312
 
293
- Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
313
+ #### `.getCookieString(...)`
294
314
 
295
- ### `.getCookieString(...)`
315
+ Accepts the same options as [`.getCookies()`](#getcookiescurrenturl-options-callbackerr-cookies) but returns a string suitable for a Cookie header rather than an Array.
296
316
 
297
- Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`.
317
+ #### `.getCookieStringSync(...)`
298
318
 
299
- ### `.getCookieStringSync(...)`
319
+ Synchronous version of [`getCookieString`](#getcookiestring); only works with synchronous stores (for example, the default `MemoryCookieStore`).
300
320
 
301
- Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
321
+ #### `.getSetCookieStrings(...)`
302
322
 
303
- ### `.getSetCookieStrings(...)`
323
+ Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as [`.getCookies()`](#getcookiescurrenturl-options-callbackerr-cookies). Simply maps the cookie array via `.toString()`.
304
324
 
305
- Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`.
325
+ #### `.getSetCookieStringsSync(...)`
306
326
 
307
- ### `.getSetCookieStringsSync(...)`
327
+ Synchronous version of [`getSetCookieStrings`](#getsetcookiestrings); only works with synchronous stores (for example, the default `MemoryCookieStore`).
308
328
 
309
- Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
329
+ #### `.serialize([callback(err, serializedObject)])`
310
330
 
311
- ### `.serialize(cb(err,serializedObject))`
331
+ Returns a promise if a callback is not provided.
312
332
 
313
333
  Serialize the Jar if the underlying store supports `.getAllCookies`.
314
334
 
315
- **NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array.
335
+ > **NOTE**: Custom `Cookie` properties are discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array.
316
336
 
317
- See [Serialization Format].
337
+ See [Serialization Format](#serialization-format).
318
338
 
319
- ### `.serializeSync()`
339
+ #### `.serializeSync()`
320
340
 
321
- Sync version of .serialize
341
+ Synchronous version of [`serialize`](#serializecallbackerr-serializedobject); only works with synchronous stores (for example, the default `MemoryCookieStore`).
322
342
 
323
- ### `.toJSON()`
343
+ #### `.toJSON()`
324
344
 
325
- Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`.
345
+ Alias of [`.serializeSync()`](#serializesync) for the convenience of `JSON.stringify(cookiejar)`.
326
346
 
327
- ### `CookieJar.deserialize(serialized, [store], cb(err,object))`
347
+ #### `CookieJar.deserialize(serialized[, store][, callback(err, object)])`
328
348
 
329
- A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization.
349
+ A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. A promise is returned if a callback is not provided.
330
350
 
331
351
  The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created.
332
352
 
333
- As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback.
353
+ As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first.
334
354
 
335
- ### `CookieJar.deserializeSync(serialized, [store])`
355
+ #### `CookieJar.deserializeSync(serialized[, store])`
336
356
 
337
- Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work.
357
+ Sync version of [`.deserialize`](#cookiejardeserializeserialized-store-callbackerr-object); only works with synchronous stores (for example, the default `MemoryCookieStore`).
338
358
 
339
- ### `CookieJar.fromJSON(string)`
359
+ #### `CookieJar.fromJSON(string)`
340
360
 
341
- Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`.
361
+ Alias of [`.deserializeSync`](#cookiejardeserializesyncserialized-store) to provide consistency with [`Cookie.fromJSON()`](#cookiefromjsonstrorobj).
342
362
 
343
- ### `.clone([store,]cb(err,newJar))`
363
+ #### `.clone([store][, callback(err, cloned))`
344
364
 
345
- Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa.
365
+ Produces a deep clone of this jar. Modifications to the original do not affect the clone, and vice versa. Returns a promise if a callback is not provided.
346
366
 
347
367
  The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`.
348
368
 
349
- ### `.cloneSync([store])`
369
+ #### `.cloneSync([store])`
350
370
 
351
- Synchronous version of `.clone`, returning a new `CookieJar` instance.
371
+ Synchronous version of [`.clone`](#clonestore-callbackerr-cloned), returning a new `CookieJar` instance.
352
372
 
353
373
  The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used.
354
374
 
355
375
  The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls.
356
376
 
357
- ### `.removeAllCookies(cb(err))`
377
+ #### `.removeAllCookies([callback(err)])`
358
378
 
359
- Removes all cookies from the jar.
379
+ Removes all cookies from the jar. Returns a promise if a callback is not provided.
360
380
 
361
381
  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, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned.
362
382
 
363
- ### `.removeAllCookiesSync()`
383
+ #### `.removeAllCookiesSync()`
364
384
 
365
- Sync version of `.removeAllCookies()`
385
+ Sync version of [`.removeAllCookies()`](#removeallcookiescallbackerr); only works with synchronous stores (for example, the default `MemoryCookieStore`).
366
386
 
367
- ## Store
387
+ ### Store
368
388
 
369
389
  Base class for CookieJar stores. Available as `tough.Store`.
370
390
 
371
- ## Store API
391
+ ### Store API
372
392
 
373
- The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores.
393
+ The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in [`lib/memstore.js`](https://github.com/salesforce/tough-cookie/blob/master/lib/memstore.js). The API uses continuation-passing-style to allow for asynchronous stores.
374
394
 
375
- Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`.
395
+ Stores should inherit from the base `Store` class, which is available as a top-level export.
376
396
 
377
- Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style
397
+ Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods of the containing `CookieJar` can be used.
378
398
 
379
- All `domain` parameters will have been normalized before calling.
399
+ All `domain` parameters are normalized before calling.
380
400
 
381
- The Cookie store must have all of the following methods.
401
+ The Cookie store must have all of the following methods. Note that asynchronous implementations **must** support callback parameters.
382
402
 
383
- ### `store.findCookie(domain, path, key, cb(err,cookie))`
403
+ #### `store.findCookie(domain, path, key, callback(err, cookie))`
384
404
 
385
- Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned.
405
+ Retrieve a cookie with the given domain, path, and key (name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest or newest such cookie should be returned.
386
406
 
387
- Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error).
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).
388
408
 
389
- ### `store.findCookies(domain, path, cb(err,cookies))`
409
+ #### `store.findCookies(domain, path, callback(err, cookies))`
390
410
 
391
- Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above.
411
+ Locates cookies matching the given domain and path. This is most often called in the context of [`cookiejar.getCookies()`](#getcookiescurrenturl-options-callbackerr-cookies).
392
412
 
393
413
  If no cookies are found, the callback MUST be passed an empty array.
394
414
 
395
- The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done.
415
+ The resulting list is checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, and so on), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done.
396
416
 
397
- As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only).
417
+ As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above causes the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (that is, domain-matching only).
398
418
 
399
- ### `store.putCookie(cookie, cb(err))`
419
+ #### `store.putCookie(cookie, callback(err))`
400
420
 
401
- Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur.
421
+ Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties. Depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur.
402
422
 
403
- The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties.
423
+ The `cookie` object MUST NOT be modified; as the caller has already updated the `.creation` and `.lastAccessed` properties.
404
424
 
405
425
  Pass an error if the cookie cannot be stored.
406
426
 
407
- ### `store.updateCookie(oldCookie, newCookie, cb(err))`
427
+ #### `store.updateCookie(oldCookie, newCookie, callback(err))`
408
428
 
409
- Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store.
429
+ Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path`, and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store.
410
430
 
411
- The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement).
431
+ The `.lastAccessed` property is always different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (for example, least-recently-used, which is up to the store to implement).
412
432
 
413
- Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object.
433
+ Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method, a stub that calls [`putCookie`](#storeputcookiecookie-callbackerr) is added to the store object.
414
434
 
415
435
  The `newCookie` and `oldCookie` objects MUST NOT be modified.
416
436
 
417
437
  Pass an error if the newCookie cannot be stored.
418
438
 
419
- ### `store.removeCookie(domain, path, key, cb(err))`
439
+ #### `store.removeCookie(domain, path, key, callback(err))`
420
440
 
421
- Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint).
441
+ Remove a cookie from the store (see notes on [`findCookie`](#storefindcookiedomain-path-key-callbackerr-cookie) about the uniqueness constraint).
422
442
 
423
- The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie.
443
+ The implementation MUST NOT pass an error if the cookie doesn't exist, and only pass an error due to the failure to remove an existing cookie.
424
444
 
425
- ### `store.removeCookies(domain, path, cb(err))`
445
+ #### `store.removeCookies(domain, path, callback(err))`
426
446
 
427
- Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed.
447
+ Removes matching cookies from the store. The `path` parameter is optional and if missing, means all paths in a domain should be removed.
428
448
 
429
449
  Pass an error ONLY if removing any existing cookies failed.
430
450
 
431
- ### `store.removeAllCookies(cb(err))`
451
+ #### `store.removeAllCookies(callback(err))`
432
452
 
433
453
  _Optional_. Removes all cookies from the store.
434
454
 
435
455
  Pass an error if one or more cookies can't be removed.
436
456
 
437
- **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this.
438
-
439
- ### `store.getAllCookies(cb(err, cookies))`
457
+ #### `store.getAllCookies(callback(err, cookies))`
440
458
 
441
- _Optional_. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure.
459
+ _Optional_. Produces an `Array` of all cookies during [`jar.serialize()`](#serializecallbackerr-serializedobject). The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format](#serialization-format) data structure.
442
460
 
443
- Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail.
461
+ Cookies SHOULD be returned in creation order to preserve sorting via [`compareCookie()`](#cookiecomparea-b). For reference, `MemoryCookieStore` sorts by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1-ms. See `cookieCompare` for more detail.
444
462
 
445
463
  Pass an error if retrieval fails.
446
464
 
447
- **Note**: not all Stores can implement this due to technical limitations, so it is optional.
465
+ **Note**: Not all Stores can implement this due to technical limitations, so it is optional.
448
466
 
449
- ## MemoryCookieStore
467
+ ### MemoryCookieStore
450
468
 
451
469
  Inherits from `Store`.
452
470
 
453
471
  A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. Supports serialization, `getAllCookies`, and `removeAllCookies`.
454
472
 
455
- ## Community Cookie Stores
473
+ ### Community Cookie Stores
456
474
 
457
475
  These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look:
458
476
 
@@ -462,10 +480,9 @@ These are some Store implementations authored and maintained by the community. T
462
480
  - [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk
463
481
  - [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage
464
482
 
483
+ ## Serialization Format
465
484
 
466
- # Serialization Format
467
-
468
- **NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`.
485
+ **NOTE**: If you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`.
469
486
 
470
487
  ```js
471
488
  {
@@ -491,7 +508,59 @@ These are some Store implementations authored and maintained by the community. T
491
508
  }
492
509
  ```
493
510
 
494
- # Copyright and License
511
+ ## RFC 6265bis
512
+
513
+ Support for RFC 6265bis revision 02 is being developed. Since this is a bit of an omnibus revision to the RFC 6252, support is broken up into the functional areas.
514
+
515
+ ### Leave Secure Cookies Alone
516
+
517
+ Not yet supported.
518
+
519
+ This change makes it so that if a cookie is sent from the server to the client with a `Secure` attribute, the channel must also be secure or the cookie is ignored.
520
+
521
+ ### SameSite Cookies
522
+
523
+ Supported.
524
+
525
+ This change makes it possible for servers, and supporting clients, to mitigate certain types of CSRF attacks by disallowing `SameSite` cookies from being sent cross-origin.
526
+
527
+ On the Cookie object itself, you can get or set the `.sameSite` attribute, which is serialized into the `SameSite=` cookie attribute. When unset or `undefined`, no `SameSite=` attribute is serialized. The valid values of this attribute are `'none'`, `'lax'`, or `'strict'`. Other values are serialized as-is.
528
+
529
+ When parsing cookies with a `SameSite` cookie attribute, values other than `'lax'` or `'strict'` are parsed as `'none'`. For example, `SomeCookie=SomeValue; SameSite=garbage` parses so that `cookie.sameSite === 'none'`.
530
+
531
+ In order to support SameSite cookies, you must provide a `sameSiteContext` option to _both_ `setCookie` and `getCookies`. Valid values for this option are just like for the Cookie object, but have particular meanings:
532
+
533
+ 1. `'strict'` mode - 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.
534
+ 2. `'lax'` mode - If the request is from another site, _but_ is directly because of navigation by the user, such as, `<link type=prefetch>` or `<a href="...">`, pass `sameSiteContext: 'lax'`.
535
+ 3. `'none'` - Otherwise, pass `sameSiteContext: 'none'` (this indicates a cross-origin request).
536
+ 4. unset/`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.
537
+
538
+ It is highly recommended that you read RFC 6265bis for fine details on SameSite cookies. In particular [Section 8.8](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02##section-8.8) discusses security considerations and defense in depth.
539
+
540
+ ### Cookie Prefixes
541
+
542
+ Supported.
543
+
544
+ 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.
545
+
546
+ Cookie prefixes are defined in [Section 4.1.3 of 6265bis](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03##section-4.1.3).
547
+
548
+ Two prefixes are defined:
549
+
550
+ 1. `"__Secure-" Prefix`: If a cookie's name begins with a case-sensitive match for the string "\_\_Secure-", then the cookie was set with a "Secure" attribute.
551
+ 2. `"__Host-" Prefix`: If a cookie's name begins with a case-sensitive match for the string "\_\_Host-", then the cookie was set with a "Secure" attribute, a "Path" attribute with a value of "/", and no "Domain" attribute.
552
+
553
+ If `prefixSecurity` is enabled for `CookieJar`, then cookies that match the prefixes defined above but do not obey the attribute restrictions are not added.
554
+
555
+ You can define this functionality by passing in the `prefixSecurity` option to `CookieJar`. It can be one of 3 values:
556
+
557
+ 1. `silent`: Enable cookie prefix checking but silently fail to add the cookie if conditions are not met. Default.
558
+ 2. `strict`: Enable cookie prefix checking and error out if conditions are not met.
559
+ 3. `unsafe-disabled`: Disable cookie prefix checking.
560
+
561
+ Note that if `ignoreError` is passed in as `true` then the error is silent regardless of the `prefixSecurity` option (assuming it's enabled).
562
+
563
+ ## Copyright and License
495
564
 
496
565
  BSD-3-Clause:
497
566