diff --git a/members_map/__init__.py b/members_map/__init__.py index 3d20a81..ba3c577 100644 --- a/members_map/__init__.py +++ b/members_map/__init__.py @@ -1,6 +1,9 @@ +import hashlib import logging import os import secrets +from functools import cache +from pathlib import Path from flask import Flask @@ -27,6 +30,17 @@ def create_app(config: dict | None = None) -> Flask: db.init_app(app) app.register_blueprint(views.bp) + @cache + def static_version(filename: str) -> str: + path = Path(app.static_folder) / filename + return hashlib.sha256(path.read_bytes()).hexdigest()[:12] + + @app.url_defaults + def version_static_urls(endpoint: str, values: dict) -> None: + # Cloudflare caches /static/ for hours, so changed files need new URLs + if endpoint == "static" and "v" not in values: + values["v"] = static_version(values["filename"]) + @app.after_request def set_referrer_policy(response): # OpenStreetMap's tile servers refuse requests without a Referer diff --git a/tests/test_views.py b/tests/test_views.py index c10b45f..feffa97 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -1,5 +1,7 @@ import base64 +import hashlib import json +from pathlib import Path import pytest @@ -63,6 +65,16 @@ def test_tiles_use_https_osm_without_subdomains(client): assert "{s}" not in js +def test_static_urls_are_versioned_by_content(app, client): + css = (Path(app.static_folder) / "style.css").read_bytes() + version = hashlib.sha256(css).hexdigest()[:12] + + html = client.get("/").text + + assert f"/static/style.css?v={version}" in html + assert "/static/vendor/leaflet.js?v=" in html + + def test_referrer_policy_header_sends_origin(client): response = client.get("/")