feat(analytics): Cloudflare Web Analytics via the manual beacon snippet (#77)

The dashboard site is switched to JS-snippet (manual) mode; this adds the snippet.

- src/components/CfBeacon.astro renders the owner's snippet as-is (`type="module"`,
  `data-cf-beacon` with the public site token) in the <head> of BaseLayout and
  ErrorLayout. Module scripts load deferred, so it stays off the first-paint path.
  `type="module"` is safe: the CDN answers CORS with `*`, and the beacon falls back to
  querySelector("script[data-cf-beacon]") when document.currentScript is null.
- Only production builds report: PUBLIC_CF_BEACON (astro:env, client/public) defaults
  to true only when WORKERS_CI=1 and WORKERS_CI_BRANCH=main, i.e. Workers Builds on
  main. CI, Lighthouse CI and branch previews render nothing. Overridable per build.
- CSP: script-src += https://static.cloudflareinsights.com, connect-src +=
  https://cloudflareinsights.com (where manual-mode beacons report). The CSP guard
  skips src-only scripts, and the built pages carry both hosts.

Docs: 07 §12 now documents manual mode (and why automatic must stay off — it would
double-count and inject an inline script the CSP blocks), 06 §5 lists the one external
script, 14 §2 notes it is deferred and absent from Lighthouse CI.

Verified with PUBLIC_CF_BEACON=true: 63/63 pages carry exactly one beacon tag; CSP
check ok.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 authored and GitHub committed 2026-10-07 19:33:57 +07:00
1 parent e2344fb39b
commit 48d4e7bbdc
7 files changed
+56 -6

No files matched your search

