cookie.js 37 KB

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