index.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*!
  2. * cookie
  3. * Copyright(c) 2012-2014 Roman Shtylman
  4. * Copyright(c) 2015 Douglas Christopher Wilson
  5. * MIT Licensed
  6. */
  7. 'use strict';
  8. /**
  9. * Module exports.
  10. * @public
  11. */
  12. exports.parse = parse;
  13. exports.serialize = serialize;
  14. /**
  15. * Module variables.
  16. * @private
  17. */
  18. var __toString = Object.prototype.toString
  19. /**
  20. * RegExp to match cookie-name in RFC 6265 sec 4.1.1
  21. * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2
  22. * which has been replaced by the token definition in RFC 7230 appendix B.
  23. *
  24. * cookie-name = token
  25. * token = 1*tchar
  26. * tchar = "!" / "#" / "$" / "%" / "&" / "'" /
  27. * "*" / "+" / "-" / "." / "^" / "_" /
  28. * "`" / "|" / "~" / DIGIT / ALPHA
  29. */
  30. var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  31. /**
  32. * RegExp to match cookie-value in RFC 6265 sec 4.1.1
  33. *
  34. * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
  35. * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
  36. * ; US-ASCII characters excluding CTLs,
  37. * ; whitespace DQUOTE, comma, semicolon,
  38. * ; and backslash
  39. */
  40. var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/;
  41. /**
  42. * RegExp to match domain-value in RFC 6265 sec 4.1.1
  43. *
  44. * domain-value = <subdomain>
  45. * ; defined in [RFC1034], Section 3.5, as
  46. * ; enhanced by [RFC1123], Section 2.1
  47. * <subdomain> = <label> | <subdomain> "." <label>
  48. * <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]
  49. * Labels must be 63 characters or less.
  50. * 'let-dig' not 'letter' in the first char, per RFC1123
  51. * <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>
  52. * <let-dig-hyp> = <let-dig> | "-"
  53. * <let-dig> = <letter> | <digit>
  54. * <letter> = any one of the 52 alphabetic characters A through Z in
  55. * upper case and a through z in lower case
  56. * <digit> = any one of the ten digits 0 through 9
  57. *
  58. * Keep support for leading dot: https://github.com/jshttp/cookie/issues/173
  59. *
  60. * > (Note that a leading %x2E ("."), if present, is ignored even though that
  61. * character is not permitted, but a trailing %x2E ("."), if present, will
  62. * cause the user agent to ignore the attribute.)
  63. */
  64. var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
  65. /**
  66. * RegExp to match path-value in RFC 6265 sec 4.1.1
  67. *
  68. * path-value = <any CHAR except CTLs or ";">
  69. * CHAR = %x01-7F
  70. * ; defined in RFC 5234 appendix B.1
  71. */
  72. var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
  73. /**
  74. * Parse a cookie header.
  75. *
  76. * Parse the given cookie header string into an object
  77. * The object has the various cookies as keys(names) => values
  78. *
  79. * @param {string} str
  80. * @param {object} [opt]
  81. * @return {object}
  82. * @public
  83. */
  84. function parse(str, opt) {
  85. if (typeof str !== 'string') {
  86. throw new TypeError('argument str must be a string');
  87. }
  88. var obj = {};
  89. var len = str.length;
  90. // RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.
  91. if (len < 2) return obj;
  92. var dec = (opt && opt.decode) || decode;
  93. var index = 0;
  94. var eqIdx = 0;
  95. var endIdx = 0;
  96. do {
  97. eqIdx = str.indexOf('=', index);
  98. if (eqIdx === -1) break; // No more cookie pairs.
  99. endIdx = str.indexOf(';', index);
  100. if (endIdx === -1) {
  101. endIdx = len;
  102. } else if (eqIdx > endIdx) {
  103. // backtrack on prior semicolon
  104. index = str.lastIndexOf(';', eqIdx - 1) + 1;
  105. continue;
  106. }
  107. var keyStartIdx = startIndex(str, index, eqIdx);
  108. var keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
  109. var key = str.slice(keyStartIdx, keyEndIdx);
  110. // only assign once
  111. if (!obj.hasOwnProperty(key)) {
  112. var valStartIdx = startIndex(str, eqIdx + 1, endIdx);
  113. var valEndIdx = endIndex(str, endIdx, valStartIdx);
  114. if (str.charCodeAt(valStartIdx) === 0x22 /* " */ && str.charCodeAt(valEndIdx - 1) === 0x22 /* " */) {
  115. valStartIdx++;
  116. valEndIdx--;
  117. }
  118. var val = str.slice(valStartIdx, valEndIdx);
  119. obj[key] = tryDecode(val, dec);
  120. }
  121. index = endIdx + 1
  122. } while (index < len);
  123. return obj;
  124. }
  125. function startIndex(str, index, max) {
  126. do {
  127. var code = str.charCodeAt(index);
  128. if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index;
  129. } while (++index < max);
  130. return max;
  131. }
  132. function endIndex(str, index, min) {
  133. while (index > min) {
  134. var code = str.charCodeAt(--index);
  135. if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index + 1;
  136. }
  137. return min;
  138. }
  139. /**
  140. * Serialize data into a cookie header.
  141. *
  142. * Serialize a name value pair into a cookie string suitable for
  143. * http headers. An optional options object specifies cookie parameters.
  144. *
  145. * serialize('foo', 'bar', { httpOnly: true })
  146. * => "foo=bar; httpOnly"
  147. *
  148. * @param {string} name
  149. * @param {string} val
  150. * @param {object} [opt]
  151. * @return {string}
  152. * @public
  153. */
  154. function serialize(name, val, opt) {
  155. var enc = (opt && opt.encode) || encodeURIComponent;
  156. if (typeof enc !== 'function') {
  157. throw new TypeError('option encode is invalid');
  158. }
  159. if (!cookieNameRegExp.test(name)) {
  160. throw new TypeError('argument name is invalid');
  161. }
  162. var value = enc(val);
  163. if (!cookieValueRegExp.test(value)) {
  164. throw new TypeError('argument val is invalid');
  165. }
  166. var str = name + '=' + value;
  167. if (!opt) return str;
  168. if (null != opt.maxAge) {
  169. var maxAge = Math.floor(opt.maxAge);
  170. if (!isFinite(maxAge)) {
  171. throw new TypeError('option maxAge is invalid')
  172. }
  173. str += '; Max-Age=' + maxAge;
  174. }
  175. if (opt.domain) {
  176. if (!domainValueRegExp.test(opt.domain)) {
  177. throw new TypeError('option domain is invalid');
  178. }
  179. str += '; Domain=' + opt.domain;
  180. }
  181. if (opt.path) {
  182. if (!pathValueRegExp.test(opt.path)) {
  183. throw new TypeError('option path is invalid');
  184. }
  185. str += '; Path=' + opt.path;
  186. }
  187. if (opt.expires) {
  188. var expires = opt.expires
  189. if (!isDate(expires) || isNaN(expires.valueOf())) {
  190. throw new TypeError('option expires is invalid');
  191. }
  192. str += '; Expires=' + expires.toUTCString()
  193. }
  194. if (opt.httpOnly) {
  195. str += '; HttpOnly';
  196. }
  197. if (opt.secure) {
  198. str += '; Secure';
  199. }
  200. if (opt.partitioned) {
  201. str += '; Partitioned'
  202. }
  203. if (opt.priority) {
  204. var priority = typeof opt.priority === 'string'
  205. ? opt.priority.toLowerCase() : opt.priority;
  206. switch (priority) {
  207. case 'low':
  208. str += '; Priority=Low'
  209. break
  210. case 'medium':
  211. str += '; Priority=Medium'
  212. break
  213. case 'high':
  214. str += '; Priority=High'
  215. break
  216. default:
  217. throw new TypeError('option priority is invalid')
  218. }
  219. }
  220. if (opt.sameSite) {
  221. var sameSite = typeof opt.sameSite === 'string'
  222. ? opt.sameSite.toLowerCase() : opt.sameSite;
  223. switch (sameSite) {
  224. case true:
  225. str += '; SameSite=Strict';
  226. break;
  227. case 'lax':
  228. str += '; SameSite=Lax';
  229. break;
  230. case 'strict':
  231. str += '; SameSite=Strict';
  232. break;
  233. case 'none':
  234. str += '; SameSite=None';
  235. break;
  236. default:
  237. throw new TypeError('option sameSite is invalid');
  238. }
  239. }
  240. return str;
  241. }
  242. /**
  243. * URL-decode string value. Optimized to skip native call when no %.
  244. *
  245. * @param {string} str
  246. * @returns {string}
  247. */
  248. function decode (str) {
  249. return str.indexOf('%') !== -1
  250. ? decodeURIComponent(str)
  251. : str
  252. }
  253. /**
  254. * Determine if value is a Date.
  255. *
  256. * @param {*} val
  257. * @private
  258. */
  259. function isDate (val) {
  260. return __toString.call(val) === '[object Date]';
  261. }
  262. /**
  263. * Try decoding a string using a decoding function.
  264. *
  265. * @param {string} str
  266. * @param {function} decode
  267. * @private
  268. */
  269. function tryDecode(str, decode) {
  270. try {
  271. return decode(str);
  272. } catch (e) {
  273. return str;
  274. }
  275. }