tough-cookie 1.2.0 → 2.2.1

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/LICENSE CHANGED
@@ -17,58 +17,11 @@ The following exceptions apply:
17
17
 
18
18
  ===
19
19
 
20
- `pubSufTest()` of generate-pubsuffix.js is in the public domain.
21
-
22
- // Any copyright is dedicated to the Public Domain.
23
- // http://creativecommons.org/publicdomain/zero/1.0/
24
-
25
- ===
26
-
27
- `public-suffix.txt` was obtained from
28
- <https://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1>
29
- via <http://publicsuffix.org>.
30
-
31
- That file contains the usual Mozilla triple-license, for which this project uses it
32
- under the terms of the MPL 1.1:
33
-
34
- // ***** BEGIN LICENSE BLOCK *****
35
- // Version: MPL 1.1/GPL 2.0/LGPL 2.1
36
- //
37
- // The contents of this file are subject to the Mozilla Public License Version
38
- // 1.1 (the "License"); you may not use this file except in compliance with
39
- // the License. You may obtain a copy of the License at
40
- // http://www.mozilla.org/MPL/
41
- //
42
- // Software distributed under the License is distributed on an "AS IS" basis,
43
- // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
44
- // for the specific language governing rights and limitations under the
45
- // License.
46
- //
47
- // The Original Code is the Public Suffix List.
48
- //
49
- // The Initial Developer of the Original Code is
50
- // Jo Hermans <jo.hermans@gmail.com>.
51
- // Portions created by the Initial Developer are Copyright (C) 2007
52
- // the Initial Developer. All Rights Reserved.
53
- //
54
- // Contributor(s):
55
- // Ruben Arakelyan <ruben@rubenarakelyan.com>
56
- // Gervase Markham <gerv@gerv.net>
57
- // Pamela Greene <pamg.bugs@gmail.com>
58
- // David Triendl <david@triendl.name>
59
- // Jothan Frakes <jothan@gmail.com>
60
- // The kind representatives of many TLD registries
61
- //
62
- // Alternatively, the contents of this file may be used under the terms of
63
- // either the GNU General Public License Version 2 or later (the "GPL"), or
64
- // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
65
- // in which case the provisions of the GPL or the LGPL are applicable instead
66
- // of those above. If you wish to allow use of your version of this file only
67
- // under the terms of either the GPL or the LGPL, and not to allow others to
68
- // use your version of this file under the terms of the MPL, indicate your
69
- // decision by deleting the provisions above and replace them with the notice
70
- // and other provisions required by the GPL or the LGPL. If you do not delete
71
- // the provisions above, a recipient may use your version of this file under
72
- // the terms of any one of the MPL, the GPL or the LGPL.
73
- //
74
- // ***** END LICENSE BLOCK *****
20
+ `public_suffix_list.dat` was obtained from
21
+ <https://publicsuffix.org/list/public_suffix_list.dat> via
22
+ <http://publicsuffix.org>. The license for this file is MPL/2.0. The header of
23
+ that file reads as follows:
24
+
25
+ // This Source Code Form is subject to the terms of the Mozilla Public
26
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
27
+ // file, You can obtain one at http://mozilla.org/MPL/2.0/.
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
  # Synopsis
9
9
 
10
10
  ``` javascript
11
- var tough = require('tough-cookie'); // note: not 'cookie', 'cookies' or 'node-cookie'
11
+ var tough = require('tough-cookie');
12
12
  var Cookie = tough.Cookie;
13
13
  var cookie = Cookie.parse(header);
14
14
  cookie.value = 'somethingdifferent';
@@ -32,61 +32,51 @@ Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already take
32
32
 
33
33
  # API
34
34
 
35
- tough
36
- =====
35
+ ## tough
37
36
 
38
37
  Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound".
39
38
 
40
39
  **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.
41
40
 
42
- parseDate(string)
43
- -----------------
41
+ ### `parseDate(string)`
44
42
 
45
43
  Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`.
46
44
 
47
- formatDate(date)
48
- ----------------
45
+ ### `formatDate(date)`
49
46
 
50
47
  Format a Date into a RFC1123 string (the RFC6265-recommended format).
51
48
 
