Load the owner's Google tag on every page
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
0d6197bedd
9 files changed
+112
-7
No files matched your search
@@ -1,5 +1,9 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-11-20 - A Google tag to count visits
|
||||
|
||||
- Every page now loads a Google tag, so that visits can be counted with Google Analytics. The About page no longer says the site has no tracking or analytics.
|
||||
|
||||
## 2026-11-20 - Pages for national parks, mountain ranges and wilderness areas
|
||||
|
||||
- There are now 81 pages for named places: 21 national parks and other Park Service units (such as the Blue Ridge Parkway and Glen Canyon National Recreation Area), 36 mountain ranges and other named landforms (the Colorado Plateau and the Mogollon Rim are labelled and worded as what they are, "on the Colorado Plateau") and 24 wilderness areas, each with 3 or more trails. Every page has the search box and the filters that have something to offer, however few trails it holds, and every title keeps its count of trails. They answer searches such as "Wind River Range hikes" or "backpacking in Glacier National Park", and each has the same filter bar, trail rows and map as a state page. A place with fewer than 3 trails has no page: the Uinta Mountains have one. A range or wilderness area that holds exactly the trails of the park of the same name (Great Smoky Mountains, Olympic Mountains) has no page of its own either, and six places that were only another name for trails already on a neighbour's page are left out: the Longfellow Mountains, Finger Lakes, Gore Range, Mosquito Range, Great Western Divide and Russian Wilderness.
|
||||
|
||||
+1
-1
@@ -302,7 +302,7 @@ def maintainer_section(site):
|
||||
<li>The records and the compiled index are public domain (CC0 1.0). Each track keeps the licence of its source.</li>
|
||||
<li>Every fact in a record names the page it was read on, and each record keeps a history of what changed and why.</li>
|
||||
<li>To correct a fact, suggest a trail or ask for a track or logo to be removed, {ask}. Every trail page has its own “Report a problem” link.</li>
|
||||
<li>The site has no ads, no accounts, no tracking and no analytics. Your theme, units and saved trails stay in your own browser. Maps load their tiles from OpenFreeMap.</li>
|
||||
<li>The site has no ads and no accounts. Your theme, units and saved trails stay in your own browser. Maps load their tiles from OpenFreeMap.</li>
|
||||
</ul>
|
||||
</section>
|
||||
"""
|
||||
|
||||
@@ -216,6 +216,17 @@ def skip_links(body):
|
||||
return out
|
||||
|
||||
|
||||
# The owner's Google tag, as given; only the container id comes from site.toml (google_tag).
|
||||
# The inline script's hash is in the Content-Security-Policy (web/static/_headers); a test keeps them equal.
|
||||
GOOGLE_TAG_INLINE = """
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
"""
|
||||
GOOGLE_TAG = ('<script async src="https://www.googletagmanager.com/gtm.js?id={id}"></script>\n'
|
||||
'<script>' + GOOGLE_TAG_INLINE + '</script>')
|
||||
|
||||
|
||||
def layout(title, body, *, path, description="", maps=False, outdoor=False, scripts=(), data=None, site=None,
|
||||
jsonld=None, og_type="website", noindex=False, image="", image_alt="", alternates=()):
|
||||
"""Return a complete HTML document.
|
||||
@@ -262,6 +273,8 @@ def layout(title, body, *, path, description="", maps=False, outdoor=False, scri
|
||||
f"<title>{esc(tag)}</title>",
|
||||
f'<meta name="description" content="{esc(description)}">',
|
||||
]
|
||||
if site.google_tag:
|
||||
head.append(GOOGLE_TAG.replace("{id}", esc(site.google_tag)))
|
||||
if noindex:
|
||||
head.append('<meta name="robots" content="noindex">')
|
||||
if canonical:
|
||||
|
||||
+5
-2
@@ -12,7 +12,7 @@ class Site:
|
||||
"""The settings every page needs. Build one with load()."""
|
||||
|
||||
def __init__(self, name, tagline, base_url="", repo_url="", repo_branch="main",
|
||||
contact_url="", name_lang=None, home_title="", maintainer_name="", maintainer_url=""):
|
||||
contact_url="", name_lang=None, home_title="", maintainer_name="", maintainer_url="", google_tag=""):
|
||||
if not name:
|
||||
raise ValueError("site.toml: name must not be empty")
|
||||
self.name = name
|
||||
@@ -27,6 +27,8 @@ class Site:
|
||||
# named in the structured data. Both are public by the owner's choice.
|
||||
self.maintainer_name = maintainer_name.strip()
|
||||
self.maintainer_url = maintainer_url.strip()
|
||||
# Google tag container id (GTM-XXXXXXX): when set, every page loads the tag; empty: none.
|
||||
self.google_tag = google_tag.strip()
|
||||
# record id -> language tag of its name ("fr"), for names that are not English
|
||||
self.name_lang = dict(name_lang or {})
|
||||
|
||||
@@ -123,7 +125,8 @@ def from_file(path):
|
||||
repo_branch=data.get("repo_branch", "main"),
|
||||
contact_url=data.get("contact_url", ""), name_lang=data.get("name_lang", {}),
|
||||
home_title=data.get("home_title", ""),
|
||||
maintainer_name=data.get("maintainer_name", ""), maintainer_url=data.get("maintainer_url", ""))
|
||||
maintainer_name=data.get("maintainer_name", ""), maintainer_url=data.get("maintainer_url", ""),
|
||||
google_tag=data.get("google_tag", ""))
|
||||
|
||||
|
||||
@functools.cache
|
||||
|
||||
@@ -40,6 +40,10 @@ contact_url = ""
|
||||
maintainer_name = "Stephen Waits"
|
||||
maintainer_url = "https://github.com/swaits"
|
||||
|
||||
# Google tag container id. When set, every page loads the tag (web/olt/layout.py) to count visits;
|
||||
# the Content-Security-Policy in web/static/_headers allows it. Empty: no tag.
|
||||
google_tag = "GTM-WWLZSH6Q"
|
||||
|
||||
# Language of record names that are not English, by record id (a BCP 47 tag).
|
||||
# Every place a page shows one of these names as text marks it with lang="..",
|
||||
# so screen readers pronounce it in that language.
|
||||
|
||||
+4
-2
@@ -13,7 +13,9 @@
|
||||
# Netlify applies all of them, so each header is set by one rule only
|
||||
# (web/tests/test_headers.py checks this against the built site).
|
||||
|
||||
# Security headers for every response. No inline scripts or style elements:
|
||||
# Security headers for every response. The one inline script is the Google tag's data-layer
|
||||
# setup (allowed by its hash, GOOGLE_TAG_INLINE in web/olt/layout.py) and its loader comes from
|
||||
# www.googletagmanager.com. Otherwise no inline scripts or style elements:
|
||||
# pages load same-origin scripts and styles, MapLibre and the contour add-on
|
||||
# run from blob: workers, map images are self/data:/blob:, fonts are
|
||||
# self-hosted, and tiles, glyphs and sprites are fetched from OpenFreeMap
|
||||
@@ -26,7 +28,7 @@
|
||||
/*
|
||||
X-Content-Type-Options: nosniff
|
||||
Referrer-Policy: strict-origin-when-cross-origin
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; worker-src 'self' blob:; child-src 'self' blob:; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https://tiles.openfreemap.org https://s3.amazonaws.com/elevation-tiles-prod/terrarium/; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self' https://www.googletagmanager.com 'sha256-jYHg7tXSuuVUqjy+JeRT8vyG97+Spkw5IFHdQEBbmrw='; style-src 'self'; style-src-attr 'unsafe-inline'; worker-src 'self' blob:; child-src 'self' blob:; img-src 'self' data: blob: https://*.google-analytics.com https://*.googletagmanager.com; font-src 'self'; connect-src 'self' https://tiles.openfreemap.org https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com https://s3.amazonaws.com/elevation-tiles-prod/terrarium/; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
|
||||
# Site data. Matched by file type, not /data/*, so the pages under /data/
|
||||
# (/data/, /data/schema/, /data/changelog/) revalidate like every other page.
|
||||
|
||||
@@ -223,7 +223,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
def test_the_content_security_policy_stays_strict(self):
|
||||
csp = self.value("/index.html", "Content-Security-Policy")
|
||||
self.assertIn("default-src 'self'", csp)
|
||||
self.assertIn("script-src 'self';", csp)
|
||||
self.assertIn("script-src 'self' https://www.googletagmanager.com 'sha256-", csp)
|
||||
self.assertIn("style-src 'self';", csp)
|
||||
self.assertNotIn("unsafe-eval", csp)
|
||||
self.assertNotIn("script-src 'self' 'unsafe-inline'", csp)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""The Google tag: on every built page exactly once, only when site.toml sets it, and allowed by the CSP."""
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import layout, pages, site # noqa: E402
|
||||
|
||||
TAG_ID = "GTM-TEST1234"
|
||||
LOADER = f'<script async src="https://www.googletagmanager.com/gtm.js?id={TAG_ID}"></script>'
|
||||
|
||||
|
||||
def html_files(root):
|
||||
for base, _, names in os.walk(root):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
yield os.path.join(base, n)
|
||||
|
||||
|
||||
def build(out, tag):
|
||||
cfg = os.path.join(os.path.dirname(out), "site.toml")
|
||||
with open(os.path.join(WEB, "site.toml"), encoding="utf-8") as f:
|
||||
text = re.sub(r'(?m)^google_tag = .*\n', "", f.read())
|
||||
with open(cfg, "w", encoding="utf-8") as f:
|
||||
f.write((f'google_tag = "{tag}"\n' if tag else "") + text)
|
||||
code = ("import sys; sys.path.insert(0, %r); from olt import site; "
|
||||
"site.SITE_TOML = %r; site.load.cache_clear(); import build; build.main(['--out', %r])"
|
||||
% (WEB, cfg, out))
|
||||
subprocess.run([sys.executable, "-c", code], check=True, cwd=WEB,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
class GoogleTagTest(unittest.TestCase):
|
||||
def test_every_built_page_has_the_tag_once_and_none_without_the_setting(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
on, off = os.path.join(tmp, "on", "site"), os.path.join(tmp, "off", "site")
|
||||
for out, tag in ((on, TAG_ID), (off, "")):
|
||||
os.makedirs(os.path.dirname(out))
|
||||
build(out, tag)
|
||||
pages_on = list(html_files(on))
|
||||
self.assertGreater(len(pages_on), 200)
|
||||
for name in ("404.html", os.path.join("saved", "index.html"), "index.html"):
|
||||
self.assertTrue(os.path.isfile(os.path.join(on, name)), name)
|
||||
for path in pages_on:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
head = text[:text.index("</head>")]
|
||||
self.assertEqual(text.count("googletagmanager.com"), 1, path)
|
||||
self.assertEqual(text.count(LOADER), 1, path)
|
||||
self.assertEqual(text.count("gtag('js', new Date());"), 1, path)
|
||||
self.assertIn(LOADER, head, path)
|
||||
for path in html_files(off):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
self.assertNotIn("googletagmanager", text, path)
|
||||
self.assertNotIn("gtag", text, path)
|
||||
|
||||
def test_the_real_setting_is_the_owners_container(self):
|
||||
self.assertEqual(site.load().google_tag, "GTM-WWLZSH6Q")
|
||||
|
||||
def test_the_policy_allows_the_tag_and_its_inline_script_by_hash(self):
|
||||
digest = base64.b64encode(hashlib.sha256(layout.GOOGLE_TAG_INLINE.encode()).digest()).decode()
|
||||
with open(os.path.join(WEB, "static", "_headers"), encoding="utf-8") as f:
|
||||
policy = next(l for l in f if "Content-Security-Policy:" in l)
|
||||
script_src = re.search(r"script-src ([^;]*);", policy).group(1)
|
||||
self.assertIn("https://www.googletagmanager.com", script_src)
|
||||
self.assertIn(f"'sha256-{digest}'", script_src)
|
||||
self.assertNotIn("unsafe-inline", script_src)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -74,7 +74,7 @@ class MaintainerSettings(unittest.TestCase):
|
||||
self.assertIn(f'<a href="{SITE.issue_chooser_url}">open an issue on GitHub</a>', body)
|
||||
section = body[body.index('id="who-maintains"'):]
|
||||
section = section[:section.index("</section>")]
|
||||
for claim in ("public domain", "names the page it was read on", "no ads, no accounts, no tracking and no analytics"):
|
||||
for claim in ("public domain", "names the page it was read on", "no ads and no accounts"):
|
||||
self.assertIn(claim, section)
|
||||
self.assertNotRegex(section, r"[\w.]+@[\w.]+", "no email address")
|
||||
|
||||
|
||||
Reference in new issue
Block a user