From 06dc928ce73a8e5888bd0f574fb6351a4274f286 Mon Sep 17 00:00:00 2001 From: Dan Fabulich Date: Tue, 3 Dec 2024 21:02:57 -0800 Subject: [PATCH] Only allow client to force unconditional request if options permit it Koa's `ctx.fresh` uses https://github.com/jshttp/fresh/blob/v0.5.2/index.js#L43-L49 which always honors `Cache-Control: no-cache` in the request header. That's unfortunate, because Chrome passes a `Cache-Control: no-cache` request header if you check "Disable cache" in Chrome Dev Tools, making it difficult/confusing to verify that nginx conditional requests are working. In this commit, we use `ctx.fresh` only if our `options` object allows nginx itself to support bypassing the cache. If we don't support clients bypassing the cache, then we'll return `304 Not Modified` if `if-modified-since` matches `last-modified`, regardless of what other headers the client sends. --- app/src/app.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/app/src/app.js b/app/src/app.js index 0989821..2a64f2c 100644 --- a/app/src/app.js +++ b/app/src/app.js @@ -93,7 +93,7 @@ export default class UnboxApp { try { await next() } finally { - console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}"`) + console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}" "${ctx.headers['cache-control']}"`) } }) @@ -115,6 +115,17 @@ export default class UnboxApp { ctx.set('Cache-Control', `max-age=1`) + const ctxFresh = () => { + if (this.options.nginx?.cache?.support_bypass) { + // ctx fresh uses https://github.com/jshttp/fresh/blob/v0.5.2/index.js#L43-L49 + // which always honors `Cache-Control: no-cache` in the request header + return ctx.fresh + } else { + const modifiedSince = ctx.request.headers['if-modified-since'] + return !!modifiedSince && modifiedSince === ctx.response.headers['last-modified'] + } + } + // Front page if (request_path === '/') { // Allow the IF Archive admins to direct us to update the index as soon as it changes @@ -214,7 +225,7 @@ export default class UnboxApp { // Send and check the Last-Modified/If-Modified-Since headers ctx.status = 200 ctx.lastModified = new Date(details.date) - if (ctx.fresh) { + if (ctxFresh()) { ctx.status = 304 return } @@ -375,7 +386,7 @@ export default class UnboxApp { // Send and check the Last-Modified/If-Modified-Since headers ctx.status = 200 ctx.lastModified = new Date(details.date) - if (ctx.fresh) { + if (ctxFresh()) { ctx.status = 304 return }