tough-cookie 0.13.0 → 2.0.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/test/api_test.js CHANGED
@@ -247,22 +247,6 @@ vows
247
247
  assert.instanceOf(cookie, Cookie);
248
248
  }
249
249
  },
250
- "setCookieSync strict parse error": {
251
- topic: function () {
252
- var jar = new CookieJar();
253
- var opts = {strict: true};
254
- try {
255
- jar.setCookieSync("farbe=weiß", 'http://example.com/index.html', opts);
256
- return false;
257
- } catch (e) {
258
- return e;
259
- }
260
- },
261
- "throws the error": function (err) {
262
- assert.instanceOf(err, Error);
263
- assert.equal(err.message, "Cookie failed to parse");
264
- }
265
- },
266
250
  "getCookiesSync": {
267
251
  topic: function () {
268
252
  var jar = new CookieJar();
@@ -33,6 +33,7 @@ var vows = require('vows');
33
33
  var assert = require('assert');
34
34
  var tough = require('../lib/cookie');
35
35
  var Cookie = tough.Cookie;
36
+ var CookieJar = tough.CookieJar;
36
37
 
37
38
  function toKeyArray(cookies) {
38
39
  return cookies.map(function (c) {
@@ -42,6 +43,71 @@ function toKeyArray(cookies) {
42
43
 
43
44
  vows
44
45
  .describe('Cookie sorting')
46
+ .addBatch({
47
+ "Assumptions:": {
48
+ ".creationIndex is set during construction": function() {
49
+ var now = new Date();
50
+ var c1 = new Cookie();
51
+ var c2 = new Cookie();
52
+ assert.isNumber(c1.creationIndex);
53
+ assert.isNumber(c2.creationIndex);
54
+ assert(c1.creationIndex < c2.creationIndex,
55
+ 'creationIndex should increase with each construction');
56
+ },
57
+
58
+ ".creationIndex is set during construction (forced ctime)": function() {
59
+ var now = new Date();
60
+ var c1 = new Cookie({creation: now});
61
+ var c2 = new Cookie({creation: now});
62
+ assert.strictEqual(c1.creation, c2.creation);
63
+ assert.isNumber(c1.creationIndex);
64
+ assert.isNumber(c2.creationIndex);
65
+ assert(c1.creationIndex < c2.creationIndex,
66
+ 'creationIndex should increase with each construction');
67
+ },
68
+
69
+ ".creationIndex is left alone during new setCookie": function() {
70
+ var jar = new CookieJar();
71
+ var c = new Cookie({key:'k', value:'v', domain:'example.com'});
72
+ var now = new Date();
73
+ var beforeDate = c.creation;
74
+ assert.instanceOf(beforeDate, Date);
75
+ assert.notStrictEqual(now, beforeDate);
76
+ var beforeIndex = c.creationIndex;
77
+ assert.isNumber(c.creationIndex);
78
+
79
+ jar.setCookieSync(c, 'http://example.com/', {now: now});
80
+
81
+ assert.strictEqual(c.creation, now);
82
+ assert.strictEqual(c.creationIndex, beforeIndex);
83
+ },
84
+
85
+ ".creationIndex is preserved during update setCookie": function() {
86
+ var jar = new CookieJar();
87
+
88
+ var thisMs = Date.now();
89
+ var t1 = new Date(thisMs);
90
+ var t2 = new Date(thisMs);
91
+ assert.notStrictEqual(t1, t2); // Date objects are distinct
92
+
93
+ var c = new Cookie({key:'k', value:'v1', domain:'example.com'});
94
+ jar.setCookieSync(c, 'http://example.com/', {now: t1});
95
+ var originalIndex = c.creationIndex;
96
+
97
+ assert.strictEqual(c.creation, t1);
98
+ assert.strictEqual(c.lastAccessed, t1);
99
+
100
+ c = new Cookie({key:'k', value:'v2', domain:'example.com'});
101
+ assert.notStrictEqual(c.creation, t1); // new timestamp assigned
102
+
103
+ jar.setCookieSync(c, 'http://example.com/', {now: t2});
104
+
105
+ assert.strictEqual(c.creation, t1); // retained
106
+ assert.strictEqual(c.lastAccessed, t2); // updated
107
+ assert.strictEqual(c.creationIndex, originalIndex); // retained
108
+ },
109
+ }
110
+ })
45
111
  .addBatch({
46
112
  "Cookie Sorting": {
47
113
  topic: function () {
@@ -123,8 +123,8 @@ vows
123
123
  },
124
124
  "null": {
125
125
  topic: function(f) { return f(null) },
126
- "looks good": function(str) {
127
- assert.match(str, /"maxAge":null/);
126
+ "absent": function(str) {
127
+ assert.match(str, /(?!"maxAge":null)/); // NB: negative RegExp
128
128
  }
129
129
  }
130
130
  },
@@ -148,10 +148,10 @@ vows
148
148
  assert.deepEqual(list, ['example.com', 'bar.example.com', 'foo.bar.example.com']);
149
149
  }
150
150
  },
151
- "invalid domain": {
151
+ "local domain": {
152
152
  topic: tough.permuteDomain.bind(null, 'foo.bar.example.localduhmain'),
153
153
  "got three things": function (list) {
154
- assert.equal(list, null);
154
+ assert.deepEqual(list, ['example.localduhmain', 'bar.example.localduhmain', 'foo.bar.example.localduhmain']);
155
155
  }
156
156
  }
157
157
  },
package/test/ietf_test.js CHANGED
@@ -61,8 +61,7 @@ function setGetCookieVows() {
61
61
  jar.setCookieSync(cookieStr, sentFrom, {ignoreError: true});
62
62
  });
63
63
 
64
- var actual = jar.getCookiesSync(sentTo);
65
- actual = actual.sort(tough.cookieCompare);
64
+ var actual = jar.getCookiesSync(sentTo,{sort:true});
66
65
 
67
66
  assert.strictEqual(actual.length, expected.length);
68
67
 
@@ -0,0 +1,348 @@
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
+
32
+ 'use strict';
33
+ var vows = require('vows');
34
+ var assert = require('assert');
35
+ var tough = require('../lib/cookie');
36
+ var Cookie = tough.Cookie;
37
+ var CookieJar = tough.CookieJar;
38
+ var Store = tough.Store;
39
+ var MemoryCookieStore = tough.MemoryCookieStore;
40
+ var VERSION = require('../package.json').version;
41
+
42
+ var domains = ['example.com','www.example.com','example.net'];
43
+ var paths = ['/','/foo','/foo/bar'];
44
+
45
+ var isInteger = Number.isInteger || function(value) {
46
+ // Node 0.10 (still supported) doesn't have Number.isInteger
47
+ // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
48
+ return typeof value === "number" &&
49
+ isFinite(value) &&
50
+ Math.floor(value) === value;
51
+ };
52
+
53
+ function setUp(context) {
54
+ context.now = new Date();
55
+ context.nowISO = context.now.toISOString();
56
+ context.expires = new Date(context.now.getTime() + 86400000);
57
+
58
+ var c, domain;
59
+ context.jar = new CookieJar();
60
+
61
+ context.totalCookies = 0;
62
+
63
+ // Do paths first since the MemoryCookieStore index is domain at the top
64
+ // level. This should cause the preservation of creation order in
65
+ // getAllCookies to be exercised.
66
+ for (var i = 0; i<paths.length; i++) {
67
+ var path = paths[i];
68
+ for (var j = 0; j<domains.length; j++) {
69
+ domain = domains[j];
70
+ c = new Cookie({
71
+ expires: context.expires,
72
+ domain: domain,
73
+ path: path,
74
+ key: 'key',
75
+ value: 'value'+j+i
76
+ });
77
+ context.jar.setCookieSync(c, 'http://'+domain+'/', {now: context.now});
78
+ context.totalCookies++;
79
+ }
80
+ }
81
+
82
+ // corner cases
83
+ domain = 'example.com';
84
+ var cornerCases = [
85
+ { expires: 'Infinity', key: 'infExp', value: 'infExp' },
86
+ { maxAge: 3600, key: 'max', value: 'max' },
87
+ { expires: context.expires, key: 'flags', value: 'flags',
88
+ secure: true, httpOnly: true },
89
+ { expires: context.expires, key: 'honly', value: 'honly',
90
+ hostOnly: true, domain: 'www.example.org' },
91
+ ];
92
+
93
+ for (var i = 0; i<cornerCases.length; i++) {
94
+ cornerCases[i].domain = cornerCases[i].domain || 'example.org';
95
+ cornerCases[i].path = '/';
96
+ c = new Cookie(cornerCases[i]);
97
+ context.jar.setCookieSync(c, 'https://www.example.org/', {now: context.now});
98
+ context.totalCookies++;
99
+ }
100
+ }
101
+
102
+ function checkMetadata(serialized) {
103
+ assert.notEqual(serialized, null);
104
+ assert.isObject(serialized);
105
+ assert.equal(serialized.version, 'tough-cookie@'+VERSION);
106
+ assert.equal(serialized.storeType, 'MemoryCookieStore');
107
+ assert.typeOf(serialized.rejectPublicSuffixes, 'boolean');
108
+ assert.isArray(serialized.cookies);
109
+ }
110
+
111
+ var serializedCookiePropTypes = {
112
+ 'key': 'string',
113
+ 'value': 'string',
114
+ 'expires': 'isoDate', // if "Infinity" it's supposed to be missing
115
+ 'maxAge': 'intOrInf',
116
+ 'domain': 'string',
117
+ 'path': 'string',
118
+ 'secure': 'boolean',
119
+ 'httpOnly': 'boolean',
120
+ 'extensions': 'array', // of strings, technically
121
+ 'hostOnly': 'boolean',
122
+ 'pathIsDefault': 'boolean',
123
+ 'creation': 'isoDate',
124
+ 'lastAccessed': 'isoDate'
125
+ };
126
+
127
+ function validateSerializedCookie(cookie) {
128
+ assert.isObject(cookie);
129
+ assert.isFalse(cookie instanceof Cookie);
130
+
131
+ Object.keys(cookie).forEach(function(prop) {
132
+ var type = serializedCookiePropTypes[prop];
133
+ switch(type) {
134
+ case 'string':
135
+ case 'boolean':
136
+ case 'array':
137
+ case 'number':
138
+ assert.typeOf(cookie[prop], type);
139
+ break;
140
+
141
+ case 'intOrInf':
142
+ if (cookie[prop] === 'Infinity' || cookie[prop] === '-Infinity') {
143
+ assert(true);
144
+ } else {
145
+ assert(isInteger(cookie[prop]),
146
+ "serialized property isn't integer: "+prop);
147
+ }
148
+ break;
149
+
150
+ case 'isoDate':
151
+ // rather than a regexp, assert it's parsable and equal
152
+ var parsed = Date.parse(cookie[prop]);
153
+ assert(parsed, 'could not parse serialized date property');
154
+ // assert.equals(cookie[prop], parsed.toISOString());
155
+ break;
156
+
157
+ default:
158
+ assert.fail("unexpected serialized property: "+prop);
159
+ }
160
+ });
161
+
162
+ }
163
+
164
+ vows
165
+ .describe('CookieJar serialization')
166
+ .addBatch({
167
+ "Assumptions:": {
168
+ "serializableProperties all accounted for": function() {
169
+ var actualKeys = Cookie.serializableProperties.concat([]); // copy
170
+ actualKeys.sort();
171
+ var expectedKeys = Object.keys(serializedCookiePropTypes);
172
+ expectedKeys.sort();
173
+ assert.deepEqual(actualKeys, expectedKeys);
174
+ }
175
+ }
176
+ })
177
+ .addBatch({
178
+ "For Stores without getAllCookies": {
179
+ topic: function() {
180
+ var store = new Store();
181
+ store.synchronous = true;
182
+ var jar = new CookieJar(store);
183
+ return jar;
184
+ },
185
+ "Cannot call toJSON": function(jar) {
186
+ assert.throws(function() {
187
+ jar.toJSON();
188
+ }, 'getAllCookies is not implemented (therefore jar cannot be serialized)');
189
+ }
190
+ }
191
+ })
192
+ .addBatch({
193
+ "For async stores": {
194
+ topic: function() {
195
+ var store = new MemoryCookieStore();
196
+ store.synchronous = false; // pretend it's async
197
+ var jar = new CookieJar(store);
198
+ return jar;
199
+ },
200
+ "Cannot call toJSON": function(jar) {
201
+ assert.throws(function() {
202
+ jar.toJSON();
203
+ }, 'CookieJar store is not synchronous; use async API instead.');
204
+ }
205
+ }
206
+ })
207
+ .addBatch({
208
+ "With a small store": {
209
+ topic: function() {
210
+ var now = this.now = new Date();
211
+ this.jar = new CookieJar();
212
+ // domain cookie with custom extension
213
+ var cookie = Cookie.parse('sid=one; domain=example.com; path=/; fubar');
214
+ this.jar.setCookieSync(cookie, 'http://example.com/', {now: this.now});
215
+
216
+ cookie = Cookie.parse('sid=two; domain=example.net; path=/; fubar');
217
+ this.jar.setCookieSync(cookie, 'http://example.net/', {now: this.now});
218
+
219
+ return this.jar;
220
+ },
221
+
222
+ "serialize synchronously": {
223
+ topic: function(jar) {
224
+ return jar.serializeSync();
225
+ },
226
+ "it gives a serialization with the two cookies": function(data) {
227
+ checkMetadata(data);
228
+ assert.equal(data.cookies.length, 2);
229
+ data.cookies.forEach(function(cookie) {
230
+ validateSerializedCookie(cookie);
231
+ });
232
+ },
233
+ "then deserialize": {
234
+ topic: function(data) {
235
+ return CookieJar.deserializeSync(data);
236
+ },
237
+ "memstores are identical": function(newJar) {
238
+ assert.deepEqual(this.jar.store, newJar.store);
239
+ }
240
+ }
241
+ },
242
+
243
+ "serialize asynchronously": {
244
+ topic: function(jar) {
245
+ jar.serialize(this.callback);
246
+ },
247
+ "it gives a serialization with the two cookies": function(data) {
248
+ checkMetadata(data);
249
+ assert.equal(data.cookies.length, 2);
250
+ data.cookies.forEach(function(cookie) {
251
+ validateSerializedCookie(cookie);
252
+ });
253
+ },
254
+ "then deserialize": {
255
+ topic: function(data) {
256
+ CookieJar.deserialize(data, this.callback);
257
+ },
258
+ "memstores are identical": function(newJar) {
259
+ assert.deepEqual(this.jar.store, newJar.store);
260
+ }
261
+ }
262
+ }
263
+ }
264
+ })
265
+ .addBatch({
266
+ "With a moderately-sized store": {
267
+ topic: function() {
268
+ setUp(this);
269
+ this.jar.serialize(this.callback);
270
+ },
271
+ "has expected metadata": function(err,jsonObj) {
272
+ assert.isNull(err);
273
+ assert.equal(jsonObj.version, 'tough-cookie@'+VERSION);
274
+ assert.isTrue(jsonObj.rejectPublicSuffixes);
275
+ assert.equal(jsonObj.storeType, 'MemoryCookieStore');
276
+ },
277
+ "has a bunch of objects as 'raw' cookies": function(jsonObj) {
278
+ assert.isArray(jsonObj.cookies);
279
+ assert.equal(jsonObj.cookies.length, this.totalCookies);
280
+
281
+ jsonObj.cookies.forEach(function(cookie) {
282
+ validateSerializedCookie(cookie);
283
+
284
+ if (cookie.key === 'key') {
285
+ assert.match(cookie.value, /^value\d\d/);
286
+ }
287
+
288
+ if (cookie.key === 'infExp' || cookie.key === 'max') {
289
+ assert.isUndefined(cookie.expires);
290
+ } else {
291
+ assert.strictEqual(cookie.expires, this.expires.toISOString())
292
+ }
293
+
294
+ if (cookie.key === 'max') {
295
+ assert.strictEqual(cookie.maxAge, 3600);
296
+ } else {
297
+ assert.isUndefined(cookie.maxAge);
298
+ }
299
+
300
+ assert.equal(cookie.hostOnly, cookie.key === 'honly');
301
+
302
+ if (cookie.key === 'flags') {
303
+ assert.isTrue(cookie.secure);
304
+ assert.isTrue(cookie.httpOnly);
305
+ } else {
306
+ assert.isUndefined(cookie.secure);
307
+ assert.isUndefined(cookie.httpOnly);
308
+ }
309
+
310
+ assert.strictEqual(cookie.creation, this.nowISO);
311
+ assert.strictEqual(cookie.lastAccessed, this.nowISO);
312
+
313
+ }, this);
314
+ },
315
+
316
+ "then taking it for a round-trip": {
317
+ topic: function(jsonObj) {
318
+ CookieJar.deserialize(jsonObj, this.callback);
319
+ },
320
+ "memstore index is identical": function(err,newJar) {
321
+ assert.deepEqual(newJar.store.idx, this.jar.store.idx);
322
+ },
323
+ "then spot-check retrieval": {
324
+ topic: function(newJar) {
325
+ newJar.getCookies('http://example.org/', this.callback);
326
+ },
327
+ "gets expected cookies": function(results) {
328
+ assert.isArray(results);
329
+ assert.equal(results.length, 2);
330
+
331
+ results.forEach(function(cookie) {
332
+ assert.instanceOf(cookie, Cookie);
333
+
334
+ if (cookie.key === 'infExp') {
335
+ assert.strictEqual(cookie.expires, "Infinity");
336
+ assert.strictEqual(cookie.TTL(this.now), Infinity);
337
+ } else if (cookie.key === 'max') {
338
+ assert.strictEqual(cookie.TTL(this.now), 3600*1000);
339
+ } else {
340
+ assert.fail('Unexpected cookie key: '+cookie.key);
341
+ }
342
+ }.bind(this));
343
+ }
344
+ }
345
+ }
346
+ }
347
+ })
348
+ .export(module);