52
- canonicalDomain(str)
53
- --------------------
49
+ ### `canonicalDomain(str)`
54
50
 
55
51
  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).
56
52
 
57
- domainMatch(str,domStr[,canonicalize=true])
58
- -------------------------------------------
53
+ ### `domainMatch(str,domStr[,canonicalize=true])`
59
54
 
60
55
  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".
61
56
 
62
57
  The `canonicalize` parameter will run the other two paramters through `canonicalDomain` or not.
63
58
 
64
- defaultPath(path)
65
- -----------------
59
+ ### `defaultPath(path)`
66
60
 
67
61
  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.
68
62
 
69
63
  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.
70
64
 
71
- pathMatch(reqPath,cookiePath)
72
- -----------------------------
65
+ ### `pathMatch(reqPath,cookiePath)`
73
66
 
74
67
  Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean.
75
68
 
76
69
  This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`.
77
70
 
78
- parse(header)
79
- ----------------------------
71
+ ### `parse(cookieString[, options])`
80
72
 
81
- alias for `Cookie.parse(header)`
73
+ alias for `Cookie.parse(cookieString[, options])`
82
74
 
83
- fromJSON(string)
84
- ----------------
75
+ ### `fromJSON(string)`
85
76
 
86
77
  alias for `Cookie.fromJSON(string)`
87
78
 
88
- getPublicSuffix(hostname)
89
- -------------------------
79
+ ### `getPublicSuffix(hostname)`
90
80
 
91
81
  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.
92
82
 
@@ -94,51 +84,56 @@ For example: `www.example.com` and `www.subdomain.example.com` both have public
94
84
 
95
85
  For further information, see http://publicsuffix.org/. This module derives its list from that site.
96
86
 
97
- cookieCompare(a,b)
98
- ------------------
87
+ ### `cookieCompare(a,b)`
99
88
 
100
- For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). Longest `.path`s go first, then sorted oldest to youngest.
89
+ 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:
90
+
91
+ * Longest `.path`
92
+ * oldest `.creation` (which has a 1ms precision, same as `Date`)
93
+ * lowest `.creationIndex` (to get beyond the 1ms precision)
101
94
 
102
95
  ``` javascript
103
96
  var cookies = [ /* unsorted array of Cookie objects */ ];
104
97
  cookies = cookies.sort(cookieCompare);
105
98
  ```
106
99
 
107
- permuteDomain(domain)
108
- ---------------------
100
+ **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`.
109
101
 
110
- Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores.
102
+ ### `permuteDomain(domain)`
111
103
 
104
+ Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores.
112
105
 
113
- permutePath(path)
114
- -----------------
106
+ ### `permutePath(path)`
115
107
 
116
108
  Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores.
117
109
 
118
- Cookie
119
- ======
120
110
 
121
- Cookie.parse(header)
122
- -----------------------------------
111
+ ## Cookie
112
+
113
+ Exported via `tough.Cookie`.
114
+
115
+ ### `Cookie.parse(cookieString[, options])`
123
116
 
124
117
  Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed.
125
118
 
119
+ The options parameter is not required and currently has only one property:
120
+
121
+ * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant.
122
+
123
+ If options is not an object, it is ignored, which means you can use `Array#map` with it.
124
+
126
125
  Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response:
127
126
 
128
127
  ``` javascript
129
128
  if (res.headers['set-cookie'] instanceof Array)
130
- cookies = res.headers['set-cookie'].map(function (c) { return (Cookie.parse(c)); });
129
+ cookies = res.headers['set-cookie'].map(Cookie.parse);
131
130
  else
132
131
  cookies = [Cookie.parse(res.headers['set-cookie'])];
133
132
  ```
134
133
 
135
- Cookie.fromJSON(string)
136
- -----------------------
134
+ ### Properties
137
135
 
138
- Convert a JSON string to a `Cookie` object. Does a `JSON.parse()` and converts the `.created`, `.lastAccessed` and `.expires` properties into `Date` objects.
139
-
140
- Properties
141
- ==========
136
+ Cookie object properties:
142
137
 
143
138
  * _key_ - string - the name or key of the cookie (default "")
144
139
  * _value_ - string - the value of the cookie (default "")
