index.js 8.0 KB

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