├── .eslintrc.json ├── .gitignore ├── .prettierrc.json ├── .travis.yml ├── LICENSE ├── README.md ├── fresh.jpg ├── index.js ├── package.json └── test ├── misctest.js ├── okhttptest.js ├── requesttest.js ├── responsetest.js ├── revalidatetest.js ├── satisfytest.js ├── updatetest.js └── varytest.js /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "es6": true, 5 | "mocha": true 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .nyc_output/ 3 | coverage/ 4 | node4/ 5 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "tabWidth": 4, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - '11' 5 | - '10' 6 | - '8' 7 | - '6' 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2016-2018 Kornel Lesiński 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 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. 8 | 9 | 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. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Can I cache this? 2 | 3 | This library tells when responses can be reused from a cache, taking into account [HTTP RFC 7234/9111](http://httpwg.org/specs/rfc9111.html) rules for user agents and shared caches. 4 | It also implements `stale-if-error` and `stale-while-revalidate` from [RFC 5861](https://tools.ietf.org/html/rfc5861). 5 | It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses. 6 | 7 | ## Basic Usage 8 | 9 | `CachePolicy` is a metadata object that is meant to be stored in the cache, and it will keep track of cacheability of the response. 10 | 11 | Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy. 12 | 13 | ```js 14 | const policy = new CachePolicy(request, response, options); 15 | 16 | if (!policy.storable()) { 17 | // throw the response away, it's not usable at all 18 | return; 19 | } 20 | 21 | // Cache the data AND the policy object in your cache 22 | // (this is pseudocode, roll your own cache (lru-cache package works)) 23 | letsPretendThisIsSomeCache.set( 24 | request.url, 25 | { policy, body: response.body }, // you only need to store the response body. CachePolicy holds the headers. 26 | policy.timeToLive() 27 | ); 28 | ``` 29 | 30 | ```js 31 | // And later, when you receive a new request: 32 | const { policy, body } = letsPretendThisIsSomeCache.get(newRequest.url); 33 | 34 | // It's not enough that it exists in the cache, it has to match the new request, too: 35 | if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { 36 | // OK, the previous response can be used to respond to the `newRequest`. 37 | // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. 38 | return { 39 | headers: policy.responseHeaders(), 40 | body, 41 | } 42 | } 43 | 44 | // Cache miss. See revalidationHeaders() and revalidatedPolicy() for advanced usage. 45 | ``` 46 | 47 | 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. 48 | 49 | The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met. 50 | 51 | ### Constructor options 52 | 53 | 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). 54 | 55 | ```js 56 | const request = { 57 | url: '/', 58 | method: 'GET', 59 | headers: { 60 | accept: '*/*', 61 | }, 62 | }; 63 | 64 | const response = { 65 | status: 200, 66 | headers: { 67 | 'cache-control': 'public, max-age=7234', 68 | }, 69 | }; 70 | 71 | const options = { 72 | shared: true, 73 | cacheHeuristic: 0.1, 74 | immutableMinTimeToLive: 24 * 3600 * 1000, // 24h 75 | ignoreCargoCult: false, 76 | }; 77 | ``` 78 | 79 | 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. 80 | 81 | `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. 82 | 83 | `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. 84 | 85 | 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. 86 | 87 | ### `storable()` 88 | 89 | 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. 90 | 91 | ### `satisfiesWithoutRevalidation(newRequest)` 92 | 93 | Use this method to check whether the cached response is still fresh in the context of the new request. 94 | 95 | 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()`. 96 | 97 | 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()`). 98 | 99 | ### `responseHeaders()` 100 | 101 | 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. 102 | 103 | ```js 104 | cachedResponse.headers = cachePolicy.responseHeaders(); 105 | ``` 106 | 107 | ### `timeToLive()` 108 | 109 | Suggests a time in _milliseconds_ for how long this cache entry may be useful. This is not freshness, so always check with `satisfiesWithoutRevalidation()`. This time may be longer than response's `max-age` to allow for `stale-if-error` and `stale-while-revalidate`. 110 | 111 | After that time (when `timeToLive() <= 0`) the response may still be usable in certain cases, e.g. if client can explicitly allows stale responses. 112 | 113 | ### `toObject()`/`fromObject(json)` 114 | 115 | 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. 116 | 117 | ## Complete Usage 118 | 119 | ### `evaluateRequest(newRequest)` 120 | 121 | Returns an object telling what to do next — optional `revalidation`, and optional `response` from cache. Either one of these properties will be present. Both may be present at the same time. 122 | 123 | ```js 124 | { 125 | // If defined, you must send a request to the server. 126 | revalidation: { 127 | headers: {}, // HTTP headers to use when sending the revalidation response 128 | // If true, you MUST wait for a response from the server before using the cache 129 | // If false, this is stale-while-revalidate. The cache is stale, but you can use it while you update it asynchronously. 130 | synchronous: bool, 131 | }, 132 | // If defined, you can use this cached response. 133 | response: { 134 | headers: {}, // Updated cached HTTP headers you must use when responding to the client 135 | }, 136 | } 137 | ``` 138 | 139 | ### Example 140 | 141 | ```js 142 | let cached = cacheStorage.get(incomingRequest.url); 143 | 144 | // Cache miss - make a request to the origin and cache it 145 | if (!cached) { 146 | const newResponse = await makeRequest(incomingRequest); 147 | const policy = new CachePolicy(incomingRequest, newResponse); 148 | 149 | cacheStorage.set( 150 | incomingRequest.url, 151 | { policy, body: newResponse.body }, 152 | policy.timeToLive() 153 | ); 154 | 155 | return { 156 | // use responseHeaders() to remove hop-by-hop headers that should not be passed through proxies 157 | headers: policy.responseHeaders(), 158 | body: newResponse.body, 159 | } 160 | } 161 | 162 | // There's something cached, see if it's a hit 163 | let { revalidation, response } = cached.policy.evaluateRequest(incomingRequest); 164 | 165 | // Revalidation always goes first 166 | if (revalidation) { 167 | // It's very important to update the request headers to make a correct revalidation request 168 | incomingRequest.headers = revalidation.headers; // Same as cached.policy.revalidationHeaders() 169 | 170 | // The cache may be updated immediately or in the background, 171 | // so use a Promise to optionally defer the update 172 | const updatedResponsePromise = makeRequest(incomingRequest).then(() => { 173 | // Refresh the old response with the new information, if applicable 174 | const { policy, modified } = cached.policy.revalidatedPolicy(incomingRequest, newResponse); 175 | 176 | const body = modified ? newResponse.body : cached.body; 177 | 178 | // Update the cache with the newer response 179 | if (policy.storable()) { 180 | cacheStorage.set( 181 | incomingRequest.url, 182 | { policy, body }, 183 | policy.timeToLive() 184 | ); 185 | } 186 | 187 | return { 188 | headers: policy.responseHeaders(), // these are from the new revalidated policy 189 | body, 190 | } 191 | }); 192 | 193 | if (revalidation.synchronous) { 194 | // If synchronous, then you MUST get a reply from the server first 195 | return await updatedResponsePromise; 196 | } 197 | 198 | // If not synchronous, it can fall thru to returning the cached response, 199 | // while the request to the server is happening in the background. 200 | } 201 | 202 | return { 203 | headers: response.headers, // Same as cached.policy.responseHeaders() 204 | body: cached.body, 205 | } 206 | ``` 207 | 208 | ### Refreshing stale cache (revalidation) 209 | 210 | 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. 211 | 212 | The following methods help perform the update efficiently and correctly. 213 | 214 | #### `revalidationHeaders(newRequest)` 215 | 216 | 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. 217 | 218 | Use this method when updating cache from the origin server. Also available in `evaluateRequest(newRequest).revalidation.headers`. 219 | 220 | ```js 221 | updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); 222 | ``` 223 | 224 | #### `revalidatedPolicy(revalidationRequest, revalidationResponse)` 225 | 226 | Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys: 227 | 228 | - `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one. 229 | - `modified` — Boolean indicating whether the response body has changed, and you should use the new response body sent by the server. 230 | - If `true`, you should use the new response body, and you can replace the old cached response with the updated one. 231 | - If `false`, then you should reuse the old cached response body. Either a valid 304 Not Modified response has been received, or an error happened and `stale-if-error` allows falling back to the cache. 232 | 233 | # Yo, FRESH 234 | 235 | ![satisfiesWithoutRevalidation](fresh.jpg) 236 | 237 | ## Used by 238 | 239 | - [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) 240 | - [Rust version of this library](https://lib.rs/crates/http-cache-semantics). 241 | 242 | ## Implemented 243 | 244 | - `Cache-Control` response header with all the quirks. 245 | - `Expires` with check for bad clocks. 246 | - `Pragma` response header. 247 | - `Age` response header. 248 | - `Vary` response header. 249 | - Default cacheability of statuses and methods. 250 | - Requests for stale data. 251 | - Filtering of hop-by-hop headers. 252 | - Basic revalidation request 253 | - `stale-if-error` 254 | - `stale-while-revalidate` 255 | 256 | ## Unimplemented 257 | 258 | - Merging of range requests, `If-Range` (but correctly supports them as non-cacheable) 259 | - Revalidation of multiple representations 260 | 261 | ### Trusting server `Date` 262 | 263 | 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: 264 | 265 | * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong). 266 | * 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). 267 | 268 | 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). 269 | -------------------------------------------------------------------------------- /fresh.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kornelski/http-cache-semantics/f01112e954b83cfa8765b633ba880e5e980aa54c/fresh.jpg -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @typedef {Object} HttpRequest 5 | * @property {Record} headers - Request headers 6 | * @property {string} [method] - HTTP method 7 | * @property {string} [url] - Request URL 8 | */ 9 | 10 | /** 11 | * @typedef {Object} HttpResponse 12 | * @property {Record} headers - Response headers 13 | * @property {number} [status] - HTTP status code 14 | */ 15 | 16 | /** 17 | * Set of default cacheable status codes per RFC 7231 section 6.1. 18 | * @type {Set} 19 | */ 20 | const statusCodeCacheableByDefault = new Set([ 21 | 200, 22 | 203, 23 | 204, 24 | 206, 25 | 300, 26 | 301, 27 | 308, 28 | 404, 29 | 405, 30 | 410, 31 | 414, 32 | 501, 33 | ]); 34 | 35 | /** 36 | * Set of HTTP status codes that the cache implementation understands. 37 | * Note: This implementation does not understand partial responses (206). 38 | * @type {Set} 39 | */ 40 | const understoodStatuses = new Set([ 41 | 200, 42 | 203, 43 | 204, 44 | 300, 45 | 301, 46 | 302, 47 | 303, 48 | 307, 49 | 308, 50 | 404, 51 | 405, 52 | 410, 53 | 414, 54 | 501, 55 | ]); 56 | 57 | /** 58 | * Set of HTTP error status codes. 59 | * @type {Set} 60 | */ 61 | const errorStatusCodes = new Set([ 62 | 500, 63 | 502, 64 | 503, 65 | 504, 66 | ]); 67 | 68 | /** 69 | * Object representing hop-by-hop headers that should be removed. 70 | * @type {Record} 71 | */ 72 | const hopByHopHeaders = { 73 | date: true, // included, because we add Age update Date 74 | connection: true, 75 | 'keep-alive': true, 76 | 'proxy-authenticate': true, 77 | 'proxy-authorization': true, 78 | te: true, 79 | trailer: true, 80 | 'transfer-encoding': true, 81 | upgrade: true, 82 | }; 83 | 84 | /** 85 | * Headers that are excluded from revalidation update. 86 | * @type {Record} 87 | */ 88 | const excludedFromRevalidationUpdate = { 89 | // Since the old body is reused, it doesn't make sense to change properties of the body 90 | 'content-length': true, 91 | 'content-encoding': true, 92 | 'transfer-encoding': true, 93 | 'content-range': true, 94 | }; 95 | 96 | /** 97 | * Converts a string to a number or returns zero if the conversion fails. 98 | * @param {string} s - The string to convert. 99 | * @returns {number} The parsed number or 0. 100 | */ 101 | function toNumberOrZero(s) { 102 | const n = parseInt(s, 10); 103 | return isFinite(n) ? n : 0; 104 | } 105 | 106 | /** 107 | * Determines if the given response is an error response. 108 | * Implements RFC 5861 behavior. 109 | * @param {HttpResponse|undefined} response - The HTTP response object. 110 | * @returns {boolean} true if the response is an error or undefined, false otherwise. 111 | */ 112 | function isErrorResponse(response) { 113 | // consider undefined response as faulty 114 | if (!response) { 115 | return true; 116 | } 117 | return errorStatusCodes.has(response.status); 118 | } 119 | 120 | /** 121 | * Parses a Cache-Control header string into an object. 122 | * @param {string} [header] - The Cache-Control header value. 123 | * @returns {Record} An object representing Cache-Control directives. 124 | */ 125 | function parseCacheControl(header) { 126 | /** @type {Record} */ 127 | const cc = {}; 128 | if (!header) return cc; 129 | 130 | // 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), 131 | // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale 132 | const parts = header.trim().split(/,/); 133 | for (const part of parts) { 134 | const [k, v] = part.split(/=/, 2); 135 | cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); 136 | } 137 | 138 | return cc; 139 | } 140 | 141 | /** 142 | * Formats a Cache-Control directives object into a header string. 143 | * @param {Record} cc - The Cache-Control directives. 144 | * @returns {string|undefined} A formatted Cache-Control header string or undefined if empty. 145 | */ 146 | function formatCacheControl(cc) { 147 | let parts = []; 148 | for (const k in cc) { 149 | const v = cc[k]; 150 | parts.push(v === true ? k : k + '=' + v); 151 | } 152 | if (!parts.length) { 153 | return undefined; 154 | } 155 | return parts.join(', '); 156 | } 157 | 158 | module.exports = class CachePolicy { 159 | /** 160 | * Creates a new CachePolicy instance. 161 | * @param {HttpRequest} req - Incoming client request. 162 | * @param {HttpResponse} res - Received server response. 163 | * @param {Object} [options={}] - Configuration options. 164 | * @param {boolean} [options.shared=true] - Is the cache shared (a public proxy)? `false` for personal browser caches. 165 | * @param {number} [options.cacheHeuristic=0.1] - Fallback heuristic (age fraction) for cache duration. 166 | * @param {number} [options.immutableMinTimeToLive=86400000] - Minimum TTL for immutable responses in milliseconds. 167 | * @param {boolean} [options.ignoreCargoCult=false] - Detect nonsense cache headers, and override them. 168 | * @param {any} [options._fromObject] - Internal parameter for deserialization. Do not use. 169 | */ 170 | constructor( 171 | req, 172 | res, 173 | { 174 | shared, 175 | cacheHeuristic, 176 | immutableMinTimeToLive, 177 | ignoreCargoCult, 178 | _fromObject, 179 | } = {} 180 | ) { 181 | if (_fromObject) { 182 | this._fromObject(_fromObject); 183 | return; 184 | } 185 | 186 | if (!res || !res.headers) { 187 | throw Error('Response headers missing'); 188 | } 189 | this._assertRequestHasHeaders(req); 190 | 191 | /** @type {number} Timestamp when the response was received */ 192 | this._responseTime = this.now(); 193 | /** @type {boolean} Indicates if the cache is shared */ 194 | this._isShared = shared !== false; 195 | /** @type {boolean} Indicates if legacy cargo cult directives should be ignored */ 196 | this._ignoreCargoCult = !!ignoreCargoCult; 197 | /** @type {number} Heuristic cache fraction */ 198 | this._cacheHeuristic = 199 | undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE 200 | /** @type {number} Minimum TTL for immutable responses in ms */ 201 | this._immutableMinTtl = 202 | undefined !== immutableMinTimeToLive 203 | ? immutableMinTimeToLive 204 | : 24 * 3600 * 1000; 205 | 206 | /** @type {number} HTTP status code */ 207 | this._status = 'status' in res ? res.status : 200; 208 | /** @type {Record} Response headers */ 209 | this._resHeaders = res.headers; 210 | /** @type {Record} Parsed Cache-Control directives from response */ 211 | this._rescc = parseCacheControl(res.headers['cache-control']); 212 | /** @type {string} HTTP method (e.g., GET, POST) */ 213 | this._method = 'method' in req ? req.method : 'GET'; 214 | /** @type {string} Request URL */ 215 | this._url = req.url; 216 | /** @type {string} Host header from the request */ 217 | this._host = req.headers.host; 218 | /** @type {boolean} Whether the request does not include an Authorization header */ 219 | this._noAuthorization = !req.headers.authorization; 220 | /** @type {Record|null} Request headers used for Vary matching */ 221 | this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used 222 | /** @type {Record} Parsed Cache-Control directives from request */ 223 | this._reqcc = parseCacheControl(req.headers['cache-control']); 224 | 225 | // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, 226 | // so there's no point stricly adhering to the blindly copy&pasted directives. 227 | if ( 228 | this._ignoreCargoCult && 229 | 'pre-check' in this._rescc && 230 | 'post-check' in this._rescc 231 | ) { 232 | delete this._rescc['pre-check']; 233 | delete this._rescc['post-check']; 234 | delete this._rescc['no-cache']; 235 | delete this._rescc['no-store']; 236 | delete this._rescc['must-revalidate']; 237 | this._resHeaders = Object.assign({}, this._resHeaders, { 238 | 'cache-control': formatCacheControl(this._rescc), 239 | }); 240 | delete this._resHeaders.expires; 241 | delete this._resHeaders.pragma; 242 | } 243 | 244 | // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive 245 | // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). 246 | if ( 247 | res.headers['cache-control'] == null && 248 | /no-cache/.test(res.headers.pragma) 249 | ) { 250 | this._rescc['no-cache'] = true; 251 | } 252 | } 253 | 254 | /** 255 | * You can monkey-patch it for testing. 256 | * @returns {number} Current time in milliseconds. 257 | */ 258 | now() { 259 | return Date.now(); 260 | } 261 | 262 | /** 263 | * Determines if the response is storable in a cache. 264 | * @returns {boolean} `false` if can never be cached. 265 | */ 266 | storable() { 267 | // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. 268 | return !!( 269 | !this._reqcc['no-store'] && 270 | // A cache MUST NOT store a response to any request, unless: 271 | // The request method is understood by the cache and defined as being cacheable, and 272 | ('GET' === this._method || 273 | 'HEAD' === this._method || 274 | ('POST' === this._method && this._hasExplicitExpiration())) && 275 | // the response status code is understood by the cache, and 276 | understoodStatuses.has(this._status) && 277 | // the "no-store" cache directive does not appear in request or response header fields, and 278 | !this._rescc['no-store'] && 279 | // the "private" response directive does not appear in the response, if the cache is shared, and 280 | (!this._isShared || !this._rescc.private) && 281 | // the Authorization header field does not appear in the request, if the cache is shared, 282 | (!this._isShared || 283 | this._noAuthorization || 284 | this._allowsStoringAuthenticated()) && 285 | // the response either: 286 | // contains an Expires header field, or 287 | (this._resHeaders.expires || 288 | // contains a max-age response directive, or 289 | // contains a s-maxage response directive and the cache is shared, or 290 | // contains a public response directive. 291 | this._rescc['max-age'] || 292 | (this._isShared && this._rescc['s-maxage']) || 293 | this._rescc.public || 294 | // has a status code that is defined as cacheable by default 295 | statusCodeCacheableByDefault.has(this._status)) 296 | ); 297 | } 298 | 299 | /** 300 | * @returns {boolean} true if expiration is explicitly defined. 301 | */ 302 | _hasExplicitExpiration() { 303 | // 4.2.1 Calculating Freshness Lifetime 304 | return !!( 305 | (this._isShared && this._rescc['s-maxage']) || 306 | this._rescc['max-age'] || 307 | this._resHeaders.expires 308 | ); 309 | } 310 | 311 | /** 312 | * @param {HttpRequest} req - a request 313 | * @throws {Error} if the headers are missing. 314 | */ 315 | _assertRequestHasHeaders(req) { 316 | if (!req || !req.headers) { 317 | throw Error('Request headers missing'); 318 | } 319 | } 320 | 321 | /** 322 | * Checks if the request matches the cache and can be satisfied from the cache immediately, 323 | * without having to make a request to the server. 324 | * 325 | * This doesn't support `stale-while-revalidate`. See `evaluateRequest()` for a more complete solution. 326 | * 327 | * @param {HttpRequest} req - The new incoming HTTP request. 328 | * @returns {boolean} `true`` if the cached response used to construct this cache policy satisfies the request without revalidation. 329 | */ 330 | satisfiesWithoutRevalidation(req) { 331 | const result = this.evaluateRequest(req); 332 | return !result.revalidation; 333 | } 334 | 335 | /** 336 | * @param {{headers: Record, synchronous: boolean}|undefined} revalidation - Revalidation information, if any. 337 | * @returns {{response: {headers: Record}, revalidation: {headers: Record, synchronous: boolean}|undefined}} An object with a cached response headers and revalidation info. 338 | */ 339 | _evaluateRequestHitResult(revalidation) { 340 | return { 341 | response: { 342 | headers: this.responseHeaders(), 343 | }, 344 | revalidation, 345 | }; 346 | } 347 | 348 | /** 349 | * @param {HttpRequest} request - new incoming 350 | * @param {boolean} synchronous - whether revalidation must be synchronous (not s-w-r). 351 | * @returns {{headers: Record, synchronous: boolean}} An object with revalidation headers and a synchronous flag. 352 | */ 353 | _evaluateRequestRevalidation(request, synchronous) { 354 | return { 355 | synchronous, 356 | headers: this.revalidationHeaders(request), 357 | }; 358 | } 359 | 360 | /** 361 | * @param {HttpRequest} request - new incoming 362 | * @returns {{response: undefined, revalidation: {headers: Record, synchronous: boolean}}} An object indicating no cached response and revalidation details. 363 | */ 364 | _evaluateRequestMissResult(request) { 365 | return { 366 | response: undefined, 367 | revalidation: this._evaluateRequestRevalidation(request, true), 368 | }; 369 | } 370 | 371 | /** 372 | * Checks if the given request matches this cache entry, and how the cache can be used to satisfy it. Returns an object with: 373 | * 374 | * ``` 375 | * { 376 | * // If defined, you must send a request to the server. 377 | * revalidation: { 378 | * headers: {}, // HTTP headers to use when sending the revalidation response 379 | * // If true, you MUST wait for a response from the server before using the cache 380 | * // If false, this is stale-while-revalidate. The cache is stale, but you can use it while you update it asynchronously. 381 | * synchronous: bool, 382 | * }, 383 | * // If defined, you can use this cached response. 384 | * response: { 385 | * headers: {}, // Updated cached HTTP headers you must use when responding to the client 386 | * }, 387 | * } 388 | * ``` 389 | * @param {HttpRequest} req - new incoming HTTP request 390 | * @returns {{response: {headers: Record}|undefined, revalidation: {headers: Record, synchronous: boolean}|undefined}} An object containing keys: 391 | * - revalidation: { headers: Record, synchronous: boolean } Set if you should send this to the origin server 392 | * - response: { headers: Record } Set if you can respond to the client with these cached headers 393 | */ 394 | evaluateRequest(req) { 395 | this._assertRequestHasHeaders(req); 396 | 397 | // In all circumstances, a cache MUST NOT ignore the must-revalidate directive 398 | if (this._rescc['must-revalidate']) { 399 | return this._evaluateRequestMissResult(req); 400 | } 401 | 402 | if (!this._requestMatches(req, false)) { 403 | return this._evaluateRequestMissResult(req); 404 | } 405 | 406 | // When presented with a request, a cache MUST NOT reuse a stored response, unless: 407 | // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, 408 | // unless the stored response is successfully validated (Section 4.3), and 409 | const requestCC = parseCacheControl(req.headers['cache-control']); 410 | 411 | if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { 412 | return this._evaluateRequestMissResult(req); 413 | } 414 | 415 | if (requestCC['max-age'] && this.age() > toNumberOrZero(requestCC['max-age'])) { 416 | return this._evaluateRequestMissResult(req); 417 | } 418 | 419 | if (requestCC['min-fresh'] && this.maxAge() - this.age() < toNumberOrZero(requestCC['min-fresh'])) { 420 | return this._evaluateRequestMissResult(req); 421 | } 422 | 423 | // the stored response is either: 424 | // fresh, or allowed to be served stale 425 | if (this.stale()) { 426 | // If a value is present, then the client is willing to accept a response that has 427 | // exceeded its freshness lifetime by no more than the specified number of seconds 428 | const allowsStaleWithoutRevalidation = 'max-stale' in requestCC && 429 | (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge()); 430 | 431 | if (allowsStaleWithoutRevalidation) { 432 | return this._evaluateRequestHitResult(undefined); 433 | } 434 | 435 | if (this.useStaleWhileRevalidate()) { 436 | return this._evaluateRequestHitResult(this._evaluateRequestRevalidation(req, false)); 437 | } 438 | 439 | return this._evaluateRequestMissResult(req); 440 | } 441 | 442 | return this._evaluateRequestHitResult(undefined); 443 | } 444 | 445 | /** 446 | * @param {HttpRequest} req - check if this is for the same cache entry 447 | * @param {boolean} allowHeadMethod - allow a HEAD method to match. 448 | * @returns {boolean} `true` if the request matches. 449 | */ 450 | _requestMatches(req, allowHeadMethod) { 451 | // The presented effective request URI and that of the stored response match, and 452 | return !!( 453 | (!this._url || this._url === req.url) && 454 | this._host === req.headers.host && 455 | // the request method associated with the stored response allows it to be used for the presented request, and 456 | (!req.method || 457 | this._method === req.method || 458 | (allowHeadMethod && 'HEAD' === req.method)) && 459 | // selecting header fields nominated by the stored response (if any) match those presented, and 460 | this._varyMatches(req) 461 | ); 462 | } 463 | 464 | /** 465 | * Determines whether storing authenticated responses is allowed. 466 | * @returns {boolean} `true` if allowed. 467 | */ 468 | _allowsStoringAuthenticated() { 469 | // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. 470 | return !!( 471 | this._rescc['must-revalidate'] || 472 | this._rescc.public || 473 | this._rescc['s-maxage'] 474 | ); 475 | } 476 | 477 | /** 478 | * Checks whether the Vary header in the response matches the new request. 479 | * @param {HttpRequest} req - incoming HTTP request 480 | * @returns {boolean} `true` if the vary headers match. 481 | */ 482 | _varyMatches(req) { 483 | if (!this._resHeaders.vary) { 484 | return true; 485 | } 486 | 487 | // A Vary header field-value of "*" always fails to match 488 | if (this._resHeaders.vary === '*') { 489 | return false; 490 | } 491 | 492 | const fields = this._resHeaders.vary 493 | .trim() 494 | .toLowerCase() 495 | .split(/\s*,\s*/); 496 | for (const name of fields) { 497 | if (req.headers[name] !== this._reqHeaders[name]) return false; 498 | } 499 | return true; 500 | } 501 | 502 | /** 503 | * Creates a copy of the given headers without any hop-by-hop headers. 504 | * @param {Record} inHeaders - old headers from the cached response 505 | * @returns {Record} A new headers object without hop-by-hop headers. 506 | */ 507 | _copyWithoutHopByHopHeaders(inHeaders) { 508 | /** @type {Record} */ 509 | const headers = {}; 510 | for (const name in inHeaders) { 511 | if (hopByHopHeaders[name]) continue; 512 | headers[name] = inHeaders[name]; 513 | } 514 | // 9.1. Connection 515 | if (inHeaders.connection) { 516 | const tokens = inHeaders.connection.trim().split(/\s*,\s*/); 517 | for (const name of tokens) { 518 | delete headers[name]; 519 | } 520 | } 521 | if (headers.warning) { 522 | const warnings = headers.warning.split(/,/).filter(warning => { 523 | return !/^\s*1[0-9][0-9]/.test(warning); 524 | }); 525 | if (!warnings.length) { 526 | delete headers.warning; 527 | } else { 528 | headers.warning = warnings.join(',').trim(); 529 | } 530 | } 531 | return headers; 532 | } 533 | 534 | /** 535 | * Returns the response headers adjusted for serving the cached response. 536 | * Removes hop-by-hop headers and updates the Age and Date headers. 537 | * @returns {Record} The adjusted response headers. 538 | */ 539 | responseHeaders() { 540 | const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); 541 | const age = this.age(); 542 | 543 | // A cache SHOULD generate 113 warning if it heuristically chose a freshness 544 | // lifetime greater than 24 hours and the response's age is greater than 24 hours. 545 | if ( 546 | age > 3600 * 24 && 547 | !this._hasExplicitExpiration() && 548 | this.maxAge() > 3600 * 24 549 | ) { 550 | headers.warning = 551 | (headers.warning ? `${headers.warning}, ` : '') + 552 | '113 - "rfc7234 5.5.4"'; 553 | } 554 | headers.age = `${Math.round(age)}`; 555 | headers.date = new Date(this.now()).toUTCString(); 556 | return headers; 557 | } 558 | 559 | /** 560 | * Returns the Date header value from the response or the current time if invalid. 561 | * @returns {number} Timestamp (in milliseconds) representing the Date header or response time. 562 | */ 563 | date() { 564 | const serverDate = Date.parse(this._resHeaders.date); 565 | if (isFinite(serverDate)) { 566 | return serverDate; 567 | } 568 | return this._responseTime; 569 | } 570 | 571 | /** 572 | * Value of the Age header, in seconds, updated for the current time. 573 | * May be fractional. 574 | * @returns {number} The age in seconds. 575 | */ 576 | age() { 577 | let age = this._ageValue(); 578 | 579 | const residentTime = (this.now() - this._responseTime) / 1000; 580 | return age + residentTime; 581 | } 582 | 583 | /** 584 | * @returns {number} The Age header value as a number. 585 | */ 586 | _ageValue() { 587 | return toNumberOrZero(this._resHeaders.age); 588 | } 589 | 590 | /** 591 | * Possibly outdated value of applicable max-age (or heuristic equivalent) in seconds. 592 | * This counts since response's `Date`. 593 | * 594 | * For an up-to-date value, see `timeToLive()`. 595 | * 596 | * Returns the maximum age (freshness lifetime) of the response in seconds. 597 | * @returns {number} The max-age value in seconds. 598 | */ 599 | maxAge() { 600 | if (!this.storable() || this._rescc['no-cache']) { 601 | return 0; 602 | } 603 | 604 | // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default 605 | // so this implementation requires explicit opt-in via public header 606 | if ( 607 | this._isShared && 608 | (this._resHeaders['set-cookie'] && 609 | !this._rescc.public && 610 | !this._rescc.immutable) 611 | ) { 612 | return 0; 613 | } 614 | 615 | if (this._resHeaders.vary === '*') { 616 | return 0; 617 | } 618 | 619 | if (this._isShared) { 620 | if (this._rescc['proxy-revalidate']) { 621 | return 0; 622 | } 623 | // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. 624 | if (this._rescc['s-maxage']) { 625 | return toNumberOrZero(this._rescc['s-maxage']); 626 | } 627 | } 628 | 629 | // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. 630 | if (this._rescc['max-age']) { 631 | return toNumberOrZero(this._rescc['max-age']); 632 | } 633 | 634 | const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; 635 | 636 | const serverDate = this.date(); 637 | if (this._resHeaders.expires) { 638 | const expires = Date.parse(this._resHeaders.expires); 639 | // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). 640 | if (Number.isNaN(expires) || expires < serverDate) { 641 | return 0; 642 | } 643 | return Math.max(defaultMinTtl, (expires - serverDate) / 1000); 644 | } 645 | 646 | if (this._resHeaders['last-modified']) { 647 | const lastModified = Date.parse(this._resHeaders['last-modified']); 648 | if (isFinite(lastModified) && serverDate > lastModified) { 649 | return Math.max( 650 | defaultMinTtl, 651 | ((serverDate - lastModified) / 1000) * this._cacheHeuristic 652 | ); 653 | } 654 | } 655 | 656 | return defaultMinTtl; 657 | } 658 | 659 | /** 660 | * Remaining time this cache entry may be useful for, in *milliseconds*. 661 | * You can use this as an expiration time for your cache storage. 662 | * 663 | * Prefer this method over `maxAge()`, because it includes other factors like `age` and `stale-while-revalidate`. 664 | * @returns {number} Time-to-live in milliseconds. 665 | */ 666 | timeToLive() { 667 | const age = this.maxAge() - this.age(); 668 | const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); 669 | const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); 670 | return Math.round(Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000); 671 | } 672 | 673 | /** 674 | * If true, this cache entry is past its expiration date. 675 | * Note that stale cache may be useful sometimes, see `evaluateRequest()`. 676 | * @returns {boolean} `false` doesn't mean it's fresh nor usable 677 | */ 678 | stale() { 679 | return this.maxAge() <= this.age(); 680 | } 681 | 682 | /** 683 | * @returns {boolean} `true` if `stale-if-error` condition allows use of a stale response. 684 | */ 685 | _useStaleIfError() { 686 | return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); 687 | } 688 | 689 | /** See `evaluateRequest()` for a more complete solution 690 | * @returns {boolean} `true` if `stale-while-revalidate` is currently allowed. 691 | */ 692 | useStaleWhileRevalidate() { 693 | const swr = toNumberOrZero(this._rescc['stale-while-revalidate']); 694 | return swr > 0 && this.maxAge() + swr > this.age(); 695 | } 696 | 697 | /** 698 | * Creates a `CachePolicy` instance from a serialized object. 699 | * @param {Object} obj - The serialized object. 700 | * @returns {CachePolicy} A new CachePolicy instance. 701 | */ 702 | static fromObject(obj) { 703 | return new this(undefined, undefined, { _fromObject: obj }); 704 | } 705 | 706 | /** 707 | * @param {any} obj - The serialized object. 708 | * @throws {Error} If already initialized or if the object is invalid. 709 | */ 710 | _fromObject(obj) { 711 | if (this._responseTime) throw Error('Reinitialized'); 712 | if (!obj || obj.v !== 1) throw Error('Invalid serialization'); 713 | 714 | this._responseTime = obj.t; 715 | this._isShared = obj.sh; 716 | this._cacheHeuristic = obj.ch; 717 | this._immutableMinTtl = 718 | obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; 719 | this._ignoreCargoCult = !!obj.icc; 720 | this._status = obj.st; 721 | this._resHeaders = obj.resh; 722 | this._rescc = obj.rescc; 723 | this._method = obj.m; 724 | this._url = obj.u; 725 | this._host = obj.h; 726 | this._noAuthorization = obj.a; 727 | this._reqHeaders = obj.reqh; 728 | this._reqcc = obj.reqcc; 729 | } 730 | 731 | /** 732 | * Serializes the `CachePolicy` instance into a JSON-serializable object. 733 | * @returns {Object} The serialized object. 734 | */ 735 | toObject() { 736 | return { 737 | v: 1, 738 | t: this._responseTime, 739 | sh: this._isShared, 740 | ch: this._cacheHeuristic, 741 | imm: this._immutableMinTtl, 742 | icc: this._ignoreCargoCult, 743 | st: this._status, 744 | resh: this._resHeaders, 745 | rescc: this._rescc, 746 | m: this._method, 747 | u: this._url, 748 | h: this._host, 749 | a: this._noAuthorization, 750 | reqh: this._reqHeaders, 751 | reqcc: this._reqcc, 752 | }; 753 | } 754 | 755 | /** 756 | * Headers for sending to the origin server to revalidate stale response. 757 | * Allows server to return 304 to allow reuse of the previous response. 758 | * 759 | * Hop by hop headers are always stripped. 760 | * Revalidation headers may be added or removed, depending on request. 761 | * @param {HttpRequest} incomingReq - The incoming HTTP request. 762 | * @returns {Record} The headers for the revalidation request. 763 | */ 764 | revalidationHeaders(incomingReq) { 765 | this._assertRequestHasHeaders(incomingReq); 766 | const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); 767 | 768 | // This implementation does not understand range requests 769 | delete headers['if-range']; 770 | 771 | if (!this._requestMatches(incomingReq, true) || !this.storable()) { 772 | // revalidation allowed via HEAD 773 | // not for the same resource, or wasn't allowed to be cached anyway 774 | delete headers['if-none-match']; 775 | delete headers['if-modified-since']; 776 | return headers; 777 | } 778 | 779 | /* 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. */ 780 | if (this._resHeaders.etag) { 781 | headers['if-none-match'] = headers['if-none-match'] 782 | ? `${headers['if-none-match']}, ${this._resHeaders.etag}` 783 | : this._resHeaders.etag; 784 | } 785 | 786 | // 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. 787 | const forbidsWeakValidators = 788 | headers['accept-ranges'] || 789 | headers['if-match'] || 790 | headers['if-unmodified-since'] || 791 | (this._method && this._method != 'GET'); 792 | 793 | /* 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. 794 | Note: This implementation does not understand partial responses (206) */ 795 | if (forbidsWeakValidators) { 796 | delete headers['if-modified-since']; 797 | 798 | if (headers['if-none-match']) { 799 | const etags = headers['if-none-match'] 800 | .split(/,/) 801 | .filter(etag => { 802 | return !/^\s*W\//.test(etag); 803 | }); 804 | if (!etags.length) { 805 | delete headers['if-none-match']; 806 | } else { 807 | headers['if-none-match'] = etags.join(',').trim(); 808 | } 809 | } 810 | } else if ( 811 | this._resHeaders['last-modified'] && 812 | !headers['if-modified-since'] 813 | ) { 814 | headers['if-modified-since'] = this._resHeaders['last-modified']; 815 | } 816 | 817 | return headers; 818 | } 819 | 820 | /** 821 | * Creates new CachePolicy with information combined from the previews response, 822 | * and the new revalidation response. 823 | * 824 | * Returns {policy, modified} where modified is a boolean indicating 825 | * whether the response body has been modified, and old cached body can't be used. 826 | * 827 | * @param {HttpRequest} request - The latest HTTP request asking for the cached entry. 828 | * @param {HttpResponse} response - The latest revalidation HTTP response from the origin server. 829 | * @returns {{policy: CachePolicy, modified: boolean, matches: boolean}} The updated policy and modification status. 830 | * @throws {Error} If the response headers are missing. 831 | */ 832 | revalidatedPolicy(request, response) { 833 | this._assertRequestHasHeaders(request); 834 | 835 | if (this._useStaleIfError() && isErrorResponse(response)) { 836 | return { 837 | policy: this, 838 | modified: false, 839 | matches: true, 840 | }; 841 | } 842 | 843 | if (!response || !response.headers) { 844 | throw Error('Response headers missing'); 845 | } 846 | 847 | // These aren't going to be supported exactly, since one CachePolicy object 848 | // doesn't know about all the other cached objects. 849 | let matches = false; 850 | if (response.status !== undefined && response.status != 304) { 851 | matches = false; 852 | } else if ( 853 | response.headers.etag && 854 | !/^\s*W\//.test(response.headers.etag) 855 | ) { 856 | // "All of the stored responses with the same strong validator are selected. 857 | // If none of the stored responses contain the same strong validator, 858 | // then the cache MUST NOT use the new response to update any stored responses." 859 | matches = 860 | this._resHeaders.etag && 861 | this._resHeaders.etag.replace(/^\s*W\//, '') === 862 | response.headers.etag; 863 | } else if (this._resHeaders.etag && response.headers.etag) { 864 | // "If the new response contains a weak validator and that validator corresponds 865 | // to one of the cache's stored responses, 866 | // then the most recent of those matching stored responses is selected for update." 867 | matches = 868 | this._resHeaders.etag.replace(/^\s*W\//, '') === 869 | response.headers.etag.replace(/^\s*W\//, ''); 870 | } else if (this._resHeaders['last-modified']) { 871 | matches = 872 | this._resHeaders['last-modified'] === 873 | response.headers['last-modified']; 874 | } else { 875 | // If the new response does not include any form of validator (such as in the case where 876 | // a client generates an If-Modified-Since request from a source other than the Last-Modified 877 | // response header field), and there is only one stored response, and that stored response also 878 | // lacks a validator, then that stored response is selected for update. 879 | if ( 880 | !this._resHeaders.etag && 881 | !this._resHeaders['last-modified'] && 882 | !response.headers.etag && 883 | !response.headers['last-modified'] 884 | ) { 885 | matches = true; 886 | } 887 | } 888 | 889 | const optionsCopy = { 890 | shared: this._isShared, 891 | cacheHeuristic: this._cacheHeuristic, 892 | immutableMinTimeToLive: this._immutableMinTtl, 893 | ignoreCargoCult: this._ignoreCargoCult, 894 | }; 895 | 896 | if (!matches) { 897 | return { 898 | policy: new this.constructor(request, response, optionsCopy), 899 | // Client receiving 304 without body, even if it's invalid/mismatched has no option 900 | // but to reuse a cached body. We don't have a good way to tell clients to do 901 | // error recovery in such case. 902 | modified: response.status != 304, 903 | matches: false, 904 | }; 905 | } 906 | 907 | // use other header fields provided in the 304 (Not Modified) response to replace all instances 908 | // of the corresponding header fields in the stored response. 909 | const headers = {}; 910 | for (const k in this._resHeaders) { 911 | headers[k] = 912 | k in response.headers && !excludedFromRevalidationUpdate[k] 913 | ? response.headers[k] 914 | : this._resHeaders[k]; 915 | } 916 | 917 | const newResponse = Object.assign({}, response, { 918 | status: this._status, 919 | method: this._method, 920 | headers, 921 | }); 922 | return { 923 | policy: new this.constructor(request, newResponse, optionsCopy), 924 | modified: false, 925 | matches: true, 926 | }; 927 | } 928 | }; 929 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "http-cache-semantics", 3 | "version": "4.2.0", 4 | "description": "Parses Cache-Control and other headers. Helps building correct HTTP caches and proxies", 5 | "repository": "https://github.com/kornelski/http-cache-semantics.git", 6 | "main": "index.js", 7 | "types": "index.js", 8 | "scripts": { 9 | "test": "mocha" 10 | }, 11 | "files": [ 12 | "index.js" 13 | ], 14 | "author": "Kornel Lesiński (https://kornel.ski/)", 15 | "license": "BSD-2-Clause", 16 | "devDependencies": { 17 | "mocha": "^11.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/misctest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | describe('Other', function() { 7 | it('Thaw wrong object', function() { 8 | assert.throws(() => { 9 | CachePolicy.fromObject({}); 10 | }); 11 | }); 12 | 13 | it('Missing headers', function() { 14 | assert.throws(() => { 15 | new CachePolicy({}); 16 | }); 17 | assert.throws(() => { 18 | new CachePolicy({ headers: {} }, {}); 19 | }); 20 | 21 | const cache = new CachePolicy({ headers: {} }, { headers: {} }); 22 | assert.throws(() => { 23 | cache.satisfiesWithoutRevalidation({}); 24 | }); 25 | assert.throws(() => { 26 | cache.revalidatedPolicy({}); 27 | }); 28 | assert.throws(() => { 29 | cache.revalidatedPolicy({ headers: {} }, {}); 30 | }); 31 | }); 32 | 33 | it('GitHub response with small clock skew', function() { 34 | const res = { 35 | headers: { 36 | server: 'GitHub.com', 37 | date: new Date(Date.now() - 77 * 1000).toUTCString(), 38 | 'content-type': 'application/json; charset=utf-8', 39 | 'transfer-encoding': 'chunked', 40 | connection: 'close', 41 | status: '200 OK', 42 | 'x-ratelimit-limit': '5000', 43 | 'x-ratelimit-remaining': '4836', 44 | 'x-ratelimit-reset': '1524313615', 45 | 'cache-control': 'private, max-age=60, s-maxage=60', 46 | vary: 'Accept, Authorization, Cookie, X-GitHub-OTP', 47 | etag: 'W/"4876f954d40e3efc6d32aab08b9bdc47"', 48 | 'x-oauth-scopes': 49 | 'public_repo, read:user, repo:invite, repo:status, repo_deployment', 50 | 'x-accepted-oauth-scopes': '', 51 | 'x-github-media-type': 'github.v3', 52 | link: 53 | '; rel="next", ; rel="last"', 54 | 'access-control-expose-headers': 55 | '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', 56 | 'access-control-allow-origin': '*', 57 | 'strict-transport-security': 58 | 'max-age=31536000; includeSubdomains; preload', 59 | 'x-frame-options': 'deny', 60 | 'x-content-type-options': 'nosniff', 61 | 'x-xss-protection': '1; mode=block', 62 | 'referrer-policy': 63 | 'origin-when-cross-origin, strict-origin-when-cross-origin', 64 | 'content-security-policy': "default-src 'none'", 65 | 'x-runtime-rack': '0.051653', 66 | 'content-encoding': 'gzip', 67 | 'x-github-request-id': 'C6EE:12E7:3E6CA0D:87F0004:5ADB2B35', 68 | }, 69 | }; 70 | 71 | const req = { 72 | headers: {}, 73 | }; 74 | 75 | const c = new CachePolicy(req, res, { 76 | shared: false, 77 | }); 78 | assert(c.satisfiesWithoutRevalidation(req)); 79 | }); 80 | }); 81 | -------------------------------------------------------------------------------- /test/okhttptest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* 3 | * Copyright (C) 2011 The Android Open Source Project 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | const assert = require('assert'); 19 | const CachePolicy = require('..'); 20 | 21 | describe('okhttp tests', function() { 22 | it('response caching by response code', function() { 23 | // Test each documented HTTP/1.1 code, plus the first unused value in each range. 24 | // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 25 | 26 | assertCached(false, 100); 27 | assertCached(false, 101); 28 | assertCached(false, 102); 29 | assertCached(true, 200); 30 | assertCached(false, 201); 31 | assertCached(false, 202); 32 | assertCached(true, 203); 33 | assertCached(true, 204); 34 | assertCached(false, 205); 35 | assertCached(false, 206); //Electing to not cache partial responses 36 | assertCached(false, 207); 37 | assertCached(true, 300); 38 | assertCached(true, 301); 39 | assertCached(true, 302); 40 | // assertCached(false, 303); 41 | assertCached(false, 304); 42 | assertCached(false, 305); 43 | assertCached(false, 306); 44 | assertCached(true, 307); 45 | assertCached(true, 308); 46 | assertCached(false, 400); 47 | assertCached(false, 401); 48 | assertCached(false, 402); 49 | assertCached(false, 403); 50 | assertCached(true, 404); 51 | assertCached(true, 405); 52 | assertCached(false, 406); 53 | assertCached(false, 408); 54 | assertCached(false, 409); 55 | // the HTTP spec permits caching 410s, but the RI doesn't. 56 | assertCached(true, 410); 57 | assertCached(false, 411); 58 | assertCached(false, 412); 59 | assertCached(false, 413); 60 | assertCached(true, 414); 61 | assertCached(false, 415); 62 | assertCached(false, 416); 63 | assertCached(false, 417); 64 | assertCached(false, 418); 65 | assertCached(false, 429); 66 | 67 | assertCached(false, 500); 68 | assertCached(true, 501); 69 | assertCached(false, 502); 70 | assertCached(false, 503); 71 | assertCached(false, 504); 72 | assertCached(false, 505); 73 | assertCached(false, 506); 74 | }); 75 | 76 | function assertCached(shouldPut, responseCode) { 77 | let expectedResponseCode = responseCode; 78 | 79 | const mockResponse = { 80 | headers: { 81 | 'last-modified': formatDate(-1, 3600), 82 | expires: formatDate(1, 3600), 83 | 'www-authenticate': 'challenge', 84 | }, 85 | status: responseCode, 86 | body: 'ABCDE', 87 | }; 88 | if (responseCode == 407) { 89 | mockResponse.headers['proxy-authenticate'] = 90 | 'Basic realm="protected area"'; 91 | } else if (responseCode == 401) { 92 | mockResponse.headers['www-authenticate'] = 93 | 'Basic realm="protected area"'; 94 | } else if (responseCode == 204 || responseCode == 205) { 95 | mockResponse.body = ''; // We forbid bodies for 204 and 205. 96 | } 97 | 98 | const request = { url: '/', headers: {} }; 99 | 100 | const cache = new CachePolicy(request, mockResponse, { shared: false }); 101 | 102 | assert.equal(shouldPut, cache.storable()); 103 | } 104 | 105 | it('default expiration date fully cached for less than24 hours', function() { 106 | // last modified: 105 seconds ago 107 | // served: 5 seconds ago 108 | // default lifetime: (105 - 5) / 10 = 10 seconds 109 | // expires: 10 seconds from served date = 5 seconds from now 110 | const cache = new CachePolicy( 111 | { headers: {} }, 112 | { 113 | headers: { 114 | 'last-modified': formatDate(-105, 1), 115 | date: formatDate(-5, 1), 116 | }, 117 | body: 'A', 118 | }, 119 | { shared: false } 120 | ); 121 | 122 | assert(cache.timeToLive() > 4000); 123 | }); 124 | 125 | it('default expiration date fully cached for more than24 hours', function() { 126 | // last modified: 105 days ago 127 | // served: 5 days ago 128 | // default lifetime: (105 - 5) / 10 = 10 days 129 | // expires: 10 days from served date = 5 days from now 130 | const cache = new CachePolicy( 131 | { headers: {} }, 132 | { 133 | headers: { 134 | 'last-modified': formatDate(-105, 3600 * 24), 135 | date: formatDate(-5, 3600 * 24), 136 | }, 137 | body: 'A', 138 | }, 139 | { shared: false } 140 | ); 141 | 142 | assert(cache.maxAge() >= 10 * 3600 * 24); 143 | assert(cache.timeToLive() + 1000 >= 5 * 3600 * 24); 144 | }); 145 | 146 | it('max age in the past with date header but no last modified header', function() { 147 | // Chrome interprets max-age relative to the local clock. Both our cache 148 | // and Firefox both use the earlier of the local and server's clock. 149 | const cache = new CachePolicy( 150 | { headers: {} }, 151 | { 152 | headers: { 153 | date: formatDate(-120, 1), 154 | 'cache-control': 'max-age=60', 155 | }, 156 | }, 157 | { shared: false } 158 | ); 159 | 160 | assert(!cache.stale()); 161 | }); 162 | 163 | it('maxAge timetolive', function() { 164 | const cache = new CachePolicy( 165 | { headers: {} }, 166 | { 167 | headers: { 168 | date: formatDate(120, 1), 169 | 'cache-control': 'max-age=60', 170 | }, 171 | }, 172 | { shared: false } 173 | ); 174 | const now = Date.now(); 175 | cache.now = () => now 176 | 177 | assert(!cache.stale()); 178 | assert.equal(cache.timeToLive(), 60000); 179 | }); 180 | 181 | it('stale-if-error timetolive', function() { 182 | const cache = new CachePolicy( 183 | { headers: {} }, 184 | { 185 | headers: { 186 | date: formatDate(120, 1), 187 | 'cache-control': 'max-age=60, stale-if-error=200', 188 | }, 189 | }, 190 | { shared: false } 191 | ); 192 | 193 | assert(!cache.stale()); 194 | assert.equal(cache.timeToLive(), 260000); 195 | }); 196 | 197 | it('stale-while-revalidate timetolive', function() { 198 | const cache = new CachePolicy( 199 | { headers: {} }, 200 | { 201 | headers: { 202 | date: formatDate(120, 1), 203 | 'cache-control': 'max-age=60, stale-while-revalidate=200', 204 | }, 205 | }, 206 | { shared: false } 207 | ); 208 | 209 | assert(!cache.stale()); 210 | assert.equal(cache.timeToLive(), 260000); 211 | }); 212 | 213 | it('stale-while-revalidate does not satisfy when stale because it requires revalidation', function() { 214 | const cache = new CachePolicy( 215 | { headers: {} }, 216 | { 217 | headers: { 218 | age: 120, 219 | 'cache-control': 'max-age=60, stale-while-revalidate=200', 220 | }, 221 | }, 222 | { shared: false } 223 | ); 224 | 225 | assert(cache.stale()); 226 | assert(cache.useStaleWhileRevalidate()); 227 | assert(!cache.satisfiesWithoutRevalidation({ headers: {} })); 228 | }); 229 | 230 | it('stale-while-revalidate does not satisfy when stale and must-revalidate because it requires revalidation', function() { 231 | const cache = new CachePolicy( 232 | { headers: {} }, 233 | { 234 | headers: { 235 | age: 120, 236 | 'cache-control': 'max-age=60, stale-while-revalidate=200, must-revalidate', 237 | }, 238 | }, 239 | { shared: false } 240 | ); 241 | 242 | assert(cache.stale()); 243 | assert(!cache.satisfiesWithoutRevalidation({ headers: {} })); 244 | }); 245 | 246 | it('stale-while-revalidate work with max-stale', function() { 247 | const cache = new CachePolicy( 248 | { headers: {} }, 249 | { 250 | headers: { 251 | age: 100, 252 | 'cache-control': 'max-age=60, stale-while-revalidate=200', 253 | }, 254 | }, 255 | { shared: false } 256 | ); 257 | 258 | assert(cache.stale()); 259 | assert(cache.satisfiesWithoutRevalidation({ 260 | headers: { 261 | 'cache-control': 'max-stale', 262 | } 263 | })); 264 | assert(!cache.satisfiesWithoutRevalidation({ 265 | headers: { 266 | 'cache-control': 'max-stale=40', 267 | } 268 | })); 269 | }); 270 | 271 | it('stale-while-revalidate not satisfies when stale and expired', function() { 272 | const cache = new CachePolicy( 273 | { headers: {} }, 274 | { 275 | headers: { 276 | age: 260, 277 | 'cache-control': 'max-age=60, stale-while-revalidate=200', 278 | }, 279 | }, 280 | { shared: false } 281 | ); 282 | 283 | assert(cache.stale()); 284 | assert(!cache.useStaleWhileRevalidate()); 285 | assert(!cache.satisfiesWithoutRevalidation({ headers: {} })); 286 | }); 287 | 288 | it('max age preferred over lower shared max age', function() { 289 | const cache = new CachePolicy( 290 | { headers: {} }, 291 | { 292 | headers: { 293 | date: formatDate(-2, 60), 294 | 'cache-control': 's-maxage=60, max-age=180', 295 | }, 296 | }, 297 | { shared: false } 298 | ); 299 | 300 | assert.equal(cache.maxAge(), 180); 301 | }); 302 | 303 | it('max age preferred over higher max age', function() { 304 | const cache = new CachePolicy( 305 | { headers: {} }, 306 | { 307 | headers: { 308 | age: 360, 309 | 'cache-control': 's-maxage=60, max-age=180', 310 | }, 311 | }, 312 | { shared: false } 313 | ); 314 | 315 | assert(cache.stale()); 316 | }); 317 | 318 | it('request method options is not cached', function() { 319 | testRequestMethodNotCached('OPTIONS'); 320 | }); 321 | 322 | it('request method put is not cached', function() { 323 | testRequestMethodNotCached('PUT'); 324 | }); 325 | 326 | it('request method delete is not cached', function() { 327 | testRequestMethodNotCached('DELETE'); 328 | }); 329 | 330 | it('request method trace is not cached', function() { 331 | testRequestMethodNotCached('TRACE'); 332 | }); 333 | 334 | function testRequestMethodNotCached(method) { 335 | // 1. seed the cache (potentially) 336 | // 2. expect a cache hit or miss 337 | const cache = new CachePolicy( 338 | { method, headers: {} }, 339 | { 340 | headers: { 341 | expires: formatDate(1, 3600), 342 | }, 343 | }, 344 | { shared: false } 345 | ); 346 | 347 | assert(cache.stale()); 348 | } 349 | 350 | it('etag and expiration date in the future', function() { 351 | const cache = new CachePolicy( 352 | { headers: {} }, 353 | { 354 | headers: { 355 | etag: 'v1', 356 | 'last-modified': formatDate(-2, 3600), 357 | expires: formatDate(1, 3600), 358 | }, 359 | }, 360 | { shared: false } 361 | ); 362 | 363 | assert(cache.timeToLive() > 0); 364 | }); 365 | 366 | it('client side no store', function() { 367 | const cache = new CachePolicy( 368 | { 369 | headers: { 370 | 'cache-control': 'no-store', 371 | }, 372 | }, 373 | { 374 | headers: { 375 | 'cache-control': 'max-age=60', 376 | }, 377 | }, 378 | { shared: false } 379 | ); 380 | 381 | assert(!cache.storable()); 382 | }); 383 | 384 | it('request max age', function() { 385 | const cache = new CachePolicy( 386 | { headers: {} }, 387 | { 388 | headers: { 389 | 'last-modified': formatDate(-2, 3600), 390 | age: 60, 391 | expires: formatDate(1, 3600), 392 | }, 393 | }, 394 | { shared: false } 395 | ); 396 | 397 | assert(!cache.stale()); 398 | assert(cache.age() >= 60); 399 | 400 | assert( 401 | cache.satisfiesWithoutRevalidation({ 402 | headers: { 403 | 'cache-control': 'max-age=90', 404 | }, 405 | }) 406 | ); 407 | 408 | assert( 409 | !cache.satisfiesWithoutRevalidation({ 410 | headers: { 411 | 'cache-control': 'max-age=30', 412 | }, 413 | }) 414 | ); 415 | }); 416 | 417 | it('request min fresh', function() { 418 | const cache = new CachePolicy( 419 | { headers: {} }, 420 | { 421 | headers: { 422 | 'cache-control': 'max-age=60', 423 | }, 424 | }, 425 | { shared: false } 426 | ); 427 | 428 | assert(!cache.stale()); 429 | 430 | assert( 431 | !cache.satisfiesWithoutRevalidation({ 432 | headers: { 433 | 'cache-control': 'min-fresh=120', 434 | }, 435 | }) 436 | ); 437 | 438 | assert( 439 | cache.satisfiesWithoutRevalidation({ 440 | headers: { 441 | 'cache-control': 'min-fresh=10', 442 | }, 443 | }) 444 | ); 445 | }); 446 | 447 | it('request min fresh with stale-while-revalidate', function() { 448 | const cache = new CachePolicy( 449 | { headers: {} }, 450 | { headers: {'cache-control': 'max-age=60, stale-while-revalidate=100000'} }, 451 | { shared: false } 452 | ); 453 | 454 | assert(!cache.satisfiesWithoutRevalidation({headers: {'cache-control': 'min-fresh=120'}})); 455 | assert(cache.satisfiesWithoutRevalidation({headers: {'cache-control': 'min-fresh=10'}})); 456 | }); 457 | 458 | it('request max stale', function() { 459 | const cache = new CachePolicy( 460 | { headers: {} }, 461 | { 462 | headers: { 463 | 'cache-control': 'max-age=120', 464 | age: 4*60, 465 | }, 466 | }, 467 | { shared: false } 468 | ); 469 | 470 | assert(cache.stale()); 471 | 472 | assert( 473 | cache.satisfiesWithoutRevalidation({ 474 | headers: { 475 | 'cache-control': 'max-stale=180', 476 | }, 477 | }) 478 | ); 479 | 480 | assert( 481 | cache.satisfiesWithoutRevalidation({ 482 | headers: { 483 | 'cache-control': 'max-stale', 484 | }, 485 | }) 486 | ); 487 | 488 | assert( 489 | !cache.satisfiesWithoutRevalidation({ 490 | headers: { 491 | 'cache-control': 'max-stale=10', 492 | }, 493 | }) 494 | ); 495 | }); 496 | 497 | it('request max stale not honored with must revalidate', function() { 498 | const cache = new CachePolicy( 499 | { headers: {} }, 500 | { 501 | headers: { 502 | 'cache-control': 'max-age=120, must-revalidate', 503 | age: 360, 504 | }, 505 | }, 506 | { shared: false } 507 | ); 508 | 509 | assert(cache.stale()); 510 | 511 | assert( 512 | !cache.satisfiesWithoutRevalidation({ 513 | headers: { 514 | 'cache-control': 'max-stale=180', 515 | }, 516 | }) 517 | ); 518 | 519 | assert( 520 | !cache.satisfiesWithoutRevalidation({ 521 | headers: { 522 | 'cache-control': 'max-stale', 523 | }, 524 | }) 525 | ); 526 | }); 527 | 528 | it('get headers deletes cached100 level warnings', function() { 529 | const cache = new CachePolicy( 530 | { headers: {} }, 531 | { 532 | headers: { 533 | warning: '199 test danger, 200 ok ok', 534 | }, 535 | } 536 | ); 537 | 538 | assert.equal('200 ok ok', cache.responseHeaders().warning); 539 | }); 540 | 541 | it('do not cache partial response', function() { 542 | const cache = new CachePolicy( 543 | { headers: {} }, 544 | { 545 | status: 206, 546 | headers: { 547 | 'content-range': 'bytes 100-100/200', 548 | 'cache-control': 'max-age=60', 549 | }, 550 | } 551 | ); 552 | assert(!cache.storable()); 553 | }); 554 | 555 | function formatDate(delta, unit) { 556 | return new Date(Date.now() + delta * unit * 1000).toUTCString(); 557 | } 558 | }); 559 | -------------------------------------------------------------------------------- /test/requesttest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | const publicCacheableResponse = { 7 | headers: { 'cache-control': 'public, max-age=222' }, 8 | }; 9 | const cacheableResponse = { headers: { 'cache-control': 'max-age=111' } }; 10 | 11 | describe('Request properties', function() { 12 | it('No store kills cache', function() { 13 | const cache = new CachePolicy( 14 | { method: 'GET', headers: { 'cache-control': 'no-store' } }, 15 | publicCacheableResponse 16 | ); 17 | assert(cache.stale()); 18 | assert(!cache.storable()); 19 | }); 20 | 21 | it('POST not cacheable by default', function() { 22 | const cache = new CachePolicy( 23 | { method: 'POST', headers: {} }, 24 | { headers: { 'cache-control': 'public' } } 25 | ); 26 | assert(cache.stale()); 27 | assert(!cache.storable()); 28 | }); 29 | 30 | it('POST cacheable explicitly', function() { 31 | const cache = new CachePolicy( 32 | { method: 'POST', headers: {} }, 33 | publicCacheableResponse 34 | ); 35 | assert(!cache.stale()); 36 | assert(cache.storable()); 37 | }); 38 | 39 | it('Public cacheable auth is OK', function() { 40 | const cache = new CachePolicy( 41 | { method: 'GET', headers: { authorization: 'test' } }, 42 | publicCacheableResponse 43 | ); 44 | assert(!cache.stale()); 45 | assert(cache.storable()); 46 | }); 47 | 48 | it('Proxy cacheable auth is OK', function() { 49 | const cache = new CachePolicy( 50 | { method: 'GET', headers: { authorization: 'test' } }, 51 | { headers: { 'cache-control': 'max-age=0,s-maxage=12' } } 52 | ); 53 | assert(!cache.stale()); 54 | assert(cache.storable()); 55 | 56 | const cache2 = CachePolicy.fromObject( 57 | JSON.parse(JSON.stringify(cache.toObject())) 58 | ); 59 | assert(cache2 instanceof CachePolicy); 60 | assert(!cache2.stale()); 61 | assert(cache2.storable()); 62 | }); 63 | 64 | it('Private auth is OK', function() { 65 | const cache = new CachePolicy( 66 | { method: 'GET', headers: { authorization: 'test' } }, 67 | cacheableResponse, 68 | { shared: false } 69 | ); 70 | assert(!cache.stale()); 71 | assert(cache.storable()); 72 | }); 73 | 74 | it('Revalidated auth is OK', function() { 75 | const cache = new CachePolicy( 76 | { headers: { authorization: 'test' } }, 77 | { headers: { 'cache-control': 'max-age=88,must-revalidate' } } 78 | ); 79 | assert(cache.storable()); 80 | }); 81 | 82 | it('Auth prevents caching by default', function() { 83 | const cache = new CachePolicy( 84 | { method: 'GET', headers: { authorization: 'test' } }, 85 | cacheableResponse 86 | ); 87 | assert(cache.stale()); 88 | assert(!cache.storable()); 89 | }); 90 | }); 91 | -------------------------------------------------------------------------------- /test/responsetest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | const req = { method: 'GET', headers: {} }; 7 | 8 | describe('Response headers', function() { 9 | it('simple miss', function() { 10 | const cache = new CachePolicy(req, { headers: {} }); 11 | assert(cache.stale()); 12 | }); 13 | 14 | it('simple hit', function() { 15 | const cache = new CachePolicy(req, { 16 | headers: { 'cache-control': 'public, max-age=999999' }, 17 | }); 18 | assert(!cache.stale()); 19 | assert.equal(cache.maxAge(), 999999); 20 | }); 21 | 22 | it('weird syntax', function() { 23 | const cache = new CachePolicy(req, { 24 | headers: { 'cache-control': ',,,,max-age = 456 ,' }, 25 | }); 26 | assert(!cache.stale()); 27 | assert.equal(cache.maxAge(), 456); 28 | 29 | const cache2 = CachePolicy.fromObject( 30 | JSON.parse(JSON.stringify(cache.toObject())) 31 | ); 32 | assert(cache2 instanceof CachePolicy); 33 | assert(!cache2.stale()); 34 | assert.equal(cache2.maxAge(), 456); 35 | }); 36 | 37 | it('quoted syntax', function() { 38 | const cache = new CachePolicy(req, { 39 | headers: { 'cache-control': ' max-age = "678" ' }, 40 | }); 41 | assert(!cache.stale()); 42 | assert.equal(cache.maxAge(), 678); 43 | }); 44 | 45 | it('IIS', function() { 46 | const cache = new CachePolicy( 47 | req, 48 | { headers: { 'cache-control': 'private, public, max-age=259200' } }, 49 | { shared: false } 50 | ); 51 | assert(!cache.stale()); 52 | assert.equal(cache.maxAge(), 259200); 53 | }); 54 | 55 | it('pre-check tolerated', function() { 56 | const cc = 'pre-check=0, post-check=0, no-store, no-cache, max-age=100'; 57 | const cache = new CachePolicy(req, { 58 | headers: { 'cache-control': cc }, 59 | }); 60 | assert(cache.stale()); 61 | assert(!cache.storable()); 62 | assert.equal(cache.maxAge(), 0); 63 | assert.equal(cache.responseHeaders()['cache-control'], cc); 64 | }); 65 | 66 | it('pre-check poison', function() { 67 | const origCC = 68 | 'pre-check=0, post-check=0, no-cache, no-store, max-age=100, custom, foo=bar'; 69 | const res = { 70 | headers: { 'cache-control': origCC, pragma: 'no-cache' }, 71 | }; 72 | const cache = new CachePolicy(req, res, { ignoreCargoCult: true }); 73 | assert(!cache.stale()); 74 | assert(cache.storable()); 75 | assert.equal(cache.maxAge(), 100); 76 | 77 | const cc = cache.responseHeaders()['cache-control']; 78 | assert(!/pre-check/.test(cc), cc); 79 | assert(!/post-check/.test(cc), cc); 80 | assert(!/no-store/.test(cc), cc); 81 | 82 | assert(/max-age=100/.test(cc)); 83 | assert(/custom(,|$)/.test(cc)); 84 | assert(/foo=bar/.test(cc)); 85 | 86 | assert.equal(res.headers['cache-control'], origCC); 87 | assert(res.headers['pragma']); 88 | assert(!cache.responseHeaders()['pragma']); 89 | }); 90 | 91 | it('pre-check poison undefined header', function() { 92 | const origCC = 'pre-check=0, post-check=0, no-cache, no-store'; 93 | const res = { 94 | headers: { 'cache-control': origCC, expires: 'yesterday!' }, 95 | }; 96 | const cache = new CachePolicy(req, res, { ignoreCargoCult: true }); 97 | assert(cache.stale()); 98 | assert(cache.storable()); 99 | assert.equal(cache.maxAge(), 0); 100 | 101 | const cc = cache.responseHeaders()['cache-control']; 102 | assert(!cc); 103 | 104 | assert(res.headers['expires']); 105 | assert(!cache.responseHeaders()['expires']); 106 | }); 107 | 108 | it('cache with expires', function() { 109 | const now = Date.now(); 110 | const cache = new CachePolicy(req, { 111 | headers: { 112 | date: new Date(now).toGMTString(), 113 | expires: new Date(now + 2000).toGMTString(), 114 | }, 115 | }); 116 | assert(!cache.stale()); 117 | assert.equal(2, cache.maxAge()); 118 | }); 119 | 120 | it('cache with expires relative to date', function() { 121 | const now = Date.now(); 122 | const cache = new CachePolicy(req, { 123 | headers: { 124 | date: new Date(now - 3000).toGMTString(), 125 | expires: new Date(now).toGMTString(), 126 | }, 127 | }); 128 | assert.equal(3, cache.maxAge()); 129 | }); 130 | 131 | it('cache with expires always relative to date', function() { 132 | const now = Date.now(); 133 | const cache = new CachePolicy( 134 | req, 135 | { 136 | headers: { 137 | date: new Date(now - 3000).toGMTString(), 138 | expires: new Date(now).toGMTString(), 139 | }, 140 | }, 141 | ); 142 | assert.equal(3, cache.maxAge()); 143 | }); 144 | 145 | it('cache expires no date', function() { 146 | const cache = new CachePolicy(req, { 147 | headers: { 148 | 'cache-control': 'public', 149 | expires: new Date(Date.now() + 3600 * 1000).toGMTString(), 150 | }, 151 | }); 152 | assert(!cache.stale()); 153 | assert(cache.maxAge() > 3595); 154 | assert(cache.maxAge() < 3605); 155 | }); 156 | 157 | it('Ages', function() { 158 | let now = 1000; 159 | class TimeTravellingPolicy extends CachePolicy { 160 | now() { 161 | return now; 162 | } 163 | } 164 | const cache = new TimeTravellingPolicy(req, { 165 | headers: { 166 | 'cache-control': 'max-age=100', 167 | age: '50', 168 | }, 169 | }); 170 | assert(cache.storable()); 171 | 172 | assert.equal(50 * 1000, cache.timeToLive()); 173 | assert(!cache.stale()); 174 | now += 48 * 1000; 175 | assert.equal(2 * 1000, cache.timeToLive()); 176 | assert(!cache.stale()); 177 | now += 5 * 1000; 178 | assert(cache.stale()); 179 | assert.equal(0, cache.timeToLive()); 180 | }); 181 | 182 | it('Age can make stale', function() { 183 | const cache = new CachePolicy(req, { 184 | headers: { 185 | 'cache-control': 'max-age=100', 186 | age: '101', 187 | }, 188 | }); 189 | assert(cache.stale()); 190 | assert(cache.storable()); 191 | }); 192 | 193 | it('Age not always stale', function() { 194 | const cache = new CachePolicy(req, { 195 | headers: { 196 | 'cache-control': 'max-age=20', 197 | age: '15', 198 | }, 199 | }); 200 | assert(!cache.stale()); 201 | assert(cache.storable()); 202 | }); 203 | 204 | it('Bogus age ignored', function() { 205 | const cache = new CachePolicy(req, { 206 | headers: { 207 | 'cache-control': 'max-age=20', 208 | age: 'golden', 209 | }, 210 | }); 211 | assert(!cache.stale()); 212 | assert(cache.storable()); 213 | }); 214 | 215 | it('cache old files', function() { 216 | const cache = new CachePolicy(req, { 217 | headers: { 218 | date: new Date().toGMTString(), 219 | 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', 220 | }, 221 | }); 222 | assert(!cache.stale()); 223 | assert(cache.maxAge() > 100); 224 | }); 225 | 226 | it('immutable simple hit', function() { 227 | const cache = new CachePolicy(req, { 228 | headers: { 'cache-control': 'immutable, max-age=999999' }, 229 | }); 230 | assert(!cache.stale()); 231 | assert.equal(cache.maxAge(), 999999); 232 | }); 233 | 234 | it('immutable can expire', function() { 235 | const cache = new CachePolicy(req, { 236 | headers: { 'cache-control': 'immutable, max-age=0' }, 237 | }); 238 | assert(cache.stale()); 239 | assert.equal(cache.maxAge(), 0); 240 | }); 241 | 242 | it('cache immutable files', function() { 243 | const cache = new CachePolicy(req, { 244 | headers: { 245 | date: new Date().toGMTString(), 246 | 'cache-control': 'immutable', 247 | 'last-modified': new Date().toGMTString(), 248 | }, 249 | }); 250 | assert(!cache.stale()); 251 | assert(cache.maxAge() > 100); 252 | }); 253 | 254 | it('immutable can be off', function() { 255 | const cache = new CachePolicy( 256 | req, 257 | { 258 | headers: { 259 | date: new Date().toGMTString(), 260 | 'cache-control': 'immutable', 261 | 'last-modified': new Date().toGMTString(), 262 | }, 263 | }, 264 | { immutableMinTimeToLive: 0 } 265 | ); 266 | assert(cache.stale()); 267 | assert.equal(cache.maxAge(), 0); 268 | }); 269 | 270 | it('pragma: no-cache', function() { 271 | const cache = new CachePolicy(req, { 272 | headers: { 273 | pragma: 'no-cache', 274 | 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', 275 | }, 276 | }); 277 | assert(cache.stale()); 278 | }); 279 | 280 | it('blank cache-control and pragma: no-cache', function() { 281 | const cache = new CachePolicy(req, { 282 | headers: { 283 | 'cache-control': '', 284 | pragma: 'no-cache', 285 | 'last-modified': new Date(Date.now() - 10000).toGMTString(), 286 | }, 287 | }); 288 | assert(cache.maxAge() > 0); 289 | assert(!cache.stale()); 290 | }); 291 | 292 | it('no-store', function() { 293 | const cache = new CachePolicy(req, { 294 | headers: { 295 | 'cache-control': 'no-store, public, max-age=1', 296 | }, 297 | }); 298 | assert(cache.stale()); 299 | assert.equal(0, cache.maxAge()); 300 | }); 301 | 302 | it('observe private cache', function() { 303 | const privateHeader = { 304 | 'cache-control': 'private, max-age=1234', 305 | }; 306 | const proxyCache = new CachePolicy(req, { headers: privateHeader }); 307 | assert(proxyCache.stale()); 308 | assert.equal(0, proxyCache.maxAge()); 309 | 310 | const uaCache = new CachePolicy( 311 | req, 312 | { headers: privateHeader }, 313 | { shared: false } 314 | ); 315 | assert(!uaCache.stale()); 316 | assert.equal(1234, uaCache.maxAge()); 317 | }); 318 | 319 | it("don't share cookies", function() { 320 | const cookieHeader = { 321 | 'set-cookie': 'foo=bar', 322 | 'cache-control': 'max-age=99', 323 | }; 324 | const proxyCache = new CachePolicy( 325 | req, 326 | { headers: cookieHeader }, 327 | { shared: true } 328 | ); 329 | assert(proxyCache.stale()); 330 | assert.equal(0, proxyCache.maxAge()); 331 | 332 | const uaCache = new CachePolicy( 333 | req, 334 | { headers: cookieHeader }, 335 | { shared: false } 336 | ); 337 | assert(!uaCache.stale()); 338 | assert.equal(99, uaCache.maxAge()); 339 | }); 340 | 341 | it('do share cookies if immutable', function() { 342 | const cookieHeader = { 343 | 'set-cookie': 'foo=bar', 344 | 'cache-control': 'immutable, max-age=99', 345 | }; 346 | const proxyCache = new CachePolicy( 347 | req, 348 | { headers: cookieHeader }, 349 | { shared: true } 350 | ); 351 | assert(!proxyCache.stale()); 352 | assert.equal(99, proxyCache.maxAge()); 353 | }); 354 | 355 | it('cache explicitly public cookie', function() { 356 | const cookieHeader = { 357 | 'set-cookie': 'foo=bar', 358 | 'cache-control': 'max-age=5, public', 359 | }; 360 | const proxyCache = new CachePolicy( 361 | req, 362 | { headers: cookieHeader }, 363 | { shared: true } 364 | ); 365 | assert(!proxyCache.stale()); 366 | assert.equal(5, proxyCache.maxAge()); 367 | }); 368 | 369 | it('miss max-age=0', function() { 370 | const cache = new CachePolicy(req, { 371 | headers: { 372 | 'cache-control': 'public, max-age=0', 373 | }, 374 | }); 375 | assert(cache.stale()); 376 | assert.equal(0, cache.maxAge()); 377 | }); 378 | 379 | it('uncacheable 503', function() { 380 | const cache = new CachePolicy(req, { 381 | status: 503, 382 | headers: { 383 | 'cache-control': 'public, max-age=1000', 384 | }, 385 | }); 386 | assert(cache.stale()); 387 | assert.equal(0, cache.maxAge()); 388 | }); 389 | 390 | it('cacheable 301', function() { 391 | const cache = new CachePolicy(req, { 392 | status: 301, 393 | headers: { 394 | 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', 395 | }, 396 | }); 397 | assert(!cache.stale()); 398 | }); 399 | 400 | it('uncacheable 303', function() { 401 | const cache = new CachePolicy(req, { 402 | status: 303, 403 | headers: { 404 | 'last-modified': 'Mon, 07 Mar 2016 11:52:56 GMT', 405 | }, 406 | }); 407 | assert(cache.stale()); 408 | assert.equal(0, cache.maxAge()); 409 | }); 410 | 411 | it('cacheable 303', function() { 412 | const cache = new CachePolicy(req, { 413 | status: 303, 414 | headers: { 415 | 'cache-control': 'max-age=1000', 416 | }, 417 | }); 418 | assert(!cache.stale()); 419 | }); 420 | 421 | it('uncacheable 412', function() { 422 | const cache = new CachePolicy(req, { 423 | status: 412, 424 | headers: { 425 | 'cache-control': 'public, max-age=1000', 426 | }, 427 | }); 428 | assert(cache.stale()); 429 | assert.equal(0, cache.maxAge()); 430 | }); 431 | 432 | it('expired expires cached with max-age', function() { 433 | const cache = new CachePolicy(req, { 434 | headers: { 435 | 'cache-control': 'public, max-age=9999', 436 | expires: 'Sat, 07 May 2016 15:35:18 GMT', 437 | }, 438 | }); 439 | assert(!cache.stale()); 440 | assert.equal(9999, cache.maxAge()); 441 | }); 442 | 443 | it('expired expires cached with s-maxage', function() { 444 | const sMaxAgeHeaders = { 445 | 'cache-control': 'public, s-maxage=9999', 446 | expires: 'Sat, 07 May 2016 15:35:18 GMT', 447 | }; 448 | const proxyCache = new CachePolicy(req, { headers: sMaxAgeHeaders }); 449 | assert(!proxyCache.stale()); 450 | assert.equal(9999, proxyCache.maxAge()); 451 | 452 | const uaCache = new CachePolicy( 453 | req, 454 | { headers: sMaxAgeHeaders }, 455 | { shared: false } 456 | ); 457 | assert(uaCache.stale()); 458 | assert.equal(0, uaCache.maxAge()); 459 | }); 460 | 461 | it('max-age wins over future expires', function() { 462 | const cache = new CachePolicy(req, { 463 | headers: { 464 | 'cache-control': 'public, max-age=333', 465 | expires: new Date(Date.now() + 3600 * 1000).toGMTString(), 466 | }, 467 | }); 468 | assert(!cache.stale()); 469 | assert.equal(333, cache.maxAge()); 470 | }); 471 | 472 | it('remove hop headers', function() { 473 | let now = 10000; 474 | class TimeTravellingPolicy extends CachePolicy { 475 | now() { 476 | return now; 477 | } 478 | } 479 | 480 | const res = { 481 | headers: { 482 | te: 'deflate', 483 | date: 'now', 484 | custom: 'header', 485 | oompa: 'lumpa', 486 | connection: 'close, oompa, header', 487 | age: '10', 488 | 'cache-control': 'public, max-age=333', 489 | }, 490 | }; 491 | const cache = new TimeTravellingPolicy(req, res); 492 | 493 | now += 1005; 494 | const h = cache.responseHeaders(); 495 | assert(!h.connection); 496 | assert(!h.te); 497 | assert(!h.oompa); 498 | assert.equal(h['cache-control'], 'public, max-age=333'); 499 | assert.notEqual(h.date, 'now', 'updated age requires updated date'); 500 | assert.equal(h.custom, 'header'); 501 | assert.equal(h.age, '11'); 502 | assert.equal(res.headers.age, '10'); 503 | 504 | const cache2 = TimeTravellingPolicy.fromObject( 505 | JSON.parse(JSON.stringify(cache.toObject())) 506 | ); 507 | assert(cache2 instanceof TimeTravellingPolicy); 508 | const h2 = cache2.responseHeaders(); 509 | assert.deepEqual(h, h2); 510 | }); 511 | }); 512 | -------------------------------------------------------------------------------- /test/revalidatetest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | const simpleRequest = { 7 | method: 'GET', 8 | headers: { 9 | host: 'www.w3c.org', 10 | connection: 'close', 11 | 'x-custom': 'yes', 12 | }, 13 | url: '/Protocols/rfc2616/rfc2616-sec14.html', 14 | }; 15 | function simpleRequestBut(overrides) { 16 | return Object.assign({}, simpleRequest, overrides); 17 | } 18 | 19 | const cacheableResponse = { headers: { 'cache-control': 'max-age=111' } }; 20 | const etaggedResponse = { 21 | headers: Object.assign({ etag: '"123456789"' }, cacheableResponse.headers), 22 | }; 23 | const lastModifiedResponse = { 24 | headers: Object.assign( 25 | { 'last-modified': 'Tue, 15 Nov 1994 12:45:26 GMT' }, 26 | cacheableResponse.headers 27 | ), 28 | }; 29 | const multiValidatorResponse = { 30 | headers: Object.assign( 31 | {}, 32 | etaggedResponse.headers, 33 | lastModifiedResponse.headers 34 | ), 35 | }; 36 | const alwaysVariableResponse = { 37 | headers: Object.assign({ vary: '*' }, cacheableResponse.headers), 38 | }; 39 | 40 | function assertHeadersPassed(headers) { 41 | assert.strictEqual(headers.connection, undefined); 42 | assert.strictEqual(headers['x-custom'], 'yes'); 43 | } 44 | function assertNoValidators(headers) { 45 | assert.strictEqual(headers['if-none-match'], undefined); 46 | assert.strictEqual(headers['if-modified-since'], undefined); 47 | } 48 | 49 | describe('Can be revalidated?', function() { 50 | it('ok if method changes to HEAD', function() { 51 | const cache = new CachePolicy(simpleRequest, etaggedResponse); 52 | const headers = cache.revalidationHeaders( 53 | simpleRequestBut({ method: 'HEAD' }) 54 | ); 55 | assertHeadersPassed(headers); 56 | assert.equal(headers['if-none-match'], '"123456789"'); 57 | }); 58 | 59 | it('not if method mismatch (other than HEAD)', function() { 60 | const cache = new CachePolicy(simpleRequest, etaggedResponse); 61 | const incomingRequest = simpleRequestBut({ method: 'POST' }); 62 | const headers = cache.revalidationHeaders(incomingRequest); 63 | assertHeadersPassed(headers); 64 | assertNoValidators(headers); 65 | }); 66 | 67 | it('not if url mismatch', function() { 68 | const cache = new CachePolicy(simpleRequest, etaggedResponse); 69 | const incomingRequest = simpleRequestBut({ url: '/yomomma' }); 70 | const headers = cache.revalidationHeaders(incomingRequest); 71 | assertHeadersPassed(headers); 72 | assertNoValidators(headers); 73 | }); 74 | 75 | it('not if host mismatch', function() { 76 | const cache = new CachePolicy(simpleRequest, etaggedResponse); 77 | const incomingRequest = simpleRequestBut({ 78 | headers: { host: 'www.w4c.org' }, 79 | }); 80 | const headers = cache.revalidationHeaders(incomingRequest); 81 | assertNoValidators(headers); 82 | assert.strictEqual(headers['x-custom'], undefined); 83 | }); 84 | 85 | it('not if vary fields prevent', function() { 86 | const cache = new CachePolicy(simpleRequest, alwaysVariableResponse); 87 | const headers = cache.revalidationHeaders(simpleRequest); 88 | assertHeadersPassed(headers); 89 | assertNoValidators(headers); 90 | }); 91 | 92 | it('when entity tag validator is present', function() { 93 | const cache = new CachePolicy(simpleRequest, etaggedResponse); 94 | const headers = cache.revalidationHeaders(simpleRequest); 95 | assertHeadersPassed(headers); 96 | assert.equal(headers['if-none-match'], '"123456789"'); 97 | }); 98 | 99 | it('skips weak validators on post', function() { 100 | const postReq = simpleRequestBut({ 101 | method: 'POST', 102 | headers: { 'if-none-match': 'W/"weak", "strong", W/"weak2"' }, 103 | }); 104 | const cache = new CachePolicy(postReq, multiValidatorResponse); 105 | const headers = cache.revalidationHeaders(postReq); 106 | assert.equal(headers['if-none-match'], '"strong", "123456789"'); 107 | assert.strictEqual(undefined, headers['if-modified-since']); 108 | }); 109 | 110 | it('skips weak validators on post 2', function() { 111 | const postReq = simpleRequestBut({ 112 | method: 'POST', 113 | headers: { 'if-none-match': 'W/"weak"' }, 114 | }); 115 | const cache = new CachePolicy(postReq, lastModifiedResponse); 116 | const headers = cache.revalidationHeaders(postReq); 117 | assert.strictEqual(undefined, headers['if-none-match']); 118 | assert.strictEqual(undefined, headers['if-modified-since']); 119 | }); 120 | 121 | it('merges validators', function() { 122 | const postReq = simpleRequestBut({ 123 | headers: { 'if-none-match': 'W/"weak", "strong", W/"weak2"' }, 124 | }); 125 | const cache = new CachePolicy(postReq, multiValidatorResponse); 126 | const headers = cache.revalidationHeaders(postReq); 127 | assert.equal( 128 | headers['if-none-match'], 129 | 'W/"weak", "strong", W/"weak2", "123456789"' 130 | ); 131 | assert.equal( 132 | 'Tue, 15 Nov 1994 12:45:26 GMT', 133 | headers['if-modified-since'] 134 | ); 135 | }); 136 | 137 | it('when last-modified validator is present', function() { 138 | const cache = new CachePolicy(simpleRequest, lastModifiedResponse); 139 | const headers = cache.revalidationHeaders(simpleRequest); 140 | assertHeadersPassed(headers); 141 | assert.equal( 142 | headers['if-modified-since'], 143 | 'Tue, 15 Nov 1994 12:45:26 GMT' 144 | ); 145 | assert(!/113/.test(headers.warning)); 146 | }); 147 | 148 | it('not without validators', function() { 149 | const cache = new CachePolicy(simpleRequest, cacheableResponse); 150 | const headers = cache.revalidationHeaders(simpleRequest); 151 | assertHeadersPassed(headers); 152 | assertNoValidators(headers); 153 | assert(!/113/.test(headers.warning)); 154 | }); 155 | 156 | it('113 added', function() { 157 | const veryOldResponse = { 158 | headers: { 159 | age: 3600 * 72, 160 | 'last-modified': 'Tue, 15 Nov 1994 12:45:26 GMT', 161 | }, 162 | }; 163 | 164 | const cache = new CachePolicy(simpleRequest, veryOldResponse); 165 | const headers = cache.responseHeaders(); 166 | assert(/113/.test(headers.warning)); 167 | }); 168 | }); 169 | 170 | describe('Validation request', function() { 171 | it('removes warnings', function() { 172 | const cache = new CachePolicy( 173 | { headers: {} }, 174 | { 175 | headers: { 176 | warning: '199 test danger', 177 | }, 178 | } 179 | ); 180 | 181 | assert.strictEqual(undefined, cache.responseHeaders().warning); 182 | }); 183 | 184 | it('must contain any etag', function() { 185 | const cache = new CachePolicy(simpleRequest, multiValidatorResponse); 186 | const expected = multiValidatorResponse.headers.etag; 187 | const actual = cache.revalidationHeaders(simpleRequest)[ 188 | 'if-none-match' 189 | ]; 190 | assert.equal(actual, expected); 191 | }); 192 | 193 | it('merges etags', function() { 194 | const cache = new CachePolicy(simpleRequest, etaggedResponse); 195 | const expected = `"foo", "bar", ${etaggedResponse.headers.etag}`; 196 | const headers = cache.revalidationHeaders( 197 | simpleRequestBut({ 198 | headers: { 199 | host: 'www.w3c.org', 200 | 'if-none-match': '"foo", "bar"', 201 | }, 202 | }) 203 | ); 204 | assert.equal(headers['if-none-match'], expected); 205 | }); 206 | 207 | it('should send the Last-Modified value', function() { 208 | const cache = new CachePolicy(simpleRequest, multiValidatorResponse); 209 | const expected = multiValidatorResponse.headers['last-modified']; 210 | const actual = cache.revalidationHeaders(simpleRequest)[ 211 | 'if-modified-since' 212 | ]; 213 | assert.equal(actual, expected); 214 | }); 215 | 216 | it('should not send the Last-Modified value for POST', function() { 217 | const postReq = { 218 | method: 'POST', 219 | headers: { 'if-modified-since': 'yesterday' }, 220 | }; 221 | const cache = new CachePolicy(postReq, lastModifiedResponse); 222 | const actual = cache.revalidationHeaders(postReq)['if-modified-since']; 223 | assert.equal(actual, undefined); 224 | }); 225 | 226 | it('should not send the Last-Modified value for range requests', function() { 227 | const rangeReq = { 228 | method: 'GET', 229 | headers: { 230 | 'accept-ranges': '1-3', 231 | 'if-modified-since': 'yesterday', 232 | }, 233 | }; 234 | const cache = new CachePolicy(rangeReq, lastModifiedResponse); 235 | const actual = cache.revalidationHeaders(rangeReq)['if-modified-since']; 236 | assert.equal(actual, undefined); 237 | }); 238 | }); 239 | -------------------------------------------------------------------------------- /test/satisfytest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | describe('Satisfies', function() { 7 | it('when URLs match', function() { 8 | const policy = new CachePolicy( 9 | { url: '/', headers: {} }, 10 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 11 | ); 12 | assert(policy.satisfiesWithoutRevalidation({ url: '/', headers: {} })); 13 | }); 14 | 15 | it('when expires is present', function() { 16 | const policy = new CachePolicy( 17 | { headers: {} }, 18 | { 19 | status: 302, 20 | headers: { expires: new Date(Date.now() + 2000).toGMTString() }, 21 | } 22 | ); 23 | assert(policy.satisfiesWithoutRevalidation({ headers: {} })); 24 | }); 25 | 26 | it('not when URLs mismatch', function() { 27 | const policy = new CachePolicy( 28 | { url: '/foo', headers: {} }, 29 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 30 | ); 31 | assert( 32 | !policy.satisfiesWithoutRevalidation({ 33 | url: '/foo?bar', 34 | headers: {}, 35 | }) 36 | ); 37 | }); 38 | 39 | it('when methods match', function() { 40 | const policy = new CachePolicy( 41 | { method: 'GET', headers: {} }, 42 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 43 | ); 44 | assert( 45 | policy.satisfiesWithoutRevalidation({ method: 'GET', headers: {} }) 46 | ); 47 | }); 48 | 49 | it('not when hosts mismatch', function() { 50 | const policy = new CachePolicy( 51 | { headers: { host: 'foo' } }, 52 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 53 | ); 54 | assert( 55 | policy.satisfiesWithoutRevalidation({ headers: { host: 'foo' } }) 56 | ); 57 | assert( 58 | !policy.satisfiesWithoutRevalidation({ 59 | headers: { host: 'foofoo' }, 60 | }) 61 | ); 62 | }); 63 | 64 | it('when methods match HEAD', function() { 65 | const policy = new CachePolicy( 66 | { method: 'HEAD', headers: {} }, 67 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 68 | ); 69 | assert( 70 | policy.satisfiesWithoutRevalidation({ method: 'HEAD', headers: {} }) 71 | ); 72 | }); 73 | 74 | it('not when methods mismatch', function() { 75 | const policy = new CachePolicy( 76 | { method: 'POST', headers: {} }, 77 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 78 | ); 79 | assert( 80 | !policy.satisfiesWithoutRevalidation({ method: 'GET', headers: {} }) 81 | ); 82 | }); 83 | 84 | it('not when methods mismatch HEAD', function() { 85 | const policy = new CachePolicy( 86 | { method: 'HEAD', headers: {} }, 87 | { status: 200, headers: { 'cache-control': 'max-age=2' } } 88 | ); 89 | assert( 90 | !policy.satisfiesWithoutRevalidation({ method: 'GET', headers: {} }) 91 | ); 92 | }); 93 | 94 | it('not when proxy revalidating', function() { 95 | const policy = new CachePolicy( 96 | { headers: {} }, 97 | { 98 | status: 200, 99 | headers: { 'cache-control': 'max-age=2, proxy-revalidate ' }, 100 | } 101 | ); 102 | assert(!policy.satisfiesWithoutRevalidation({ headers: {} })); 103 | }); 104 | 105 | it('when not a proxy revalidating', function() { 106 | const policy = new CachePolicy( 107 | { headers: {} }, 108 | { 109 | status: 200, 110 | headers: { 'cache-control': 'max-age=2, proxy-revalidate ' }, 111 | }, 112 | { shared: false } 113 | ); 114 | assert(policy.satisfiesWithoutRevalidation({ headers: {} })); 115 | }); 116 | 117 | it('not when no-cache requesting', function() { 118 | const policy = new CachePolicy( 119 | { headers: {} }, 120 | { headers: { 'cache-control': 'max-age=2' } } 121 | ); 122 | assert( 123 | policy.satisfiesWithoutRevalidation({ 124 | headers: { 'cache-control': 'fine' }, 125 | }) 126 | ); 127 | assert( 128 | !policy.satisfiesWithoutRevalidation({ 129 | headers: { 'cache-control': 'no-cache' }, 130 | }) 131 | ); 132 | assert( 133 | !policy.satisfiesWithoutRevalidation({ 134 | headers: { pragma: 'no-cache' }, 135 | }) 136 | ); 137 | }); 138 | }); 139 | -------------------------------------------------------------------------------- /test/updatetest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | const simpleRequest = { 7 | method: 'GET', 8 | headers: { 9 | host: 'www.w3c.org', 10 | connection: 'close', 11 | }, 12 | url: '/Protocols/rfc2616/rfc2616-sec14.html', 13 | }; 14 | function withHeaders(request, headers) { 15 | return Object.assign({}, request, { 16 | headers: Object.assign({}, request.headers, headers), 17 | }); 18 | } 19 | 20 | const cacheableResponse = { headers: { 'cache-control': 'max-age=111' } }; 21 | const etaggedResponse = { 22 | headers: Object.assign({ etag: '"123456789"' }, cacheableResponse.headers), 23 | }; 24 | const weakTaggedResponse = { 25 | headers: Object.assign( 26 | { etag: 'W/"123456789"' }, 27 | cacheableResponse.headers 28 | ), 29 | }; 30 | const lastModifiedResponse = { 31 | headers: Object.assign( 32 | { 'last-modified': 'Tue, 15 Nov 1994 12:45:26 GMT' }, 33 | cacheableResponse.headers 34 | ), 35 | }; 36 | const multiValidatorResponse = { 37 | headers: Object.assign( 38 | {}, 39 | etaggedResponse.headers, 40 | lastModifiedResponse.headers 41 | ), 42 | }; 43 | 44 | function notModifiedResponseHeaders( 45 | firstRequest, 46 | firstResponse, 47 | secondRequest, 48 | secondResponse 49 | ) { 50 | const cache = new CachePolicy(firstRequest, firstResponse); 51 | const headers = cache.revalidationHeaders(secondRequest); 52 | const { policy: newCache, modified } = cache.revalidatedPolicy( 53 | { headers }, 54 | secondResponse 55 | ); 56 | if (modified) { 57 | return false; 58 | } 59 | return newCache.responseHeaders(); 60 | } 61 | 62 | function assertUpdates( 63 | firstRequest, 64 | firstResponse, 65 | secondRequest, 66 | secondResponse 67 | ) { 68 | firstResponse = withHeaders(firstResponse, { foo: 'original', 'x-other': 'original' }); 69 | if (!firstResponse.status) { 70 | firstResponse.status = 200; 71 | } 72 | secondResponse = withHeaders(secondResponse, { 73 | foo: 'updated', 74 | 'x-ignore-new': 'ignoreme', 75 | }); 76 | if (!secondResponse.status) { 77 | secondResponse.status = 304; 78 | } 79 | 80 | const headers = notModifiedResponseHeaders( 81 | firstRequest, 82 | firstResponse, 83 | secondRequest, 84 | secondResponse 85 | ); 86 | assert(headers); 87 | assert.equal(headers['foo'], 'updated'); 88 | assert.equal(headers['x-other'], 'original'); 89 | assert.strictEqual(headers['x-ignore-new'], undefined); 90 | assert.strictEqual(headers['etag'], secondResponse.headers.etag); 91 | } 92 | 93 | describe('Update revalidated', function() { 94 | it('Matching etags are updated', function() { 95 | assertUpdates( 96 | simpleRequest, 97 | etaggedResponse, 98 | simpleRequest, 99 | etaggedResponse 100 | ); 101 | }); 102 | 103 | it('Matching weak etags are updated', function() { 104 | assertUpdates( 105 | simpleRequest, 106 | weakTaggedResponse, 107 | simpleRequest, 108 | weakTaggedResponse 109 | ); 110 | }); 111 | 112 | it('Matching lastmod are updated', function() { 113 | assertUpdates( 114 | simpleRequest, 115 | lastModifiedResponse, 116 | simpleRequest, 117 | lastModifiedResponse 118 | ); 119 | }); 120 | 121 | it('Both matching are updated', function() { 122 | assertUpdates( 123 | simpleRequest, 124 | multiValidatorResponse, 125 | simpleRequest, 126 | multiValidatorResponse 127 | ); 128 | }); 129 | 130 | it('Checks status', function() { 131 | const response304 = Object.assign({}, multiValidatorResponse, { 132 | status: 304, 133 | }); 134 | const response200 = Object.assign({}, multiValidatorResponse, { 135 | status: 200, 136 | }); 137 | assertUpdates( 138 | simpleRequest, 139 | multiValidatorResponse, 140 | simpleRequest, 141 | response304 142 | ); 143 | assert( 144 | !notModifiedResponseHeaders( 145 | simpleRequest, 146 | multiValidatorResponse, 147 | simpleRequest, 148 | response200 149 | ) 150 | ); 151 | }); 152 | 153 | it('Last-mod ignored if etag is wrong', function() { 154 | assert( 155 | !notModifiedResponseHeaders( 156 | simpleRequest, 157 | multiValidatorResponse, 158 | simpleRequest, 159 | withHeaders(multiValidatorResponse, { etag: 'bad' }) 160 | ) 161 | ); 162 | assert( 163 | !notModifiedResponseHeaders( 164 | simpleRequest, 165 | multiValidatorResponse, 166 | simpleRequest, 167 | withHeaders(multiValidatorResponse, { etag: 'W/bad' }) 168 | ) 169 | ); 170 | }); 171 | 172 | it('Ignored if validator is missing', function() { 173 | assert( 174 | !notModifiedResponseHeaders( 175 | simpleRequest, 176 | etaggedResponse, 177 | simpleRequest, 178 | cacheableResponse 179 | ) 180 | ); 181 | assert( 182 | !notModifiedResponseHeaders( 183 | simpleRequest, 184 | weakTaggedResponse, 185 | simpleRequest, 186 | cacheableResponse 187 | ) 188 | ); 189 | assert( 190 | !notModifiedResponseHeaders( 191 | simpleRequest, 192 | lastModifiedResponse, 193 | simpleRequest, 194 | cacheableResponse 195 | ) 196 | ); 197 | }); 198 | 199 | it('Skips update of content-length', function() { 200 | const etaggedResponseWithLenght1 = withHeaders(etaggedResponse, { 201 | 'content-length': 1, 202 | }); 203 | const etaggedResponseWithLenght2 = withHeaders(etaggedResponse, { 204 | 'content-length': 2, 205 | }); 206 | const headers = notModifiedResponseHeaders( 207 | simpleRequest, 208 | etaggedResponseWithLenght1, 209 | simpleRequest, 210 | etaggedResponseWithLenght2 211 | ); 212 | assert.equal(1, headers['content-length']); 213 | }); 214 | 215 | it('Ignored if validator is different', function() { 216 | assert( 217 | !notModifiedResponseHeaders( 218 | simpleRequest, 219 | lastModifiedResponse, 220 | simpleRequest, 221 | etaggedResponse 222 | ) 223 | ); 224 | assert( 225 | !notModifiedResponseHeaders( 226 | simpleRequest, 227 | lastModifiedResponse, 228 | simpleRequest, 229 | weakTaggedResponse 230 | ) 231 | ); 232 | assert( 233 | !notModifiedResponseHeaders( 234 | simpleRequest, 235 | etaggedResponse, 236 | simpleRequest, 237 | lastModifiedResponse 238 | ) 239 | ); 240 | }); 241 | 242 | it("Ignored if validator doesn't match", function() { 243 | assert( 244 | !notModifiedResponseHeaders( 245 | simpleRequest, 246 | etaggedResponse, 247 | simpleRequest, 248 | withHeaders(etaggedResponse, { etag: '"other"' }) 249 | ), 250 | 'bad etag' 251 | ); 252 | assert( 253 | !notModifiedResponseHeaders( 254 | simpleRequest, 255 | lastModifiedResponse, 256 | simpleRequest, 257 | withHeaders(lastModifiedResponse, { 'last-modified': 'dunno' }) 258 | ), 259 | 'bad lastmod' 260 | ); 261 | }); 262 | 263 | it("staleIfError revalidate, no response", function() { 264 | const cacheableStaleResponse = { headers: { 'cache-control': 'max-age=200, stale-if-error=300' } }; 265 | const cache = new CachePolicy(simpleRequest, cacheableStaleResponse); 266 | 267 | const { policy, modified } = cache.revalidatedPolicy( 268 | simpleRequest, 269 | null 270 | ); 271 | assert(policy === cache); 272 | assert(modified === false); 273 | }); 274 | 275 | it("staleIfError revalidate, server error", function() { 276 | const cacheableStaleResponse = { headers: { 'cache-control': 'max-age=200, stale-if-error=300' } }; 277 | const cache = new CachePolicy(simpleRequest, cacheableStaleResponse); 278 | 279 | const { policy, modified } = cache.revalidatedPolicy( 280 | simpleRequest, 281 | { status: 500, headers: {} } 282 | ); 283 | assert(policy === cache); 284 | assert(modified === false); 285 | }); 286 | }); 287 | -------------------------------------------------------------------------------- /test/varytest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const assert = require('assert'); 4 | const CachePolicy = require('..'); 5 | 6 | describe('Vary', function() { 7 | it('Basic', function() { 8 | const policy = new CachePolicy( 9 | { headers: { weather: 'nice' } }, 10 | { headers: { 'cache-control': 'max-age=5', vary: 'weather' } } 11 | ); 12 | 13 | assert( 14 | policy.satisfiesWithoutRevalidation({ 15 | headers: { weather: 'nice' }, 16 | }) 17 | ); 18 | assert( 19 | !policy.satisfiesWithoutRevalidation({ 20 | headers: { weather: 'bad' }, 21 | }) 22 | ); 23 | }); 24 | 25 | it("* doesn't match", function() { 26 | const policy = new CachePolicy( 27 | { headers: { weather: 'ok' } }, 28 | { headers: { 'cache-control': 'max-age=5', vary: '*' } } 29 | ); 30 | 31 | assert( 32 | !policy.satisfiesWithoutRevalidation({ headers: { weather: 'ok' } }) 33 | ); 34 | }); 35 | 36 | it('* is stale', function() { 37 | const policy1 = new CachePolicy( 38 | { headers: { weather: 'ok' } }, 39 | { headers: { 'cache-control': 'public,max-age=99', vary: '*' } } 40 | ); 41 | const policy2 = new CachePolicy( 42 | { headers: { weather: 'ok' } }, 43 | { 44 | headers: { 45 | 'cache-control': 'public,max-age=99', 46 | vary: 'weather', 47 | }, 48 | } 49 | ); 50 | 51 | assert(policy1.stale()); 52 | assert(!policy2.stale()); 53 | }); 54 | 55 | it('Values are case-sensitive', function() { 56 | const policy = new CachePolicy( 57 | { headers: { weather: 'BAD' } }, 58 | { headers: { 'cache-control': 'max-age=5', vary: 'Weather' } } 59 | ); 60 | 61 | assert( 62 | policy.satisfiesWithoutRevalidation({ headers: { weather: 'BAD' } }) 63 | ); 64 | assert( 65 | !policy.satisfiesWithoutRevalidation({ 66 | headers: { weather: 'bad' }, 67 | }) 68 | ); 69 | }); 70 | 71 | it('Irrelevant headers ignored', function() { 72 | const policy = new CachePolicy( 73 | { headers: { weather: 'nice' } }, 74 | { headers: { 'cache-control': 'max-age=5', vary: 'moon-phase' } } 75 | ); 76 | 77 | assert( 78 | policy.satisfiesWithoutRevalidation({ headers: { weather: 'bad' } }) 79 | ); 80 | assert( 81 | policy.satisfiesWithoutRevalidation({ headers: { sun: 'shining' } }) 82 | ); 83 | assert( 84 | !policy.satisfiesWithoutRevalidation({ 85 | headers: { 'moon-phase': 'full' }, 86 | }) 87 | ); 88 | }); 89 | 90 | it('Absence is meaningful', function() { 91 | const policy = new CachePolicy( 92 | { headers: { weather: 'nice' } }, 93 | { 94 | headers: { 95 | 'cache-control': 'max-age=5', 96 | vary: 'moon-phase, weather', 97 | }, 98 | } 99 | ); 100 | 101 | assert( 102 | policy.satisfiesWithoutRevalidation({ 103 | headers: { weather: 'nice' }, 104 | }) 105 | ); 106 | assert( 107 | !policy.satisfiesWithoutRevalidation({ 108 | headers: { weather: 'nice', 'moon-phase': '' }, 109 | }) 110 | ); 111 | assert(!policy.satisfiesWithoutRevalidation({ headers: {} })); 112 | }); 113 | 114 | it('All values must match', function() { 115 | const policy = new CachePolicy( 116 | { headers: { sun: 'shining', weather: 'nice' } }, 117 | { headers: { 'cache-control': 'max-age=5', vary: 'weather, sun' } } 118 | ); 119 | 120 | assert( 121 | policy.satisfiesWithoutRevalidation({ 122 | headers: { sun: 'shining', weather: 'nice' }, 123 | }) 124 | ); 125 | assert( 126 | !policy.satisfiesWithoutRevalidation({ 127 | headers: { sun: 'shining', weather: 'bad' }, 128 | }) 129 | ); 130 | }); 131 | 132 | it('Whitespace is OK', function() { 133 | const policy = new CachePolicy( 134 | { headers: { sun: 'shining', weather: 'nice' } }, 135 | { 136 | headers: { 137 | 'cache-control': 'max-age=5', 138 | vary: ' weather , sun ', 139 | }, 140 | } 141 | ); 142 | 143 | assert( 144 | policy.satisfiesWithoutRevalidation({ 145 | headers: { sun: 'shining', weather: 'nice' }, 146 | }) 147 | ); 148 | assert( 149 | !policy.satisfiesWithoutRevalidation({ 150 | headers: { weather: 'nice' }, 151 | }) 152 | ); 153 | assert( 154 | !policy.satisfiesWithoutRevalidation({ 155 | headers: { sun: 'shining' }, 156 | }) 157 | ); 158 | }); 159 | 160 | it('Order is irrelevant', function() { 161 | const policy1 = new CachePolicy( 162 | { headers: { sun: 'shining', weather: 'nice' } }, 163 | { headers: { 'cache-control': 'max-age=5', vary: 'weather, sun' } } 164 | ); 165 | const policy2 = new CachePolicy( 166 | { headers: { sun: 'shining', weather: 'nice' } }, 167 | { headers: { 'cache-control': 'max-age=5', vary: 'sun, weather' } } 168 | ); 169 | 170 | assert( 171 | policy1.satisfiesWithoutRevalidation({ 172 | headers: { weather: 'nice', sun: 'shining' }, 173 | }) 174 | ); 175 | assert( 176 | policy1.satisfiesWithoutRevalidation({ 177 | headers: { sun: 'shining', weather: 'nice' }, 178 | }) 179 | ); 180 | assert( 181 | policy2.satisfiesWithoutRevalidation({ 182 | headers: { weather: 'nice', sun: 'shining' }, 183 | }) 184 | ); 185 | assert( 186 | policy2.satisfiesWithoutRevalidation({ 187 | headers: { sun: 'shining', weather: 'nice' }, 188 | }) 189 | ); 190 | }); 191 | }); 192 | --------------------------------------------------------------------------------