@@ -149,70 +144,81 @@ Properties
149
144
  * _secure_ - boolean - the `Secure` cookie flag
150
145
  * _httpOnly_ - boolean - the `HttpOnly` cookie flag
151
146
  * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside)
147
+ * _creation_ - `Date` - when this cookie was constructed
148
+ * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation)
152
149
 
153
150
  After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes:
154
151
 
155
152
  * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied)
156
153
  * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one.
157
- * _created_ - `Date` - when this cookie was added to the jar
154
+ * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar
158
155
  * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute.
159
156
 
160
- Construction([{options}])
161
- ------------
157
+ ### `Cookie([{properties}])`
162
158
 
163
- Receives an options object that can contain any Cookie properties, uses the default for unspecified properties.
159
+ Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties.
164
160
 
165
- .toString()
166
- -----------
161
+ ### `.toString()`
167
162
 
168
163
  encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`.
169
164
 
170
- .cookieString()
171
- ---------------
165
+ ### `.cookieString()`
172
166
 
173
167
  encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '=').
174
168
 
175
- .setExpires(String)
176
- -------------------
169
+ ### `.setExpires(String)`
177
170
 
178
171
  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.
179
172
 
180
- .setMaxAge(number)
181
- -------------------
173
+ ### `.setMaxAge(number)`
182
174
 
183
175
  sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly.
184
176
 
185
- .expiryTime([now=Date.now()])
186
- -----------------------------
177
+ ### `.expiryTime([now=Date.now()])`
187
178
 
188
- .expiryDate([now=Date.now()])
189
- -----------------------------
179
+ ### `.expiryDate([now=Date.now()])`
190
180
 
191
181
  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.
192
182
 
193
- Max-Age takes precedence over Expires (as per the RFC). The `.created` attribute -- or, by default, the `now` paramter -- is used to offset the `.maxAge` attribute.
183
+ Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` paramter -- is used to offset the `.maxAge` attribute.
194
184
 
195
185
  If Expires (`.expires`) is set, that's returned.
196
186
 
197
187
  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).
198
188
 
199
- .TTL([now=Date.now()])
200
- ---------
189
+ ### `.TTL([now=Date.now()])`
201
190
 
202
191
  compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply.
203
192
 
204
193
  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.
205
194
 
206
- .canonicalizedDoman()
207
- ---------------------
195
+ ### `.canonicalizedDoman()`
208
196
 
209
- .cdomain()
210
- ----------
197
+ ### `.cdomain()`
211
198
 
212
199
  return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters.
213
200
 
214
- .validate()
215
- -----------
201
+ ### `.toJSON()`
202
+
203
+ For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized.
204
+
205
+ Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`).
206
+
207
+ **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.
208
+
209
+ ### `Cookie.fromJSON(strOrObj)`
210
+
211
+ Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first.
212
+
213
+ 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.
214
+
215
+ Returns `null` upon JSON parsing error.
216
+
217
+ ### `.clone()`
218
+
219
+ Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`.
220
+
221
+ ### `.validate()`
216
222
 
217
223
  Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive.
218
224
 
@@ -226,48 +232,41 @@ if (cookie.validate() === true) {
226
232
  }
227
233
  ```
228
234
 
229
- CookieJar
230
- =========
231
235
 
232
- Construction([store = new MemoryCookieStore()][, rejectPublicSuffixes])
233
- ------------
236
+ ## CookieJar
234
237
 
235
- 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.
238
+ Exported via `tough.CookieJar`.
239
+
240
+ ### `CookieJar([store],[options])`
236
241
 
242
+ 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.
237
243
 
238
- Attributes
239
- ----------
244
+ The `options` object can be omitted and can have the following properties:
240
245
 
241
- * _rejectPublicSuffixes_ - boolean - reject cookies with domains like "com" and "co.uk" (default: `true`)
246
+ * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk"
247
+ * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name.
248
+ This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers.
242
249
 
243
250
  Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods.
244
251
 
245
- .setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))
246
- -------------------------------------------------------------------
252
+ ### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))`
247
253
 
248
- 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 `.created`, `.lastAccessed` and `.hostOnly` properties.
254
+ 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.
249
255
 
