umd-tough-cookie.js 265 KB
Newer Older
Chok's avatar
Chok committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["ToughCookie"] = factory();
	else
		root["ToughCookie"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}


/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

	/*!
	 * Copyright (c) 2015, Salesforce.com, Inc.
	 * All rights reserved.
	 *
	 * Redistribution and use in source and binary forms, with or without
	 * modification, are permitted provided that the following conditions are met:
	 *
	 * 1. Redistributions of source code must retain the above copyright notice,
	 * this list of conditions and the following disclaimer.
	 *
	 * 2. Redistributions in binary form must reproduce the above copyright notice,
	 * this list of conditions and the following disclaimer in the documentation
	 * and/or other materials provided with the distribution.
	 *
	 * 3. Neither the name of Salesforce.com nor the names of its contributors may
	 * be used to endorse or promote products derived from this software without
	 * specific prior written permission.
	 *
	 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
	 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
	 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	 * POSSIBILITY OF SUCH DAMAGE.
	 */
	'use strict';
	var urlParse = __webpack_require__(1).parse;
	var util = __webpack_require__(8);
	var ipRegex = __webpack_require__(12)({ exact: true });
	var pubsuffix = __webpack_require__(13);
	var Store = __webpack_require__(17).Store;
	var MemoryCookieStore = __webpack_require__(18).MemoryCookieStore;
	var pathMatch = __webpack_require__(20).pathMatch;
	var VERSION = __webpack_require__(21);

	var punycode;
	try {
	  punycode = __webpack_require__(15);
	} catch(e) {
	  console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
	}

	// From RFC6265 S4.1.1
	// note that it excludes \x3B ";"
	var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;

	var CONTROL_CHARS = /[\x00-\x1F]/;

	// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
	// the "relaxed" mode, see:
	// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
	var TERMINATORS = ['\n', '\r', '\0'];

	// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
	// Note ';' is \x3B
	var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;

	// date-time parsing constants (RFC6265 S5.1.1)

	var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;

	var MONTH_TO_NUM = {
	  jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
	  jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
	};
	var NUM_TO_MONTH = [
	  'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
	];
	var NUM_TO_DAY = [
	  'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
	];

	var MAX_TIME = 2147483647000; // 31-bit max
	var MIN_TIME = 0; // 31-bit min

	/*
	 * Parses a Natural number (i.e., non-negative integer) with either the
	 *    <min>*<max>DIGIT ( non-digit *OCTET )
	 * or
	 *    <min>*<max>DIGIT
	 * grammar (RFC6265 S5.1.1).
	 *
	 * The "trailingOK" boolean controls if the grammar accepts a
	 * "( non-digit *OCTET )" trailer.
	 */
	function parseDigits(token, minDigits, maxDigits, trailingOK) {
	  var count = 0;
	  while (count < token.length) {
	    var c = token.charCodeAt(count);
	    // "non-digit = %x00-2F / %x3A-FF"
	    if (c <= 0x2F || c >= 0x3A) {
	      break;
	    }
	    count++;
	  }

	  // constrain to a minimum and maximum number of digits.
	  if (count < minDigits || count > maxDigits) {
	    return null;
	  }

	  if (!trailingOK && count != token.length) {
	    return null;
	  }

	  return parseInt(token.substr(0,count), 10);
	}

	function parseTime(token) {
	  var parts = token.split(':');
	  var result = [0,0,0];

	  /* RF6256 S5.1.1:
	   *      time            = hms-time ( non-digit *OCTET )
	   *      hms-time        = time-field ":" time-field ":" time-field
	   *      time-field      = 1*2DIGIT
	   */

	  if (parts.length !== 3) {
	    return null;
	  }

	  for (var i = 0; i < 3; i++) {
	    // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
	    // followed by "( non-digit *OCTET )" so therefore the last time-field can
	    // have a trailer
	    var trailingOK = (i == 2);
	    var num = parseDigits(parts[i], 1, 2, trailingOK);
	    if (num === null) {
	      return null;
	    }
	    result[i] = num;
	  }

	  return result;
	}

	function parseMonth(token) {
	  token = String(token).substr(0,3).toLowerCase();
	  var num = MONTH_TO_NUM[token];
	  return num >= 0 ? num : null;
	}

	/*
	 * RFC6265 S5.1.1 date parser (see RFC for full grammar)
	 */
	function parseDate(str) {
	  if (!str) {
	    return;
	  }

	  /* RFC6265 S5.1.1:
	   * 2. Process each date-token sequentially in the order the date-tokens
	   * appear in the cookie-date
	   */
	  var tokens = str.split(DATE_DELIM);
	  if (!tokens) {
	    return;
	  }

	  var hour = null;
	  var minute = null;
	  var second = null;
	  var dayOfMonth = null;
	  var month = null;
	  var year = null;

	  for (var i=0; i<tokens.length; i++) {
	    var token = tokens[i].trim();
	    if (!token.length) {
	      continue;
	    }

	    var result;

	    /* 2.1. If the found-time flag is not set and the token matches the time
	     * production, set the found-time flag and set the hour- value,
	     * minute-value, and second-value to the numbers denoted by the digits in
	     * the date-token, respectively.  Skip the remaining sub-steps and continue
	     * to the next date-token.
	     */
	    if (second === null) {
	      result = parseTime(token);
	      if (result) {
	        hour = result[0];
	        minute = result[1];
	        second = result[2];
	        continue;
	      }
	    }

	    /* 2.2. If the found-day-of-month flag is not set and the date-token matches
	     * the day-of-month production, set the found-day-of- month flag and set
	     * the day-of-month-value to the number denoted by the date-token.  Skip
	     * the remaining sub-steps and continue to the next date-token.
	     */
	    if (dayOfMonth === null) {
	      // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
	      result = parseDigits(token, 1, 2, true);
	      if (result !== null) {
	        dayOfMonth = result;
	        continue;
	      }
	    }

	    /* 2.3. If the found-month flag is not set and the date-token matches the
	     * month production, set the found-month flag and set the month-value to
	     * the month denoted by the date-token.  Skip the remaining sub-steps and
	     * continue to the next date-token.
	     */
	    if (month === null) {
	      result = parseMonth(token);
	      if (result !== null) {
	        month = result;
	        continue;
	      }
	    }

	    /* 2.4. If the found-year flag is not set and the date-token matches the
	     * year production, set the found-year flag and set the year-value to the
	     * number denoted by the date-token.  Skip the remaining sub-steps and
	     * continue to the next date-token.
	     */
	    if (year === null) {
	      // "year = 2*4DIGIT ( non-digit *OCTET )"
	      result = parseDigits(token, 2, 4, true);
	      if (result !== null) {
	        year = result;
	        /* From S5.1.1:
	         * 3.  If the year-value is greater than or equal to 70 and less
	         * than or equal to 99, increment the year-value by 1900.
	         * 4.  If the year-value is greater than or equal to 0 and less
	         * than or equal to 69, increment the year-value by 2000.
	         */
	        if (year >= 70 && year <= 99) {
	          year += 1900;
	        } else if (year >= 0 && year <= 69) {
	          year += 2000;
	        }
	      }
	    }
	  }

	  /* RFC 6265 S5.1.1
	   * "5. Abort these steps and fail to parse the cookie-date if:
	   *     *  at least one of the found-day-of-month, found-month, found-
	   *        year, or found-time flags is not set,
	   *     *  the day-of-month-value is less than 1 or greater than 31,
	   *     *  the year-value is less than 1601,
	   *     *  the hour-value is greater than 23,
	   *     *  the minute-value is greater than 59, or
	   *     *  the second-value is greater than 59.
	   *     (Note that leap seconds cannot be represented in this syntax.)"
	   *
	   * So, in order as above:
	   */
	  if (
	    dayOfMonth === null || month === null || year === null || second === null ||
	    dayOfMonth < 1 || dayOfMonth > 31 ||
	    year < 1601 ||
	    hour > 23 ||
	    minute > 59 ||
	    second > 59
	  ) {
	    return;
	  }

	  return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
	}

	function formatDate(date) {
	  var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
	  var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
	  var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
	  var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
	  return NUM_TO_DAY[date.getUTCDay()] + ', ' +
	    d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
	    h+':'+m+':'+s+' GMT';
	}

	// S5.1.2 Canonicalized Host Names
	function canonicalDomain(str) {
	  if (str == null) {
	    return null;
	  }
	  str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .

	  // convert to IDN if any non-ASCII characters
	  if (punycode && /[^\u0001-\u007f]/.test(str)) {
	    str = punycode.toASCII(str);
	  }

	  return str.toLowerCase();
	}

	// S5.1.3 Domain Matching
	function domainMatch(str, domStr, canonicalize) {
	  if (str == null || domStr == null) {
	    return null;
	  }
	  if (canonicalize !== false) {
	    str = canonicalDomain(str);
	    domStr = canonicalDomain(domStr);
	  }

	  /*
	   * "The domain string and the string are identical. (Note that both the
	   * domain string and the string will have been canonicalized to lower case at
	   * this point)"
	   */
	  if (str == domStr) {
	    return true;
	  }

	  /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */

	  /* "* The string is a host name (i.e., not an IP address)." */
	  if (ipRegex.test(str)) {
	    return false;
	  }

	  /* "* The domain string is a suffix of the string" */
	  var idx = str.indexOf(domStr);
	  if (idx <= 0) {
	    return false; // it's a non-match (-1) or prefix (0)
	  }

	  // e.g "a.b.c".indexOf("b.c") === 2
	  // 5 === 3+2
	  if (str.length !== domStr.length + idx) { // it's not a suffix
	    return false;
	  }

	  /* "* The last character of the string that is not included in the domain
	  * string is a %x2E (".") character." */
	  if (str.substr(idx-1,1) !== '.') {
	    return false;
	  }

	  return true;
	}


	// RFC6265 S5.1.4 Paths and Path-Match

	/*
	 * "The user agent MUST use an algorithm equivalent to the following algorithm
	 * to compute the default-path of a cookie:"
	 *
	 * Assumption: the path (and not query part or absolute uri) is passed in.
	 */
	function defaultPath(path) {
	  // "2. If the uri-path is empty or if the first character of the uri-path is not
	  // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
	  if (!path || path.substr(0,1) !== "/") {
	    return "/";
	  }

	  // "3. If the uri-path contains no more than one %x2F ("/") character, output
	  // %x2F ("/") and skip the remaining step."
	  if (path === "/") {
	    return path;
	  }

	  var rightSlash = path.lastIndexOf("/");
	  if (rightSlash === 0) {
	    return "/";
	  }

	  // "4. Output the characters of the uri-path from the first character up to,
	  // but not including, the right-most %x2F ("/")."
	  return path.slice(0, rightSlash);
	}

	function trimTerminator(str) {
	  for (var t = 0; t < TERMINATORS.length; t++) {
	    var terminatorIdx = str.indexOf(TERMINATORS[t]);
	    if (terminatorIdx !== -1) {
	      str = str.substr(0,terminatorIdx);
	    }
	  }

	  return str;
	}

	function parseCookiePair(cookiePair, looseMode) {
	  cookiePair = trimTerminator(cookiePair);

	  var firstEq = cookiePair.indexOf('=');
	  if (looseMode) {
	    if (firstEq === 0) { // '=' is immediately at start
	      cookiePair = cookiePair.substr(1);
	      firstEq = cookiePair.indexOf('='); // might still need to split on '='
	    }
	  } else { // non-loose mode
	    if (firstEq <= 0) { // no '=' or is at start
	      return; // needs to have non-empty "cookie-name"
	    }
	  }

	  var cookieName, cookieValue;
	  if (firstEq <= 0) {
	    cookieName = "";
	    cookieValue = cookiePair.trim();
	  } else {
	    cookieName = cookiePair.substr(0, firstEq).trim();
	    cookieValue = cookiePair.substr(firstEq+1).trim();
	  }

	  if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
	    return;
	  }

	  var c = new Cookie();
	  c.key = cookieName;
	  c.value = cookieValue;
	  return c;
	}

	function parse(str, options) {
	  if (!options || typeof options !== 'object') {
	    options = {};
	  }
	  str = str.trim();

	  // We use a regex to parse the "name-value-pair" part of S5.2
	  var firstSemi = str.indexOf(';'); // S5.2 step 1
	  var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
	  var c = parseCookiePair(cookiePair, !!options.loose);
	  if (!c) {
	    return;
	  }

	  if (firstSemi === -1) {
	    return c;
	  }

	  // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
	  // (including the %x3B (";") in question)." plus later on in the same section
	  // "discard the first ";" and trim".
	  var unparsed = str.slice(firstSemi + 1).trim();

	  // "If the unparsed-attributes string is empty, skip the rest of these
	  // steps."
	  if (unparsed.length === 0) {
	    return c;
	  }

	  /*
	   * S5.2 says that when looping over the items "[p]rocess the attribute-name
	   * and attribute-value according to the requirements in the following
	   * subsections" for every item.  Plus, for many of the individual attributes
	   * in S5.3 it says to use the "attribute-value of the last attribute in the
	   * cookie-attribute-list".  Therefore, in this implementation, we overwrite
	   * the previous value.
	   */
	  var cookie_avs = unparsed.split(';');
	  while (cookie_avs.length) {
	    var av = cookie_avs.shift().trim();
	    if (av.length === 0) { // happens if ";;" appears
	      continue;
	    }
	    var av_sep = av.indexOf('=');
	    var av_key, av_value;

	    if (av_sep === -1) {
	      av_key = av;
	      av_value = null;
	    } else {
	      av_key = av.substr(0,av_sep);
	      av_value = av.substr(av_sep+1);
	    }

	    av_key = av_key.trim().toLowerCase();

	    if (av_value) {
	      av_value = av_value.trim();
	    }

	    switch(av_key) {
	    case 'expires': // S5.2.1
	      if (av_value) {
	        var exp = parseDate(av_value);
	        // "If the attribute-value failed to parse as a cookie date, ignore the
	        // cookie-av."
	        if (exp) {
	          // over and underflow not realistically a concern: V8's getTime() seems to
	          // store something larger than a 32-bit time_t (even with 32-bit node)
	          c.expires = exp;
	        }
	      }
	      break;

	    case 'max-age': // S5.2.2
	      if (av_value) {
	        // "If the first character of the attribute-value is not a DIGIT or a "-"
	        // character ...[or]... If the remainder of attribute-value contains a
	        // non-DIGIT character, ignore the cookie-av."
	        if (/^-?[0-9]+$/.test(av_value)) {
	          var delta = parseInt(av_value, 10);
	          // "If delta-seconds is less than or equal to zero (0), let expiry-time
	          // be the earliest representable date and time."
	          c.setMaxAge(delta);
	        }
	      }
	      break;

	    case 'domain': // S5.2.3
	      // "If the attribute-value is empty, the behavior is undefined.  However,
	      // the user agent SHOULD ignore the cookie-av entirely."
	      if (av_value) {
	        // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
	        // (".") character."
	        var domain = av_value.trim().replace(/^\./, '');
	        if (domain) {
	          // "Convert the cookie-domain to lower case."
	          c.domain = domain.toLowerCase();
	        }
	      }
	      break;

	    case 'path': // S5.2.4
	      /*
	       * "If the attribute-value is empty or if the first character of the
	       * attribute-value is not %x2F ("/"):
	       *   Let cookie-path be the default-path.
	       * Otherwise:
	       *   Let cookie-path be the attribute-value."
	       *
	       * We'll represent the default-path as null since it depends on the
	       * context of the parsing.
	       */
	      c.path = av_value && av_value[0] === "/" ? av_value : null;
	      break;

	    case 'secure': // S5.2.5
	      /*
	       * "If the attribute-name case-insensitively matches the string "Secure",
	       * the user agent MUST append an attribute to the cookie-attribute-list
	       * with an attribute-name of Secure and an empty attribute-value."
	       */
	      c.secure = true;
	      break;

	    case 'httponly': // S5.2.6 -- effectively the same as 'secure'
	      c.httpOnly = true;
	      break;

	    default:
	      c.extensions = c.extensions || [];
	      c.extensions.push(av);
	      break;
	    }
	  }

	  return c;
	}

	// avoid the V8 deoptimization monster!
	function jsonParse(str) {
	  var obj;
	  try {
	    obj = JSON.parse(str);
	  } catch (e) {
	    return e;
	  }
	  return obj;
	}

	function fromJSON(str) {
	  if (!str) {
	    return null;
	  }

	  var obj;
	  if (typeof str === 'string') {
	    obj = jsonParse(str);
	    if (obj instanceof Error) {
	      return null;
	    }
	  } else {
	    // assume it's an Object
	    obj = str;
	  }

	  var c = new Cookie();
	  for (var i=0; i<Cookie.serializableProperties.length; i++) {
	    var prop = Cookie.serializableProperties[i];
	    if (obj[prop] === undefined ||
	        obj[prop] === Cookie.prototype[prop])
	    {
	      continue; // leave as prototype default
	    }

	    if (prop === 'expires' ||
	        prop === 'creation' ||
	        prop === 'lastAccessed')
	    {
	      if (obj[prop] === null) {
	        c[prop] = null;
	      } else {
	        c[prop] = obj[prop] == "Infinity" ?
	          "Infinity" : new Date(obj[prop]);
	      }
	    } else {
	      c[prop] = obj[prop];
	    }
	  }

	  return c;
	}

	/* Section 5.4 part 2:
	 * "*  Cookies with longer paths are listed before cookies with
	 *     shorter paths.
	 *
	 *  *  Among cookies that have equal-length path fields, cookies with
	 *     earlier creation-times are listed before cookies with later
	 *     creation-times."
	 */

	function cookieCompare(a,b) {
	  var cmp = 0;

	  // descending for length: b CMP a
	  var aPathLen = a.path ? a.path.length : 0;
	  var bPathLen = b.path ? b.path.length : 0;
	  cmp = bPathLen - aPathLen;
	  if (cmp !== 0) {
	    return cmp;
	  }

	  // ascending for time: a CMP b
	  var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
	  var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
	  cmp = aTime - bTime;
	  if (cmp !== 0) {
	    return cmp;
	  }

	  // break ties for the same millisecond (precision of JavaScript's clock)
	  cmp = a.creationIndex - b.creationIndex;

	  return cmp;
	}

	// Gives the permutation of all possible pathMatch()es of a given path. The
	// array is in longest-to-shortest order.  Handy for indexing.
	function permutePath(path) {
	  if (path === '/') {
	    return ['/'];
	  }
	  if (path.lastIndexOf('/') === path.length-1) {
	    path = path.substr(0,path.length-1);
	  }
	  var permutations = [path];
	  while (path.length > 1) {
	    var lindex = path.lastIndexOf('/');
	    if (lindex === 0) {
	      break;
	    }
	    path = path.substr(0,lindex);
	    permutations.push(path);
	  }
	  permutations.push('/');
	  return permutations;
	}

	function getCookieContext(url) {
	  if (url instanceof Object) {
	    return url;
	  }
	  // NOTE: decodeURI will throw on malformed URIs (see GH-32).
	  // Therefore, we will just skip decoding for such URIs.
	  try {
	    url = decodeURI(url);
	  }
	  catch(err) {
	    // Silently swallow error
	  }

	  return urlParse(url);
	}

	function Cookie(options) {
	  options = options || {};

	  Object.keys(options).forEach(function(prop) {
	    if (Cookie.prototype.hasOwnProperty(prop) &&
	        Cookie.prototype[prop] !== options[prop] &&
	        prop.substr(0,1) !== '_')
	    {
	      this[prop] = options[prop];
	    }
	  }, this);

	  this.creation = this.creation || new Date();

	  // used to break creation ties in cookieCompare():
	  Object.defineProperty(this, 'creationIndex', {
	    configurable: false,
	    enumerable: false, // important for assert.deepEqual checks
	    writable: true,
	    value: ++Cookie.cookiesCreated
	  });
	}

	Cookie.cookiesCreated = 0; // incremented each time a cookie is created

	Cookie.parse = parse;
	Cookie.fromJSON = fromJSON;

	Cookie.prototype.key = "";
	Cookie.prototype.value = "";

	// the order in which the RFC has them:
	Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
	Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
	Cookie.prototype.domain = null;
	Cookie.prototype.path = null;
	Cookie.prototype.secure = false;
	Cookie.prototype.httpOnly = false;
	Cookie.prototype.extensions = null;

	// set by the CookieJar:
	Cookie.prototype.hostOnly = null; // boolean when set
	Cookie.prototype.pathIsDefault = null; // boolean when set
	Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
	Cookie.prototype.lastAccessed = null; // Date when set
	Object.defineProperty(Cookie.prototype, 'creationIndex', {
	  configurable: true,
	  enumerable: false,
	  writable: true,
	  value: 0
	});

	Cookie.serializableProperties = Object.keys(Cookie.prototype)
	  .filter(function(prop) {
	    return !(
	      Cookie.prototype[prop] instanceof Function ||
	      prop === 'creationIndex' ||
	      prop.substr(0,1) === '_'
	    );
	  });

	Cookie.prototype.inspect = function inspect() {
	  var now = Date.now();
	  return 'Cookie="'+this.toString() +
	    '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
	    '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
	    '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
	    '"';
	};

	// Use the new custom inspection symbol to add the custom inspect function if
	// available.
	if (util.inspect.custom) {
	  Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
	}

	Cookie.prototype.toJSON = function() {
	  var obj = {};

	  var props = Cookie.serializableProperties;
	  for (var i=0; i<props.length; i++) {
	    var prop = props[i];
	    if (this[prop] === Cookie.prototype[prop]) {
	      continue; // leave as prototype default
	    }

	    if (prop === 'expires' ||
	        prop === 'creation' ||
	        prop === 'lastAccessed')
	    {
	      if (this[prop] === null) {
	        obj[prop] = null;
	      } else {
	        obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
	          "Infinity" : this[prop].toISOString();
	      }
	    } else if (prop === 'maxAge') {
	      if (this[prop] !== null) {
	        // again, intentionally not ===
	        obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
	          this[prop].toString() : this[prop];
	      }
	    } else {
	      if (this[prop] !== Cookie.prototype[prop]) {
	        obj[prop] = this[prop];
	      }
	    }
	  }

	  return obj;
	};

	Cookie.prototype.clone = function() {
	  return fromJSON(this.toJSON());
	};

	Cookie.prototype.validate = function validate() {
	  if (!COOKIE_OCTETS.test(this.value)) {
	    return false;
	  }
	  if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
	    return false;
	  }
	  if (this.maxAge != null && this.maxAge <= 0) {
	    return false; // "Max-Age=" non-zero-digit *DIGIT
	  }
	  if (this.path != null && !PATH_VALUE.test(this.path)) {
	    return false;
	  }

	  var cdomain = this.cdomain();
	  if (cdomain) {
	    if (cdomain.match(/\.$/)) {
	      return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
	    }
	    var suffix = pubsuffix.getPublicSuffix(cdomain);
	    if (suffix == null) { // it's a public suffix
	      return false;
	    }
	  }
	  return true;
	};

	Cookie.prototype.setExpires = function setExpires(exp) {
	  if (exp instanceof Date) {
	    this.expires = exp;
	  } else {
	    this.expires = parseDate(exp) || "Infinity";
	  }
	};

	Cookie.prototype.setMaxAge = function setMaxAge(age) {
	  if (age === Infinity || age === -Infinity) {
	    this.maxAge = age.toString(); // so JSON.stringify() works
	  } else {
	    this.maxAge = age;
	  }
	};

	// gives Cookie header format
	Cookie.prototype.cookieString = function cookieString() {
	  var val = this.value;
	  if (val == null) {
	    val = '';
	  }
	  if (this.key === '') {
	    return val;
	  }
	  return this.key+'='+val;
	};

	// gives Set-Cookie header format
	Cookie.prototype.toString = function toString() {
	  var str = this.cookieString();

	  if (this.expires != Infinity) {
	    if (this.expires instanceof Date) {
	      str += '; Expires='+formatDate(this.expires);
	    } else {
	      str += '; Expires='+this.expires;
	    }
	  }

	  if (this.maxAge != null && this.maxAge != Infinity) {
	    str += '; Max-Age='+this.maxAge;
	  }

	  if (this.domain && !this.hostOnly) {
	    str += '; Domain='+this.domain;
	  }
	  if (this.path) {
	    str += '; Path='+this.path;
	  }

	  if (this.secure) {
	    str += '; Secure';
	  }
	  if (this.httpOnly) {
	    str += '; HttpOnly';
	  }
	  if (this.extensions) {
	    this.extensions.forEach(function(ext) {
	      str += '; '+ext;
	    });
	  }

	  return str;
	};

	// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
	// elsewhere)
	// S5.3 says to give the "latest representable date" for which we use Infinity
	// For "expired" we use 0
	Cookie.prototype.TTL = function TTL(now) {
	  /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
	   * attribute, the Max-Age attribute has precedence and controls the
	   * expiration date of the cookie.
	   * (Concurs with S5.3 step 3)
	   */
	  if (this.maxAge != null) {
	    return this.maxAge<=0 ? 0 : this.maxAge*1000;
	  }

	  var expires = this.expires;
	  if (expires != Infinity) {
	    if (!(expires instanceof Date)) {
	      expires = parseDate(expires) || Infinity;
	    }

	    if (expires == Infinity) {
	      return Infinity;
	    }

	    return expires.getTime() - (now || Date.now());
	  }

	  return Infinity;
	};

	// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
	// elsewhere)
	Cookie.prototype.expiryTime = function expiryTime(now) {
	  if (this.maxAge != null) {
	    var relativeTo = now || this.creation || new Date();
	    var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
	    return relativeTo.getTime() + age;
	  }

	  if (this.expires == Infinity) {
	    return Infinity;
	  }
	  return this.expires.getTime();
	};

	// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
For faster browsing, not all history is shown. View entire blame