cookie.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 util = require('util');
  35. var pubsuffix = require('./pubsuffix-psl');
  36. var Store = require('./store').Store;
  37. var MemoryCookieStore = require('./memstore').MemoryCookieStore;
  38. var pathMatch = require('./pathMatch').pathMatch;
  39. var VERSION = require('./version');
  40. var punycode;
  41. try {
  42. punycode = require('punycode');
  43. } catch(e) {
  44. console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
  45. }
  46. // From RFC6265 S4.1.1
  47. // note that it excludes \x3B ";"
  48. var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
  49. var CONTROL_CHARS = /[\x00-\x1F]/;
  50. // From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
  51. // the "relaxed" mode, see:
  52. // https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
  53. var TERMINATORS = ['\n', '\r', '\0'];
  54. // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
  55. // Note ';' is \x3B
  56. var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
  57. // date-time parsing constants (RFC6265 S5.1.1)
  58. var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
  59. var MONTH_TO_NUM = {
  60. jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
  61. jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
  62. };
  63. var NUM_TO_MONTH = [
  64. 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
  65. ];
  66. var NUM_TO_DAY = [
  67. 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
  68. ];
  69. var MAX_TIME = 2147483647000; // 31-bit max
  70. var MIN_TIME = 0; // 31-bit min
  71. /*
  72. * Parses a Natural number (i.e., non-negative integer) with either the
  73. * <min>*<max>DIGIT ( non-digit *OCTET )
  74. * or
  75. * <min>*<max>DIGIT
  76. * grammar (RFC6265 S5.1.1).
  77. *
  78. * The "trailingOK" boolean controls if the grammar accepts a
  79. * "( non-digit *OCTET )" trailer.
  80. */
  81. function parseDigits(token, minDigits, maxDigits, trailingOK) {
  82. var count = 0;
  83. while (count < token.length) {
  84. var c = token.charCodeAt(count);
  85. // "non-digit = %x00-2F / %x3A-FF"
  86. if (c <= 0x2F || c >= 0x3A) {
  87. break;
  88. }
  89. count++;
  90. }
  91. // constrain to a minimum and maximum number of digits.
  92. if (count < minDigits || count > maxDigits) {
  93. return null;
  94. }
  95. if (!trailingOK && count != token.length) {
  96. return null;
  97. }
  98. return parseInt(token.substr(0,count), 10);
  99. }
  100. function parseTime(token) {
  101. var parts = token.split(':');
  102. var result = [0,0,0];
  103. /* RF6256 S5.1.1:
  104. * time = hms-time ( non-digit *OCTET )
  105. * hms-time = time-field ":" time-field ":" time-field
  106. * time-field = 1*2DIGIT
  107. */
  108. if (parts.length !== 3) {
  109. return null;
  110. }
  111. for (var i = 0; i < 3; i++) {
  112. // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
  113. // followed by "( non-digit *OCTET )" so therefore the last time-field can
  114. // have a trailer
  115. var trailingOK = (i == 2);
  116. var num = parseDigits(parts[i], 1, 2, trailingOK);
  117. if (num === null) {
  118. return null;
  119. }
  120. result[i] = num;
  121. }
  122. return result;
  123. }
  124. function parseMonth(token) {
  125. token = String(token).substr(0,3).toLowerCase();
  126. var num = MONTH_TO_NUM[token];
  127. return num >= 0 ? num : null;
  128. }
  129. /*
  130. * RFC6265 S5.1.1 date parser (see RFC for full grammar)
  131. */
  132. function parseDate(str) {
  133. if (!str) {
  134. return;
  135. }
  136. /* RFC6265 S5.1.1:
  137. * 2. Process each date-token sequentially in the order the date-tokens
  138. * appear in the cookie-date
  139. */
  140. var tokens = str.split(DATE_DELIM);
  141. if (!tokens) {
  142. return;
  143. }
  144. var hour = null;
  145. var minute = null;
  146. var second = null;
  147. var dayOfMonth = null;
  148. var month = null;
  149. var year = null;
  150. for (var i=0; i<tokens.length; i++) {
  151. var token = tokens[i].trim();
  152. if (!token.length) {
  153. continue;
  154. }
  155. var result;
  156. /* 2.1. If the found-time flag is not set and the token matches the time
  157. * production, set the found-time flag and set the hour- value,
  158. * minute-value, and second-value to the numbers denoted by the digits in
  159. * the date-token, respectively. Skip the remaining sub-steps and continue
  160. * to the next date-token.
  161. */
  162. if (second === null) {
  163. result = parseTime(token);
  164. if (result) {
  165. hour = result[0];
  166. minute = result[1];
  167. second = result[2];
  168. continue;
  169. }
  170. }
  171. /* 2.2. If the found-day-of-month flag is not set and the date-token matches
  172. * the day-of-month production, set the found-day-of- month flag and set
  173. * the day-of-month-value to the number denoted by the date-token. Skip
  174. * the remaining sub-steps and continue to the next date-token.
  175. */
  176. if (dayOfMonth === null) {
  177. // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
  178. result = parseDigits(token, 1, 2, true);
  179. if (result !== null) {
  180. dayOfMonth = result;
  181. continue;
  182. }
  183. }
  184. /* 2.3. If the found-month flag is not set and the date-token matches the
  185. * month production, set the found-month flag and set the month-value to
  186. * the month denoted by the date-token. Skip the remaining sub-steps and
  187. * continue to the next date-token.
  188. */
  189. if (month === null) {
  190. result = parseMonth(token);
  191. if (result !== null) {
  192. month = result;
  193. continue;
  194. }
  195. }
  196. /* 2.4. If the found-year flag is not set and the date-token matches the
  197. * year production, set the found-year flag and set the year-value to the
  198. * number denoted by the date-token. Skip the remaining sub-steps and
  199. * continue to the next date-token.
  200. */
  201. if (year === null) {
  202. // "year = 2*4DIGIT ( non-digit *OCTET )"
  203. result = parseDigits(token, 2, 4, true);
  204. if (result !== null) {
  205. year = result;
  206. /* From S5.1.1:
  207. * 3. If the year-value is greater than or equal to 70 and less
  208. * than or equal to 99, increment the year-value by 1900.
  209. * 4. If the year-value is greater than or equal to 0 and less
  210. * than or equal to 69, increment the year-value by 2000.
  211. */
  212. if (year >= 70 && year <= 99) {
  213. year += 1900;
  214. } else if (year >= 0 && year <= 69) {
  215. year += 2000;
  216. }
  217. }
  218. }
  219. }
  220. /* RFC 6265 S5.1.1
  221. * "5. Abort these steps and fail to parse the cookie-date if:
  222. * * at least one of the found-day-of-month, found-month, found-
  223. * year, or found-time flags is not set,
  224. * * the day-of-month-value is less than 1 or greater than 31,
  225. * * the year-value is less than 1601,
  226. * * the hour-value is greater than 23,
  227. * * the minute-value is greater than 59, or
  228. * * the second-value is greater than 59.
  229. * (Note that leap seconds cannot be represented in this syntax.)"
  230. *
  231. * So, in order as above:
  232. */
  233. if (
  234. dayOfMonth === null || month === null || year === null || second === null ||
  235. dayOfMonth < 1 || dayOfMonth > 31 ||
  236. year < 1601 ||
  237. hour > 23 ||
  238. minute > 59 ||
  239. second > 59
  240. ) {
  241. return;
  242. }
  243. return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
  244. }
  245. function formatDate(date) {
  246. var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
  247. var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
  248. var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
  249. var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
  250. return NUM_TO_DAY[date.getUTCDay()] + ', ' +
  251. d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
  252. h+':'+m+':'+s+' GMT';
  253. }
  254. // S5.1.2 Canonicalized Host Names
  255. function canonicalDomain(str) {
  256. if (str == null) {
  257. return null;
  258. }
  259. str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
  260. // convert to IDN if any non-ASCII characters
  261. if (punycode && /[^\u0001-\u007f]/.test(str)) {
  262. str = punycode.toASCII(str);
  263. }
  264. return str.toLowerCase();
  265. }
  266. // S5.1.3 Domain Matching
  267. function domainMatch(str, domStr, canonicalize) {
  268. if (str == null || domStr == null) {
  269. return null;
  270. }
  271. if (canonicalize !== false) {
  272. str = canonicalDomain(str);
  273. domStr = canonicalDomain(domStr);
  274. }
  275. /*
  276. * "The domain string and the string are identical. (Note that both the
  277. * domain string and the string will have been canonicalized to lower case at
  278. * this point)"
  279. */
  280. if (str == domStr) {
  281. return true;
  282. }
  283. /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
  284. /* "* The string is a host name (i.e., not an IP address)." */
  285. if (net.isIP(str)) {
  286. return false;
  287. }
  288. /* "* The domain string is a suffix of the string" */
  289. var idx = str.indexOf(domStr);
  290. if (idx <= 0) {
  291. return false; // it's a non-match (-1) or prefix (0)
  292. }
  293. // e.g "a.b.c".indexOf("b.c") === 2
  294. // 5 === 3+2
  295. if (str.length !== domStr.length + idx) { // it's not a suffix
  296. return false;
  297. }
  298. /* "* The last character of the string that is not included in the domain
  299. * string is a %x2E (".") character." */
  300. if (str.substr(idx-1,1) !== '.') {
  301. return false;
  302. }
  303. return true;
  304. }
  305. // RFC6265 S5.1.4 Paths and Path-Match
  306. /*
  307. * "The user agent MUST use an algorithm equivalent to the following algorithm
  308. * to compute the default-path of a cookie:"
  309. *
  310. * Assumption: the path (and not query part or absolute uri) is passed in.
  311. */
  312. function defaultPath(path) {
  313. // "2. If the uri-path is empty or if the first character of the uri-path is not
  314. // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
  315. if (!path || path.substr(0,1) !== "/") {
  316. return "/";
  317. }
  318. // "3. If the uri-path contains no more than one %x2F ("/") character, output
  319. // %x2F ("/") and skip the remaining step."
  320. if (path === "/") {
  321. return path;
  322. }
  323. var rightSlash = path.lastIndexOf("/");
  324. if (rightSlash === 0) {
  325. return "/";
  326. }
  327. // "4. Output the characters of the uri-path from the first character up to,
  328. // but not including, the right-most %x2F ("/")."
  329. return path.slice(0, rightSlash);
  330. }
  331. function trimTerminator(str) {
  332. for (var t = 0; t < TERMINATORS.length; t++) {
  333. var terminatorIdx = str.indexOf(TERMINATORS[t]);
  334. if (terminatorIdx !== -1) {
  335. str = str.substr(0,terminatorIdx);
  336. }
  337. }
  338. return str;
  339. }
  340. function parseCookiePair(cookiePair, looseMode) {
  341. cookiePair = trimTerminator(cookiePair);
  342. var firstEq = cookiePair.indexOf('=');
  343. if (looseMode) {
  344. if (firstEq === 0) { // '=' is immediately at start
  345. cookiePair = cookiePair.substr(1);
  346. firstEq = cookiePair.indexOf('='); // might still need to split on '='
  347. }
  348. } else { // non-loose mode
  349. if (firstEq <= 0) { // no '=' or is at start
  350. return; // needs to have non-empty "cookie-name"
  351. }
  352. }
  353. var cookieName, cookieValue;
  354. if (firstEq <= 0) {
  355. cookieName = "";
  356. cookieValue = cookiePair.trim();
  357. } else {
  358. cookieName = cookiePair.substr(0, firstEq).trim();
  359. cookieValue = cookiePair.substr(firstEq+1).trim();
  360. }
  361. if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
  362. return;
  363. }
  364. var c = new Cookie();
  365. c.key = cookieName;
  366. c.value = cookieValue;
  367. return c;
  368. }
  369. function parse(str, options) {
  370. if (!options || typeof options !== 'object') {
  371. options = {};
  372. }
  373. str = str.trim();
  374. // We use a regex to parse the "name-value-pair" part of S5.2
  375. var firstSemi = str.indexOf(';'); // S5.2 step 1
  376. var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
  377. var c = parseCookiePair(cookiePair, !!options.loose);
  378. if (!c) {
  379. return;
  380. }
  381. if (firstSemi === -1) {
  382. return c;
  383. }
  384. // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
  385. // (including the %x3B (";") in question)." plus later on in the same section
  386. // "discard the first ";" and trim".
  387. var unparsed = str.slice(firstSemi + 1).trim();
  388. // "If the unparsed-attributes string is empty, skip the rest of these
  389. // steps."
  390. if (unparsed.length === 0) {
  391. return c;
  392. }
  393. /*
  394. * S5.2 says that when looping over the items "[p]rocess the attribute-name
  395. * and attribute-value according to the requirements in the following
  396. * subsections" for every item. Plus, for many of the individual attributes
  397. * in S5.3 it says to use the "attribute-value of the last attribute in the
  398. * cookie-attribute-list". Therefore, in this implementation, we overwrite
  399. * the previous value.
  400. */
  401. var cookie_avs = unparsed.split(';');
  402. while (cookie_avs.length) {
  403. var av = cookie_avs.shift().trim();
  404. if (av.length === 0) { // happens if ";;" appears
  405. continue;
  406. }
  407. var av_sep = av.indexOf('=');
  408. var av_key, av_value;
  409. if (av_sep === -1) {
  410. av_key = av;
  411. av_value = null;
  412. } else {
  413. av_key = av.substr(0,av_sep);
  414. av_value = av.substr(av_sep+1);
  415. }
  416. av_key = av_key.trim().toLowerCase();
  417. if (av_value) {
  418. av_value = av_value.trim();
  419. }
  420. switch(av_key) {
  421. case 'expires': // S5.2.1
  422. if (av_value) {
  423. var exp = parseDate(av_value);
  424. // "If the attribute-value failed to parse as a cookie date, ignore the
  425. // cookie-av."
  426. if (exp) {
  427. // over and underflow not realistically a concern: V8's getTime() seems to
  428. // store something larger than a 32-bit time_t (even with 32-bit node)
  429. c.expires = exp;
  430. }
  431. }
  432. break;
  433. case 'max-age': // S5.2.2
  434. if (av_value) {
  435. // "If the first character of the attribute-value is not a DIGIT or a "-"
  436. // character ...[or]... If the remainder of attribute-value contains a
  437. // non-DIGIT character, ignore the cookie-av."
  438. if (/^-?[0-9]+$/.test(av_value)) {
  439. var delta = parseInt(av_value, 10);
  440. // "If delta-seconds is less than or equal to zero (0), let expiry-time
  441. // be the earliest representable date and time."
  442. c.setMaxAge(delta);
  443. }
  444. }
  445. break;
  446. case 'domain': // S5.2.3
  447. // "If the attribute-value is empty, the behavior is undefined. However,
  448. // the user agent SHOULD ignore the cookie-av entirely."
  449. if (av_value) {
  450. // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
  451. // (".") character."
  452. var domain = av_value.trim().replace(/^\./, '');
  453. if (domain) {
  454. // "Convert the cookie-domain to lower case."
  455. c.domain = domain.toLowerCase();
  456. }
  457. }
  458. break;
  459. case 'path': // S5.2.4
  460. /*
  461. * "If the attribute-value is empty or if the first character of the
  462. * attribute-value is not %x2F ("/"):
  463. * Let cookie-path be the default-path.
  464. * Otherwise:
  465. * Let cookie-path be the attribute-value."
  466. *
  467. * We'll represent the default-path as null since it depends on the
  468. * context of the parsing.
  469. */
  470. c.path = av_value && av_value[0] === "/" ? av_value : null;
  471. break;
  472. case 'secure': // S5.2.5
  473. /*
  474. * "If the attribute-name case-insensitively matches the string "Secure",
  475. * the user agent MUST append an attribute to the cookie-attribute-list
  476. * with an attribute-name of Secure and an empty attribute-value."
  477. */
  478. c.secure = true;
  479. break;
  480. case 'httponly': // S5.2.6 -- effectively the same as 'secure'
  481. c.httpOnly = true;
  482. break;
  483. default:
  484. c.extensions = c.extensions || [];
  485. c.extensions.push(av);
  486. break;
  487. }
  488. }
  489. return c;
  490. }
  491. // avoid the V8 deoptimization monster!
  492. function jsonParse(str) {
  493. var obj;
  494. try {
  495. obj = JSON.parse(str);
  496. } catch (e) {
  497. return e;
  498. }
  499. return obj;
  500. }
  501. function fromJSON(str) {
  502. if (!str) {
  503. return null;
  504. }
  505. var obj;
  506. if (typeof str === 'string') {
  507. obj = jsonParse(str);
  508. if (obj instanceof Error) {
  509. return null;
  510. }
  511. } else {
  512. // assume it's an Object
  513. obj = str;
  514. }
  515. var c = new Cookie();
  516. for (var i=0; i<Cookie.serializableProperties.length; i++) {
  517. var prop = Cookie.serializableProperties[i];
  518. if (obj[prop] === undefined ||
  519. obj[prop] === Cookie.prototype[prop])
  520. {
  521. continue; // leave as prototype default
  522. }
  523. if (prop === 'expires' ||
  524. prop === 'creation' ||
  525. prop === 'lastAccessed')
  526. {
  527. if (obj[prop] === null) {
  528. c[prop] = null;
  529. } else {
  530. c[prop] = obj[prop] == "Infinity" ?
  531. "Infinity" : new Date(obj[prop]);
  532. }
  533. } else {
  534. c[prop] = obj[prop];
  535. }
  536. }
  537. return c;
  538. }
  539. /* Section 5.4 part 2:
  540. * "* Cookies with longer paths are listed before cookies with
  541. * shorter paths.
  542. *
  543. * * Among cookies that have equal-length path fields, cookies with
  544. * earlier creation-times are listed before cookies with later
  545. * creation-times."
  546. */
  547. function cookieCompare(a,b) {
  548. var cmp = 0;
  549. // descending for length: b CMP a
  550. var aPathLen = a.path ? a.path.length : 0;
  551. var bPathLen = b.path ? b.path.length : 0;
  552. cmp = bPathLen - aPathLen;
  553. if (cmp !== 0) {
  554. return cmp;
  555. }
  556. // ascending for time: a CMP b
  557. var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
  558. var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
  559. cmp = aTime - bTime;
  560. if (cmp !== 0) {
  561. return cmp;
  562. }
  563. // break ties for the same millisecond (precision of JavaScript's clock)
  564. cmp = a.creationIndex - b.creationIndex;
  565. return cmp;
  566. }
  567. // Gives the permutation of all possible pathMatch()es of a given path. The
  568. // array is in longest-to-shortest order. Handy for indexing.
  569. function permutePath(path) {
  570. if (path === '/') {
  571. return ['/'];
  572. }
  573. if (path.lastIndexOf('/') === path.length-1) {
  574. path = path.substr(0,path.length-1);
  575. }
  576. var permutations = [path];
  577. while (path.length > 1) {
  578. var lindex = path.lastIndexOf('/');
  579. if (lindex === 0) {
  580. break;
  581. }
  582. path = path.substr(0,lindex);
  583. permutations.push(path);
  584. }
  585. permutations.push('/');
  586. return permutations;
  587. }
  588. function getCookieContext(url) {
  589. if (url instanceof Object) {
  590. return url;
  591. }
  592. // NOTE: decodeURI will throw on malformed URIs (see GH-32).
  593. // Therefore, we will just skip decoding for such URIs.
  594. try {
  595. url = decodeURI(url);
  596. }
  597. catch(err) {
  598. // Silently swallow error
  599. }
  600. return urlParse(url);
  601. }
  602. function Cookie(options) {
  603. options = options || {};
  604. Object.keys(options).forEach(function(prop) {
  605. if (Cookie.prototype.hasOwnProperty(prop) &&
  606. Cookie.prototype[prop] !== options[prop] &&
  607. prop.substr(0,1) !== '_')
  608. {
  609. this[prop] = options[prop];
  610. }
  611. }, this);
  612. this.creation = this.creation || new Date();
  613. // used to break creation ties in cookieCompare():
  614. Object.defineProperty(this, 'creationIndex', {
  615. configurable: false,
  616. enumerable: false, // important for assert.deepEqual checks
  617. writable: true,
  618. value: ++Cookie.cookiesCreated
  619. });
  620. }
  621. Cookie.cookiesCreated = 0; // incremented each time a cookie is created
  622. Cookie.parse = parse;
  623. Cookie.fromJSON = fromJSON;
  624. Cookie.prototype.key = "";
  625. Cookie.prototype.value = "";
  626. // the order in which the RFC has them:
  627. Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
  628. Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
  629. Cookie.prototype.domain = null;
  630. Cookie.prototype.path = null;
  631. Cookie.prototype.secure = false;
  632. Cookie.prototype.httpOnly = false;
  633. Cookie.prototype.extensions = null;
  634. // set by the CookieJar:
  635. Cookie.prototype.hostOnly = null; // boolean when set
  636. Cookie.prototype.pathIsDefault = null; // boolean when set
  637. Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
  638. Cookie.prototype.lastAccessed = null; // Date when set
  639. Object.defineProperty(Cookie.prototype, 'creationIndex', {
  640. configurable: true,
  641. enumerable: false,
  642. writable: true,
  643. value: 0
  644. });
  645. Cookie.serializableProperties = Object.keys(Cookie.prototype)
  646. .filter(function(prop) {
  647. return !(
  648. Cookie.prototype[prop] instanceof Function ||
  649. prop === 'creationIndex' ||
  650. prop.substr(0,1) === '_'
  651. );
  652. });
  653. Cookie.prototype.inspect = function inspect() {
  654. var now = Date.now();
  655. return 'Cookie="'+this.toString() +
  656. '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
  657. '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
  658. '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
  659. '"';
  660. };
  661. // Use the new custom inspection symbol to add the custom inspect function if
  662. // available.
  663. if (util.inspect.custom) {
  664. Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
  665. }
  666. Cookie.prototype.toJSON = function() {
  667. var obj = {};
  668. var props = Cookie.serializableProperties;
  669. for (var i=0; i<props.length; i++) {
  670. var prop = props[i];
  671. if (this[prop] === Cookie.prototype[prop]) {
  672. continue; // leave as prototype default
  673. }
  674. if (prop === 'expires' ||
  675. prop === 'creation' ||
  676. prop === 'lastAccessed')
  677. {
  678. if (this[prop] === null) {
  679. obj[prop] = null;
  680. } else {
  681. obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
  682. "Infinity" : this[prop].toISOString();
  683. }
  684. } else if (prop === 'maxAge') {
  685. if (this[prop] !== null) {
  686. // again, intentionally not ===
  687. obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
  688. this[prop].toString() : this[prop];
  689. }
  690. } else {
  691. if (this[prop] !== Cookie.prototype[prop]) {
  692. obj[prop] = this[prop];
  693. }
  694. }
  695. }
  696. return obj;
  697. };
  698. Cookie.prototype.clone = function() {
  699. return fromJSON(this.toJSON());
  700. };
  701. Cookie.prototype.validate = function validate() {
  702. if (!COOKIE_OCTETS.test(this.value)) {
  703. return false;
  704. }
  705. if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
  706. return false;
  707. }
  708. if (this.maxAge != null && this.maxAge <= 0) {
  709. return false; // "Max-Age=" non-zero-digit *DIGIT
  710. }
  711. if (this.path != null && !PATH_VALUE.test(this.path)) {
  712. return false;
  713. }
  714. var cdomain = this.cdomain();
  715. if (cdomain) {
  716. if (cdomain.match(/\.$/)) {
  717. return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
  718. }
  719. var suffix = pubsuffix.getPublicSuffix(cdomain);
  720. if (suffix == null) { // it's a public suffix
  721. return false;
  722. }
  723. }
  724. return true;
  725. };
  726. Cookie.prototype.setExpires = function setExpires(exp) {
  727. if (exp instanceof Date) {
  728. this.expires = exp;
  729. } else {
  730. this.expires = parseDate(exp) || "Infinity";
  731. }
  732. };
  733. Cookie.prototype.setMaxAge = function setMaxAge(age) {
  734. if (age === Infinity || age === -Infinity) {
  735. this.maxAge = age.toString(); // so JSON.stringify() works
  736. } else {
  737. this.maxAge = age;
  738. }
  739. };
  740. // gives Cookie header format
  741. Cookie.prototype.cookieString = function cookieString() {
  742. var val = this.value;
  743. if (val == null) {
  744. val = '';
  745. }
  746. if (this.key === '') {
  747. return val;
  748. }
  749. return this.key+'='+val;
  750. };
  751. // gives Set-Cookie header format
  752. Cookie.prototype.toString = function toString() {
  753. var str = this.cookieString();
  754. if (this.expires != Infinity) {
  755. if (this.expires instanceof Date) {
  756. str += '; Expires='+formatDate(this.expires);
  757. } else {
  758. str += '; Expires='+this.expires;
  759. }
  760. }
  761. if (this.maxAge != null && this.maxAge != Infinity) {
  762. str += '; Max-Age='+this.maxAge;
  763. }
  764. if (this.domain && !this.hostOnly) {
  765. str += '; Domain='+this.domain;
  766. }
  767. if (this.path) {
  768. str += '; Path='+this.path;
  769. }
  770. if (this.secure) {
  771. str += '; Secure';
  772. }
  773. if (this.httpOnly) {
  774. str += '; HttpOnly';
  775. }
  776. if (this.extensions) {
  777. this.extensions.forEach(function(ext) {
  778. str += '; '+ext;
  779. });
  780. }
  781. return str;
  782. };
  783. // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
  784. // elsewhere)
  785. // S5.3 says to give the "latest representable date" for which we use Infinity
  786. // For "expired" we use 0
  787. Cookie.prototype.TTL = function TTL(now) {
  788. /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
  789. * attribute, the Max-Age attribute has precedence and controls the
  790. * expiration date of the cookie.
  791. * (Concurs with S5.3 step 3)
  792. */
  793. if (this.maxAge != null) {
  794. return this.maxAge<=0 ? 0 : this.maxAge*1000;
  795. }
  796. var expires = this.expires;
  797. if (expires != Infinity) {
  798. if (!(expires instanceof Date)) {
  799. expires = parseDate(expires) || Infinity;
  800. }
  801. if (expires == Infinity) {
  802. return Infinity;
  803. }
  804. return expires.getTime() - (now || Date.now());
  805. }
  806. return Infinity;
  807. };
  808. // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
  809. // elsewhere)
  810. Cookie.prototype.expiryTime = function expiryTime(now) {
  811. if (this.maxAge != null) {
  812. var relativeTo = now || this.creation || new Date();
  813. var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
  814. return relativeTo.getTime() + age;
  815. }
  816. if (this.expires == Infinity) {
  817. return Infinity;
  818. }
  819. return this.expires.getTime();
  820. };
  821. // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
  822. // elsewhere), except it returns a Date
  823. Cookie.prototype.expiryDate = function expiryDate(now) {
  824. var millisec = this.expiryTime(now);
  825. if (millisec == Infinity) {
  826. return new Date(MAX_TIME);
  827. } else if (millisec == -Infinity) {
  828. return new Date(MIN_TIME);
  829. } else {
  830. return new Date(millisec);
  831. }
  832. };
  833. // This replaces the "persistent-flag" parts of S5.3 step 3
  834. Cookie.prototype.isPersistent = function isPersistent() {
  835. return (this.maxAge != null || this.expires != Infinity);
  836. };
  837. // Mostly S5.1.2 and S5.2.3:
  838. Cookie.prototype.cdomain =
  839. Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
  840. if (this.domain == null) {
  841. return null;
  842. }
  843. return canonicalDomain(this.domain);
  844. };
  845. function CookieJar(store, options) {
  846. if (typeof options === "boolean") {
  847. options = {rejectPublicSuffixes: options};
  848. } else if (options == null) {
  849. options = {};
  850. }
  851. if (options.rejectPublicSuffixes != null) {
  852. this.rejectPublicSuffixes = options.rejectPublicSuffixes;
  853. }
  854. if (options.looseMode != null) {
  855. this.enableLooseMode = options.looseMode;
  856. }
  857. if (!store) {
  858. store = new MemoryCookieStore();
  859. }
  860. this.store = store;
  861. }
  862. CookieJar.prototype.store = null;
  863. CookieJar.prototype.rejectPublicSuffixes = true;
  864. CookieJar.prototype.enableLooseMode = false;
  865. var CAN_BE_SYNC = [];
  866. CAN_BE_SYNC.push('setCookie');
  867. CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
  868. var err;
  869. var context = getCookieContext(url);
  870. if (options instanceof Function) {
  871. cb = options;
  872. options = {};
  873. }
  874. var host = canonicalDomain(context.hostname);
  875. var loose = this.enableLooseMode;
  876. if (options.loose != null) {
  877. loose = options.loose;
  878. }
  879. // S5.3 step 1
  880. if (!(cookie instanceof Cookie)) {
  881. cookie = Cookie.parse(cookie, { loose: loose });
  882. }
  883. if (!cookie) {
  884. err = new Error("Cookie failed to parse");
  885. return cb(options.ignoreError ? null : err);
  886. }
  887. // S5.3 step 2
  888. var now = options.now || new Date(); // will assign later to save effort in the face of errors
  889. // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
  890. // S5.3 step 4: NOOP; domain is null by default
  891. // S5.3 step 5: public suffixes
  892. if (this.rejectPublicSuffixes && cookie.domain) {
  893. var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
  894. if (suffix == null) { // e.g. "com"
  895. err = new Error("Cookie has domain set to a public suffix");
  896. return cb(options.ignoreError ? null : err);
  897. }
  898. }
  899. // S5.3 step 6:
  900. if (cookie.domain) {
  901. if (!domainMatch(host, cookie.cdomain(), false)) {
  902. err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
  903. return cb(options.ignoreError ? null : err);
  904. }
  905. if (cookie.hostOnly == null) { // don't reset if already set
  906. cookie.hostOnly = false;
  907. }
  908. } else {
  909. cookie.hostOnly = true;
  910. cookie.domain = host;
  911. }
  912. //S5.2.4 If the attribute-value is empty or if the first character of the
  913. //attribute-value is not %x2F ("/"):
  914. //Let cookie-path be the default-path.
  915. if (!cookie.path || cookie.path[0] !== '/') {
  916. cookie.path = defaultPath(context.pathname);
  917. cookie.pathIsDefault = true;
  918. }
  919. // S5.3 step 8: NOOP; secure attribute
  920. // S5.3 step 9: NOOP; httpOnly attribute
  921. // S5.3 step 10
  922. if (options.http === false && cookie.httpOnly) {
  923. err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
  924. return cb(options.ignoreError ? null : err);
  925. }
  926. var store = this.store;
  927. if (!store.updateCookie) {
  928. store.updateCookie = function(oldCookie, newCookie, cb) {
  929. this.putCookie(newCookie, cb);
  930. };
  931. }
  932. function withCookie(err, oldCookie) {
  933. if (err) {
  934. return cb(err);
  935. }
  936. var next = function(err) {
  937. if (err) {
  938. return cb(err);
  939. } else {
  940. cb(null, cookie);
  941. }
  942. };
  943. if (oldCookie) {
  944. // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
  945. // domain, and path as the newly created cookie:"
  946. if (options.http === false && oldCookie.httpOnly) { // step 11.2
  947. err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
  948. return cb(options.ignoreError ? null : err);
  949. }
  950. cookie.creation = oldCookie.creation; // step 11.3
  951. cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
  952. cookie.lastAccessed = now;
  953. // Step 11.4 (delete cookie) is implied by just setting the new one:
  954. store.updateCookie(oldCookie, cookie, next); // step 12
  955. } else {
  956. cookie.creation = cookie.lastAccessed = now;
  957. store.putCookie(cookie, next); // step 12
  958. }
  959. }
  960. store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
  961. };
  962. // RFC6365 S5.4
  963. CAN_BE_SYNC.push('getCookies');
  964. CookieJar.prototype.getCookies = function(url, options, cb) {
  965. var context = getCookieContext(url);
  966. if (options instanceof Function) {
  967. cb = options;
  968. options = {};
  969. }
  970. var host = canonicalDomain(context.hostname);
  971. var path = context.pathname || '/';
  972. var secure = options.secure;
  973. if (secure == null && context.protocol &&
  974. (context.protocol == 'https:' || context.protocol == 'wss:'))
  975. {
  976. secure = true;
  977. }
  978. var http = options.http;
  979. if (http == null) {
  980. http = true;
  981. }
  982. var now = options.now || Date.now();
  983. var expireCheck = options.expire !== false;
  984. var allPaths = !!options.allPaths;
  985. var store = this.store;
  986. function matchingCookie(c) {
  987. // "Either:
  988. // The cookie's host-only-flag is true and the canonicalized
  989. // request-host is identical to the cookie's domain.
  990. // Or:
  991. // The cookie's host-only-flag is false and the canonicalized
  992. // request-host domain-matches the cookie's domain."
  993. if (c.hostOnly) {
  994. if (c.domain != host) {
  995. return false;
  996. }
  997. } else {
  998. if (!domainMatch(host, c.domain, false)) {
  999. return false;
  1000. }
  1001. }
  1002. // "The request-uri's path path-matches the cookie's path."
  1003. if (!allPaths && !pathMatch(path, c.path)) {
  1004. return false;
  1005. }
  1006. // "If the cookie's secure-only-flag is true, then the request-uri's
  1007. // scheme must denote a "secure" protocol"
  1008. if (c.secure && !secure) {
  1009. return false;
  1010. }
  1011. // "If the cookie's http-only-flag is true, then exclude the cookie if the
  1012. // cookie-string is being generated for a "non-HTTP" API"
  1013. if (c.httpOnly && !http) {
  1014. return false;
  1015. }
  1016. // deferred from S5.3
  1017. // non-RFC: allow retention of expired cookies by choice
  1018. if (expireCheck && c.expiryTime() <= now) {
  1019. store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
  1020. return false;
  1021. }
  1022. return true;
  1023. }
  1024. store.findCookies(host, allPaths ? null : path, function(err,cookies) {
  1025. if (err) {
  1026. return cb(err);
  1027. }
  1028. cookies = cookies.filter(matchingCookie);
  1029. // sorting of S5.4 part 2
  1030. if (options.sort !== false) {
  1031. cookies = cookies.sort(cookieCompare);
  1032. }
  1033. // S5.4 part 3
  1034. var now = new Date();
  1035. cookies.forEach(function(c) {
  1036. c.lastAccessed = now;
  1037. });
  1038. // TODO persist lastAccessed
  1039. cb(null,cookies);
  1040. });
  1041. };
  1042. CAN_BE_SYNC.push('getCookieString');
  1043. CookieJar.prototype.getCookieString = function(/*..., cb*/) {
  1044. var args = Array.prototype.slice.call(arguments,0);
  1045. var cb = args.pop();
  1046. var next = function(err,cookies) {
  1047. if (err) {
  1048. cb(err);
  1049. } else {
  1050. cb(null, cookies
  1051. .sort(cookieCompare)
  1052. .map(function(c){
  1053. return c.cookieString();
  1054. })
  1055. .join('; '));
  1056. }
  1057. };
  1058. args.push(next);
  1059. this.getCookies.apply(this,args);
  1060. };
  1061. CAN_BE_SYNC.push('getSetCookieStrings');
  1062. CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
  1063. var args = Array.prototype.slice.call(arguments,0);
  1064. var cb = args.pop();
  1065. var next = function(err,cookies) {
  1066. if (err) {
  1067. cb(err);
  1068. } else {
  1069. cb(null, cookies.map(function(c){
  1070. return c.toString();
  1071. }));
  1072. }
  1073. };
  1074. args.push(next);
  1075. this.getCookies.apply(this,args);
  1076. };
  1077. CAN_BE_SYNC.push('serialize');
  1078. CookieJar.prototype.serialize = function(cb) {
  1079. var type = this.store.constructor.name;
  1080. if (type === 'Object') {
  1081. type = null;
  1082. }
  1083. // update README.md "Serialization Format" if you change this, please!
  1084. var serialized = {
  1085. // The version of tough-cookie that serialized this jar. Generally a good
  1086. // practice since future versions can make data import decisions based on
  1087. // known past behavior. When/if this matters, use `semver`.
  1088. version: 'tough-cookie@'+VERSION,
  1089. // add the store type, to make humans happy:
  1090. storeType: type,
  1091. // CookieJar configuration:
  1092. rejectPublicSuffixes: !!this.rejectPublicSuffixes,
  1093. // this gets filled from getAllCookies:
  1094. cookies: []
  1095. };
  1096. if (!(this.store.getAllCookies &&
  1097. typeof this.store.getAllCookies === 'function'))
  1098. {
  1099. return cb(new Error('store does not support getAllCookies and cannot be serialized'));
  1100. }
  1101. this.store.getAllCookies(function(err,cookies) {
  1102. if (err) {
  1103. return cb(err);
  1104. }
  1105. serialized.cookies = cookies.map(function(cookie) {
  1106. // convert to serialized 'raw' cookies
  1107. cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
  1108. // Remove the index so new ones get assigned during deserialization
  1109. delete cookie.creationIndex;
  1110. return cookie;
  1111. });
  1112. return cb(null, serialized);
  1113. });
  1114. };
  1115. // well-known name that JSON.stringify calls
  1116. CookieJar.prototype.toJSON = function() {
  1117. return this.serializeSync();
  1118. };
  1119. // use the class method CookieJar.deserialize instead of calling this directly
  1120. CAN_BE_SYNC.push('_importCookies');
  1121. CookieJar.prototype._importCookies = function(serialized, cb) {
  1122. var jar = this;
  1123. var cookies = serialized.cookies;
  1124. if (!cookies || !Array.isArray(cookies)) {
  1125. return cb(new Error('serialized jar has no cookies array'));
  1126. }
  1127. cookies = cookies.slice(); // do not modify the original
  1128. function putNext(err) {
  1129. if (err) {
  1130. return cb(err);
  1131. }
  1132. if (!cookies.length) {
  1133. return cb(err, jar);
  1134. }
  1135. var cookie;
  1136. try {
  1137. cookie = fromJSON(cookies.shift());
  1138. } catch (e) {
  1139. return cb(e);
  1140. }
  1141. if (cookie === null) {
  1142. return putNext(null); // skip this cookie
  1143. }
  1144. jar.store.putCookie(cookie, putNext);
  1145. }
  1146. putNext();
  1147. };
  1148. CookieJar.deserialize = function(strOrObj, store, cb) {
  1149. if (arguments.length !== 3) {
  1150. // store is optional
  1151. cb = store;
  1152. store = null;
  1153. }
  1154. var serialized;
  1155. if (typeof strOrObj === 'string') {
  1156. serialized = jsonParse(strOrObj);
  1157. if (serialized instanceof Error) {
  1158. return cb(serialized);
  1159. }
  1160. } else {
  1161. serialized = strOrObj;
  1162. }
  1163. var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  1164. jar._importCookies(serialized, function(err) {
  1165. if (err) {
  1166. return cb(err);
  1167. }
  1168. cb(null, jar);
  1169. });
  1170. };
  1171. CookieJar.deserializeSync = function(strOrObj, store) {
  1172. var serialized = typeof strOrObj === 'string' ?
  1173. JSON.parse(strOrObj) : strOrObj;
  1174. var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  1175. // catch this mistake early:
  1176. if (!jar.store.synchronous) {
  1177. throw new Error('CookieJar store is not synchronous; use async API instead.');
  1178. }
  1179. jar._importCookiesSync(serialized);
  1180. return jar;
  1181. };
  1182. CookieJar.fromJSON = CookieJar.deserializeSync;
  1183. CookieJar.prototype.clone = function(newStore, cb) {
  1184. if (arguments.length === 1) {
  1185. cb = newStore;
  1186. newStore = null;
  1187. }
  1188. this.serialize(function(err,serialized) {
  1189. if (err) {
  1190. return cb(err);
  1191. }
  1192. CookieJar.deserialize(serialized, newStore, cb);
  1193. });
  1194. };
  1195. CAN_BE_SYNC.push('removeAllCookies');
  1196. CookieJar.prototype.removeAllCookies = function(cb) {
  1197. var store = this.store;
  1198. // Check that the store implements its own removeAllCookies(). The default
  1199. // implementation in Store will immediately call the callback with a "not
  1200. // implemented" Error.
  1201. if (store.removeAllCookies instanceof Function &&
  1202. store.removeAllCookies !== Store.prototype.removeAllCookies)
  1203. {
  1204. return store.removeAllCookies(cb);
  1205. }
  1206. store.getAllCookies(function(err, cookies) {
  1207. if (err) {
  1208. return cb(err);
  1209. }
  1210. if (cookies.length === 0) {
  1211. return cb(null);
  1212. }
  1213. var completedCount = 0;
  1214. var removeErrors = [];
  1215. function removeCookieCb(removeErr) {
  1216. if (removeErr) {
  1217. removeErrors.push(removeErr);
  1218. }
  1219. completedCount++;
  1220. if (completedCount === cookies.length) {
  1221. return cb(removeErrors.length ? removeErrors[0] : null);
  1222. }
  1223. }
  1224. cookies.forEach(function(cookie) {
  1225. store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb);
  1226. });
  1227. });
  1228. };
  1229. CookieJar.prototype._cloneSync = syncWrap('clone');
  1230. CookieJar.prototype.cloneSync = function(newStore) {
  1231. if (!newStore.synchronous) {
  1232. throw new Error('CookieJar clone destination store is not synchronous; use async API instead.');
  1233. }
  1234. return this._cloneSync(newStore);
  1235. };
  1236. // Use a closure to provide a true imperative API for synchronous stores.
  1237. function syncWrap(method) {
  1238. return function() {
  1239. if (!this.store.synchronous) {
  1240. throw new Error('CookieJar store is not synchronous; use async API instead.');
  1241. }
  1242. var args = Array.prototype.slice.call(arguments);
  1243. var syncErr, syncResult;
  1244. args.push(function syncCb(err, result) {
  1245. syncErr = err;
  1246. syncResult = result;
  1247. });
  1248. this[method].apply(this, args);
  1249. if (syncErr) {
  1250. throw syncErr;
  1251. }
  1252. return syncResult;
  1253. };
  1254. }
  1255. // wrap all declared CAN_BE_SYNC methods in the sync wrapper
  1256. CAN_BE_SYNC.forEach(function(method) {
  1257. CookieJar.prototype[method+'Sync'] = syncWrap(method);
  1258. });
  1259. exports.version = VERSION;
  1260. exports.CookieJar = CookieJar;
  1261. exports.Cookie = Cookie;
  1262. exports.Store = Store;
  1263. exports.MemoryCookieStore = MemoryCookieStore;
  1264. exports.parseDate = parseDate;
  1265. exports.formatDate = formatDate;
  1266. exports.parse = parse;
  1267. exports.fromJSON = fromJSON;
  1268. exports.domainMatch = domainMatch;
  1269. exports.defaultPath = defaultPath;
  1270. exports.pathMatch = pathMatch;
  1271. exports.getPublicSuffix = pubsuffix.getPublicSuffix;
  1272. exports.cookieCompare = cookieCompare;
  1273. exports.permuteDomain = require('./permuteDomain').permuteDomain;
  1274. exports.permutePath = permutePath;
  1275. exports.canonicalDomain = canonicalDomain;