From dc0443b43b61dec74378703325e5e9cc67b8ec5c Mon Sep 17 00:00:00 2001 From: Edwin Veldhuizen Date: Tue, 14 May 2024 22:39:34 +0200 Subject: [PATCH] [interpreter] prevent caching private responses server-side --- src/header/interpreter.ts | 14 ++++++++++---- test/header/interpreter.test.ts | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/header/interpreter.ts b/src/header/interpreter.ts index 7d23b461..e9680bf8 100644 --- a/src/header/interpreter.ts +++ b/src/header/interpreter.ts @@ -8,12 +8,18 @@ export const defaultHeaderInterpreter: HeaderInterpreter = (headers) => { const cacheControl: unknown = headers[Header.CacheControl]; if (cacheControl) { - const { noCache, noStore, maxAge, maxStale, immutable, staleWhileRevalidate } = parse( - String(cacheControl) - ); + const { + noCache, + noStore, + maxAge, + maxStale, + immutable, + staleWhileRevalidate, + private: _private + } = parse(String(cacheControl)); // Header told that this response should not be cached. - if (noCache || noStore) { + if (noCache || noStore || (_private && typeof window === 'undefined')) { return 'dont cache'; } diff --git a/test/header/interpreter.test.ts b/test/header/interpreter.test.ts index bbf7b2f7..94234c46 100644 --- a/test/header/interpreter.test.ts +++ b/test/header/interpreter.test.ts @@ -44,6 +44,26 @@ describe('Header Interpreter', () => { assert.deepEqual(result, { cache: 1000 * 60 * 60 * 24 * 365 }); }); + it("Don't cache private, no-cache and no-store", () => { + const privateResult = defaultHeaderInterpreter({ + [Header.CacheControl]: 'private' + }); + + assert.deepEqual(privateResult, 'dont cache'); + + const noCacheResult = defaultHeaderInterpreter({ + [Header.CacheControl]: 'no-cache' + }); + + assert.deepEqual(noCacheResult, 'dont cache'); + + const noStoreResult = defaultHeaderInterpreter({ + [Header.CacheControl]: 'no-store' + }); + + assert.deepEqual(noStoreResult, 'dont cache'); + }); + it('MaxAge=10 and Age=3 and StaleWhileRevalidate Headers', () => { const result = defaultHeaderInterpreter({ [Header.CacheControl]: 'max-age=10, stale-while-revalidate=5',