cookie.js 36 KB

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