Skip to content

Self-improving AI Employees for everyone

2.5 KB
Raw Blame
diff --git a/index.js b/index.js
index 56c26025074cbcf218e3ec4d810662da93f8024e..fe659d74a73dbaf1f99029ad800ce554e155e0b1 100644
--- a/index.js
+++ b/index.js
@@ -369,6 +369,21 @@ module.exports = class CachePolicy {
         };
     }
 
+    _requiresRevalidation() {
+        // Stale allowances cannot override storage or reuse prohibitions.
+        return !!(
+            !this.storable() ||
+            this._rescc['no-cache'] ||
+            this._rescc['must-revalidate'] ||
+            this._resHeaders.vary === '*' ||
+            (this._isShared &&
+                (this._rescc['proxy-revalidate'] ||
+                    (this._resHeaders['set-cookie'] &&
+                        !this._rescc.public &&
+                        !this._rescc.immutable)))
+        );
+    }
+
     /**
      * Checks if the given request matches this cache entry, and how the cache can be used to satisfy it. Returns an object with:
      *
@@ -396,7 +411,7 @@ module.exports = class CachePolicy {
         this._assertRequestHasHeaders(req);
 
         // In all circumstances, a cache MUST NOT ignore the must-revalidate directive
-        if (this._rescc['must-revalidate']) {
+        if (this._requiresRevalidation()) {
             return this._evaluateRequestMissResult(req);
         }
 
@@ -706,7 +721,8 @@ module.exports = class CachePolicy {
      * @returns {boolean} `true` if `stale-if-error` condition allows use of a stale response.
      */
     _useStaleIfError() {
-        return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();
+        return !this._requiresRevalidation() &&
+            this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();
     }
 
     /** See `evaluateRequest()` for a more complete solution
@@ -714,7 +730,8 @@ module.exports = class CachePolicy {
      */
     useStaleWhileRevalidate() {
         const swr = toNumberOrZero(this._rescc['stale-while-revalidate']);
-        return swr > 0 && this.maxAge() + swr > this.age();
+        return !this._requiresRevalidation() &&
+            swr > 0 && this.maxAge() + swr > this.age();
     }
 
     /**
@@ -855,7 +872,7 @@ module.exports = class CachePolicy {
     revalidatedPolicy(request, response) {
         this._assertRequestHasHeaders(request);
 
-        if (this._useStaleIfError() && isErrorResponse(response)) {
+        if (this._requestMatches(request, true) && this._useStaleIfError() && isErrorResponse(response)) {
           return {
               policy: this,
               modified: false,