A platform for community discussion. Free, open, simple.
FIX: Prevent browsers from restoring stale documents in bfcache mode (#42207)
Régis Hanolf5cd83cab639
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rbindex dee67237eb6..21c8b9d7567 100644--- a/app/controllers/application_controller.rb+++ b/app/controllers/application_controller.rb@@ -97,14 +97,15 @@ class ApplicationController < ActionController::Baseresponse.cache_control[:extras] = ["immutable"]end+ def bfcache_compatibility_mode?+ SiteSetting.cache_control_bfcache_compatibility+ end+ helper_method :bfcache_compatibility_mode?+def dont_cache_pageif !response.headers["Cache-Control"] && response.cache_control.blank?- if SiteSetting.cache_control_bfcache_compatibility- response.cache_control[:no_cache] = true- else- response.cache_control[:no_cache] = true- response.cache_control[:extras] = ["no-store"]- end+ response.cache_control[:no_cache] = true+ response.cache_control[:extras] = [bfcache_compatibility_mode? ? "private" : "no-store"]endresponse.headers["Discourse-No-Onebox"] = "1" if SiteSetting.login_requiredenddiff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erbindex 521e727efff..5fcb3573082 100644--- a/app/views/layouts/application.html.erb+++ b/app/views/layouts/application.html.erb@@ -31,6 +31,17 @@<%= build_plugin_html 'server:before-script-load' %>+ <%- if bfcache_compatibility_mode? %>+ <script id="bfcache-stale-document-check" nonce="<%= csp_nonce_placeholder %>">+ {+ const nav = performance.getEntriesByType("navigation")[0];+ if (nav?.type === "back_forward" && nav.transferSize === 0) {+ location.reload();+ }+ }+ </script>+ <%- end %>+<script nonce="<%= csp_nonce_placeholder %>">window.EmberENV ??= {};window.EmberENV._DEFAULT_ASYNC_OBSERVERS = true;diff --git a/config/site_settings.yml b/config/site_settings.ymlindex b09e3c372da..913d550c6d1 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -3235,6 +3235,7 @@ security:area: "group_permissions"cache_control_bfcache_compatibility:default: false+ client: truehidden: trueonebox:diff --git a/frontend/discourse/app/instance-initializers/verify-session-after-restore.js b/frontend/discourse/app/instance-initializers/verify-session-after-restore.jsnew file mode 100644index 00000000000..9697573521d--- /dev/null+++ b/frontend/discourse/app/instance-initializers/verify-session-after-restore.js@@ -0,0 +1,50 @@+import { isTesting } from "discourse/lib/environment";+import getURL from "discourse/lib/get-url";++export async function restoredSessionMatches(bootedUserId) {+ try {+ const response = await fetch(getURL("/session/current.json"), {+ headers: { Accept: "application/json" },+ });++ if (response.status === 404) {+ return bootedUserId === null;+ }++ if (!response.ok) {+ return true;+ }++ const json = await response.json();+ return (json.current_user?.id ?? null) === bootedUserId;+ } catch {+ return true;+ }+}++export default {+ initialize(owner) {+ if (isTesting()) {+ return;+ }++ const siteSettings = owner.lookup("service:site-settings");+ if (!siteSettings.cache_control_bfcache_compatibility) {+ return;+ }++ const bootedUserId = owner.lookup("service:current-user")?.id ?? null;++ this.handler = async (event) => {+ if (event.persisted && !(await restoredSessionMatches(bootedUserId))) {+ window.location.reload();+ }+ };++ window.addEventListener("pageshow", this.handler);+ },++ teardown() {+ window.removeEventListener("pageshow", this.handler);+ },+};diff --git a/frontend/discourse/tests/unit/instance-initializers/verify-session-after-restore-test.js b/frontend/discourse/tests/unit/instance-initializers/verify-session-after-restore-test.jsnew file mode 100644index 00000000000..ebd2014e218--- /dev/null+++ b/frontend/discourse/tests/unit/instance-initializers/verify-session-after-restore-test.js@@ -0,0 +1,68 @@+import { module, test } from "qunit";+import sinon from "sinon";+import { restoredSessionMatches } from "discourse/instance-initializers/verify-session-after-restore";++module(+ "Unit | Instance Initializer | verify-session-after-restore",+ function () {+ function stubSession(status, body = null) {+ sinon+ .stub(window, "fetch")+ .resolves(new Response(body && JSON.stringify(body), { status }));+ }++ test("matches when the same user is still logged in", async function (assert) {+ stubSession(200, { current_user: { id: 1 } });++ assert.true(await restoredSessionMatches(1), "same user id matches");+ });++ test("does not match when a different user is logged in", async function (assert) {+ stubSession(200, { current_user: { id: 2 } });++ assert.false(await restoredSessionMatches(1), "user id changed");+ });++ test("does not match when the session became anonymous", async function (assert) {+ stubSession(404);++ assert.false(+ await restoredSessionMatches(1),+ "document has a user but the session is anonymous"+ );+ });++ test("matches when both the document and the session are anonymous", async function (assert) {+ stubSession(404);++ assert.true(await restoredSessionMatches(null), "still anonymous");+ });++ test("does not match when the session gained a user", async function (assert) {+ stubSession(200, { current_user: { id: 1 } });++ assert.false(+ await restoredSessionMatches(null),+ "anonymous document but the session is logged in"+ );+ });++ test("matches on server errors", async function (assert) {+ stubSession(500);++ assert.true(+ await restoredSessionMatches(1),+ "server errors do not trigger a reload"+ );+ });++ test("matches on network failures", async function (assert) {+ sinon.stub(window, "fetch").rejects(new TypeError("network down"));++ assert.true(+ await restoredSessionMatches(1),+ "network failures do not trigger a reload"+ );+ });+ }+);diff --git a/spec/requests/application_controller_spec.rb b/spec/requests/application_controller_spec.rbindex e1ee665556b..4cb3f0ddc0a 100644--- a/spec/requests/application_controller_spec.rb+++ b/spec/requests/application_controller_spec.rb@@ -53,27 +53,34 @@ RSpec.describe ApplicationController docontext "when cache_control_bfcache_compatibility is enabled" dobefore { SiteSetting.cache_control_bfcache_compatibility = true }- it "sets bfcache-compatible cache control headers" do+ it "sets bfcache-compatible cache control headers and includes the stale document reload script" doget "/latest"expect(response.status).to eq(200)- expect(response.headers["Cache-Control"]).to eq("no-cache")+ expect(response.headers["Cache-Control"]).to eq("no-cache, private")+ expect(response.body).to include("bfcache-stale-document-check")endit "sets bfcache-compatible cache control headers on 404" doget "/invalid-urlllllllllll"expect(response.status).to eq(404)- expect(response.headers["Cache-Control"]).to eq("no-cache")+ expect(response.headers["Cache-Control"]).to eq("no-cache, private")endit "sets bfcache-compatible cache control headers on 403" doget "/latest.json", headers: { HTTP_API_KEY: "invalid-api-key" }expect(response.status).to eq(403)- expect(response.headers["Cache-Control"]).to eq("no-cache")+ expect(response.headers["Cache-Control"]).to eq("no-cache, private")endend++ it "does not include the stale document reload script in the HTML document by default" do+ get "/latest"++ expect(response.body).not_to include("bfcache-stale-document-check")+ endendcontext "when visiting an invalid URL" do