index.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 field-content in RFC 7230 sec 3.2
  21. *
  22. * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
  23. * field-vchar = VCHAR / obs-text
  24. * obs-text = %x80-FF
  25. */
  26. var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
  27. /**
  28. * Parse a cookie header.
  29. *
  30. * Parse the given cookie header string into an object
  31. * The object has the various cookies as keys(names) => values
  32. *
  33. * @param {string} str
  34. * @param {object} [options]
  35. * @return {object}
  36. * @public
  37. */
  38. function parse(str, options) {
  39. if (typeof str !== 'string') {
  40. throw new TypeError('argument str must be a string');
  41. }
  42. var obj = {}
  43. var opt = options || {};
  44. var dec = opt.decode || decode;
  45. var index = 0
  46. while (index < str.length) {
  47. var eqIdx = str.indexOf('=', index)
  48. // no more cookie pairs
  49. if (eqIdx === -1) {
  50. break
  51. }
  52. var endIdx = str.indexOf(';', index)
  53. if (endIdx === -1) {
  54. endIdx = str.length
  55. } else if (endIdx < eqIdx) {
  56. // backtrack on prior semicolon
  57. index = str.lastIndexOf(';', eqIdx - 1) + 1
  58. continue
  59. }
  60. var key = str.slice(index, eqIdx).trim()
  61. // only assign once
  62. if (undefined === obj[key]) {
  63. var val = str.slice(eqIdx + 1, endIdx).trim()
  64. // quoted values
  65. if (val.charCodeAt(0) === 0x22) {
  66. val = val.slice(1, -1)
  67. }
  68. obj[key] = tryDecode(val, dec);
  69. }
  70. index = endIdx + 1
  71. }
  72. return obj;
  73. }
  74. /**
  75. * Serialize data into a cookie header.
  76. *
  77. * Serialize the a name value pair into a cookie string suitable for
  78. * http headers. An optional options object specified cookie parameters.
  79. *
  80. * serialize('foo', 'bar', { httpOnly: true })
  81. * => "foo=bar; httpOnly"
  82. *
  83. * @param {string} name
  84. * @param {string} val
  85. * @param {object} [options]
  86. * @return {string}
  87. * @public
  88. */
  89. function serialize(name, val, options) {
  90. var opt = options || {};
  91. var enc = opt.encode || encode;
  92. if (typeof enc !== 'function') {
  93. throw new TypeError('option encode is invalid');
  94. }
  95. if (!fieldContentRegExp.test(name)) {
  96. throw new TypeError('argument name is invalid');
  97. }
  98. var value = enc(val);
  99. if (value && !fieldContentRegExp.test(value)) {
  100. throw new TypeError('argument val is invalid');
  101. }
  102. var str = name + '=' + value;
  103. if (null != opt.maxAge) {
  104. var maxAge = opt.maxAge - 0;
  105. if (isNaN(maxAge) || !isFinite(maxAge)) {
  106. throw new TypeError('option maxAge is invalid')
  107. }
  108. str += '; Max-Age=' + Math.floor(maxAge);
  109. }
  110. if (opt.domain) {
  111. if (!fieldContentRegExp.test(opt.domain)) {
  112. throw new TypeError('option domain is invalid');
  113. }
  114. str += '; Domain=' + opt.domain;
  115. }
  116. if (opt.path) {
  117. if (!fieldContentRegExp.test(opt.path)) {
  118. throw new TypeError('option path is invalid');
  119. }
  120. str += '; Path=' + opt.path;
  121. }
  122. if (opt.expires) {
  123. var expires = opt.expires
  124. if (!isDate(expires) || isNaN(expires.valueOf())) {
  125. throw new TypeError('option expires is invalid');
  126. }
  127. str += '; Expires=' + expires.toUTCString()
  128. }
  129. if (opt.httpOnly) {
  130. str += '; HttpOnly';
  131. }
  132. if (opt.secure) {
  133. str += '; Secure';
  134. }
  135. if (opt.priority) {
  136. var priority = typeof opt.priority === 'string'
  137. ? opt.priority.toLowerCase()
  138. : opt.priority
  139. switch (priority) {
  140. case 'low':
  141. str += '; Priority=Low'
  142. break
  143. case 'medium':
  144. str += '; Priority=Medium'
  145. break
  146. case 'high':
  147. str += '; Priority=High'
  148. break
  149. default:
  150. throw new TypeError('option priority is invalid')
  151. }
  152. }
  153. if (opt.sameSite) {
  154. var sameSite = typeof opt.sameSite === 'string'
  155. ? opt.sameSite.toLowerCase() : opt.sameSite;
  156. switch (sameSite) {
  157. case true:
  158. str += '; SameSite=Strict';
  159. break;
  160. case 'lax':
  161. str += '; SameSite=Lax';
  162. break;
  163. case 'strict':
  164. str += '; SameSite=Strict';
  165. break;
  166. case 'none':
  167. str += '; SameSite=None';
  168. break;
  169. default:
  170. throw new TypeError('option sameSite is invalid');
  171. }
  172. }
  173. return str;
  174. }
  175. /**
  176. * URL-decode string value. Optimized to skip native call when no %.
  177. *
  178. * @param {string} str
  179. * @returns {string}
  180. */
  181. function decode (str) {
  182. return str.indexOf('%') !== -1
  183. ? decodeURIComponent(str)
  184. : str
  185. }
  186. /**
  187. * URL-encode value.
  188. *
  189. * @param {string} str
  190. * @returns {string}
  191. */
  192. function encode (val) {
  193. return encodeURIComponent(val)
  194. }
  195. /**
  196. * Determine if value is a Date.
  197. *
  198. * @param {*} val
  199. * @private
  200. */
  201. function isDate (val) {
  202. return __toString.call(val) === '[object Date]' ||
  203. val instanceof Date
  204. }
  205. /**
  206. * Try decoding a string using a decoding function.
  207. *
  208. * @param {string} str
  209. * @param {function} decode
  210. * @private
  211. */
  212. function tryDecode(str, decode) {
  213. try {
  214. return decode(str);
  215. } catch (e) {
  216. return str;
  217. }
  218. }