Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

cookie.js 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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 urlParse = require('url').parse;
  33. var util = require('util');
  34. var ipRegex = require('ip-regex')({ exact: true });
  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 (ipRegex.test(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 (typeof(cookie) === 'string' || cookie instanceof String) {
  881. cookie = Cookie.parse(cookie, { loose: loose });
  882. if (!cookie) {
  883. err = new Error("Cookie failed to parse");
  884. return cb(options.ignoreError ? null : err);
  885. }
  886. }
  887. else if (!(cookie instanceof Cookie)) {
  888. // If you're seeing this error, and are passing in a Cookie object,
  889. // it *might* be a Cookie object from another loaded version of tough-cookie.
  890. err = new Error("First argument to setCookie must be a Cookie object or string");
  891. return cb(options.ignoreError ? null : err);
  892. }
  893. // S5.3 step 2
  894. var now = options.now || new Date(); // will assign later to save effort in the face of errors
  895. // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
  896. // S5.3 step 4: NOOP; domain is null by default
  897. // S5.3 step 5: public suffixes
  898. if (this.rejectPublicSuffixes && cookie.domain) {
  899. var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
  900. if (suffix == null) { // e.g. "com"
  901. err = new Error("Cookie has domain set to a public suffix");
  902. return cb(options.ignoreError ? null : err);
  903. }
  904. }
  905. // S5.3 step 6:
  906. if (cookie.domain) {
  907. if (!domainMatch(host, cookie.cdomain(), false)) {
  908. err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
  909. return cb(options.ignoreError ? null : err);
  910. }
  911. if (cookie.hostOnly == null) { // don't reset if already set
  912. cookie.hostOnly = false;
  913. }
  914. } else {
  915. cookie.hostOnly = true;
  916. cookie.domain = host;
  917. }
  918. //S5.2.4 If the attribute-value is empty or if the first character of the
  919. //attribute-value is not %x2F ("/"):
  920. //Let cookie-path be the default-path.
  921. if (!cookie.path || cookie.path[0] !== '/') {
  922. cookie.path = defaultPath(context.pathname);
  923. cookie.pathIsDefault = true;
  924. }
  925. // S5.3 step 8: NOOP; secure attribute
  926. // S5.3 step 9: NOOP; httpOnly attribute
  927. // S5.3 step 10
  928. if (options.http === false && cookie.httpOnly) {
  929. err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
  930. return cb(options.ignoreError ? null : err);
  931. }
  932. var store = this.store;
  933. if (!store.updateCookie) {
  934. store.updateCookie = function(oldCookie, newCookie, cb) {
  935. this.putCookie(newCookie, cb);
  936. };
  937. }
  938. function withCookie(err, oldCookie) {
  939. if (err) {
  940. return cb(err);
  941. }
  942. var next = function(err) {
  943. if (err) {
  944. return cb(err);
  945. } else {
  946. cb(null, cookie);
  947. }
  948. };
  949. if (oldCookie) {
  950. // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
  951. // domain, and path as the newly created cookie:"
  952. if (options.http === false && oldCookie.httpOnly) { // step 11.2
  953. err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
  954. return cb(options.ignoreError ? null : err);
  955. }
  956. cookie.creation = oldCookie.creation; // step 11.3
  957. cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
  958. cookie.lastAccessed = now;
  959. // Step 11.4 (delete cookie) is implied by just setting the new one:
  960. store.updateCookie(oldCookie, cookie, next); // step 12
  961. } else {
  962. cookie.creation = cookie.lastAccessed = now;
  963. store.putCookie(cookie, next); // step 12
  964. }
  965. }
  966. store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
  967. };
  968. // RFC6365 S5.4
  969. CAN_BE_SYNC.push('getCookies');
  970. CookieJar.prototype.getCookies = function(url, options, cb) {
  971. var context = getCookieContext(url);
  972. if (options instanceof Function) {
  973. cb = options;
  974. options = {};
  975. }
  976. var host = canonicalDomain(context.hostname);
  977. var path = context.pathname || '/';
  978. var secure = options.secure;
  979. if (secure == null && context.protocol &&
  980. (context.protocol == 'https:' || context.protocol == 'wss:'))
  981. {
  982. secure = true;
  983. }
  984. var http = options.http;
  985. if (http == null) {
  986. http = true;
  987. }
  988. var now = options.now || Date.now();
  989. var expireCheck = options.expire !== false;
  990. var allPaths = !!options.allPaths;
  991. var store = this.store;
  992. function matchingCookie(c) {
  993. // "Either:
  994. // The cookie's host-only-flag is true and the canonicalized
  995. // request-host is identical to the cookie's domain.
  996. // Or:
  997. // The cookie's host-only-flag is false and the canonicalized
  998. // request-host domain-matches the cookie's domain."
  999. if (c.hostOnly) {
  1000. if (c.domain != host) {
  1001. return false;
  1002. }
  1003. } else {
  1004. if (!domainMatch(host, c.domain, false)) {
  1005. return false;
  1006. }
  1007. }
  1008. // "The request-uri's path path-matches the cookie's path."
  1009. if (!allPaths && !pathMatch(path, c.path)) {
  1010. return false;
  1011. }
  1012. // "If the cookie's secure-only-flag is true, then the request-uri's
  1013. // scheme must denote a "secure" protocol"
  1014. if (c.secure && !secure) {
  1015. return false;
  1016. }
  1017. // "If the cookie's http-only-flag is true, then exclude the cookie if the
  1018. // cookie-string is being generated for a "non-HTTP" API"
  1019. if (c.httpOnly && !http) {
  1020. return false;
  1021. }
  1022. // deferred from S5.3
  1023. // non-RFC: allow retention of expired cookies by choice
  1024. if (expireCheck && c.expiryTime() <= now) {
  1025. store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
  1026. return false;
  1027. }
  1028. return true;
  1029. }
  1030. store.findCookies(host, allPaths ? null : path, function(err,cookies) {
  1031. if (err) {
  1032. return cb(err);
  1033. }
  1034. cookies = cookies.filter(matchingCookie);
  1035. // sorting of S5.4 part 2
  1036. if (options.sort !== false) {
  1037. cookies = cookies.sort(cookieCompare);
  1038. }
  1039. // S5.4 part 3
  1040. var now = new Date();
  1041. cookies.forEach(function(c) {
  1042. c.lastAccessed = now;
  1043. });
  1044. // TODO persist lastAccessed
  1045. cb(null,cookies);
  1046. });
  1047. };
  1048. CAN_BE_SYNC.push('getCookieString');
  1049. CookieJar.prototype.getCookieString = function(/*..., cb*/) {
  1050. var args = Array.prototype.slice.call(arguments,0);
  1051. var cb = args.pop();
  1052. var next = function(err,cookies) {
  1053. if (err) {
  1054. cb(err);
  1055. } else {
  1056. cb(null, cookies
  1057. .sort(cookieCompare)
  1058. .map(function(c){
  1059. return c.cookieString();
  1060. })
  1061. .join('; '));
  1062. }
  1063. };
  1064. args.push(next);
  1065. this.getCookies.apply(this,args);
  1066. };
  1067. CAN_BE_SYNC.push('getSetCookieStrings');
  1068. CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
  1069. var args = Array.prototype.slice.call(arguments,0);
  1070. var cb = args.pop();
  1071. var next = function(err,cookies) {
  1072. if (err) {
  1073. cb(err);
  1074. } else {
  1075. cb(null, cookies.map(function(c){
  1076. return c.toString();
  1077. }));
  1078. }
  1079. };
  1080. args.push(next);
  1081. this.getCookies.apply(this,args);
  1082. };
  1083. CAN_BE_SYNC.push('serialize');
  1084. CookieJar.prototype.serialize = function(cb) {
  1085. var type = this.store.constructor.name;
  1086. if (type === 'Object') {
  1087. type = null;
  1088. }
  1089. // update README.md "Serialization Format" if you change this, please!
  1090. var serialized = {
  1091. // The version of tough-cookie that serialized this jar. Generally a good
  1092. // practice since future versions can make data import decisions based on
  1093. // known past behavior. When/if this matters, use `semver`.
  1094. version: 'tough-cookie@'+VERSION,
  1095. // add the store type, to make humans happy:
  1096. storeType: type,
  1097. // CookieJar configuration:
  1098. rejectPublicSuffixes: !!this.rejectPublicSuffixes,
  1099. // this gets filled from getAllCookies:
  1100. cookies: []
  1101. };
  1102. if (!(this.store.getAllCookies &&
  1103. typeof this.store.getAllCookies === 'function'))
  1104. {
  1105. return cb(new Error('store does not support getAllCookies and cannot be serialized'));
  1106. }
  1107. this.store.getAllCookies(function(err,cookies) {
  1108. if (err) {
  1109. return cb(err);
  1110. }
  1111. serialized.cookies = cookies.map(function(cookie) {
  1112. // convert to serialized 'raw' cookies
  1113. cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
  1114. // Remove the index so new ones get assigned during deserialization
  1115. delete cookie.creationIndex;
  1116. return cookie;
  1117. });
  1118. return cb(null, serialized);
  1119. });
  1120. };
  1121. // well-known name that JSON.stringify calls
  1122. CookieJar.prototype.toJSON = function() {
  1123. return this.serializeSync();
  1124. };
  1125. // use the class method CookieJar.deserialize instead of calling this directly
  1126. CAN_BE_SYNC.push('_importCookies');
  1127. CookieJar.prototype._importCookies = function(serialized, cb) {
  1128. var jar = this;
  1129. var cookies = serialized.cookies;
  1130. if (!cookies || !Array.isArray(cookies)) {
  1131. return cb(new Error('serialized jar has no cookies array'));
  1132. }
  1133. cookies = cookies.slice(); // do not modify the original
  1134. function putNext(err) {
  1135. if (err) {
  1136. return cb(err);
  1137. }
  1138. if (!cookies.length) {
  1139. return cb(err, jar);
  1140. }
  1141. var cookie;
  1142. try {
  1143. cookie = fromJSON(cookies.shift());
  1144. } catch (e) {
  1145. return cb(e);
  1146. }
  1147. if (cookie === null) {
  1148. return putNext(null); // skip this cookie
  1149. }
  1150. jar.store.putCookie(cookie, putNext);
  1151. }
  1152. putNext();
  1153. };
  1154. CookieJar.deserialize = function(strOrObj, store, cb) {
  1155. if (arguments.length !== 3) {
  1156. // store is optional
  1157. cb = store;
  1158. store = null;
  1159. }
  1160. var serialized;
  1161. if (typeof strOrObj === 'string') {
  1162. serialized = jsonParse(strOrObj);
  1163. if (serialized instanceof Error) {
  1164. return cb(serialized);
  1165. }
  1166. } else {
  1167. serialized = strOrObj;
  1168. }
  1169. var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  1170. jar._importCookies(serialized, function(err) {
  1171. if (err) {
  1172. return cb(err);
  1173. }
  1174. cb(null, jar);
  1175. });
  1176. };
  1177. CookieJar.deserializeSync = function(strOrObj, store) {
  1178. var serialized = typeof strOrObj === 'string' ?
  1179. JSON.parse(strOrObj) : strOrObj;
  1180. var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  1181. // catch this mistake early:
  1182. if (!jar.store.synchronous) {
  1183. throw new Error('CookieJar store is not synchronous; use async API instead.');
  1184. }
  1185. jar._importCookiesSync(serialized);
  1186. return jar;
  1187. };
  1188. CookieJar.fromJSON = CookieJar.deserializeSync;
  1189. CookieJar.prototype.clone = function(newStore, cb) {
  1190. if (arguments.length === 1) {
  1191. cb = newStore;
  1192. newStore = null;
  1193. }
  1194. this.serialize(function(err,serialized) {
  1195. if (err) {
  1196. return cb(err);
  1197. }
  1198. CookieJar.deserialize(serialized, newStore, cb);
  1199. });
  1200. };
  1201. CAN_BE_SYNC.push('removeAllCookies');
  1202. CookieJar.prototype.removeAllCookies = function(cb) {
  1203. var store = this.store;
  1204. // Check that the store implements its own removeAllCookies(). The default
  1205. // implementation in Store will immediately call the callback with a "not
  1206. // implemented" Error.
  1207. if (store.removeAllCookies instanceof Function &&
  1208. store.removeAllCookies !== Store.prototype.removeAllCookies)
  1209. {
  1210. return store.removeAllCookies(cb);
  1211. }
  1212. store.getAllCookies(function(err, cookies) {
  1213. if (err) {
  1214. return cb(err);
  1215. }
  1216. if (cookies.length === 0) {
  1217. return cb(null);
  1218. }
  1219. var completedCount = 0;
  1220. var removeErrors = [];
  1221. function removeCookieCb(removeErr) {
  1222. if (removeErr) {
  1223. removeErrors.push(removeErr);
  1224. }
  1225. completedCount++;
  1226. if (completedCount === cookies.length) {
  1227. return cb(removeErrors.length ? removeErrors[0] : null);
  1228. }
  1229. }
  1230. cookies.forEach(function(cookie) {
  1231. store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb);
  1232. });
  1233. });
  1234. };
  1235. CookieJar.prototype._cloneSync = syncWrap('clone');
  1236. CookieJar.prototype.cloneSync = function(newStore) {
  1237. if (!newStore.synchronous) {
  1238. throw new Error('CookieJar clone destination store is not synchronous; use async API instead.');
  1239. }
  1240. return this._cloneSync(newStore);
  1241. };
  1242. // Use a closure to provide a true imperative API for synchronous stores.
  1243. function syncWrap(method) {
  1244. return function() {
  1245. if (!this.store.synchronous) {
  1246. throw new Error('CookieJar store is not synchronous; use async API instead.');
  1247. }
  1248. var args = Array.prototype.slice.call(arguments);
  1249. var syncErr, syncResult;
  1250. args.push(function syncCb(err, result) {
  1251. syncErr = err;
  1252. syncResult = result;
  1253. });
  1254. this[method].apply(this, args);
  1255. if (syncErr) {
  1256. throw syncErr;
  1257. }
  1258. return syncResult;
  1259. };
  1260. }
  1261. // wrap all declared CAN_BE_SYNC methods in the sync wrapper
  1262. CAN_BE_SYNC.forEach(function(method) {
  1263. CookieJar.prototype[method+'Sync'] = syncWrap(method);
  1264. });
  1265. exports.version = VERSION;
  1266. exports.CookieJar = CookieJar;
  1267. exports.Cookie = Cookie;
  1268. exports.Store = Store;
  1269. exports.MemoryCookieStore = MemoryCookieStore;
  1270. exports.parseDate = parseDate;
  1271. exports.formatDate = formatDate;
  1272. exports.parse = parse;
  1273. exports.fromJSON = fromJSON;
  1274. exports.domainMatch = domainMatch;
  1275. exports.defaultPath = defaultPath;
  1276. exports.pathMatch = pathMatch;
  1277. exports.getPublicSuffix = pubsuffix.getPublicSuffix;
  1278. exports.cookieCompare = cookieCompare;
  1279. exports.permuteDomain = require('./permuteDomain').permuteDomain;
  1280. exports.permutePath = permutePath;
  1281. exports.canonicalDomain = canonicalDomain;