pax_global_header00006660000000000000000000000064136270453730014524gustar00rootroot0000000000000052 comment=ed83aec75be817967cdac2663907d060fdc6adc3 http-cache-semantics-4.1.0/000077500000000000000000000000001362704537300155325ustar00rootroot00000000000000http-cache-semantics-4.1.0/.eslintrc.json000066400000000000000000000002101362704537300203170ustar00rootroot00000000000000{ "env": { "node": true, "es6": true, "mocha": true }, "extends": ["plugin:prettier/recommended"] } http-cache-semantics-4.1.0/.gitignore000066400000000000000000000000541362704537300175210ustar00rootroot00000000000000node_modules/ .nyc_output/ coverage/ node4/ http-cache-semantics-4.1.0/.huskyrc.json000066400000000000000000000000751362704537300201750ustar00rootroot00000000000000{ "hooks": { "pre-commit": "lint-staged" } } http-cache-semantics-4.1.0/.lintstagedrc.json000066400000000000000000000001121362704537300211600ustar00rootroot00000000000000{ "*.{js,json,md,yml,yaml}": ["prettier-eslint --write", "git add"] } http-cache-semantics-4.1.0/.prettierrc.json000066400000000000000000000001131362704537300206610ustar00rootroot00000000000000{ "singleQuote": true, "tabWidth": 4, "trailingComma": "es5" } http-cache-semantics-4.1.0/.travis.yml000066400000000000000000000001211362704537300176350ustar00rootroot00000000000000sudo: false language: node_js node_js: - '11' - '10' - '8' - '6' http-cache-semantics-4.1.0/LICENSE000066400000000000000000000023721362704537300165430ustar00rootroot00000000000000Copyright 2016-2018 Kornel Lesiński Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. http-cache-semantics-4.1.0/README.md000066400000000000000000000242231362704537300170140ustar00rootroot00000000000000# Can I cache this? [![Build Status](https://travis-ci.org/kornelski/http-cache-semantics.svg?branch=master)](https://travis-ci.org/kornelski/http-cache-semantics) `CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches. It also implements [RFC 5861](https://tools.ietf.org/html/rfc5861), implementing `stale-if-error` and `stale-while-revalidate`. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses. ## Usage Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy. ```js const policy = new CachePolicy(request, response, options); if (!policy.storable()) { // throw the response away, it's not usable at all return; } // Cache the data AND the policy object in your cache // (this is pseudocode, roll your own cache (lru-cache package works)) letsPretendThisIsSomeCache.set( request.url, { policy, response }, policy.timeToLive() ); ``` ```js // And later, when you receive a new request: const { policy, response } = letsPretendThisIsSomeCache.get(newRequest.url); // It's not enough that it exists in the cache, it has to match the new request, too: if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { // OK, the previous response can be used to respond to the `newRequest`. // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. response.headers = policy.responseHeaders(); return response; } ``` It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc. The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met. ### Constructor options Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method). ```js const request = { url: '/', method: 'GET', headers: { accept: '*/*', }, }; const response = { status: 200, headers: { 'cache-control': 'public, max-age=7234', }, }; const options = { shared: true, cacheHeuristic: 0.1, immutableMinTimeToLive: 24 * 3600 * 1000, // 24h ignoreCargoCult: false, }; ``` If `options.shared` is `true` (default), then the response is evaluated from a perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is `false`, then the response is evaluated from a perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). `shared: true` is recommended for HTTP clients. `options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100\*0.1 = 10 days. `options.immutableMinTimeToLive` is a number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. Note that [per RFC](http://httpwg.org/http-extensions/immutable.html) these can become stale, so `max-age` still overrides the default. If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults. ### `storable()` Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response. ### `satisfiesWithoutRevalidation(newRequest)` This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request. If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`. If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first (see `revalidationHeaders()`). ### `responseHeaders()` Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response's `Age` to avoid doubling cache time. ```js cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); ``` ### `timeToLive()` Returns approximate time in _milliseconds_ until the response becomes stale (i.e. not fresh). After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`. `stale-if-error` and `stale-while-revalidate` extend the time to live of the cache, that can still be used if stale. ### `toObject()`/`fromObject(json)` Chances are you'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it. ### Refreshing stale cache (revalidation) When a cached response has expired, it can be made fresh again by making a request to the origin server. The server may respond with status 304 (Not Modified) without sending the response body again, saving bandwidth. The following methods help perform the update efficiently and correctly. #### `revalidationHeaders(newRequest)` Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. These headers allow the origin server to return status 304 indicating the response is still fresh. All headers unrelated to caching are passed through as-is. Use this method when updating cache from the origin server. ```js updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); ``` #### `revalidatedPolicy(revalidationRequest, revalidationResponse)` Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys: - `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one. - `modified` — Boolean indicating whether the response body has changed. - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old cached response body. This is also affected by `stale-if-error`. - If `true`, you should use new response's body (if present), or make another request to the origin server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get the new resource. ```js // When serving requests from cache: const { oldPolicy, oldResponse } = letsPretendThisIsSomeCache.get( newRequest.url ); if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) { // Change the request to ask the origin server if the cached response can be used newRequest.headers = oldPolicy.revalidationHeaders(newRequest); // Send request to the origin server. The server may respond with status 304 const newResponse = await makeRequest(newRequest); // Create updated policy and combined response from the old and new data const { policy, modified } = oldPolicy.revalidatedPolicy( newRequest, newResponse ); const response = modified ? newResponse : oldResponse; // Update the cache with the newer/fresher response letsPretendThisIsSomeCache.set( newRequest.url, { policy, response }, policy.timeToLive() ); // And proceed returning cached response as usual response.headers = policy.responseHeaders(); return response; } ``` # Yo, FRESH ![satisfiesWithoutRevalidation](fresh.jpg) ## Used by - [ImageOptim API](https://imageoptim.com/api), [make-fetch-happen](https://github.com/zkat/make-fetch-happen), [cacheable-request](https://www.npmjs.com/package/cacheable-request) ([got](https://www.npmjs.com/package/got)), [npm/registry-fetch](https://github.com/npm/registry-fetch), [etc.](https://github.com/kornelski/http-cache-semantics/network/dependents) ## Implemented - `Cache-Control` response header with all the quirks. - `Expires` with check for bad clocks. - `Pragma` response header. - `Age` response header. - `Vary` response header. - Default cacheability of statuses and methods. - Requests for stale data. - Filtering of hop-by-hop headers. - Basic revalidation request - `stale-if-error` ## Unimplemented - Merging of range requests, `If-Range` (but correctly supports them as non-cacheable) - Revalidation of multiple representations ### Trusting server `Date` Per the RFC, the cache should take into account the time between server-supplied `Date` and the time it received the response. The RFC-mandated behavior creates two problems: * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong). * Even reasonably correct clocks may be off by a couple of seconds, breaking `max-age=1` trick (which is useful for reverse proxies on high-traffic servers). Previous versions of this library had an option to ignore the server date if it was "too inaccurate". To support the `max-age=1` trick the library also has to ignore dates that pretty accurate. There's no point of having an option to trust dates that are only a bit inaccurate, so this library won't trust any server dates. `max-age` will be interpreted from the time the response has been received, not from when it has been sent. This will affect only [RFC 1149 networks](https://tools.ietf.org/html/rfc1149). http-cache-semantics-4.1.0/fresh.jpg000066400000000000000000001161351362704537300173520ustar00rootroot00000000000000JFIF  - " " -D*2**2*D<I;7;I<lUKKUl}ici}N  - " " -D*2**2*D<I;7;I<lUKKUl}ici}NpLL2_=[sٳfݻ6۳nݛvۻf6ٳfYI "1"1c" ,lٳfͻ6mݳnݻ7mٷnݻv۳fyNS2$>Miffa2L1ac88c1@ =6l۳nͻvlݷnݻ6۷nݻv<)̃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c%0ٚ˱#/&9 tjf( fH'KgĦ5,dEx:zptũ/%CWN )#0ԗYg_.DKחzG.}gI&H: Ȫ@RddAu#|sF_mtLy8M pE4INzZa1SsB1.2أ6I$aJPI/+m+m*I#өO)TvE]i!SF9bnY9#pۈv;KhRFfH?%7taeB&HR(|Jm̱hOol#/tJ?|E-ŦJ8\HTrw [)e- .銤GÕM}&|IRXݎ+ ].x%8| :' FYB ^8YwrrN3_N)7$AқRDq[Byfp#hxDvW}N~Dd2Jjv)җZlzHe"^ BRdkF̋y!G{EBVlx=7͎BPK+S,ּ|ñzԖdՍvd2TɿƊ˵FUZfĴcnKWiۓZYĴ,aw*l'%٤NnRlp$:QqIҊXEXJ8ى|_f\d-Z AhGB"!BZ{1cz czA1ϗ?;ŋ͌cǨzQc1|c=aB! Qj-EZT{Z Ab"$ 3=X}7Jze?rOY !bż{ǽ܉nD=bOX%OT4EMdH/DZ1,c1c1hfzCjlS觲?Ob)E-)hZ2OܧzȆdw1ob~~~={-ȖOX$?Oة*hQSiSaSaSaSc*leMOdOd[eʏ}http-cache-semantics-4.1.0/index.js000066400000000000000000000563521362704537300172120ustar00rootroot00000000000000'use strict'; // rfc7231 6.1 const statusCodeCacheableByDefault = new Set([ 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501, ]); // This implementation does not understand partial responses (206) const understoodStatuses = new Set([ 200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501, ]); const errorStatusCodes = new Set([ 500, 502, 503, 504, ]); const hopByHopHeaders = { date: true, // included, because we add Age update Date connection: true, 'keep-alive': true, 'proxy-authenticate': true, 'proxy-authorization': true, te: true, trailer: true, 'transfer-encoding': true, upgrade: true, }; const excludedFromRevalidationUpdate = { // Since the old body is reused, it doesn't make sense to change properties of the body 'content-length': true, 'content-encoding': true, 'transfer-encoding': true, 'content-range': true, }; function toNumberOrZero(s) { const n = parseInt(s, 10); return isFinite(n) ? n : 0; } // RFC 5861 function isErrorResponse(response) { // consider undefined response as faulty if(!response) { return true } return errorStatusCodes.has(response.status); } function parseCacheControl(header) { const cc = {}; if (!header) return cc; // 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), // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale const parts = header.trim().split(/\s*,\s*/); // TODO: lame parsing for (const part of parts) { const [k, v] = part.split(/\s*=\s*/, 2); cc[k] = v === undefined ? true : v.replace(/^"|"$/g, ''); // TODO: lame unquoting } return cc; } function formatCacheControl(cc) { let parts = []; for (const k in cc) { const v = cc[k]; parts.push(v === true ? k : k + '=' + v); } if (!parts.length) { return undefined; } return parts.join(', '); } module.exports = class CachePolicy { constructor( req, res, { shared, cacheHeuristic, immutableMinTimeToLive, ignoreCargoCult, _fromObject, } = {} ) { if (_fromObject) { this._fromObject(_fromObject); return; } if (!res || !res.headers) { throw Error('Response headers missing'); } this._assertRequestHasHeaders(req); this._responseTime = this.now(); this._isShared = shared !== false; this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1000; this._status = 'status' in res ? res.status : 200; this._resHeaders = res.headers; this._rescc = parseCacheControl(res.headers['cache-control']); this._method = 'method' in req ? req.method : 'GET'; this._url = req.url; this._host = req.headers.host; this._noAuthorization = !req.headers.authorization; this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used this._reqcc = parseCacheControl(req.headers['cache-control']); // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, // so there's no point stricly adhering to the blindly copy&pasted directives. if ( ignoreCargoCult && 'pre-check' in this._rescc && 'post-check' in this._rescc ) { delete this._rescc['pre-check']; delete this._rescc['post-check']; delete this._rescc['no-cache']; delete this._rescc['no-store']; delete this._rescc['must-revalidate']; this._resHeaders = Object.assign({}, this._resHeaders, { 'cache-control': formatCacheControl(this._rescc), }); delete this._resHeaders.expires; delete this._resHeaders.pragma; } // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). if ( res.headers['cache-control'] == null && /no-cache/.test(res.headers.pragma) ) { this._rescc['no-cache'] = true; } } now() { return Date.now(); } storable() { // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. return !!( !this._reqcc['no-store'] && // A cache MUST NOT store a response to any request, unless: // The request method is understood by the cache and defined as being cacheable, and ('GET' === this._method || 'HEAD' === this._method || ('POST' === this._method && this._hasExplicitExpiration())) && // the response status code is understood by the cache, and understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and !this._rescc['no-store'] && // the "private" response directive does not appear in the response, if the cache is shared, and (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared, (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either: // contains an Expires header field, or (this._resHeaders.expires || // contains a max-age response directive, or // contains a s-maxage response directive and the cache is shared, or // contains a public response directive. this._rescc['max-age'] || (this._isShared && this._rescc['s-maxage']) || this._rescc.public || // has a status code that is defined as cacheable by default statusCodeCacheableByDefault.has(this._status)) ); } _hasExplicitExpiration() { // 4.2.1 Calculating Freshness Lifetime return ( (this._isShared && this._rescc['s-maxage']) || this._rescc['max-age'] || this._resHeaders.expires ); } _assertRequestHasHeaders(req) { if (!req || !req.headers) { throw Error('Request headers missing'); } } satisfiesWithoutRevalidation(req) { this._assertRequestHasHeaders(req); // When presented with a request, a cache MUST NOT reuse a stored response, unless: // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, // unless the stored response is successfully validated (Section 4.3), and const requestCC = parseCacheControl(req.headers['cache-control']); if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { return false; } if (requestCC['max-age'] && this.age() > requestCC['max-age']) { return false; } if ( requestCC['min-fresh'] && this.timeToLive() < 1000 * requestCC['min-fresh'] ) { return false; } // the stored response is either: // fresh, or allowed to be served stale if (this.stale()) { const allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge()); if (!allowsStale) { return false; } } return this._requestMatches(req, false); } _requestMatches(req, allowHeadMethod) { // The presented effective request URI and that of the stored response match, and return ( (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and (!req.method || this._method === req.method || (allowHeadMethod && 'HEAD' === req.method)) && // selecting header fields nominated by the stored response (if any) match those presented, and this._varyMatches(req) ); } _allowsStoringAuthenticated() { // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. return ( this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage'] ); } _varyMatches(req) { if (!this._resHeaders.vary) { return true; } // A Vary header field-value of "*" always fails to match if (this._resHeaders.vary === '*') { return false; } const fields = this._resHeaders.vary .trim() .toLowerCase() .split(/\s*,\s*/); for (const name of fields) { if (req.headers[name] !== this._reqHeaders[name]) return false; } return true; } _copyWithoutHopByHopHeaders(inHeaders) { const headers = {}; for (const name in inHeaders) { if (hopByHopHeaders[name]) continue; headers[name] = inHeaders[name]; } // 9.1. Connection if (inHeaders.connection) { const tokens = inHeaders.connection.trim().split(/\s*,\s*/); for (const name of tokens) { delete headers[name]; } } if (headers.warning) { const warnings = headers.warning.split(/,/).filter(warning => { return !/^\s*1[0-9][0-9]/.test(warning); }); if (!warnings.length) { delete headers.warning; } else { headers.warning = warnings.join(',').trim(); } } return headers; } responseHeaders() { const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); const age = this.age(); // A cache SHOULD generate 113 warning if it heuristically chose a freshness // lifetime greater than 24 hours and the response's age is greater than 24 hours. if ( age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24 ) { headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"'; } headers.age = `${Math.round(age)}`; headers.date = new Date(this.now()).toUTCString(); return headers; } /** * Value of the Date response header or current time if Date was invalid * @return timestamp */ date() { const serverDate = Date.parse(this._resHeaders.date); if (isFinite(serverDate)) { return serverDate; } return this._responseTime; } /** * Value of the Age header, in seconds, updated for the current time. * May be fractional. * * @return Number */ age() { let age = this._ageValue(); const residentTime = (this.now() - this._responseTime) / 1000; return age + residentTime; } _ageValue() { return toNumberOrZero(this._resHeaders.age); } /** * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. * * For an up-to-date value, see `timeToLive()`. * * @return Number */ maxAge() { if (!this.storable() || this._rescc['no-cache']) { return 0; } // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default // so this implementation requires explicit opt-in via public header if ( this._isShared && (this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable) ) { return 0; } if (this._resHeaders.vary === '*') { return 0; } if (this._isShared) { if (this._rescc['proxy-revalidate']) { return 0; } // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. if (this._rescc['s-maxage']) { return toNumberOrZero(this._rescc['s-maxage']); } } // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. if (this._rescc['max-age']) { return toNumberOrZero(this._rescc['max-age']); } const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; const serverDate = this.date(); if (this._resHeaders.expires) { const expires = Date.parse(this._resHeaders.expires); // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). if (Number.isNaN(expires) || expires < serverDate) { return 0; } return Math.max(defaultMinTtl, (expires - serverDate) / 1000); } if (this._resHeaders['last-modified']) { const lastModified = Date.parse(this._resHeaders['last-modified']); if (isFinite(lastModified) && serverDate > lastModified) { return Math.max( defaultMinTtl, ((serverDate - lastModified) / 1000) * this._cacheHeuristic ); } } return defaultMinTtl; } timeToLive() { const age = this.maxAge() - this.age(); const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; } stale() { return this.maxAge() <= this.age(); } _useStaleIfError() { return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); } useStaleWhileRevalidate() { return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); } static fromObject(obj) { return new this(undefined, undefined, { _fromObject: obj }); } _fromObject(obj) { if (this._responseTime) throw Error('Reinitialized'); if (!obj || obj.v !== 1) throw Error('Invalid serialization'); this._responseTime = obj.t; this._isShared = obj.sh; this._cacheHeuristic = obj.ch; this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; this._status = obj.st; this._resHeaders = obj.resh; this._rescc = obj.rescc; this._method = obj.m; this._url = obj.u; this._host = obj.h; this._noAuthorization = obj.a; this._reqHeaders = obj.reqh; this._reqcc = obj.reqcc; } toObject() { return { v: 1, t: this._responseTime, sh: this._isShared, ch: this._cacheHeuristic, imm: this._immutableMinTtl, st: this._status, resh: this._resHeaders, rescc: this._rescc, m: this._method, u: this._url, h: this._host, a: this._noAuthorization, reqh: this._reqHeaders, reqcc: this._reqcc, }; } /** * Headers for sending to the origin server to revalidate stale response. * Allows server to return 304 to allow reuse of the previous response. * * Hop by hop headers are always stripped. * Revalidation headers may be added or removed, depending on request. */ revalidationHeaders(incomingReq) { this._assertRequestHasHeaders(incomingReq); const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); // This implementation does not understand range requests delete headers['if-range']; if (!this._requestMatches(incomingReq, true) || !this.storable()) { // revalidation allowed via HEAD // not for the same resource, or wasn't allowed to be cached anyway delete headers['if-none-match']; delete headers['if-modified-since']; return headers; } /* 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. */ if (this._resHeaders.etag) { headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag; } // 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. const forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || (this._method && this._method != 'GET'); /* 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. Note: This implementation does not understand partial responses (206) */ if (forbidsWeakValidators) { delete headers['if-modified-since']; if (headers['if-none-match']) { const etags = headers['if-none-match'] .split(/,/) .filter(etag => { return !/^\s*W\//.test(etag); }); if (!etags.length) { delete headers['if-none-match']; } else { headers['if-none-match'] = etags.join(',').trim(); } } } else if ( this._resHeaders['last-modified'] && !headers['if-modified-since'] ) { headers['if-modified-since'] = this._resHeaders['last-modified']; } return headers; } /** * Creates new CachePolicy with information combined from the previews response, * and the new revalidation response. * * Returns {policy, modified} where modified is a boolean indicating * whether the response body has been modified, and old cached body can't be used. * * @return {Object} {policy: CachePolicy, modified: Boolean} */ revalidatedPolicy(request, response) { this._assertRequestHasHeaders(request); if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful return { modified: false, matches: false, policy: this, }; } if (!response || !response.headers) { throw Error('Response headers missing'); } // These aren't going to be supported exactly, since one CachePolicy object // doesn't know about all the other cached objects. let matches = false; if (response.status !== undefined && response.status != 304) { matches = false; } else if ( response.headers.etag && !/^\s*W\//.test(response.headers.etag) ) { // "All of the stored responses with the same strong validator are selected. // If none of the stored responses contain the same strong validator, // then the cache MUST NOT use the new response to update any stored responses." matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag; } else if (this._resHeaders.etag && response.headers.etag) { // "If the new response contains a weak validator and that validator corresponds // to one of the cache's stored responses, // then the most recent of those matching stored responses is selected for update." matches = this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag.replace(/^\s*W\//, ''); } else if (this._resHeaders['last-modified']) { matches = this._resHeaders['last-modified'] === response.headers['last-modified']; } else { // If the new response does not include any form of validator (such as in the case where // a client generates an If-Modified-Since request from a source other than the Last-Modified // response header field), and there is only one stored response, and that stored response also // lacks a validator, then that stored response is selected for update. if ( !this._resHeaders.etag && !this._resHeaders['last-modified'] && !response.headers.etag && !response.headers['last-modified'] ) { matches = true; } } if (!matches) { return { policy: new this.constructor(request, response), // Client receiving 304 without body, even if it's invalid/mismatched has no option // but to reuse a cached body. We don't have a good way to tell clients to do // error recovery in such case. modified: response.status != 304, matches: false, }; } // use other header fields provided in the 304 (Not Modified) response to replace all instances // of the corresponding header fields in the stored response. const headers = {}; for (const k in this._resHeaders) { headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k]; } const newResponse = Object.assign({}, response, { status: this._status, method: this._method, headers, }); return { policy: new this.constructor(request, newResponse, { shared: this._isShared, cacheHeuristic: this._cacheHeuristic, immutableMinTimeToLive: this._immutableMinTtl, }), modified: false, matches: true, }; } }; http-cache-semantics-4.1.0/package.json000066400000000000000000000013351362704537300200220ustar00rootroot00000000000000{ "name": "http-cache-semantics", "version": "4.1.0", "description": "Parses Cache-Control and other headers. Helps building correct HTTP caches and proxies", "repository": "https://github.com/kornelski/http-cache-semantics.git", "main": "index.js", "scripts": { "test": "mocha" }, "files": [ "index.js" ], "author": "Kornel Lesiński (https://kornel.ski/)", "license": "BSD-2-Clause", "devDependencies": { "eslint": "^5.13.0", "eslint-plugin-prettier": "^3.0.1", "husky": "^0.14.3", "lint-staged": "^8.1.3", "mocha": "^5.1.0", "prettier": "^1.14.3", "prettier-eslint-cli": "^4.7.1" } } http-cache-semantics-4.1.0/test/000077500000000000000000000000001362704537300165115ustar00rootroot00000000000000http-cache-semantics-4.1.0/test/misctest.js000066400000000000000000000061111362704537300207010ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); describe('Other', function() { it('Thaw wrong object', function() { assert.throws(() => { CachePolicy.fromObject({}); }); }); it('Missing headers', function() { assert.throws(() => { new CachePolicy({}); }); assert.throws(() => { new CachePolicy({ headers: {} }, {}); }); const cache = new CachePolicy({ headers: {} }, { headers: {} }); assert.throws(() => { cache.satisfiesWithoutRevalidation({}); }); assert.throws(() => { cache.revalidatedPolicy({}); }); assert.throws(() => { cache.revalidatedPolicy({ headers: {} }, {}); }); }); it('GitHub response with small clock skew', function() { const res = { headers: { server: 'GitHub.com', date: new Date(Date.now() - 77 * 1000).toUTCString(), 'content-type': 'application/json; charset=utf-8', 'transfer-encoding': 'chunked', connection: 'close', status: '200 OK', 'x-ratelimit-limit': '5000', 'x-ratelimit-remaining': '4836', 'x-ratelimit-reset': '1524313615', 'cache-control': 'private, max-age=60, s-maxage=60', vary: 'Accept, Authorization, Cookie, X-GitHub-OTP', etag: 'W/"4876f954d40e3efc6d32aab08b9bdc47"', 'x-oauth-scopes': 'public_repo, read:user, repo:invite, repo:status, repo_deployment', 'x-accepted-oauth-scopes': '', 'x-github-media-type': 'github.v3', link: '; rel="next", ; rel="last"', 'access-control-expose-headers': 'ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval', 'access-control-allow-origin': '*', 'strict-transport-security': 'max-age=31536000; includeSubdomains; preload', 'x-frame-options': 'deny', 'x-content-type-options': 'nosniff', 'x-xss-protection': '1; mode=block', 'referrer-policy': 'origin-when-cross-origin, strict-origin-when-cross-origin', 'content-security-policy': "default-src 'none'", 'x-runtime-rack': '0.051653', 'content-encoding': 'gzip', 'x-github-request-id': 'C6EE:12E7:3E6CA0D:87F0004:5ADB2B35', }, }; const req = { headers: {}, }; const c = new CachePolicy(req, res, { shared: false, trustServerDate: false, }); assert(c.satisfiesWithoutRevalidation(req)); }); }); http-cache-semantics-4.1.0/test/okhttptest.js000066400000000000000000000325021362704537300212620ustar00rootroot00000000000000'use strict'; /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const assert = require('assert'); const CachePolicy = require('..'); describe('okhttp tests', function() { it('response caching by response code', function() { // Test each documented HTTP/1.1 code, plus the first unused value in each range. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html assertCached(false, 100); assertCached(false, 101); assertCached(false, 102); assertCached(true, 200); assertCached(false, 201); assertCached(false, 202); assertCached(true, 203); assertCached(true, 204); assertCached(false, 205); assertCached(false, 206); //Electing to not cache partial responses assertCached(false, 207); assertCached(true, 300); assertCached(true, 301); assertCached(true, 302); // assertCached(false, 303); assertCached(false, 304); assertCached(false, 305); assertCached(false, 306); assertCached(true, 307); assertCached(true, 308); assertCached(false, 400); assertCached(false, 401); assertCached(false, 402); assertCached(false, 403); assertCached(true, 404); assertCached(true, 405); assertCached(false, 406); assertCached(false, 408); assertCached(false, 409); // the HTTP spec permits caching 410s, but the RI doesn't. assertCached(true, 410); assertCached(false, 411); assertCached(false, 412); assertCached(false, 413); assertCached(true, 414); assertCached(false, 415); assertCached(false, 416); assertCached(false, 417); assertCached(false, 418); assertCached(false, 429); assertCached(false, 500); assertCached(true, 501); assertCached(false, 502); assertCached(false, 503); assertCached(false, 504); assertCached(false, 505); assertCached(false, 506); }); function assertCached(shouldPut, responseCode) { let expectedResponseCode = responseCode; const mockResponse = { headers: { 'last-modified': formatDate(-1, 3600), expires: formatDate(1, 3600), 'www-authenticate': 'challenge', }, status: responseCode, body: 'ABCDE', }; if (responseCode == 407) { mockResponse.headers['proxy-authenticate'] = 'Basic realm="protected area"'; } else if (responseCode == 401) { mockResponse.headers['www-authenticate'] = 'Basic realm="protected area"'; } else if (responseCode == 204 || responseCode == 205) { mockResponse.body = ''; // We forbid bodies for 204 and 205. } const request = { url: '/', headers: {} }; const cache = new CachePolicy(request, mockResponse, { shared: false }); assert.equal(shouldPut, cache.storable()); } it('default expiration date fully cached for less than24 hours', function() { // last modified: 105 seconds ago // served: 5 seconds ago // default lifetime: (105 - 5) / 10 = 10 seconds // expires: 10 seconds from served date = 5 seconds from now const cache = new CachePolicy( { headers: {} }, { headers: { 'last-modified': formatDate(-105, 1), date: formatDate(-5, 1), }, body: 'A', }, { shared: false } ); assert(cache.timeToLive() > 4000); }); it('default expiration date fully cached for more than24 hours', function() { // last modified: 105 days ago // served: 5 days ago // default lifetime: (105 - 5) / 10 = 10 days // expires: 10 days from served date = 5 days from now const cache = new CachePolicy( { headers: {} }, { headers: { 'last-modified': formatDate(-105, 3600 * 24), date: formatDate(-5, 3600 * 24), }, body: 'A', }, { shared: false } ); assert(cache.maxAge() >= 10 * 3600 * 24); assert(cache.timeToLive() + 1000 >= 5 * 3600 * 24); }); it('max age in the past with date header but no last modified header', function() { // Chrome interprets max-age relative to the local clock. Both our cache // and Firefox both use the earlier of the local and server's clock. const cache = new CachePolicy( { headers: {} }, { headers: { date: formatDate(-120, 1), 'cache-control': 'max-age=60', }, }, { shared: false } ); assert(!cache.stale()); }); it('maxAge timetolive', function() { const cache = new CachePolicy( { headers: {} }, { headers: { date: formatDate(120, 1), 'cache-control': 'max-age=60', }, }, { shared: false } ); const now = Date.now(); cache.now = () => now assert(!cache.stale()); assert.equal(cache.timeToLive(), 60000); }); it('stale-if-error timetolive', function() { const cache = new CachePolicy( { headers: {} }, { headers: { date: formatDate(120, 1), 'cache-control': 'max-age=60, stale-if-error=200', }, }, { shared: false } ); assert(!cache.stale()); assert.equal(cache.timeToLive(), 260000); }); it('stale-while-revalidate timetolive', function() { const cache = new CachePolicy( { headers: {} }, { headers: { date: formatDate(120, 1), 'cache-control': 'max-age=60, stale-while-revalidate=200', }, }, { shared: false } ); assert(!cache.stale()); assert.equal(cache.timeToLive(), 260000); }); it('max age preferred over lower shared max age', function() { const cache = new CachePolicy( { headers: {} }, { headers: { date: formatDate(-2, 60), 'cache-control': 's-maxage=60, max-age=180', }, }, { shared: false } ); assert.equal(cache.maxAge(), 180); }); it('max age preferred over higher max age', function() { const cache = new CachePolicy( { headers: {} }, { headers: { age: 360, 'cache-control': 's-maxage=60, max-age=180', }, }, { shared: false } ); assert(cache.stale()); }); it('request method options is not cached', function() { testRequestMethodNotCached('OPTIONS'); }); it('request method put is not cached', function() { testRequestMethodNotCached('PUT'); }); it('request method delete is not cached', function() { testRequestMethodNotCached('DELETE'); }); it('request method trace is not cached', function() { testRequestMethodNotCached('TRACE'); }); function testRequestMethodNotCached(method) { // 1. seed the cache (potentially) // 2. expect a cache hit or miss const cache = new CachePolicy( { method, headers: {} }, { headers: { expires: formatDate(1, 3600), }, }, { shared: false } ); assert(cache.stale()); } it('etag and expiration date in the future', function() { const cache = new CachePolicy( { headers: {} }, { headers: { etag: 'v1', 'last-modified': formatDate(-2, 3600), expires: formatDate(1, 3600), }, }, { shared: false } ); assert(cache.timeToLive() > 0); }); it('client side no store', function() { const cache = new CachePolicy( { headers: { 'cache-control': 'no-store', }, }, { headers: { 'cache-control': 'max-age=60', }, }, { shared: false } ); assert(!cache.storable()); }); it('request max age', function() { const cache = new CachePolicy( { headers: {} }, { headers: { 'last-modified': formatDate(-2, 3600), age: 60, expires: formatDate(1, 3600), }, }, { shared: false } ); assert(!cache.stale()); assert(cache.age() >= 60); assert( cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-age=90', }, }) ); assert( !cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-age=30', }, }) ); }); it('request min fresh', function() { const cache = new CachePolicy( { headers: {} }, { headers: { 'cache-control': 'max-age=60', }, }, { shared: false } ); assert(!cache.stale()); assert( !cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'min-fresh=120', }, }) ); assert( cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'min-fresh=10', }, }) ); }); it('request max stale', function() { const cache = new CachePolicy( { headers: {} }, { headers: { 'cache-control': 'max-age=120', age: 4*60, }, }, { shared: false } ); assert(cache.stale()); assert( cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-stale=180', }, }) ); assert( cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-stale', }, }) ); assert( !cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-stale=10', }, }) ); }); it('request max stale not honored with must revalidate', function() { const cache = new CachePolicy( { headers: {} }, { headers: { 'cache-control': 'max-age=120, must-revalidate', age: 360, }, }, { shared: false } ); assert(cache.stale()); assert( !cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-stale=180', }, }) ); assert( !cache.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'max-stale', }, }) ); }); it('get headers deletes cached100 level warnings', function() { const cache = new CachePolicy( { headers: {} }, { headers: { warning: '199 test danger, 200 ok ok', }, } ); assert.equal('200 ok ok', cache.responseHeaders().warning); }); it('do not cache partial response', function() { const cache = new CachePolicy( { headers: {} }, { status: 206, headers: { 'content-range': 'bytes 100-100/200', 'cache-control': 'max-age=60', }, } ); assert(!cache.storable()); }); function formatDate(delta, unit) { return new Date(Date.now() + delta * unit * 1000).toUTCString(); } }); http-cache-semantics-4.1.0/test/requesttest.js000066400000000000000000000053261362704537300214450ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); const publicCacheableResponse = { headers: { 'cache-control': 'public, max-age=222' }, }; const cacheableResponse = { headers: { 'cache-control': 'max-age=111' } }; describe('Request properties', function() { it('No store kills cache', function() { const cache = new CachePolicy( { method: 'GET', headers: { 'cache-control': 'no-store' } }, publicCacheableResponse ); assert(cache.stale()); assert(!cache.storable()); }); it('POST not cacheable by default', function() { const cache = new CachePolicy( { method: 'POST', headers: {} }, { headers: { 'cache-control': 'public' } } ); assert(cache.stale()); assert(!cache.storable()); }); it('POST cacheable explicitly', function() { const cache = new CachePolicy( { method: 'POST', headers: {} }, publicCacheableResponse ); assert(!cache.stale()); assert(cache.storable()); }); it('Public cacheable auth is OK', function() { const cache = new CachePolicy( { method: 'GET', headers: { authorization: 'test' } }, publicCacheableResponse ); assert(!cache.stale()); assert(cache.storable()); }); it('Proxy cacheable auth is OK', function() { const cache = new CachePolicy( { method: 'GET', headers: { authorization: 'test' } }, { headers: { 'cache-control': 'max-age=0,s-maxage=12' } } ); assert(!cache.stale()); assert(cache.storable()); const cache2 = CachePolicy.fromObject( JSON.parse(JSON.stringify(cache.toObject())) ); assert(cache2 instanceof CachePolicy); assert(!cache2.stale()); assert(cache2.storable()); }); it('Private auth is OK', function() { const cache = new CachePolicy( { method: 'GET', headers: { authorization: 'test' } }, cacheableResponse, { shared: false } ); assert(!cache.stale()); assert(cache.storable()); }); it('Revalidated auth is OK', function() { const cache = new CachePolicy( { headers: { authorization: 'test' } }, { headers: { 'cache-control': 'max-age=88,must-revalidate' } } ); assert(cache.storable()); }); it('Auth prevents caching by default', function() { const cache = new CachePolicy( { method: 'GET', headers: { authorization: 'test' } }, cacheableResponse ); assert(cache.stale()); assert(!cache.storable()); }); }); http-cache-semantics-4.1.0/test/responsetest.js000066400000000000000000000361531362704537300216150ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); const req = { method: 'GET', headers: {} }; describe('Response headers', function() { it('simple miss', function() { const cache = new CachePolicy(req, { headers: {} }); assert(cache.stale()); }); it('simple hit', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'public, max-age=999999' }, }); assert(!cache.stale()); assert.equal(cache.maxAge(), 999999); }); it('weird syntax', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': ',,,,max-age = 456 ,' }, }); assert(!cache.stale()); assert.equal(cache.maxAge(), 456); const cache2 = CachePolicy.fromObject( JSON.parse(JSON.stringify(cache.toObject())) ); assert(cache2 instanceof CachePolicy); assert(!cache2.stale()); assert.equal(cache2.maxAge(), 456); }); it('quoted syntax', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': ' max-age = "678" ' }, }); assert(!cache.stale()); assert.equal(cache.maxAge(), 678); }); it('IIS', function() { const cache = new CachePolicy( req, { headers: { 'cache-control': 'private, public, max-age=259200' } }, { shared: false } ); assert(!cache.stale()); assert.equal(cache.maxAge(), 259200); }); it('pre-check tolerated', function() { const cc = 'pre-check=0, post-check=0, no-store, no-cache, max-age=100'; const cache = new CachePolicy(req, { headers: { 'cache-control': cc }, }); assert(cache.stale()); assert(!cache.storable()); assert.equal(cache.maxAge(), 0); assert.equal(cache.responseHeaders()['cache-control'], cc); }); it('pre-check poison', function() { const origCC = 'pre-check=0, post-check=0, no-cache, no-store, max-age=100, custom, foo=bar'; const res = { headers: { 'cache-control': origCC, pragma: 'no-cache' }, }; const cache = new CachePolicy(req, res, { ignoreCargoCult: true }); assert(!cache.stale()); assert(cache.storable()); assert.equal(cache.maxAge(), 100); const cc = cache.responseHeaders()['cache-control']; assert(!/pre-check/.test(cc), cc); assert(!/post-check/.test(cc), cc); assert(!/no-store/.test(cc), cc); assert(/max-age=100/.test(cc)); assert(/custom(,|$)/.test(cc)); assert(/foo=bar/.test(cc)); assert.equal(res.headers['cache-control'], origCC); assert(res.headers['pragma']); assert(!cache.responseHeaders()['pragma']); }); it('pre-check poison undefined header', function() { const origCC = 'pre-check=0, post-check=0, no-cache, no-store'; const res = { headers: { 'cache-control': origCC, expires: 'yesterday!' }, }; const cache = new CachePolicy(req, res, { ignoreCargoCult: true }); assert(cache.stale()); assert(cache.storable()); assert.equal(cache.maxAge(), 0); const cc = cache.responseHeaders()['cache-control']; assert(!cc); assert(res.headers['expires']); assert(!cache.responseHeaders()['expires']); }); it('cache with expires', function() { const now = Date.now(); const cache = new CachePolicy(req, { headers: { date: new Date(now).toGMTString(), expires: new Date(now + 2000).toGMTString(), }, }); assert(!cache.stale()); assert.equal(2, cache.maxAge()); }); it('cache with expires relative to date', function() { const now = Date.now(); const cache = new CachePolicy(req, { headers: { date: new Date(now - 3000).toGMTString(), expires: new Date(now).toGMTString(), }, }); assert.equal(3, cache.maxAge()); }); it('cache with expires always relative to date', function() { const now = Date.now(); const cache = new CachePolicy( req, { headers: { date: new Date(now - 3000).toGMTString(), expires: new Date(now).toGMTString(), }, }, { trustServerDate: false } ); assert.equal(3, cache.maxAge()); }); it('cache expires no date', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'public', expires: new Date(Date.now() + 3600 * 1000).toGMTString(), }, }); assert(!cache.stale()); assert(cache.maxAge() > 3595); assert(cache.maxAge() < 3605); }); it('Ages', function() { let now = 1000; class TimeTravellingPolicy extends CachePolicy { now() { return now; } } const cache = new TimeTravellingPolicy(req, { headers: { 'cache-control': 'max-age=100', age: '50', }, }); assert(cache.storable()); assert.equal(50 * 1000, cache.timeToLive()); assert(!cache.stale()); now += 48 * 1000; assert.equal(2 * 1000, cache.timeToLive()); assert(!cache.stale()); now += 5 * 1000; assert(cache.stale()); assert.equal(0, cache.timeToLive()); }); it('Age can make stale', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'max-age=100', age: '101', }, }); assert(cache.stale()); assert(cache.storable()); }); it('Age not always stale', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'max-age=20', age: '15', }, }); assert(!cache.stale()); assert(cache.storable()); }); it('Bogus age ignored', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'max-age=20', age: 'golden', }, }); assert(!cache.stale()); assert(cache.storable()); }); it('cache old files', function() { const cache = new CachePolicy(req, { headers: { date: new Date().toGMTString(), 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', }, }); assert(!cache.stale()); assert(cache.maxAge() > 100); }); it('immutable simple hit', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'immutable, max-age=999999' }, }); assert(!cache.stale()); assert.equal(cache.maxAge(), 999999); }); it('immutable can expire', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'immutable, max-age=0' }, }); assert(cache.stale()); assert.equal(cache.maxAge(), 0); }); it('cache immutable files', function() { const cache = new CachePolicy(req, { headers: { date: new Date().toGMTString(), 'cache-control': 'immutable', 'last-modified': new Date().toGMTString(), }, }); assert(!cache.stale()); assert(cache.maxAge() > 100); }); it('immutable can be off', function() { const cache = new CachePolicy( req, { headers: { date: new Date().toGMTString(), 'cache-control': 'immutable', 'last-modified': new Date().toGMTString(), }, }, { immutableMinTimeToLive: 0 } ); assert(cache.stale()); assert.equal(cache.maxAge(), 0); }); it('pragma: no-cache', function() { const cache = new CachePolicy(req, { headers: { pragma: 'no-cache', 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', }, }); assert(cache.stale()); }); it('blank cache-control and pragma: no-cache', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': '', pragma: 'no-cache', 'last-modified': new Date(Date.now() - 10000).toGMTString(), }, }); assert(cache.maxAge() > 0); assert(!cache.stale()); }); it('no-store', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'no-store, public, max-age=1', }, }); assert(cache.stale()); assert.equal(0, cache.maxAge()); }); it('observe private cache', function() { const privateHeader = { 'cache-control': 'private, max-age=1234', }; const proxyCache = new CachePolicy(req, { headers: privateHeader }); assert(proxyCache.stale()); assert.equal(0, proxyCache.maxAge()); const uaCache = new CachePolicy( req, { headers: privateHeader }, { shared: false } ); assert(!uaCache.stale()); assert.equal(1234, uaCache.maxAge()); }); it("don't share cookies", function() { const cookieHeader = { 'set-cookie': 'foo=bar', 'cache-control': 'max-age=99', }; const proxyCache = new CachePolicy( req, { headers: cookieHeader }, { shared: true } ); assert(proxyCache.stale()); assert.equal(0, proxyCache.maxAge()); const uaCache = new CachePolicy( req, { headers: cookieHeader }, { shared: false } ); assert(!uaCache.stale()); assert.equal(99, uaCache.maxAge()); }); it('do share cookies if immutable', function() { const cookieHeader = { 'set-cookie': 'foo=bar', 'cache-control': 'immutable, max-age=99', }; const proxyCache = new CachePolicy( req, { headers: cookieHeader }, { shared: true } ); assert(!proxyCache.stale()); assert.equal(99, proxyCache.maxAge()); }); it('cache explicitly public cookie', function() { const cookieHeader = { 'set-cookie': 'foo=bar', 'cache-control': 'max-age=5, public', }; const proxyCache = new CachePolicy( req, { headers: cookieHeader }, { shared: true } ); assert(!proxyCache.stale()); assert.equal(5, proxyCache.maxAge()); }); it('miss max-age=0', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'public, max-age=0', }, }); assert(cache.stale()); assert.equal(0, cache.maxAge()); }); it('uncacheable 503', function() { const cache = new CachePolicy(req, { status: 503, headers: { 'cache-control': 'public, max-age=1000', }, }); assert(cache.stale()); assert.equal(0, cache.maxAge()); }); it('cacheable 301', function() { const cache = new CachePolicy(req, { status: 301, headers: { 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', }, }); assert(!cache.stale()); }); it('uncacheable 303', function() { const cache = new CachePolicy(req, { status: 303, headers: { 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', }, }); assert(cache.stale()); assert.equal(0, cache.maxAge()); }); it('cacheable 303', function() { const cache = new CachePolicy(req, { status: 303, headers: { 'cache-control': 'max-age=1000', }, }); assert(!cache.stale()); }); it('uncacheable 412', function() { const cache = new CachePolicy(req, { status: 412, headers: { 'cache-control': 'public, max-age=1000', }, }); assert(cache.stale()); assert.equal(0, cache.maxAge()); }); it('expired expires cached with max-age', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'public, max-age=9999', expires: 'Sat, 07 May 2016 15:35:18 GMT', }, }); assert(!cache.stale()); assert.equal(9999, cache.maxAge()); }); it('expired expires cached with s-maxage', function() { const sMaxAgeHeaders = { 'cache-control': 'public, s-maxage=9999', expires: 'Sat, 07 May 2016 15:35:18 GMT', }; const proxyCache = new CachePolicy(req, { headers: sMaxAgeHeaders }); assert(!proxyCache.stale()); assert.equal(9999, proxyCache.maxAge()); const uaCache = new CachePolicy( req, { headers: sMaxAgeHeaders }, { shared: false } ); assert(uaCache.stale()); assert.equal(0, uaCache.maxAge()); }); it('max-age wins over future expires', function() { const cache = new CachePolicy(req, { headers: { 'cache-control': 'public, max-age=333', expires: new Date(Date.now() + 3600 * 1000).toGMTString(), }, }); assert(!cache.stale()); assert.equal(333, cache.maxAge()); }); it('remove hop headers', function() { let now = 10000; class TimeTravellingPolicy extends CachePolicy { now() { return now; } } const res = { headers: { te: 'deflate', date: 'now', custom: 'header', oompa: 'lumpa', connection: 'close, oompa, header', age: '10', 'cache-control': 'public, max-age=333', }, }; const cache = new TimeTravellingPolicy(req, res); now += 1005; const h = cache.responseHeaders(); assert(!h.connection); assert(!h.te); assert(!h.oompa); assert.equal(h['cache-control'], 'public, max-age=333'); assert.notEqual(h.date, 'now', 'updated age requires updated date'); assert.equal(h.custom, 'header'); assert.equal(h.age, '11'); assert.equal(res.headers.age, '10'); const cache2 = TimeTravellingPolicy.fromObject( JSON.parse(JSON.stringify(cache.toObject())) ); assert(cache2 instanceof TimeTravellingPolicy); const h2 = cache2.responseHeaders(); assert.deepEqual(h, h2); }); }); http-cache-semantics-4.1.0/test/revalidatetest.js000066400000000000000000000204371362704537300220750ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); const simpleRequest = { method: 'GET', headers: { host: 'www.w3c.org', connection: 'close', 'x-custom': 'yes', }, url: '/Protocols/rfc2616/rfc2616-sec14.html', }; function simpleRequestBut(overrides) { return Object.assign({}, simpleRequest, overrides); } const cacheableResponse = { headers: { 'cache-control': 'max-age=111' } }; const etaggedResponse = { headers: Object.assign({ etag: '"123456789"' }, cacheableResponse.headers), }; const lastModifiedResponse = { headers: Object.assign( { 'last-modified': 'Tue, 15 Nov 1994 12:45:26 GMT' }, cacheableResponse.headers ), }; const multiValidatorResponse = { headers: Object.assign( {}, etaggedResponse.headers, lastModifiedResponse.headers ), }; const alwaysVariableResponse = { headers: Object.assign({ vary: '*' }, cacheableResponse.headers), }; function assertHeadersPassed(headers) { assert.strictEqual(headers.connection, undefined); assert.strictEqual(headers['x-custom'], 'yes'); } function assertNoValidators(headers) { assert.strictEqual(headers['if-none-match'], undefined); assert.strictEqual(headers['if-modified-since'], undefined); } describe('Can be revalidated?', function() { it('ok if method changes to HEAD', function() { const cache = new CachePolicy(simpleRequest, etaggedResponse); const headers = cache.revalidationHeaders( simpleRequestBut({ method: 'HEAD' }) ); assertHeadersPassed(headers); assert.equal(headers['if-none-match'], '"123456789"'); }); it('not if method mismatch (other than HEAD)', function() { const cache = new CachePolicy(simpleRequest, etaggedResponse); const incomingRequest = simpleRequestBut({ method: 'POST' }); const headers = cache.revalidationHeaders(incomingRequest); assertHeadersPassed(headers); assertNoValidators(headers); }); it('not if url mismatch', function() { const cache = new CachePolicy(simpleRequest, etaggedResponse); const incomingRequest = simpleRequestBut({ url: '/yomomma' }); const headers = cache.revalidationHeaders(incomingRequest); assertHeadersPassed(headers); assertNoValidators(headers); }); it('not if host mismatch', function() { const cache = new CachePolicy(simpleRequest, etaggedResponse); const incomingRequest = simpleRequestBut({ headers: { host: 'www.w4c.org' }, }); const headers = cache.revalidationHeaders(incomingRequest); assertNoValidators(headers); assert.strictEqual(headers['x-custom'], undefined); }); it('not if vary fields prevent', function() { const cache = new CachePolicy(simpleRequest, alwaysVariableResponse); const headers = cache.revalidationHeaders(simpleRequest); assertHeadersPassed(headers); assertNoValidators(headers); }); it('when entity tag validator is present', function() { const cache = new CachePolicy(simpleRequest, etaggedResponse); const headers = cache.revalidationHeaders(simpleRequest); assertHeadersPassed(headers); assert.equal(headers['if-none-match'], '"123456789"'); }); it('skips weak validators on post', function() { const postReq = simpleRequestBut({ method: 'POST', headers: { 'if-none-match': 'W/"weak", "strong", W/"weak2"' }, }); const cache = new CachePolicy(postReq, multiValidatorResponse); const headers = cache.revalidationHeaders(postReq); assert.equal(headers['if-none-match'], '"strong", "123456789"'); assert.strictEqual(undefined, headers['if-modified-since']); }); it('skips weak validators on post 2', function() { const postReq = simpleRequestBut({ method: 'POST', headers: { 'if-none-match': 'W/"weak"' }, }); const cache = new CachePolicy(postReq, lastModifiedResponse); const headers = cache.revalidationHeaders(postReq); assert.strictEqual(undefined, headers['if-none-match']); assert.strictEqual(undefined, headers['if-modified-since']); }); it('merges validators', function() { const postReq = simpleRequestBut({ headers: { 'if-none-match': 'W/"weak", "strong", W/"weak2"' }, }); const cache = new CachePolicy(postReq, multiValidatorResponse); const headers = cache.revalidationHeaders(postReq); assert.equal( headers['if-none-match'], 'W/"weak", "strong", W/"weak2", "123456789"' ); assert.equal( 'Tue, 15 Nov 1994 12:45:26 GMT', headers['if-modified-since'] ); }); it('when last-modified validator is present', function() { const cache = new CachePolicy(simpleRequest, lastModifiedResponse); const headers = cache.revalidationHeaders(simpleRequest); assertHeadersPassed(headers); assert.equal( headers['if-modified-since'], 'Tue, 15 Nov 1994 12:45:26 GMT' ); assert(!/113/.test(headers.warning)); }); it('not without validators', function() { const cache = new CachePolicy(simpleRequest, cacheableResponse); const headers = cache.revalidationHeaders(simpleRequest); assertHeadersPassed(headers); assertNoValidators(headers); assert(!/113/.test(headers.warning)); }); it('113 added', function() { const veryOldResponse = { headers: { age: 3600 * 72, 'last-modified': 'Tue, 15 Nov 1994 12:45:26 GMT', }, }; const cache = new CachePolicy(simpleRequest, veryOldResponse); const headers = cache.responseHeaders(simpleRequest); assert(/113/.test(headers.warning)); }); }); describe('Validation request', function() { it('removes warnings', function() { const cache = new CachePolicy( { headers: {} }, { headers: { warning: '199 test danger', }, } ); assert.strictEqual(undefined, cache.responseHeaders().warning); }); it('must contain any etag', function() { const cache = new CachePolicy(simpleRequest, multiValidatorResponse); const expected = multiValidatorResponse.headers.etag; const actual = cache.revalidationHeaders(simpleRequest)[ 'if-none-match' ]; assert.equal(actual, expected); }); it('merges etags', function() { const cache = new CachePolicy(simpleRequest, etaggedResponse); const expected = `"foo", "bar", ${etaggedResponse.headers.etag}`; const headers = cache.revalidationHeaders( simpleRequestBut({ headers: { host: 'www.w3c.org', 'if-none-match': '"foo", "bar"', }, }) ); assert.equal(headers['if-none-match'], expected); }); it('should send the Last-Modified value', function() { const cache = new CachePolicy(simpleRequest, multiValidatorResponse); const expected = multiValidatorResponse.headers['last-modified']; const actual = cache.revalidationHeaders(simpleRequest)[ 'if-modified-since' ]; assert.equal(actual, expected); }); it('should not send the Last-Modified value for POST', function() { const postReq = { method: 'POST', headers: { 'if-modified-since': 'yesterday' }, }; const cache = new CachePolicy(postReq, lastModifiedResponse); const actual = cache.revalidationHeaders(postReq)['if-modified-since']; assert.equal(actual, undefined); }); it('should not send the Last-Modified value for range requests', function() { const rangeReq = { method: 'GET', headers: { 'accept-ranges': '1-3', 'if-modified-since': 'yesterday', }, }; const cache = new CachePolicy(rangeReq, lastModifiedResponse); const actual = cache.revalidationHeaders(rangeReq)['if-modified-since']; assert.equal(actual, undefined); }); }); http-cache-semantics-4.1.0/test/satisfytest.js000066400000000000000000000102711362704537300214320ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); describe('Satisfies', function() { it('when URLs match', function() { const policy = new CachePolicy( { url: '/', headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert(policy.satisfiesWithoutRevalidation({ url: '/', headers: {} })); }); it('when expires is present', function() { const policy = new CachePolicy( { headers: {} }, { status: 302, headers: { expires: new Date(Date.now() + 2000).toGMTString() }, } ); assert(policy.satisfiesWithoutRevalidation({ headers: {} })); }); it('not when URLs mismatch', function() { const policy = new CachePolicy( { url: '/foo', headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert( !policy.satisfiesWithoutRevalidation({ url: '/foo?bar', headers: {}, }) ); }); it('when methods match', function() { const policy = new CachePolicy( { method: 'GET', headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert( policy.satisfiesWithoutRevalidation({ method: 'GET', headers: {} }) ); }); it('not when hosts mismatch', function() { const policy = new CachePolicy( { headers: { host: 'foo' } }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert( policy.satisfiesWithoutRevalidation({ headers: { host: 'foo' } }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { host: 'foofoo' }, }) ); }); it('when methods match HEAD', function() { const policy = new CachePolicy( { method: 'HEAD', headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert( policy.satisfiesWithoutRevalidation({ method: 'HEAD', headers: {} }) ); }); it('not when methods mismatch', function() { const policy = new CachePolicy( { method: 'POST', headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert( !policy.satisfiesWithoutRevalidation({ method: 'GET', headers: {} }) ); }); it('not when methods mismatch HEAD', function() { const policy = new CachePolicy( { method: 'HEAD', headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2' } } ); assert( !policy.satisfiesWithoutRevalidation({ method: 'GET', headers: {} }) ); }); it('not when proxy revalidating', function() { const policy = new CachePolicy( { headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2, proxy-revalidate ' }, } ); assert(!policy.satisfiesWithoutRevalidation({ headers: {} })); }); it('when not a proxy revalidating', function() { const policy = new CachePolicy( { headers: {} }, { status: 200, headers: { 'cache-control': 'max-age=2, proxy-revalidate ' }, }, { shared: false } ); assert(policy.satisfiesWithoutRevalidation({ headers: {} })); }); it('not when no-cache requesting', function() { const policy = new CachePolicy( { headers: {} }, { headers: { 'cache-control': 'max-age=2' } } ); assert( policy.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'fine' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { 'cache-control': 'no-cache' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { pragma: 'no-cache' }, }) ); }); }); http-cache-semantics-4.1.0/test/updatetest.js000066400000000000000000000174161362704537300212420ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); const simpleRequest = { method: 'GET', headers: { host: 'www.w3c.org', connection: 'close', }, url: '/Protocols/rfc2616/rfc2616-sec14.html', }; function withHeaders(request, headers) { return Object.assign({}, request, { headers: Object.assign({}, request.headers, headers), }); } const cacheableResponse = { headers: { 'cache-control': 'max-age=111' } }; const etaggedResponse = { headers: Object.assign({ etag: '"123456789"' }, cacheableResponse.headers), }; const weakTaggedResponse = { headers: Object.assign( { etag: 'W/"123456789"' }, cacheableResponse.headers ), }; const lastModifiedResponse = { headers: Object.assign( { 'last-modified': 'Tue, 15 Nov 1994 12:45:26 GMT' }, cacheableResponse.headers ), }; const multiValidatorResponse = { headers: Object.assign( {}, etaggedResponse.headers, lastModifiedResponse.headers ), }; function notModifiedResponseHeaders( firstRequest, firstResponse, secondRequest, secondResponse ) { const cache = new CachePolicy(firstRequest, firstResponse); const headers = cache.revalidationHeaders(secondRequest); const { policy: newCache, modified } = cache.revalidatedPolicy( { headers }, secondResponse ); if (modified) { return false; } return newCache.responseHeaders(); } function assertUpdates( firstRequest, firstResponse, secondRequest, secondResponse ) { firstResponse = withHeaders(firstResponse, { foo: 'original', 'x-other': 'original' }); if (!firstResponse.status) { firstResponse.status = 200; } secondResponse = withHeaders(secondResponse, { foo: 'updated', 'x-ignore-new': 'ignoreme', }); if (!secondResponse.status) { secondResponse.status = 304; } const headers = notModifiedResponseHeaders( firstRequest, firstResponse, secondRequest, secondResponse ); assert(headers); assert.equal(headers['foo'], 'updated'); assert.equal(headers['x-other'], 'original'); assert.strictEqual(headers['x-ignore-new'], undefined); assert.strictEqual(headers['etag'], secondResponse.headers.etag); } describe('Update revalidated', function() { it('Matching etags are updated', function() { assertUpdates( simpleRequest, etaggedResponse, simpleRequest, etaggedResponse ); }); it('Matching weak etags are updated', function() { assertUpdates( simpleRequest, weakTaggedResponse, simpleRequest, weakTaggedResponse ); }); it('Matching lastmod are updated', function() { assertUpdates( simpleRequest, lastModifiedResponse, simpleRequest, lastModifiedResponse ); }); it('Both matching are updated', function() { assertUpdates( simpleRequest, multiValidatorResponse, simpleRequest, multiValidatorResponse ); }); it('Checks status', function() { const response304 = Object.assign({}, multiValidatorResponse, { status: 304, }); const response200 = Object.assign({}, multiValidatorResponse, { status: 200, }); assertUpdates( simpleRequest, multiValidatorResponse, simpleRequest, response304 ); assert( !notModifiedResponseHeaders( simpleRequest, multiValidatorResponse, simpleRequest, response200 ) ); }); it('Last-mod ignored if etag is wrong', function() { assert( !notModifiedResponseHeaders( simpleRequest, multiValidatorResponse, simpleRequest, withHeaders(multiValidatorResponse, { etag: 'bad' }) ) ); assert( !notModifiedResponseHeaders( simpleRequest, multiValidatorResponse, simpleRequest, withHeaders(multiValidatorResponse, { etag: 'W/bad' }) ) ); }); it('Ignored if validator is missing', function() { assert( !notModifiedResponseHeaders( simpleRequest, etaggedResponse, simpleRequest, cacheableResponse ) ); assert( !notModifiedResponseHeaders( simpleRequest, weakTaggedResponse, simpleRequest, cacheableResponse ) ); assert( !notModifiedResponseHeaders( simpleRequest, lastModifiedResponse, simpleRequest, cacheableResponse ) ); }); it('Skips update of content-length', function() { const etaggedResponseWithLenght1 = withHeaders(etaggedResponse, { 'content-length': 1, }); const etaggedResponseWithLenght2 = withHeaders(etaggedResponse, { 'content-length': 2, }); const headers = notModifiedResponseHeaders( simpleRequest, etaggedResponseWithLenght1, simpleRequest, etaggedResponseWithLenght2 ); assert.equal(1, headers['content-length']); }); it('Ignored if validator is different', function() { assert( !notModifiedResponseHeaders( simpleRequest, lastModifiedResponse, simpleRequest, etaggedResponse ) ); assert( !notModifiedResponseHeaders( simpleRequest, lastModifiedResponse, simpleRequest, weakTaggedResponse ) ); assert( !notModifiedResponseHeaders( simpleRequest, etaggedResponse, simpleRequest, lastModifiedResponse ) ); }); it("Ignored if validator doesn't match", function() { assert( !notModifiedResponseHeaders( simpleRequest, etaggedResponse, simpleRequest, withHeaders(etaggedResponse, { etag: '"other"' }) ), 'bad etag' ); assert( !notModifiedResponseHeaders( simpleRequest, lastModifiedResponse, simpleRequest, withHeaders(lastModifiedResponse, { 'last-modified': 'dunno' }) ), 'bad lastmod' ); }); it("staleIfError revalidate, no response", function() { const cacheableStaleResponse = { headers: { 'cache-control': 'max-age=200, stale-if-error=300' } }; const cache = new CachePolicy(simpleRequest, cacheableStaleResponse); const { policy, modified } = cache.revalidatedPolicy( simpleRequest, null ); assert(policy === cache); assert(modified === false); }); it("staleIfError revalidate, server error", function() { const cacheableStaleResponse = { headers: { 'cache-control': 'max-age=200, stale-if-error=300' } }; const cache = new CachePolicy(simpleRequest, cacheableStaleResponse); const { policy, modified } = cache.revalidatedPolicy( simpleRequest, { status: 500 } ); assert(policy === cache); assert(modified === false); }); }); http-cache-semantics-4.1.0/test/varytest.js000066400000000000000000000130021362704537300207240ustar00rootroot00000000000000'use strict'; const assert = require('assert'); const CachePolicy = require('..'); describe('Vary', function() { it('Basic', function() { const policy = new CachePolicy( { headers: { weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: 'weather' } } ); assert( policy.satisfiesWithoutRevalidation({ headers: { weather: 'nice' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { weather: 'bad' }, }) ); }); it("* doesn't match", function() { const policy = new CachePolicy( { headers: { weather: 'ok' } }, { headers: { 'cache-control': 'max-age=5', vary: '*' } } ); assert( !policy.satisfiesWithoutRevalidation({ headers: { weather: 'ok' } }) ); }); it('* is stale', function() { const policy1 = new CachePolicy( { headers: { weather: 'ok' } }, { headers: { 'cache-control': 'public,max-age=99', vary: '*' } } ); const policy2 = new CachePolicy( { headers: { weather: 'ok' } }, { headers: { 'cache-control': 'public,max-age=99', vary: 'weather', }, } ); assert(policy1.stale()); assert(!policy2.stale()); }); it('Values are case-sensitive', function() { const policy = new CachePolicy( { headers: { weather: 'BAD' } }, { headers: { 'cache-control': 'max-age=5', vary: 'Weather' } } ); assert( policy.satisfiesWithoutRevalidation({ headers: { weather: 'BAD' } }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { weather: 'bad' }, }) ); }); it('Irrelevant headers ignored', function() { const policy = new CachePolicy( { headers: { weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: 'moon-phase' } } ); assert( policy.satisfiesWithoutRevalidation({ headers: { weather: 'bad' } }) ); assert( policy.satisfiesWithoutRevalidation({ headers: { sun: 'shining' } }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { 'moon-phase': 'full' }, }) ); }); it('Absence is meaningful', function() { const policy = new CachePolicy( { headers: { weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: 'moon-phase, weather', }, } ); assert( policy.satisfiesWithoutRevalidation({ headers: { weather: 'nice' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { weather: 'nice', 'moon-phase': '' }, }) ); assert(!policy.satisfiesWithoutRevalidation({ headers: {} })); }); it('All values must match', function() { const policy = new CachePolicy( { headers: { sun: 'shining', weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: 'weather, sun' } } ); assert( policy.satisfiesWithoutRevalidation({ headers: { sun: 'shining', weather: 'nice' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { sun: 'shining', weather: 'bad' }, }) ); }); it('Whitespace is OK', function() { const policy = new CachePolicy( { headers: { sun: 'shining', weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: ' weather , sun ', }, } ); assert( policy.satisfiesWithoutRevalidation({ headers: { sun: 'shining', weather: 'nice' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { weather: 'nice' }, }) ); assert( !policy.satisfiesWithoutRevalidation({ headers: { sun: 'shining' }, }) ); }); it('Order is irrelevant', function() { const policy1 = new CachePolicy( { headers: { sun: 'shining', weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: 'weather, sun' } } ); const policy2 = new CachePolicy( { headers: { sun: 'shining', weather: 'nice' } }, { headers: { 'cache-control': 'max-age=5', vary: 'sun, weather' } } ); assert( policy1.satisfiesWithoutRevalidation({ headers: { weather: 'nice', sun: 'shining' }, }) ); assert( policy1.satisfiesWithoutRevalidation({ headers: { sun: 'shining', weather: 'nice' }, }) ); assert( policy2.satisfiesWithoutRevalidation({ headers: { weather: 'nice', sun: 'shining' }, }) ); assert( policy2.satisfiesWithoutRevalidation({ headers: { sun: 'shining', weather: 'nice' }, }) ); }); });