250
256
  The `options` object can be omitted and can have the following properties:
251
257
 
252
258
  * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.
253
259
  * _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`.
254
260
  * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies
255
- * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. CookieStore errors aren't ignored by this option.
261
+ * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option.
256
262
 
257
263
  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).
258
264
 
259
- .setCookieSync(cookieOrString, currentUrl, [{options}])
260
- -------------------------------------------------------
265
+ ### `.setCookieSync(cookieOrString, currentUrl, [{options}])`
261
266
 
262
267
  Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
263
268
 
264
- .storeCookie(cookie, [{options},] cb(err,cookie))
265
- -------------------------------------------------
266
-
267
- __REMOVED__ removed in lieu of the CookieStore API below
268
-
269
- .getCookies(currentUrl, [{options},] cb(err,cookies))
270
- -----------------------------------------------------
269
+ ### `.getCookies(currentUrl, [{options},] cb(err,cookies))`
271
270
 
272
271
  Retrieve the list of cookies that can be sent in a Cookie header for the current url.
273
272
 
@@ -279,59 +278,99 @@ The `options` object can be omitted and can have the following properties:
279
278
  * _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`.
280
279
  * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies
281
280
  * _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).
282
- * _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 CookieStore `fetchCookies` function (the default MemoryCookieStore supports it).
281
+ * _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).
283
282
 
284
283
  The `.lastAccessed` property of the returned cookies will have been updated.
285
284
 
286
- .getCookiesSync(currentUrl, [{options}])
287
- ----------------------------------------
285
+ ### `.getCookiesSync(currentUrl, [{options}])`
288
286
 
289
287
  Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
290
288
 
291
- .getCookieString(...)
292
- ---------------------
289
+ ### `.getCookieString(...)`
293
290
 
294
291
  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()`.
295
292
 
296
- .getCookieStringSync(...)
297
- -------------------------
293
+ ### `.getCookieStringSync(...)`
298
294
 
299
295
  Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
300
296
 
301
- .getSetCookieStrings(...)
302
- -------------------------
297
+ ### `.getSetCookieStrings(...)`
303
298
 
304
299
  Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`.
305
300
 
306
- .getSetCookieStringsSync(...)
307
- -----------------------------
301
+ ### `.getSetCookieStringsSync(...)`
308
302
 
309
303
  Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`).
310
304
 
311
- Store
312
- =====
305
+ ### `.serialize(cb(err,serializedObject))`
306
+
307
+ Serialize the Jar if the underlying store supports `.getAllCookies`.
308
+
309
+ **NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array.
310
+
311
+ See [Serialization Format].
312
+
313
+ ### `.serializeSync()`
314
+
315
+ Sync version of .serialize
313
316
 
314
- Base class for CookieJar stores.
317
+ ### `.toJSON()`
315
318
 
316
- # CookieStore API
319
+ Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`.
320
+
321
+ ### `CookieJar.deserialize(serialized, [store], cb(err,object))`
322
+
323
+ 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.
324
+
325
+ The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created.
326
+
327
+ 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.
328
+
329
+ ### `CookieJar.deserializeSync(serialized, [store])`
330
+
331
+ Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work.
332
+
333
+ ### `CookieJar.fromJSON(string)`
334
+
335
+ Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`.
336
+
337
+ ### `.clone([store,]cb(err,newJar))`
338
+
339
+ Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa.
340
+
341
+ 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()`.
342
+
343
+ ### `.cloneSync([store])`
344
+
345
+ Synchronous version of `.clone`, returning a new `CookieJar` instance.
346
+
347
+ The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used.
348
+
349
+ 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.
350
+
351
+ ## Store
352
+
353
+ Base class for CookieJar stores. Available as `tough.Store`.
354
+
355
+ ## Store API
317
356
 
318
357
  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.
319
358
 
