a zip code crypto-currency system good for red ONLY

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