+21 -3
View File
@@ -33,6 +33,12 @@ const themeBootstrap = {
},
};
// Cloudflare Web Analytics beacon: only in builds made by Workers Builds for main
// (WORKERS_CI / WORKERS_CI_BRANCH are injected there), so CI, Lighthouse and branch
// previews never report page views. Overridable with PUBLIC_CF_BEACON=true|false.
const CF_BEACON_DEFAULT =
process.env.WORKERS_CI === "1" && process.env.WORKERS_CI_BRANCH === "main";
// https://astro.build/config
export default defineConfig({
site: "https://poli0981.dev",
@@ -74,6 +80,11 @@ export default defineConfig({
TURNSTILE_SECRET: envField.string({ context: "server", access: "secret", optional: true }),
GITHUB_ISSUES_TOKEN: envField.string({ context: "server", access: "secret", optional: true }),
DISCORD_WEBHOOK_BUG: envField.string({ context: "server", access: "secret", optional: true }),
PUBLIC_CF_BEACON: envField.boolean({
context: "client",
access: "public",
default: CF_BEACON_DEFAULT,
}),
},
},
@@ -151,7 +162,8 @@ export default defineConfig({
// youtube-nocookie: video facade; challenges.cloudflare.com: Turnstile widget iframe.
"frame-src https://www.youtube-nocookie.com https://challenges.cloudflare.com",
// challenges.cloudflare.com: Turnstile client XHRs (siteverify is server-side).
"connect-src 'self' https://challenges.cloudflare.com",
// cloudflareinsights.com: Web Analytics beacon reports (manual snippet mode).
"connect-src 'self' https://challenges.cloudflare.com https://cloudflareinsights.com",
"font-src 'self'",
"base-uri 'none'",
"form-action 'self'",
@@ -159,9 +171,15 @@ export default defineConfig({
],
// 'self' keeps dynamically-imported island chunks loadable; 'wasm-unsafe-eval'
// is pre-baked for Pagefind's WebAssembly; challenges.cloudflare.com loads the
// Turnstile api.js (bug-report captcha, docs 10).
// Turnstile api.js (bug-report captcha, docs 10); static.cloudflareinsights.com
// serves the Web Analytics beacon (src/components/CfBeacon.astro).
scriptDirective: {
resources: ["'self'", "'wasm-unsafe-eval'", "https://challenges.cloudflare.com"],
resources: [
"'self'",
"'wasm-unsafe-eval'",
"https://challenges.cloudflare.com",
"https://static.cloudflareinsights.com",
],
},
styleDirective: { resources: ["'self'"] },
},
+1 -1
View File
@@ -48,7 +48,7 @@ Không secret nào trong repo/`wrangler.jsonc`; `.dev.vars` nằm trong `.gitign
## 5. Nội dung nhúng bên thứ ba
- YouTube: **click-to-load facade** (thumb tĩnh từ i.ytimg.com) → bấm mới tạo iframe `youtube-nocookie.com`. Vừa nhanh vừa gọn Privacy Policy.
- Không font/CDN/script bên ngoài nào khác — mọi asset self-host.
- Ngoại lệ duy nhất cho script bên ngoài: beacon Cloudflare Web Analytics (`static.cloudflareinsights.com`, báo về `cloudflareinsights.com`) — `type=module` nên tải trễ, không cookie, chỉ có trong bản build production của Workers Builds (`src/components/CfBeacon.astro`). CSP mở đúng 2 host đó (`script-src` + `connect-src`). Còn lại: không font/CDN/script ngoài — mọi asset self-host.
## 6. Supply chain (repo private — lưu ý riêng)
+6 -1
View File
@@ -85,7 +85,12 @@ Mail của domain chạy trên **Google Workspace** (MX → `aspmx.l.google.com`
## 12. Web Analytics
Account → Analytics & Logs → **Web Analytics → Add site** → chọn zone (tự động qua proxy, không cần gắn script — chọn chế độ automatic). Không cookie, khớp Privacy Policy.
Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở chế độ **JS snippet (manual)** — *tắt* tự động chèn, nếu không mỗi trang sẽ có 2 beacon (và beacon tự chèn là script inline mà CSP chặn).
- Snippet nằm ở `src/components/CfBeacon.astro` (token là site tag công khai, không phải secret), chèn vào `<head>` của `BaseLayout` + `ErrorLayout`.
- Chỉ render khi build trên Workers Builds nhánh `main` (`WORKERS_CI=1` + `WORKERS_CI_BRANCH=main` → `PUBLIC_CF_BEACON`), nên CI/Lighthouse/preview không làm bẩn số liệu. Ép bật/tắt: biến build `PUBLIC_CF_BEACON=true|false`.
- CSP: `script-src https://static.cloudflareinsights.com`, `connect-src https://cloudflareinsights.com`.
- Không cookie, khớp Privacy Policy §2.
## 13. Checklist nghiệm thu
+1 -1
View File
@@ -22,7 +22,7 @@
- **Font**: chỉ 4 family, subset latin+vietnamese, preload đúng 2 file, `size-adjust` fallback để CLS≈0. Literata chỉ nạp ở trang đọc.
- **Ảnh**: mọi ảnh qua Astro Image (AVIF ưu tiên), `loading=lazy` trừ LCP (`fetchpriority=high`), khai width/height luôn.
- **CSS**: Tailwind v4 tự purge; grain/scanline bằng 1 PNG nhỏ + CSS, không canvas chạy nền.
- **Third-party = 0** ở first paint (YouTube facade, widget đọc KV nội bộ).
- **Third-party = 0** ở first paint (YouTube facade, widget đọc KV nội bộ). Beacon Web Analytics là module script (tải defer, ~10 KB) nên không chặn render; nó chỉ có trong bản build production (không có trong Lighthouse CI).
## 3. Kiểm tra
+23
View File
@@ -0,0 +1,23 @@
---
// Cloudflare Web Analytics, manual JS-snippet mode (docs 07 §12). Cookie-free; reports to
// cloudflareinsights.com, which is why the CSP allows that host for script-src and
// connect-src. `type="module"` works: the CDN answers CORS with `*`, and the beacon falls
// back to `querySelector("script[data-cf-beacon]")` when `document.currentScript` is null.
//
// Rendered only for production builds made by Workers Builds on main (see PUBLIC_CF_BEACON
// in astro.config.mjs) so CI, Lighthouse and branch previews never add page views.
import { PUBLIC_CF_BEACON } from "astro:env/client";
const CF_BEACON_TOKEN = "349c7ecb1c304ff8985c878004df42b3"; // public site tag, not a secret
---
{
PUBLIC_CF_BEACON && (
<script
is:inline
type="module"
src="https://static.cloudflareinsights.com/beacon.min.js"
data-cf-beacon={JSON.stringify({ token: CF_BEACON_TOKEN })}
/>
)
}
+2
View File
@@ -9,6 +9,7 @@ import MenuSheet from "../components/MenuSheet.svelte";
import SearchModal from "../components/SearchModal.svelte";
import LegalGateSheet from "../components/LegalGateSheet.svelte";
import ReportDialog from "../components/ReportDialog.astro";
import CfBeacon from "../components/CfBeacon.astro";
import { resolveSeo, SITE, hreflangPair, personSchema, type SeoInput } from "../lib/seo";
import { toLocale, useTranslations } from "../i18n";
import { menuNav, legalNav } from "../lib/nav";
@@ -63,6 +64,7 @@ const onLegalPage = /\/legal(\/|$)/.test(Astro.url.pathname);
<title>{seo.title}</title>
<meta name="description" content={seo.description} />
<CfBeacon />
<link rel="canonical" href={seo.canonical} />
{seo.noindex && <meta name="robots" content="noindex, nofollow" />}
+2
View File
@@ -2,6 +2,7 @@
import "../styles/global.css";
import { Font } from "astro:assets";
import ReportDialog from "../components/ReportDialog.astro";
import CfBeacon from "../components/CfBeacon.astro";
interface Props {
title: string;
@@ -26,6 +27,7 @@ const { title, showLinks = true, showReport = false, ref } = Astro.props;
{/* Only the body font — no display/reading font, no islands (docs 09 §3.1). */}
<Font cssVariable="--ff-body" preload />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<CfBeacon />
</head>
<body>