320
- Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set, then the `*Sync` methods on the CookieJar can be used.
359
+ Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`.
360
+
361
+ 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
321
362
 
322
363
  All `domain` parameters will have been normalized before calling.
323
364
 
324
365
  The Cookie store must have all of the following methods.
325
366
 
326
- store.findCookie(domain, path, key, cb(err,cookie))
327
- ---------------------------------------------------
367
+ ### `store.findCookie(domain, path, key, cb(err,cookie))`
328
368
 
329
369
  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.
330
370
 
331
371
  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).
332
372
 
333
- store.findCookies(domain, path, cb(err,cookies))
334
- ------------------------------------------------
373
+ ### `store.findCookies(domain, path, cb(err,cookies))`
335
374
 
336
375
  Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above.
337
376
 
@@ -341,8 +380,7 @@ The resulting list will be checked for applicability to the current request acco
341
380
 
342
381
  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).
343
382
 
344
- store.putCookie(cookie, cb(err))
345
- --------------------------------
383
+ ### `store.putCookie(cookie, cb(err))`
346
384
 
347
385
  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.
348
386
 
@@ -350,12 +388,11 @@ The `cookie` object MUST NOT be modified; the caller will have already updated t
350
388
 
351
389
  Pass an error if the cookie cannot be stored.
352
390
 
353
- store.updateCookie(oldCookie, newCookie, cb(err))
354
- -------------------------------------------------
391
+ ### `store.updateCookie(oldCookie, newCookie, cb(err))`
355
392
 
356
393
  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.
357
394
 
358
- The `.lastAccessed` property will always be different between the two objects and `.created` will always be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are sorted (or selected for deletion).
395
+ 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).
359
396
 
360
397
  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.
361
398
 
@@ -363,30 +400,63 @@ The `newCookie` and `oldCookie` objects MUST NOT be modified.
363
400
 
364
401
  Pass an error if the newCookie cannot be stored.
365
402
 
366
- store.removeCookie(domain, path, key, cb(err))
367
- ----------------------------------------------
403
+ ### `store.removeCookie(domain, path, key, cb(err))`
368
404
 
369
405
  Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint).
370
406
 
371
407
  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.
372
408
 
373
- store.removeCookies(domain, path, cb(err))
374
- ------------------------------------------
409
+ ### `store.removeCookies(domain, path, cb(err))`
375
410
 
376
411
  Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed.
377
412
 
378
413
  Pass an error ONLY if removing any existing cookies failed.
379
414
 
380
- MemoryCookieStore
381
- =================
415
+ ### `store.getAllCookies(cb(err, cookies))`
416
+
417
+ 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.
418
+
419
+ 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.
420
+
421
+ Pass an error if retrieval fails.
422
+
423
+ ## MemoryCookieStore
382
424
 
383
- Inherits from Store.
425
+ Inherits from `Store`.
384
426
 
385
- Just-in-memory CookieJar synchronous store implementation, used by default.
427
+ 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.
428
+
429
+ # Serialization Format
430
+
431
+ **NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`.
432
+
433
+ ```js
434
+ {
435
+ // The version of tough-cookie that serialized this jar.
436
+ version: 'tough-cookie@1.x.y',
437
+
438
+ // add the store type, to make humans happy:
439
+ storeType: 'MemoryCookieStore',
440
+
441
+ // CookieJar configuration:
442
+ rejectPublicSuffixes: true,
443
+ // ... future items go here
444
+
445
+ // Gets filled from jar.store.getAllCookies():
446
+ cookies: [
447
+ {
448
+ key: 'string',
449
+ value: 'string',
450
+ // ...
451
+ /* other Cookie.serializableProperties go here */
452
+ }
453
+ ]
454
+ }
455
+ ```
386
456
 
387
457
  # Copyright and License
388
458
 
389
- (tl;dr: BSD-3-Clause with some MPL/1.1)
459
+ (tl;dr: BSD-3-Clause with some MPL/2.0)
390
460
 
391
461
  ```text
392
462
  Copyright (c) 2015, Salesforce.com, Inc.
@@ -419,4 +489,4 @@ Just-in-memory CookieJar synchronous store implementation, used by default.
419
489
  POSSIBILITY OF SUCH DAMAGE.
420
490
  ```
421
491
 
422
- Portions may be licensed under different licenses (in particular public-suffix.txt is MPL/1.1); please read the LICENSE file for full details.
492
+ Portions may be licensed under different licenses (in particular `public_suffix_list.dat` is MPL/2.0); please read that file and the LICENSE file for full details.