index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. 'use strict';
  2. // rfc7231 6.1
  3. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4. var statusCodeCacheableByDefault = [200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501];
  5. // This implementation does not understand partial responses (206)
  6. var understoodStatuses = [200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501];
  7. var hopByHopHeaders = { 'connection': true, 'keep-alive': true, 'proxy-authenticate': true, 'proxy-authorization': true, 'te': true, 'trailer': true, 'transfer-encoding': true, 'upgrade': true };
  8. var excludedFromRevalidationUpdate = {
  9. // Since the old body is reused, it doesn't make sense to change properties of the body
  10. 'content-length': true, 'content-encoding': true, 'transfer-encoding': true,
  11. 'content-range': true
  12. };
  13. function parseCacheControl(header) {
  14. var cc = {};
  15. if (!header) return cc;
  16. // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),
  17. // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale
  18. var parts = header.trim().split(/\s*,\s*/); // TODO: lame parsing
  19. for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  20. var _ref;
  21. if (_isArray) {
  22. if (_i >= _iterator.length) break;
  23. _ref = _iterator[_i++];
  24. } else {
  25. _i = _iterator.next();
  26. if (_i.done) break;
  27. _ref = _i.value;
  28. }
  29. var part = _ref;
  30. var _part$split = part.split(/\s*=\s*/, 2),
  31. k = _part$split[0],
  32. v = _part$split[1];
  33. cc[k] = v === undefined ? true : v.replace(/^"|"$/g, ''); // TODO: lame unquoting
  34. }
  35. return cc;
  36. }
  37. function formatCacheControl(cc) {
  38. var parts = [];
  39. for (var k in cc) {
  40. var v = cc[k];
  41. parts.push(v === true ? k : k + '=' + v);
  42. }
  43. if (!parts.length) {
  44. return undefined;
  45. }
  46. return parts.join(', ');
  47. }
  48. module.exports = function () {
  49. function CachePolicy(req, res) {
  50. var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  51. shared = _ref2.shared,
  52. cacheHeuristic = _ref2.cacheHeuristic,
  53. immutableMinTimeToLive = _ref2.immutableMinTimeToLive,
  54. ignoreCargoCult = _ref2.ignoreCargoCult,
  55. _fromObject = _ref2._fromObject;
  56. _classCallCheck(this, CachePolicy);
  57. if (_fromObject) {
  58. this._fromObject(_fromObject);
  59. return;
  60. }
  61. if (!res || !res.headers) {
  62. throw Error("Response headers missing");
  63. }
  64. this._assertRequestHasHeaders(req);
  65. this._responseTime = this.now();
  66. this._isShared = shared !== false;
  67. this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
  68. this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1000;
  69. this._status = 'status' in res ? res.status : 200;
  70. this._resHeaders = res.headers;
  71. this._rescc = parseCacheControl(res.headers['cache-control']);
  72. this._method = 'method' in req ? req.method : 'GET';
  73. this._url = req.url;
  74. this._host = req.headers.host;
  75. this._noAuthorization = !req.headers.authorization;
  76. this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used
  77. this._reqcc = parseCacheControl(req.headers['cache-control']);
  78. // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,
  79. // so there's no point stricly adhering to the blindly copy&pasted directives.
  80. if (ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc) {
  81. delete this._rescc['pre-check'];
  82. delete this._rescc['post-check'];
  83. delete this._rescc['no-cache'];
  84. delete this._rescc['no-store'];
  85. delete this._rescc['must-revalidate'];
  86. this._resHeaders = Object.assign({}, this._resHeaders, { 'cache-control': formatCacheControl(this._rescc) });
  87. delete this._resHeaders.expires;
  88. delete this._resHeaders.pragma;
  89. }
  90. // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive
  91. // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1).
  92. if (!res.headers['cache-control'] && /no-cache/.test(res.headers.pragma)) {
  93. this._rescc['no-cache'] = true;
  94. }
  95. }
  96. CachePolicy.prototype.now = function now() {
  97. return Date.now();
  98. };
  99. CachePolicy.prototype.storable = function storable() {
  100. // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.
  101. return !!(!this._reqcc['no-store'] && (
  102. // A cache MUST NOT store a response to any request, unless:
  103. // The request method is understood by the cache and defined as being cacheable, and
  104. 'GET' === this._method || 'HEAD' === this._method || 'POST' === this._method && this._hasExplicitExpiration()) &&
  105. // the response status code is understood by the cache, and
  106. understoodStatuses.indexOf(this._status) !== -1 &&
  107. // the "no-store" cache directive does not appear in request or response header fields, and
  108. !this._rescc['no-store'] && (
  109. // the "private" response directive does not appear in the response, if the cache is shared, and
  110. !this._isShared || !this._rescc.private) && (
  111. // the Authorization header field does not appear in the request, if the cache is shared,
  112. !this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && (
  113. // the response either:
  114. // contains an Expires header field, or
  115. this._resHeaders.expires ||
  116. // contains a max-age response directive, or
  117. // contains a s-maxage response directive and the cache is shared, or
  118. // contains a public response directive.
  119. this._rescc.public || this._rescc['max-age'] || this._rescc['s-maxage'] ||
  120. // has a status code that is defined as cacheable by default
  121. statusCodeCacheableByDefault.indexOf(this._status) !== -1));
  122. };
  123. CachePolicy.prototype._hasExplicitExpiration = function _hasExplicitExpiration() {
  124. // 4.2.1 Calculating Freshness Lifetime
  125. return this._isShared && this._rescc['s-maxage'] || this._rescc['max-age'] || this._resHeaders.expires;
  126. };
  127. CachePolicy.prototype._assertRequestHasHeaders = function _assertRequestHasHeaders(req) {
  128. if (!req || !req.headers) {
  129. throw Error("Request headers missing");
  130. }
  131. };
  132. CachePolicy.prototype.satisfiesWithoutRevalidation = function satisfiesWithoutRevalidation(req) {
  133. this._assertRequestHasHeaders(req);
  134. // When presented with a request, a cache MUST NOT reuse a stored response, unless:
  135. // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,
  136. // unless the stored response is successfully validated (Section 4.3), and
  137. var requestCC = parseCacheControl(req.headers['cache-control']);
  138. if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {
  139. return false;
  140. }
  141. if (requestCC['max-age'] && this.age() > requestCC['max-age']) {
  142. return false;
  143. }
  144. if (requestCC['min-fresh'] && this.timeToLive() < 1000 * requestCC['min-fresh']) {
  145. return false;
  146. }
  147. // the stored response is either:
  148. // fresh, or allowed to be served stale
  149. if (this.stale()) {
  150. var allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge());
  151. if (!allowsStale) {
  152. return false;
  153. }
  154. }
  155. return this._requestMatches(req, false);
  156. };
  157. CachePolicy.prototype._requestMatches = function _requestMatches(req, allowHeadMethod) {
  158. // The presented effective request URI and that of the stored response match, and
  159. return (!this._url || this._url === req.url) && this._host === req.headers.host && (
  160. // the request method associated with the stored response allows it to be used for the presented request, and
  161. !req.method || this._method === req.method || allowHeadMethod && 'HEAD' === req.method) &&
  162. // selecting header fields nominated by the stored response (if any) match those presented, and
  163. this._varyMatches(req);
  164. };
  165. CachePolicy.prototype._allowsStoringAuthenticated = function _allowsStoringAuthenticated() {
  166. // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.
  167. return this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage'];
  168. };
  169. CachePolicy.prototype._varyMatches = function _varyMatches(req) {
  170. if (!this._resHeaders.vary) {
  171. return true;
  172. }
  173. // A Vary header field-value of "*" always fails to match
  174. if (this._resHeaders.vary === '*') {
  175. return false;
  176. }
  177. var fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);
  178. for (var _iterator2 = fields, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
  179. var _ref3;
  180. if (_isArray2) {
  181. if (_i2 >= _iterator2.length) break;
  182. _ref3 = _iterator2[_i2++];
  183. } else {
  184. _i2 = _iterator2.next();
  185. if (_i2.done) break;
  186. _ref3 = _i2.value;
  187. }
  188. var name = _ref3;
  189. if (req.headers[name] !== this._reqHeaders[name]) return false;
  190. }
  191. return true;
  192. };
  193. CachePolicy.prototype._copyWithoutHopByHopHeaders = function _copyWithoutHopByHopHeaders(inHeaders) {
  194. var headers = {};
  195. for (var name in inHeaders) {
  196. if (hopByHopHeaders[name]) continue;
  197. headers[name] = inHeaders[name];
  198. }
  199. // 9.1. Connection
  200. if (inHeaders.connection) {
  201. var tokens = inHeaders.connection.trim().split(/\s*,\s*/);
  202. for (var _iterator3 = tokens, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
  203. var _ref4;
  204. if (_isArray3) {
  205. if (_i3 >= _iterator3.length) break;
  206. _ref4 = _iterator3[_i3++];
  207. } else {
  208. _i3 = _iterator3.next();
  209. if (_i3.done) break;
  210. _ref4 = _i3.value;
  211. }
  212. var _name = _ref4;
  213. delete headers[_name];
  214. }
  215. }
  216. if (headers.warning) {
  217. var warnings = headers.warning.split(/,/).filter(function (warning) {
  218. return !/^\s*1[0-9][0-9]/.test(warning);
  219. });
  220. if (!warnings.length) {
  221. delete headers.warning;
  222. } else {
  223. headers.warning = warnings.join(',').trim();
  224. }
  225. }
  226. return headers;
  227. };
  228. CachePolicy.prototype.responseHeaders = function responseHeaders() {
  229. var headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
  230. var age = this.age();
  231. // A cache SHOULD generate 113 warning if it heuristically chose a freshness
  232. // lifetime greater than 24 hours and the response's age is greater than 24 hours.
  233. if (age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24) {
  234. headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"';
  235. }
  236. headers.age = `${Math.round(age)}`;
  237. return headers;
  238. };
  239. /**
  240. * Value of the Date response header or current time if Date was demed invalid
  241. * @return timestamp
  242. */
  243. CachePolicy.prototype.date = function date() {
  244. var dateValue = Date.parse(this._resHeaders.date);
  245. var maxClockDrift = 8 * 3600 * 1000;
  246. if (Number.isNaN(dateValue) || dateValue < this._responseTime - maxClockDrift || dateValue > this._responseTime + maxClockDrift) {
  247. return this._responseTime;
  248. }
  249. return dateValue;
  250. };
  251. /**
  252. * Value of the Age header, in seconds, updated for the current time.
  253. * May be fractional.
  254. *
  255. * @return Number
  256. */
  257. CachePolicy.prototype.age = function age() {
  258. var age = Math.max(0, (this._responseTime - this.date()) / 1000);
  259. if (this._resHeaders.age) {
  260. var ageValue = this._ageValue();
  261. if (ageValue > age) age = ageValue;
  262. }
  263. var residentTime = (this.now() - this._responseTime) / 1000;
  264. return age + residentTime;
  265. };
  266. CachePolicy.prototype._ageValue = function _ageValue() {
  267. var ageValue = parseInt(this._resHeaders.age);
  268. return isFinite(ageValue) ? ageValue : 0;
  269. };
  270. /**
  271. * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
  272. *
  273. * For an up-to-date value, see `timeToLive()`.
  274. *
  275. * @return Number
  276. */
  277. CachePolicy.prototype.maxAge = function maxAge() {
  278. if (!this.storable() || this._rescc['no-cache']) {
  279. return 0;
  280. }
  281. // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default
  282. // so this implementation requires explicit opt-in via public header
  283. if (this._isShared && this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable) {
  284. return 0;
  285. }
  286. if (this._resHeaders.vary === '*') {
  287. return 0;
  288. }
  289. if (this._isShared) {
  290. if (this._rescc['proxy-revalidate']) {
  291. return 0;
  292. }
  293. // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
  294. if (this._rescc['s-maxage']) {
  295. return parseInt(this._rescc['s-maxage'], 10);
  296. }
  297. }
  298. // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
  299. if (this._rescc['max-age']) {
  300. return parseInt(this._rescc['max-age'], 10);
  301. }
  302. var defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
  303. var dateValue = this.date();
  304. if (this._resHeaders.expires) {
  305. var expires = Date.parse(this._resHeaders.expires);
  306. // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
  307. if (Number.isNaN(expires) || expires < dateValue) {
  308. return 0;
  309. }
  310. return Math.max(defaultMinTtl, (expires - dateValue) / 1000);
  311. }
  312. if (this._resHeaders['last-modified']) {
  313. var lastModified = Date.parse(this._resHeaders['last-modified']);
  314. if (isFinite(lastModified) && dateValue > lastModified) {
  315. return Math.max(defaultMinTtl, (dateValue - lastModified) / 1000 * this._cacheHeuristic);
  316. }
  317. }
  318. return defaultMinTtl;
  319. };
  320. CachePolicy.prototype.timeToLive = function timeToLive() {
  321. return Math.max(0, this.maxAge() - this.age()) * 1000;
  322. };
  323. CachePolicy.prototype.stale = function stale() {
  324. return this.maxAge() <= this.age();
  325. };
  326. CachePolicy.fromObject = function fromObject(obj) {
  327. return new this(undefined, undefined, { _fromObject: obj });
  328. };
  329. CachePolicy.prototype._fromObject = function _fromObject(obj) {
  330. if (this._responseTime) throw Error("Reinitialized");
  331. if (!obj || obj.v !== 1) throw Error("Invalid serialization");
  332. this._responseTime = obj.t;
  333. this._isShared = obj.sh;
  334. this._cacheHeuristic = obj.ch;
  335. this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;
  336. this._status = obj.st;
  337. this._resHeaders = obj.resh;
  338. this._rescc = obj.rescc;
  339. this._method = obj.m;
  340. this._url = obj.u;
  341. this._host = obj.h;
  342. this._noAuthorization = obj.a;
  343. this._reqHeaders = obj.reqh;
  344. this._reqcc = obj.reqcc;
  345. };
  346. CachePolicy.prototype.toObject = function toObject() {
  347. return {
  348. v: 1,
  349. t: this._responseTime,
  350. sh: this._isShared,
  351. ch: this._cacheHeuristic,
  352. imm: this._immutableMinTtl,
  353. st: this._status,
  354. resh: this._resHeaders,
  355. rescc: this._rescc,
  356. m: this._method,
  357. u: this._url,
  358. h: this._host,
  359. a: this._noAuthorization,
  360. reqh: this._reqHeaders,
  361. reqcc: this._reqcc
  362. };
  363. };
  364. /**
  365. * Headers for sending to the origin server to revalidate stale response.
  366. * Allows server to return 304 to allow reuse of the previous response.
  367. *
  368. * Hop by hop headers are always stripped.
  369. * Revalidation headers may be added or removed, depending on request.
  370. */
  371. CachePolicy.prototype.revalidationHeaders = function revalidationHeaders(incomingReq) {
  372. this._assertRequestHasHeaders(incomingReq);
  373. var headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
  374. // This implementation does not understand range requests
  375. delete headers['if-range'];
  376. if (!this._requestMatches(incomingReq, true) || !this.storable()) {
  377. // revalidation allowed via HEAD
  378. // not for the same resource, or wasn't allowed to be cached anyway
  379. delete headers['if-none-match'];
  380. delete headers['if-modified-since'];
  381. return headers;
  382. }
  383. /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */
  384. if (this._resHeaders.etag) {
  385. headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag;
  386. }
  387. // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.
  388. var forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || this._method && this._method != 'GET';
  389. /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.
  390. Note: This implementation does not understand partial responses (206) */
  391. if (forbidsWeakValidators) {
  392. delete headers['if-modified-since'];
  393. if (headers['if-none-match']) {
  394. var etags = headers['if-none-match'].split(/,/).filter(function (etag) {
  395. return !/^\s*W\//.test(etag);
  396. });
  397. if (!etags.length) {
  398. delete headers['if-none-match'];
  399. } else {
  400. headers['if-none-match'] = etags.join(',').trim();
  401. }
  402. }
  403. } else if (this._resHeaders['last-modified'] && !headers['if-modified-since']) {
  404. headers['if-modified-since'] = this._resHeaders['last-modified'];
  405. }
  406. return headers;
  407. };
  408. /**
  409. * Creates new CachePolicy with information combined from the previews response,
  410. * and the new revalidation response.
  411. *
  412. * Returns {policy, modified} where modified is a boolean indicating
  413. * whether the response body has been modified, and old cached body can't be used.
  414. *
  415. * @return {Object} {policy: CachePolicy, modified: Boolean}
  416. */
  417. CachePolicy.prototype.revalidatedPolicy = function revalidatedPolicy(request, response) {
  418. this._assertRequestHasHeaders(request);
  419. if (!response || !response.headers) {
  420. throw Error("Response headers missing");
  421. }
  422. // These aren't going to be supported exactly, since one CachePolicy object
  423. // doesn't know about all the other cached objects.
  424. var matches = false;
  425. if (response.status !== undefined && response.status != 304) {
  426. matches = false;
  427. } else if (response.headers.etag && !/^\s*W\//.test(response.headers.etag)) {
  428. // "All of the stored responses with the same strong validator are selected.
  429. // If none of the stored responses contain the same strong validator,
  430. // then the cache MUST NOT use the new response to update any stored responses."
  431. matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag;
  432. } else if (this._resHeaders.etag && response.headers.etag) {
  433. // "If the new response contains a weak validator and that validator corresponds
  434. // to one of the cache's stored responses,
  435. // then the most recent of those matching stored responses is selected for update."
  436. matches = this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag.replace(/^\s*W\//, '');
  437. } else if (this._resHeaders['last-modified']) {
  438. matches = this._resHeaders['last-modified'] === response.headers['last-modified'];
  439. } else {
  440. // If the new response does not include any form of validator (such as in the case where
  441. // a client generates an If-Modified-Since request from a source other than the Last-Modified
  442. // response header field), and there is only one stored response, and that stored response also
  443. // lacks a validator, then that stored response is selected for update.
  444. if (!this._resHeaders.etag && !this._resHeaders['last-modified'] && !response.headers.etag && !response.headers['last-modified']) {
  445. matches = true;
  446. }
  447. }
  448. if (!matches) {
  449. return {
  450. policy: new this.constructor(request, response),
  451. modified: true
  452. };
  453. }
  454. // use other header fields provided in the 304 (Not Modified) response to replace all instances
  455. // of the corresponding header fields in the stored response.
  456. var headers = {};
  457. for (var k in this._resHeaders) {
  458. headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k];
  459. }
  460. var newResponse = Object.assign({}, response, {
  461. status: this._status,
  462. method: this._method,
  463. headers
  464. });
  465. return {
  466. policy: new this.constructor(request, newResponse),
  467. modified: false
  468. };
  469. };
  470. return CachePolicy;
  471. }();