Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81146 views
1
/*!
2
* Copyright (c) 2015, Salesforce.com, Inc.
3
* All rights reserved.
4
*
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions are met:
7
*
8
* 1. Redistributions of source code must retain the above copyright notice,
9
* this list of conditions and the following disclaimer.
10
*
11
* 2. Redistributions in binary form must reproduce the above copyright notice,
12
* this list of conditions and the following disclaimer in the documentation
13
* and/or other materials provided with the distribution.
14
*
15
* 3. Neither the name of Salesforce.com nor the names of its contributors may
16
* be used to endorse or promote products derived from this software without
17
* specific prior written permission.
18
*
19
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
* POSSIBILITY OF SUCH DAMAGE.
30
*/
31
'use strict';
32
var net = require('net');
33
var urlParse = require('url').parse;
34
var pubsuffix = require('./pubsuffix');
35
var Store = require('./store').Store;
36
var MemoryCookieStore = require('./memstore').MemoryCookieStore;
37
var pathMatch = require('./pathMatch').pathMatch;
38
39
var punycode;
40
try {
41
punycode = require('punycode');
42
} catch(e) {
43
console.warn("cookie: can't load punycode; won't use punycode for domain normalization");
44
}
45
46
var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
47
48
// From RFC6265 S4.1.1
49
// note that it excludes \x3B ";"
50
var COOKIE_OCTET = /[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/;
51
var COOKIE_OCTETS = new RegExp('^'+COOKIE_OCTET.source+'$');
52
53
// Double quotes are part of the value (see: S4.1.1).
54
// '\r', '\n' and '\0' should be treated as a terminator in the "relaxed" mode
55
// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60)
56
// '=' and ';' are attribute/values separators
57
// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L64)
58
var COOKIE_PAIR = /^([^=;]+)\s*=\s*(("?)[^\n\r\0]*\3)/;
59
60
// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
61
// Note ';' is \x3B
62
var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
63
64
// Used for checking whether or not there is a trailing semi-colon
65
var TRAILING_SEMICOLON = /;+$/;
66
67
var DAY_OF_MONTH = /^(\d{1,2})[^\d]*$/;
68
var TIME = /^(\d{1,2})[^\d]*:(\d{1,2})[^\d]*:(\d{1,2})[^\d]*$/;
69
var MONTH = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i;
70
71
var MONTH_TO_NUM = {
72
jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
73
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
74
};
75
var NUM_TO_MONTH = [
76
'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
77
];
78
var NUM_TO_DAY = [
79
'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
80
];
81
82
var YEAR = /^(\d{2}|\d{4})$/; // 2 to 4 digits
83
84
var MAX_TIME = 2147483647000; // 31-bit max
85
var MIN_TIME = 0; // 31-bit min
86
87
var cookiesCreated = 0; // Number of cookies created in runtime
88
89
90
// RFC6265 S5.1.1 date parser:
91
function parseDate(str) {
92
if (!str) {
93
return;
94
}
95
96
/* RFC6265 S5.1.1:
97
* 2. Process each date-token sequentially in the order the date-tokens
98
* appear in the cookie-date
99
*/
100
var tokens = str.split(DATE_DELIM);
101
if (!tokens) {
102
return;
103
}
104
105
var hour = null;
106
var minutes = null;
107
var seconds = null;
108
var day = null;
109
var month = null;
110
var year = null;
111
112
for (var i=0; i<tokens.length; i++) {
113
var token = tokens[i].trim();
114
if (!token.length) {
115
continue;
116
}
117
118
var result;
119
120
/* 2.1. If the found-time flag is not set and the token matches the time
121
* production, set the found-time flag and set the hour- value,
122
* minute-value, and second-value to the numbers denoted by the digits in
123
* the date-token, respectively. Skip the remaining sub-steps and continue
124
* to the next date-token.
125
*/
126
if (seconds === null) {
127
result = TIME.exec(token);
128
if (result) {
129
hour = parseInt(result[1], 10);
130
minutes = parseInt(result[2], 10);
131
seconds = parseInt(result[3], 10);
132
/* RFC6265 S5.1.1.5:
133
* [fail if]
134
* * the hour-value is greater than 23,
135
* * the minute-value is greater than 59, or
136
* * the second-value is greater than 59.
137
*/
138
if(hour > 23 || minutes > 59 || seconds > 59) {
139
return;
140
}
141
142
continue;
143
}
144
}
145
146
/* 2.2. If the found-day-of-month flag is not set and the date-token matches
147
* the day-of-month production, set the found-day-of- month flag and set
148
* the day-of-month-value to the number denoted by the date-token. Skip
149
* the remaining sub-steps and continue to the next date-token.
150
*/
151
if (day === null) {
152
result = DAY_OF_MONTH.exec(token);
153
if (result) {
154
day = parseInt(result, 10);
155
/* RFC6265 S5.1.1.5:
156
* [fail if] the day-of-month-value is less than 1 or greater than 31
157
*/
158
if(day < 1 || day > 31) {
159
return;
160
}
161
continue;
162
}
163
}
164
165
/* 2.3. If the found-month flag is not set and the date-token matches the
166
* month production, set the found-month flag and set the month-value to
167
* the month denoted by the date-token. Skip the remaining sub-steps and
168
* continue to the next date-token.
169
*/
170
if (month === null) {
171
result = MONTH.exec(token);
172
if (result) {
173
month = MONTH_TO_NUM[result[1].toLowerCase()];
174
continue;
175
}
176
}
177
178
/* 2.4. If the found-year flag is not set and the date-token matches the year
179
* production, set the found-year flag and set the year-value to the number
180
* denoted by the date-token. Skip the remaining sub-steps and continue to
181
* the next date-token.
182
*/
183
if (year === null) {
184
result = YEAR.exec(token);
185
if (result) {
186
year = parseInt(result[0], 10);
187
/* From S5.1.1:
188
* 3. If the year-value is greater than or equal to 70 and less
189
* than or equal to 99, increment the year-value by 1900.
190
* 4. If the year-value is greater than or equal to 0 and less
191
* than or equal to 69, increment the year-value by 2000.
192
*/
193
if (70 <= year && year <= 99) {
194
year += 1900;
195
} else if (0 <= year && year <= 69) {
196
year += 2000;
197
}
198
199
if (year < 1601) {
200
return; // 5. ... the year-value is less than 1601
201
}
202
}
203
}
204
}
205
206
if (seconds === null || day === null || month === null || year === null) {
207
return; // 5. ... at least one of the found-day-of-month, found-month, found-
208
// year, or found-time flags is not set,
209
}
210
211
return new Date(Date.UTC(year, month, day, hour, minutes, seconds));
212
}
213
214
function formatDate(date) {
215
var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
216
var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
217
var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
218
var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
219
return NUM_TO_DAY[date.getUTCDay()] + ', ' +
220
d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
221
h+':'+m+':'+s+' GMT';
222
}
223
224
// S5.1.2 Canonicalized Host Names
225
function canonicalDomain(str) {
226
if (str == null) {
227
return null;
228
}
229
str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
230
231
// convert to IDN if any non-ASCII characters
232
if (punycode && /[^\u0001-\u007f]/.test(str)) {
233
str = punycode.toASCII(str);
234
}
235
236
return str.toLowerCase();
237
}
238
239
// S5.1.3 Domain Matching
240
function domainMatch(str, domStr, canonicalize) {
241
if (str == null || domStr == null) {
242
return null;
243
}
244
if (canonicalize !== false) {
245
str = canonicalDomain(str);
246
domStr = canonicalDomain(domStr);
247
}
248
249
/*
250
* "The domain string and the string are identical. (Note that both the
251
* domain string and the string will have been canonicalized to lower case at
252
* this point)"
253
*/
254
if (str == domStr) {
255
return true;
256
}
257
258
/* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
259
260
/* "* The string is a host name (i.e., not an IP address)." */
261
if (net.isIP(str)) {
262
return false;
263
}
264
265
/* "* The domain string is a suffix of the string" */
266
var idx = str.indexOf(domStr);
267
if (idx <= 0) {
268
return false; // it's a non-match (-1) or prefix (0)
269
}
270
271
// e.g "a.b.c".indexOf("b.c") === 2
272
// 5 === 3+2
273
if (str.length !== domStr.length + idx) { // it's not a suffix
274
return false;
275
}
276
277
/* "* The last character of the string that is not included in the domain
278
* string is a %x2E (".") character." */
279
if (str.substr(idx-1,1) !== '.') {
280
return false;
281
}
282
283
return true;
284
}
285
286
287
// RFC6265 S5.1.4 Paths and Path-Match
288
289
/*
290
* "The user agent MUST use an algorithm equivalent to the following algorithm
291
* to compute the default-path of a cookie:"
292
*
293
* Assumption: the path (and not query part or absolute uri) is passed in.
294
*/
295
function defaultPath(path) {
296
// "2. If the uri-path is empty or if the first character of the uri-path is not
297
// a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
298
if (!path || path.substr(0,1) !== "/") {
299
return "/";
300
}
301
302
// "3. If the uri-path contains no more than one %x2F ("/") character, output
303
// %x2F ("/") and skip the remaining step."
304
if (path === "/") {
305
return path;
306
}
307
308
var rightSlash = path.lastIndexOf("/");
309
if (rightSlash === 0) {
310
return "/";
311
}
312
313
// "4. Output the characters of the uri-path from the first character up to,
314
// but not including, the right-most %x2F ("/")."
315
return path.slice(0, rightSlash);
316
}
317
318
319
function parse(str) {
320
str = str.trim();
321
322
// S4.1.1 Trailing semi-colons are not part of the specification.
323
var semiColonCheck = TRAILING_SEMICOLON.exec(str);
324
if (semiColonCheck) {
325
str = str.slice(0, semiColonCheck.index);
326
}
327
328
// We use a regex to parse the "name-value-pair" part of S5.2
329
var firstSemi = str.indexOf(';'); // S5.2 step 1
330
var result = COOKIE_PAIR.exec(firstSemi === -1 ? str : str.substr(0,firstSemi));
331
332
// Rx satisfies the "the name string is empty" and "lacks a %x3D ("=")"
333
// constraints as well as trimming any whitespace.
334
if (!result) {
335
return;
336
}
337
338
var c = new Cookie();
339
c.key = result[1].trim();
340
c.value = result[2].trim();
341
342
if (firstSemi === -1) {
343
return c;
344
}
345
346
// S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
347
// (including the %x3B (";") in question)." plus later on in the same section
348
// "discard the first ";" and trim".
349
var unparsed = str.slice(firstSemi).replace(/^\s*;\s*/,'').trim();
350
351
// "If the unparsed-attributes string is empty, skip the rest of these
352
// steps."
353
if (unparsed.length === 0) {
354
return c;
355
}
356
357
/*
358
* S5.2 says that when looping over the items "[p]rocess the attribute-name
359
* and attribute-value according to the requirements in the following
360
* subsections" for every item. Plus, for many of the individual attributes
361
* in S5.3 it says to use the "attribute-value of the last attribute in the
362
* cookie-attribute-list". Therefore, in this implementation, we overwrite
363
* the previous value.
364
*/
365
var cookie_avs = unparsed.split(/\s*;\s*/);
366
while (cookie_avs.length) {
367
var av = cookie_avs.shift();
368
var av_sep = av.indexOf('=');
369
var av_key, av_value;
370
371
if (av_sep === -1) {
372
av_key = av;
373
av_value = null;
374
} else {
375
av_key = av.substr(0,av_sep);
376
av_value = av.substr(av_sep+1);
377
}
378
379
av_key = av_key.trim().toLowerCase();
380
381
if (av_value) {
382
av_value = av_value.trim();
383
}
384
385
switch(av_key) {
386
case 'expires': // S5.2.1
387
if (av_value) {
388
var exp = parseDate(av_value);
389
// "If the attribute-value failed to parse as a cookie date, ignore the
390
// cookie-av."
391
if (exp) {
392
// over and underflow not realistically a concern: V8's getTime() seems to
393
// store something larger than a 32-bit time_t (even with 32-bit node)
394
c.expires = exp;
395
}
396
}
397
break;
398
399
case 'max-age': // S5.2.2
400
if (av_value) {
401
// "If the first character of the attribute-value is not a DIGIT or a "-"
402
// character ...[or]... If the remainder of attribute-value contains a
403
// non-DIGIT character, ignore the cookie-av."
404
if (/^-?[0-9]+$/.test(av_value)) {
405
var delta = parseInt(av_value, 10);
406
// "If delta-seconds is less than or equal to zero (0), let expiry-time
407
// be the earliest representable date and time."
408
c.setMaxAge(delta);
409
}
410
}
411
break;
412
413
case 'domain': // S5.2.3
414
// "If the attribute-value is empty, the behavior is undefined. However,
415
// the user agent SHOULD ignore the cookie-av entirely."
416
if (av_value) {
417
// S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
418
// (".") character."
419
var domain = av_value.trim().replace(/^\./, '');
420
if (domain) {
421
// "Convert the cookie-domain to lower case."
422
c.domain = domain.toLowerCase();
423
}
424
}
425
break;
426
427
case 'path': // S5.2.4
428
/*
429
* "If the attribute-value is empty or if the first character of the
430
* attribute-value is not %x2F ("/"):
431
* Let cookie-path be the default-path.
432
* Otherwise:
433
* Let cookie-path be the attribute-value."
434
*
435
* We'll represent the default-path as null since it depends on the
436
* context of the parsing.
437
*/
438
c.path = av_value && av_value[0] === "/" ? av_value : null;
439
break;
440
441
case 'secure': // S5.2.5
442
/*
443
* "If the attribute-name case-insensitively matches the string "Secure",
444
* the user agent MUST append an attribute to the cookie-attribute-list
445
* with an attribute-name of Secure and an empty attribute-value."
446
*/
447
c.secure = true;
448
break;
449
450
case 'httponly': // S5.2.6 -- effectively the same as 'secure'
451
c.httpOnly = true;
452
break;
453
454
default:
455
c.extensions = c.extensions || [];
456
c.extensions.push(av);
457
break;
458
}
459
}
460
461
// ensure a default date for sorting:
462
c.creation = new Date();
463
//NOTE: add runtime index for the cookieCompare() to resolve the situation when Date's precision is not enough .
464
//Store initial UTC time as well, so we will be able to determine if we need to fallback to the Date object.
465
c._creationRuntimeIdx = ++cookiesCreated;
466
c._initialCreationTime = c.creation.getTime();
467
return c;
468
}
469
470
function fromJSON(str) {
471
if (!str) {
472
return null;
473
}
474
475
var obj;
476
try {
477
obj = JSON.parse(str);
478
} catch (e) {
479
return null;
480
}
481
482
var c = new Cookie();
483
for (var i=0; i<numCookieProperties; i++) {
484
var prop = cookieProperties[i];
485
if (obj[prop] == null) {
486
continue;
487
}
488
if (prop === 'expires' ||
489
prop === 'creation' ||
490
prop === 'lastAccessed')
491
{
492
c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]);
493
} else {
494
c[prop] = obj[prop];
495
}
496
}
497
498
499
// ensure a default date for sorting:
500
c.creation = c.creation || new Date();
501
502
return c;
503
}
504
505
/* Section 5.4 part 2:
506
* "* Cookies with longer paths are listed before cookies with
507
* shorter paths.
508
*
509
* * Among cookies that have equal-length path fields, cookies with
510
* earlier creation-times are listed before cookies with later
511
* creation-times."
512
*/
513
514
function cookieCompare(a,b) {
515
// descending for length: b CMP a
516
var deltaLen = (b.path ? b.path.length : 0) - (a.path ? a.path.length : 0);
517
if (deltaLen !== 0) {
518
return deltaLen;
519
}
520
521
var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
522
var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
523
524
// NOTE: if creation dates are equal and they were not modified from the outside,
525
// then use _creationRuntimeIdx for the comparison.
526
if(aTime === bTime && aTime === a._initialCreationTime && bTime === b._initialCreationTime) {
527
return a._creationRuntimeIdx - b._creationRuntimeIdx;
528
}
529
530
// ascending for time: a CMP b
531
return aTime - bTime;
532
}
533
534
// Gives the permutation of all possible pathMatch()es of a given path. The
535
// array is in longest-to-shortest order. Handy for indexing.
536
function permutePath(path) {
537
if (path === '/') {
538
return ['/'];
539
}
540
if (path.lastIndexOf('/') === path.length-1) {
541
path = path.substr(0,path.length-1);
542
}
543
var permutations = [path];
544
while (path.length > 1) {
545
var lindex = path.lastIndexOf('/');
546
if (lindex === 0) {
547
break;
548
}
549
path = path.substr(0,lindex);
550
permutations.push(path);
551
}
552
permutations.push('/');
553
return permutations;
554
}
555
556
function getCookieContext(url) {
557
if (url instanceof Object) {
558
return url;
559
}
560
// NOTE: decodeURI will throw on malformed URIs (see GH-32).
561
// Therefore, we will just skip decoding for such URIs.
562
try {
563
url = decodeURI(url);
564
}
565
catch(err) {
566
// Silently swallow error
567
}
568
569
return urlParse(url);
570
}
571
572
function Cookie (opts) {
573
if (typeof opts !== "object") {
574
return;
575
}
576
Object.keys(opts).forEach(function (key) {
577
if (Cookie.prototype.hasOwnProperty(key)) {
578
this[key] = opts[key] || Cookie.prototype[key];
579
}
580
}.bind(this));
581
}
582
583
Cookie.parse = parse;
584
Cookie.fromJSON = fromJSON;
585
586
Cookie.prototype.key = "";
587
Cookie.prototype.value = "";
588
589
// the order in which the RFC has them:
590
Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
591
Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
592
Cookie.prototype.domain = null;
593
Cookie.prototype.path = null;
594
Cookie.prototype.secure = false;
595
Cookie.prototype.httpOnly = false;
596
Cookie.prototype.extensions = null;
597
598
// set by the CookieJar:
599
Cookie.prototype.hostOnly = null; // boolean when set
600
Cookie.prototype.pathIsDefault = null; // boolean when set
601
Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
602
Cookie.prototype._initialCreationTime = null; // Used to determine if cookie.creation was modified
603
Cookie.prototype._creationRuntimeIdx = null; // Runtime index of the created cookie, used in cookieCompare()
604
Cookie.prototype.lastAccessed = null; // Date when set
605
606
var cookieProperties = Object.freeze(Object.keys(Cookie.prototype).map(function(p) {
607
if (p instanceof Function) {
608
return;
609
}
610
return p;
611
}));
612
var numCookieProperties = cookieProperties.length;
613
614
Cookie.prototype.inspect = function inspect() {
615
var now = Date.now();
616
return 'Cookie="'+this.toString() +
617
'; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
618
'; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
619
'; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
620
'"';
621
};
622
623
Cookie.prototype.validate = function validate() {
624
if (!COOKIE_OCTETS.test(this.value)) {
625
return false;
626
}
627
if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
628
return false;
629
}
630
if (this.maxAge != null && this.maxAge <= 0) {
631
return false; // "Max-Age=" non-zero-digit *DIGIT
632
}
633
if (this.path != null && !PATH_VALUE.test(this.path)) {
634
return false;
635
}
636
637
var cdomain = this.cdomain();
638
if (cdomain) {
639
if (cdomain.match(/\.$/)) {
640
return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
641
}
642
var suffix = pubsuffix.getPublicSuffix(cdomain);
643
if (suffix == null) { // it's a public suffix
644
return false;
645
}
646
}
647
return true;
648
};
649
650
Cookie.prototype.setExpires = function setExpires(exp) {
651
if (exp instanceof Date) {
652
this.expires = exp;
653
} else {
654
this.expires = parseDate(exp) || "Infinity";
655
}
656
};
657
658
Cookie.prototype.setMaxAge = function setMaxAge(age) {
659
if (age === Infinity || age === -Infinity) {
660
this.maxAge = age.toString(); // so JSON.stringify() works
661
} else {
662
this.maxAge = age;
663
}
664
};
665
666
// gives Cookie header format
667
Cookie.prototype.cookieString = function cookieString() {
668
var val = this.value;
669
if (val == null) {
670
val = '';
671
}
672
return this.key+'='+val;
673
};
674
675
// gives Set-Cookie header format
676
Cookie.prototype.toString = function toString() {
677
var str = this.cookieString();
678
679
if (this.expires != Infinity) {
680
if (this.expires instanceof Date) {
681
str += '; Expires='+formatDate(this.expires);
682
} else {
683
str += '; Expires='+this.expires;
684
}
685
}
686
687
if (this.maxAge != null && this.maxAge != Infinity) {
688
str += '; Max-Age='+this.maxAge;
689
}
690
691
if (this.domain && !this.hostOnly) {
692
str += '; Domain='+this.domain;
693
}
694
if (this.path) {
695
str += '; Path='+this.path;
696
}
697
698
if (this.secure) {
699
str += '; Secure';
700
}
701
if (this.httpOnly) {
702
str += '; HttpOnly';
703
}
704
if (this.extensions) {
705
this.extensions.forEach(function(ext) {
706
str += '; '+ext;
707
});
708
}
709
710
return str;
711
};
712
713
// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
714
// elsewhere)
715
// S5.3 says to give the "latest representable date" for which we use Infinity
716
// For "expired" we use 0
717
Cookie.prototype.TTL = function TTL(now) {
718
/* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
719
* attribute, the Max-Age attribute has precedence and controls the
720
* expiration date of the cookie.
721
* (Concurs with S5.3 step 3)
722
*/
723
if (this.maxAge != null) {
724
return this.maxAge<=0 ? 0 : this.maxAge*1000;
725
}
726
727
var expires = this.expires;
728
if (expires != Infinity) {
729
if (!(expires instanceof Date)) {
730
expires = parseDate(expires) || Infinity;
731
}
732
733
if (expires == Infinity) {
734
return Infinity;
735
}
736
737
return expires.getTime() - (now || Date.now());
738
}
739
740
return Infinity;
741
};
742
743
// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
744
// elsewhere)
745
Cookie.prototype.expiryTime = function expiryTime(now) {
746
if (this.maxAge != null) {
747
var relativeTo = this.creation || now || new Date();
748
var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
749
return relativeTo.getTime() + age;
750
}
751
752
if (this.expires == Infinity) {
753
return Infinity;
754
}
755
return this.expires.getTime();
756
};
757
758
// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
759
// elsewhere), except it returns a Date
760
Cookie.prototype.expiryDate = function expiryDate(now) {
761
var millisec = this.expiryTime(now);
762
if (millisec == Infinity) {
763
return new Date(MAX_TIME);
764
} else if (millisec == -Infinity) {
765
return new Date(MIN_TIME);
766
} else {
767
return new Date(millisec);
768
}
769
};
770
771
// This replaces the "persistent-flag" parts of S5.3 step 3
772
Cookie.prototype.isPersistent = function isPersistent() {
773
return (this.maxAge != null || this.expires != Infinity);
774
};
775
776
// Mostly S5.1.2 and S5.2.3:
777
Cookie.prototype.cdomain =
778
Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
779
if (this.domain == null) {
780
return null;
781
}
782
return canonicalDomain(this.domain);
783
};
784
785
786
function CookieJar(store, rejectPublicSuffixes) {
787
if (rejectPublicSuffixes != null) {
788
this.rejectPublicSuffixes = rejectPublicSuffixes;
789
}
790
791
if (!store) {
792
store = new MemoryCookieStore();
793
}
794
this.store = store;
795
}
796
CookieJar.prototype.store = null;
797
CookieJar.prototype.rejectPublicSuffixes = true;
798
var CAN_BE_SYNC = [];
799
800
CAN_BE_SYNC.push('setCookie');
801
CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
802
var err;
803
var context = getCookieContext(url);
804
if (options instanceof Function) {
805
cb = options;
806
options = {};
807
}
808
809
var host = canonicalDomain(context.hostname);
810
811
// S5.3 step 1
812
if (!(cookie instanceof Cookie)) {
813
cookie = Cookie.parse(cookie);
814
}
815
if (!cookie) {
816
err = new Error("Cookie failed to parse");
817
return cb(options.ignoreError ? null : err);
818
}
819
820
// S5.3 step 2
821
var now = options.now || new Date(); // will assign later to save effort in the face of errors
822
823
// S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
824
825
// S5.3 step 4: NOOP; domain is null by default
826
827
// S5.3 step 5: public suffixes
828
if (this.rejectPublicSuffixes && cookie.domain) {
829
var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
830
if (suffix == null) { // e.g. "com"
831
err = new Error("Cookie has domain set to a public suffix");
832
return cb(options.ignoreError ? null : err);
833
}
834
}
835
836
// S5.3 step 6:
837
if (cookie.domain) {
838
if (!domainMatch(host, cookie.cdomain(), false)) {
839
err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
840
return cb(options.ignoreError ? null : err);
841
}
842
843
if (cookie.hostOnly == null) { // don't reset if already set
844
cookie.hostOnly = false;
845
}
846
847
} else {
848
cookie.hostOnly = true;
849
cookie.domain = host;
850
}
851
852
//S5.2.4 If the attribute-value is empty or if the first character of the
853
//attribute-value is not %x2F ("/"):
854
//Let cookie-path be the default-path.
855
if (!cookie.path || cookie.path[0] !== '/') {
856
cookie.path = defaultPath(context.pathname);
857
cookie.pathIsDefault = true;
858
}
859
860
// S5.3 step 8: NOOP; secure attribute
861
// S5.3 step 9: NOOP; httpOnly attribute
862
863
// S5.3 step 10
864
if (options.http === false && cookie.httpOnly) {
865
err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
866
return cb(options.ignoreError ? null : err);
867
}
868
869
var store = this.store;
870
871
if (!store.updateCookie) {
872
store.updateCookie = function(oldCookie, newCookie, cb) {
873
this.putCookie(newCookie, cb);
874
};
875
}
876
877
function withCookie(err, oldCookie) {
878
if (err) {
879
return cb(err);
880
}
881
882
var next = function(err) {
883
if (err) {
884
return cb(err);
885
} else {
886
cb(null, cookie);
887
}
888
};
889
890
if (oldCookie) {
891
// S5.3 step 11 - "If the cookie store contains a cookie with the same name,
892
// domain, and path as the newly created cookie:"
893
if (options.http === false && oldCookie.httpOnly) { // step 11.2
894
err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
895
return cb(options.ignoreError ? null : err);
896
}
897
cookie.creation = oldCookie.creation; // step 11.3
898
cookie.lastAccessed = now;
899
// Step 11.4 (delete cookie) is implied by just setting the new one:
900
store.updateCookie(oldCookie, cookie, next); // step 12
901
902
} else {
903
cookie.creation = cookie.lastAccessed = now;
904
store.putCookie(cookie, next); // step 12
905
}
906
}
907
908
store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
909
};
910
911
// RFC6365 S5.4
912
CAN_BE_SYNC.push('getCookies');
913
CookieJar.prototype.getCookies = function(url, options, cb) {
914
var context = getCookieContext(url);
915
if (options instanceof Function) {
916
cb = options;
917
options = {};
918
}
919
920
var host = canonicalDomain(context.hostname);
921
var path = context.pathname || '/';
922
923
var secure = options.secure;
924
if (secure == null && context.protocol &&
925
(context.protocol == 'https:' || context.protocol == 'wss:'))
926
{
927
secure = true;
928
}
929
930
var http = options.http;
931
if (http == null) {
932
http = true;
933
}
934
935
var now = options.now || Date.now();
936
var expireCheck = options.expire !== false;
937
var allPaths = !!options.allPaths;
938
var store = this.store;
939
940
function matchingCookie(c) {
941
// "Either:
942
// The cookie's host-only-flag is true and the canonicalized
943
// request-host is identical to the cookie's domain.
944
// Or:
945
// The cookie's host-only-flag is false and the canonicalized
946
// request-host domain-matches the cookie's domain."
947
if (c.hostOnly) {
948
if (c.domain != host) {
949
return false;
950
}
951
} else {
952
if (!domainMatch(host, c.domain, false)) {
953
return false;
954
}
955
}
956
957
// "The request-uri's path path-matches the cookie's path."
958
if (!allPaths && !pathMatch(path, c.path)) {
959
return false;
960
}
961
962
// "If the cookie's secure-only-flag is true, then the request-uri's
963
// scheme must denote a "secure" protocol"
964
if (c.secure && !secure) {
965
return false;
966
}
967
968
// "If the cookie's http-only-flag is true, then exclude the cookie if the
969
// cookie-string is being generated for a "non-HTTP" API"
970
if (c.httpOnly && !http) {
971
return false;
972
}
973
974
// deferred from S5.3
975
// non-RFC: allow retention of expired cookies by choice
976
if (expireCheck && c.expiryTime() <= now) {
977
store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
978
return false;
979
}
980
981
return true;
982
}
983
984
store.findCookies(host, allPaths ? null : path, function(err,cookies) {
985
if (err) {
986
return cb(err);
987
}
988
989
cookies = cookies.filter(matchingCookie);
990
991
// sorting of S5.4 part 2
992
if (options.sort !== false) {
993
cookies = cookies.sort(cookieCompare);
994
}
995
996
// S5.4 part 3
997
var now = new Date();
998
cookies.forEach(function(c) {
999
c.lastAccessed = now;
1000
});
1001
// TODO persist lastAccessed
1002
1003
cb(null,cookies);
1004
});
1005
};
1006
1007
CAN_BE_SYNC.push('getCookieString');
1008
CookieJar.prototype.getCookieString = function(/*..., cb*/) {
1009
var args = Array.prototype.slice.call(arguments,0);
1010
var cb = args.pop();
1011
var next = function(err,cookies) {
1012
if (err) {
1013
cb(err);
1014
} else {
1015
cb(null, cookies
1016
.sort(cookieCompare)
1017
.map(function(c){
1018
return c.cookieString();
1019
})
1020
.join('; '));
1021
}
1022
};
1023
args.push(next);
1024
this.getCookies.apply(this,args);
1025
};
1026
1027
CAN_BE_SYNC.push('getSetCookieStrings');
1028
CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
1029
var args = Array.prototype.slice.call(arguments,0);
1030
var cb = args.pop();
1031
var next = function(err,cookies) {
1032
if (err) {
1033
cb(err);
1034
} else {
1035
cb(null, cookies.map(function(c){
1036
return c.toString();
1037
}));
1038
}
1039
};
1040
args.push(next);
1041
this.getCookies.apply(this,args);
1042
};
1043
1044
// Use a closure to provide a true imperative API for synchronous stores.
1045
function syncWrap(method) {
1046
return function() {
1047
if (!this.store.synchronous) {
1048
throw new Error('CookieJar store is not synchronous; use async API instead.');
1049
}
1050
1051
var args = Array.prototype.slice.call(arguments);
1052
var syncErr, syncResult;
1053
args.push(function syncCb(err, result) {
1054
syncErr = err;
1055
syncResult = result;
1056
});
1057
this[method].apply(this, args);
1058
1059
if (syncErr) {
1060
throw syncErr;
1061
}
1062
return syncResult;
1063
};
1064
}
1065
1066
// wrap all declared CAN_BE_SYNC methods in the sync wrapper
1067
CAN_BE_SYNC.forEach(function(method) {
1068
CookieJar.prototype[method+'Sync'] = syncWrap(method);
1069
});
1070
1071
module.exports = {
1072
CookieJar: CookieJar,
1073
Cookie: Cookie,
1074
Store: Store,
1075
MemoryCookieStore: MemoryCookieStore,
1076
parseDate: parseDate,
1077
formatDate: formatDate,
1078
parse: parse,
1079
fromJSON: fromJSON,
1080
domainMatch: domainMatch,
1081
defaultPath: defaultPath,
1082
pathMatch: pathMatch,
1083
getPublicSuffix: pubsuffix.getPublicSuffix,
1084
cookieCompare: cookieCompare,
1085
permuteDomain: require('./permuteDomain').permuteDomain,
1086
permutePath: permutePath,
1087
canonicalDomain: canonicalDomain
1088
};
1089
1090