cursedbelt-server 4.4.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,144 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { foreignScriptSources, scriptsRefusedByCsp } from "./injectedScripts";
3
+ import { WEB_ANALYTICS_BEACON_ORIGIN, WEB_ANALYTICS_TAG } from "./webAnalytics";
4
+
5
+ const PAGE = "https://collections.cursedalchemy.com/";
6
+
7
+ /**
8
+ * The tag Cloudflare's Automatic Setup appended, byte-for-byte as the zone emitted it on
9
+ * 2026-09-18 — pinned path, integrity hash, `crossorigin` and all. It is kept in its
10
+ * AUTOMATIC spelling on purpose: this is the shape that was arriving unasked-for, and a
11
+ * checker that only recognised the manual snippet would go quiet the moment somebody turned
12
+ * auto-install back on.
13
+ */
14
+ const BEACON =
15
+ `<script type="module" src="https://static.cloudflareinsights.com/beacon.min.js/v31edd6df95cf4e85bb4c19e7a9bdbcba1788362987495"` +
16
+ ` integrity="sha512-iIg7k2xntmwu6/uSb5tpc/hySgZc4eoL31yB29W6tJFo2akwjPWcEqnCEdJvGexCL0KEQwVYv5BlowfhVz26hg=="` +
17
+ ` data-cf-beacon='{"version":"2024.11.0","token":"bd88d63678b64bc89f9702f48846bc88","r":1,"spa":2}' crossorigin="anonymous"></script>`;
18
+
19
+ /** A real app shell: one inline script, one same-origin module. Neither is foreign. */
20
+ const SHELL = `<!doctype html><html><head>
21
+ <script>try { document.documentElement.classList.toggle("dark", true); } catch (e) {}</script>
22
+ <script type="module" crossorigin src="/assets/index-edXXbfEe.js"></script>
23
+ </head><body><div id="root"></div></body></html>`;
24
+
25
+ describe("foreignScriptSources", () => {
26
+ test("an app's own shell has none — inline and same-origin are not findings", () => {
27
+ expect(foreignScriptSources(SHELL, PAGE)).toEqual([]);
28
+ });
29
+
30
+ test("finds the beacon the edge appended, single-quoted attribute and all", () => {
31
+ const found = foreignScriptSources(SHELL.replace("</head>", `${BEACON}</head>`), PAGE);
32
+ expect(found).toHaveLength(1);
33
+ expect(found[0]?.origin).toBe(WEB_ANALYTICS_BEACON_ORIGIN);
34
+ });
35
+
36
+ test("the MANUAL snippet is found too, and names the same origin", () => {
37
+ const found = foreignScriptSources(SHELL.replace("</head>", `${WEB_ANALYTICS_TAG}</head>`), PAGE);
38
+ expect(found).toHaveLength(1);
39
+ expect(found[0]?.origin).toBe(WEB_ANALYTICS_BEACON_ORIGIN);
40
+ });
41
+
42
+ test("an absolute URL back to this app's own origin is not foreign", () => {
43
+ const html = `<script src="https://collections.cursedalchemy.com/assets/x.js"></script>`;
44
+ expect(foreignScriptSources(html, PAGE)).toEqual([]);
45
+ });
46
+
47
+ test("data: and blob: sources are skipped — no host was injected", () => {
48
+ const html = `<script src="data:text/javascript,void 0"></script><script src=blob:https://x/y></script>`;
49
+ expect(foreignScriptSources(html, PAGE)).toEqual([]);
50
+ });
51
+
52
+ test("two tags naming the same foreign origin are reported once per src", () => {
53
+ const html = `${BEACON}${BEACON}<script src="https://static.cloudflareinsights.com/other.js"></script>`;
54
+ expect(foreignScriptSources(html, PAGE)).toHaveLength(2);
55
+ });
56
+ });
57
+
58
+ describe("scriptsRefusedByCsp", () => {
59
+ const beacon = foreignScriptSources(BEACON, PAGE);
60
+
61
+ /**
62
+ * 🔴 The failure path this whole file exists for — the owner's console line, turned into a
63
+ * refusal. `script-src 'self'` with something injecting is exactly what he pasted.
64
+ */
65
+ test("script-src 'self' refuses the injected beacon and names its origin", () => {
66
+ const refused = scriptsRefusedByCsp(
67
+ "default-src 'none'; style-src 'self'; script-src 'self'; connect-src 'self'; " +
68
+ "img-src data:; form-action 'none'; base-uri 'none'; frame-ancestors 'none'",
69
+ beacon,
70
+ PAGE,
71
+ );
72
+ expect(refused.map((s) => s.origin)).toEqual([WEB_ANALYTICS_BEACON_ORIGIN]);
73
+ });
74
+
75
+ test("allowing the host in script-src clears it", () => {
76
+ const csp = "default-src 'none'; script-src 'self' https://static.cloudflareinsights.com";
77
+ expect(scriptsRefusedByCsp(csp, beacon, PAGE)).toEqual([]);
78
+ });
79
+
80
+ test("a wildcard subdomain source clears it", () => {
81
+ expect(scriptsRefusedByCsp("script-src 'self' *.cloudflareinsights.com", beacon, PAGE)).toEqual(
82
+ [],
83
+ );
84
+ });
85
+
86
+ test("no CSP header at all refuses nothing — today's public shell", () => {
87
+ expect(scriptsRefusedByCsp(null, beacon, PAGE)).toEqual([]);
88
+ expect(scriptsRefusedByCsp("", beacon, PAGE)).toEqual([]);
89
+ });
90
+
91
+ test("a CSP with no script directive and no default-src refuses nothing", () => {
92
+ expect(scriptsRefusedByCsp("frame-ancestors 'none'; base-uri 'none'", beacon, PAGE)).toEqual([]);
93
+ });
94
+
95
+ test("default-src is the fallback when script-src is absent", () => {
96
+ expect(scriptsRefusedByCsp("default-src 'self'", beacon, PAGE)).toHaveLength(1);
97
+ expect(scriptsRefusedByCsp("default-src https:", beacon, PAGE)).toEqual([]);
98
+ });
99
+
100
+ test("script-src-elem wins over script-src, which wins over default-src", () => {
101
+ const csp =
102
+ "default-src 'none'; script-src 'self'; script-src-elem https://static.cloudflareinsights.com";
103
+ expect(scriptsRefusedByCsp(csp, beacon, PAGE)).toEqual([]);
104
+ expect(scriptsRefusedByCsp("default-src https:; script-src 'self'", beacon, PAGE)).toHaveLength(
105
+ 1,
106
+ );
107
+ });
108
+
109
+ test("'none' admits nothing, even alongside a scheme in another directive", () => {
110
+ expect(scriptsRefusedByCsp("script-src 'none'", beacon, PAGE)).toHaveLength(1);
111
+ });
112
+
113
+ test("a scheme source only matches its own scheme", () => {
114
+ expect(scriptsRefusedByCsp("script-src http:", beacon, PAGE)).toHaveLength(1);
115
+ expect(scriptsRefusedByCsp("script-src https:", beacon, PAGE)).toEqual([]);
116
+ });
117
+
118
+ test("an http:// host source does not admit an https origin", () => {
119
+ expect(
120
+ scriptsRefusedByCsp("script-src http://static.cloudflareinsights.com", beacon, PAGE),
121
+ ).toHaveLength(1);
122
+ });
123
+
124
+ test("a port or path on the source narrows nothing — the conservative direction", () => {
125
+ const csp = "script-src https://static.cloudflareinsights.com:443/beacon.min.js";
126
+ expect(scriptsRefusedByCsp(csp, beacon, PAGE)).toEqual([]);
127
+ });
128
+
129
+ test("'strict-dynamic' is undecidable from markup, so it permits", () => {
130
+ expect(scriptsRefusedByCsp("script-src 'self' 'strict-dynamic' 'nonce-abc'", beacon, PAGE)).toEqual(
131
+ [],
132
+ );
133
+ });
134
+
135
+ test("* permits, and 'self' still matches this app's own origin", () => {
136
+ expect(scriptsRefusedByCsp("script-src *", beacon, PAGE)).toEqual([]);
137
+ const own = [{ src: "/assets/x.js", origin: "https://collections.cursedalchemy.com" }];
138
+ expect(scriptsRefusedByCsp("script-src 'self'", own, PAGE)).toEqual([]);
139
+ });
140
+
141
+ test("nothing injected means nothing refused, however strict the policy", () => {
142
+ expect(scriptsRefusedByCsp("script-src 'none'", [], PAGE)).toEqual([]);
143
+ });
144
+ });
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Does a page's own CSP refuse a script that arrived in that page's own HTML?
3
+ *
4
+ * ## The invariant, which names no vendor
5
+ *
6
+ * > No script that reaches the browser inside a response's HTML may be refused by the CSP on
7
+ * > that same response.
8
+ *
9
+ * Every part of the arrangement may move and this stays right. Turn an edge injection off and
10
+ * the foreign scripts disappear — green. Decide a third-party script is wanted and allow its
11
+ * host — green. Harden a page with `script-src 'self'` while something is still injecting into
12
+ * it — RED, and it names the origin, which is the console line the owner would otherwise find
13
+ * himself during an incident.
14
+ *
15
+ * ## 🔴 Why it lives in this package
16
+ *
17
+ * It was written in `apps/collections` on 2026-09-18 and it was right there, but it could only
18
+ * ever see one app — and the response it was written about, the master-lock wall, is served by
19
+ * THIS package to every app that mounts the guard. One copy here is what makes the two halves
20
+ * of `webAnalytics.ts`'s decision checkable in the same place: the wall refuses the beacon, and
21
+ * a public shell carries it.
22
+ *
23
+ * ## 🔴 Conservative on purpose
24
+ *
25
+ * Every ambiguity resolves to PERMITTED. A source expression this file cannot parse, a
26
+ * `'strict-dynamic'` that changes what host lists even mean, a CSP with no script directive at
27
+ * all — all of them pass. A deployed smoke decides whether an app's `scripts/deploy.ts` rolls
28
+ * back; a false red there discards good work over a CSP grammar corner, so the only thing that
29
+ * fails here is a script with NO source expression that could admit it.
30
+ */
31
+
32
+ /** An absolute script URL found in the HTML, with the origin already resolved. */
33
+ export interface InjectedScript {
34
+ /** Exactly as it appeared in the markup, for the failure message. */
35
+ src: string;
36
+ /** `https://static.cloudflareinsights.com`, resolved against the page's own URL. */
37
+ origin: string;
38
+ }
39
+
40
+ /**
41
+ * Every `<script src=…>` in `html` whose origin is NOT `pageUrl`'s.
42
+ *
43
+ * Inline scripts are ignored: they are the page's own (most shells here ship one, a pre-paint
44
+ * colour-scheme script) and a CSP that refuses them is a different finding from this one.
45
+ * `data:` and `blob:` are ignored for the same reason — neither is a host anything could have
46
+ * injected.
47
+ */
48
+ export function foreignScriptSources(html: string, pageUrl: string): InjectedScript[] {
49
+ const page = new URL(pageUrl);
50
+ const found: InjectedScript[] = [];
51
+ const seen = new Set<string>();
52
+ const tag = /<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
53
+ for (const match of html.matchAll(tag)) {
54
+ const raw = (match[1] ?? match[2] ?? match[3] ?? "").trim();
55
+ if (!raw) continue;
56
+ let origin: string;
57
+ try {
58
+ const url = new URL(raw, page);
59
+ if (url.protocol !== "http:" && url.protocol !== "https:") continue;
60
+ origin = url.origin;
61
+ } catch {
62
+ continue; // not a URL this check can reason about — see the conservative note
63
+ }
64
+ if (origin === page.origin) continue;
65
+ if (seen.has(origin + raw)) continue;
66
+ seen.add(origin + raw);
67
+ found.push({ src: raw, origin });
68
+ }
69
+ return found;
70
+ }
71
+
72
+ /**
73
+ * Which of `scripts` the `content-security-policy` header would refuse.
74
+ *
75
+ * `null`/absent/empty header means no policy, which refuses nothing. The directive consulted
76
+ * is `script-src-elem`, then `script-src`, then `default-src` — the browser's own fallback
77
+ * order for a `<script src>` element.
78
+ */
79
+ export function scriptsRefusedByCsp(
80
+ csp: string | null | undefined,
81
+ scripts: InjectedScript[],
82
+ pageUrl: string,
83
+ ): InjectedScript[] {
84
+ if (!csp?.trim() || scripts.length === 0) return [];
85
+ const directives = new Map<string, string[]>();
86
+ for (const part of csp.split(";")) {
87
+ const tokens = part.trim().split(/\s+/).filter(Boolean);
88
+ const name = tokens.shift()?.toLowerCase();
89
+ if (name && !directives.has(name)) directives.set(name, tokens);
90
+ }
91
+ const sources =
92
+ directives.get("script-src-elem") ??
93
+ directives.get("script-src") ??
94
+ directives.get("default-src");
95
+ if (!sources) return [];
96
+ // `'strict-dynamic'` makes host allowlists inert in ways that depend on how the script was
97
+ // reached. Not decidable from the markup alone, so it is permitted — see the header.
98
+ if (sources.some((s) => s.toLowerCase() === "'strict-dynamic'")) return [];
99
+ const self = new URL(pageUrl).origin;
100
+ return scripts.filter(
101
+ (script) => !sources.some((source) => sourceAdmits(source, script.origin, self)),
102
+ );
103
+ }
104
+
105
+ /** Does one CSP source expression admit `origin`? Unparseable ⇒ yes, deliberately. */
106
+ function sourceAdmits(source: string, origin: string, self: string): boolean {
107
+ const value = source.trim();
108
+ if (!value) return false;
109
+ if (value === "*") return true;
110
+ if (value.startsWith("'")) {
111
+ const keyword = value.toLowerCase();
112
+ if (keyword === "'self'") return origin === self;
113
+ // `'none'`, `'unsafe-inline'`, `'nonce-…'`, `'sha256-…'`, `'report-sample'`: none of
114
+ // them admits a host, and `'none'` in particular must not.
115
+ return false;
116
+ }
117
+ let target: URL;
118
+ try {
119
+ target = new URL(origin);
120
+ } catch {
121
+ return true;
122
+ }
123
+ // A bare scheme source — `https:`, `data:`.
124
+ if (/^[a-z][a-z0-9+.-]*:$/i.test(value)) return value.toLowerCase() === target.protocol;
125
+
126
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.exec(value);
127
+ let rest = value;
128
+ if (withScheme) {
129
+ if (withScheme[0].toLowerCase() !== `${target.protocol}//`) return false;
130
+ rest = value.slice(withScheme[0].length);
131
+ }
132
+ // Port and path narrow a source; ignoring them can only ever ADMIT more, which is the
133
+ // direction this file errs in.
134
+ const host = rest.split("/")[0]?.split(":")[0]?.toLowerCase() ?? "";
135
+ if (!host) return true;
136
+ if (host === "*") return true;
137
+ if (host.startsWith("*.")) return target.hostname.toLowerCase().endsWith(host.slice(1));
138
+ return target.hostname.toLowerCase() === host;
139
+ }
@@ -0,0 +1,131 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ WEB_ANALYTICS_BEACON_ORIGIN,
4
+ WEB_ANALYTICS_BEACON_SRC,
5
+ WEB_ANALYTICS_SITE_TAG,
6
+ WEB_ANALYTICS_SITE_TOKEN,
7
+ WEB_ANALYTICS_TAG,
8
+ htmlCarriesWebAnalytics,
9
+ webAnalyticsBootstrap,
10
+ webAnalyticsTag,
11
+ } from "./webAnalytics";
12
+
13
+ /**
14
+ * 🔴 The snippet, as Cloudflare's own `GET /accounts/<acct>/rum/site_info/list` returned it on
15
+ * 2026-09-18 for `cursedalchemy.com`, unescaped. Pinning it byte-for-byte is the point: this
16
+ * is the thing a shell pastes, and the day it drifts from the vendor's text is a day nobody
17
+ * would otherwise notice until a dashboard stopped filling.
18
+ */
19
+ const FROM_CLOUDFLARE =
20
+ `<!-- Cloudflare Web Analytics --><script type='module' src='https://static.cloudflareinsights.com/beacon.min.js' ` +
21
+ `data-cf-beacon='{"token": "bd88d63678b64bc89f9702f48846bc88"}'></script><!-- End Cloudflare Web Analytics -->`;
22
+
23
+ describe("the fleet's beacon", () => {
24
+ test("is exactly the snippet Cloudflare hands out for this site", () => {
25
+ expect(WEB_ANALYTICS_TAG).toBe(FROM_CLOUDFLARE);
26
+ });
27
+
28
+ test("carries the site TOKEN, never the site TAG", () => {
29
+ // Both are 32 hex characters and swapping them errors nowhere — the page loads, the
30
+ // beacon loads, and the pageview is recorded against nothing.
31
+ expect(WEB_ANALYTICS_TAG).toContain(WEB_ANALYTICS_SITE_TOKEN);
32
+ expect(WEB_ANALYTICS_TAG).not.toContain(WEB_ANALYTICS_SITE_TAG);
33
+ expect(WEB_ANALYTICS_SITE_TAG).not.toBe(WEB_ANALYTICS_SITE_TOKEN);
34
+ });
35
+
36
+ test("the src is under the origin a CSP would have to admit", () => {
37
+ expect(WEB_ANALYTICS_BEACON_SRC.startsWith(`${WEB_ANALYTICS_BEACON_ORIGIN}/`)).toBe(true);
38
+ expect(new URL(WEB_ANALYTICS_BEACON_SRC).origin).toBe(WEB_ANALYTICS_BEACON_ORIGIN);
39
+ });
40
+
41
+ test("another site's token produces that site's tag and nothing else changes", () => {
42
+ const other = webAnalyticsTag("0".repeat(32));
43
+ expect(other).toContain(WEB_ANALYTICS_BEACON_SRC);
44
+ expect(other).not.toContain(WEB_ANALYTICS_SITE_TOKEN);
45
+ });
46
+ });
47
+
48
+ /**
49
+ * 🔴 The guard is EXECUTED, not read. It is eight lines of hand-written browser JavaScript
50
+ * that nothing else runs before production, and the whole reason it exists is a failure that
51
+ * only shows up at a particular hostname — so a test that merely asserted the string contains
52
+ * "cursedalchemy.com" would pass on a guard with the condition inverted.
53
+ */
54
+ function runBootstrap(hostname: string): { appended: string[]; attrs: Record<string, string> } {
55
+ const body = /<script>([\s\S]*)<\/script>/.exec(webAnalyticsBootstrap())?.[1] ?? "";
56
+ expect(body.trim().length).toBeGreaterThan(0);
57
+ const appended: string[] = [];
58
+ const attrs: Record<string, string> = {};
59
+ const fakeDocument = {
60
+ createElement: () => ({
61
+ type: "",
62
+ src: "",
63
+ setAttribute(name: string, value: string) {
64
+ attrs[name] = value;
65
+ },
66
+ }),
67
+ head: {
68
+ appendChild(el: { src: string }) {
69
+ appended.push(el.src);
70
+ },
71
+ },
72
+ };
73
+ new Function("location", "document", body)({ hostname }, fakeDocument);
74
+ return { appended, attrs };
75
+ }
76
+
77
+ describe("the hostname guard", () => {
78
+ test("appends the beacon on the zone, and on every satellite of it", () => {
79
+ for (const host of ["cursedalchemy.com", "collections.cursedalchemy.com", "vault.cursedalchemy.com"]) {
80
+ const { appended, attrs } = runBootstrap(host);
81
+ expect(appended, `${host} should load the beacon`).toEqual([WEB_ANALYTICS_BEACON_SRC]);
82
+ expect(attrs["data-cf-beacon"]).toBe(`{"token": "${WEB_ANALYTICS_SITE_TOKEN}"}`);
83
+ }
84
+ });
85
+
86
+ /**
87
+ * 🔴 The failure this guard was added for, 2026-09-18. The beacon POSTs to
88
+ * `cloudflareinsights.com/cdn-cgi/rum`, which answers the preflight with
89
+ * `Access-Control-Allow-Origin: http://127.0.0.1` — no port — so a local page load prints a
90
+ * CORS error. `apps/music` lost 5 route-render checks to it and `apps/desk` lost 24, both
91
+ * asserting an empty console, and the owner's own `bun run dev` would have shown it too.
92
+ */
93
+ test("loads NOTHING on localhost, 127.0.0.1 or a bare host", () => {
94
+ for (const host of ["localhost", "127.0.0.1", "::1", "app.test", ""]) {
95
+ expect(runBootstrap(host).appended, `${host} must not load the beacon`).toEqual([]);
96
+ }
97
+ });
98
+
99
+ test("a lookalike domain does not get the beacon either", () => {
100
+ // `endsWith` alone would admit this, which is why the guard tests for the dot.
101
+ expect(runBootstrap("evilcursedalchemy.com").appended).toEqual([]);
102
+ });
103
+ });
104
+
105
+ describe("htmlCarriesWebAnalytics", () => {
106
+ test("true for the bootstrap block a shell actually pastes", () => {
107
+ expect(htmlCarriesWebAnalytics(webAnalyticsBootstrap())).toBe(true);
108
+ expect(htmlCarriesWebAnalytics(webAnalyticsBootstrap("0".repeat(32)))).toBe(false);
109
+ });
110
+
111
+ test("true for the tag as authored, and for a re-wrapped copy of it", () => {
112
+ expect(htmlCarriesWebAnalytics(`<head>${WEB_ANALYTICS_TAG}</head>`)).toBe(true);
113
+ // A formatter is allowed to break the attributes across lines; the check must survive it.
114
+ const rewrapped =
115
+ `<script\n\ttype="module"\n\tsrc="${WEB_ANALYTICS_BEACON_SRC}"\n` +
116
+ `\tdata-cf-beacon='{"token": "${WEB_ANALYTICS_SITE_TOKEN}"}'\n></script>`;
117
+ expect(htmlCarriesWebAnalytics(rewrapped)).toBe(true);
118
+ });
119
+
120
+ test("false for a shell with no beacon at all", () => {
121
+ expect(htmlCarriesWebAnalytics("<head><title>Vault</title></head>")).toBe(false);
122
+ });
123
+
124
+ test("false when the src is right but the token is somebody else's", () => {
125
+ expect(htmlCarriesWebAnalytics(webAnalyticsTag("0".repeat(32)))).toBe(false);
126
+ });
127
+
128
+ test("false when the token is right but the src is not the beacon", () => {
129
+ expect(htmlCarriesWebAnalytics(`<!-- ${WEB_ANALYTICS_SITE_TOKEN} -->`)).toBe(false);
130
+ });
131
+ });
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Cloudflare Web Analytics — ONE definition of the beacon, for every app on the fleet.
3
+ *
4
+ * ## 🔴 Why this is here and not in each app's `index.html` alone
5
+ *
6
+ * Until 2026-09-18 the zone carried **Automatic Setup**: Cloudflare rewrote every HTML
7
+ * response leaving `cursedalchemy.com` and appended the beacon tag. Nothing in any repo
8
+ * asked for it, nothing in any repo could see it locally, and it arrived on pages that
9
+ * deliberately refuse third-party script — including the master-lock wall, where a master
10
+ * password is typed. The owner read a console during an outage on 2026-09-17 and the FIRST
11
+ * line was that tag being refused; it broke nothing and cost an agent the first minutes of
12
+ * the incident.
13
+ *
14
+ * His decision, 2026-09-18, in his words: *"do your recommendation with option c but not on
15
+ * the wall. If we can stop the console error that would be good since we are purposely
16
+ * blocking on that page and it makes it look like there is a mistake when it shows."* — and,
17
+ * on why the wall's CSP may not simply be loosened: *"I don't want to trust cloudflare with
18
+ * master password data that is typed in."*
19
+ *
20
+ * So the install method moves from automatic to MANUAL. Same site, same dashboard, same
21
+ * data; the difference is that the fleet now decides *which pages* carry it. Public shells
22
+ * do. {@link "../master-lock/guard".MASTER_LOCK_CSP the wall} does not — and under manual
23
+ * setup it is not injected into at all, so there is no refused script and no console line.
24
+ *
25
+ * ## 🔴 `token` is the site TOKEN, not the site TAG
26
+ *
27
+ * They are both 32 hex characters and they are not interchangeable. `site_tag`
28
+ * ({@link WEB_ANALYTICS_SITE_TAG}) is the id the RUM API addresses the site by;
29
+ * `site_token` ({@link WEB_ANALYTICS_SITE_TOKEN}) is what goes in `data-cf-beacon`. Putting
30
+ * the tag in the snippet does not error anywhere — the page loads, the beacon loads, and the
31
+ * data goes nowhere. Measured 2026-09-18 against
32
+ * `GET /accounts/<acct>/rum/site_info/list`, which returns both fields **and** the ready-made
33
+ * `snippet`; {@link WEB_ANALYTICS_TAG} is that snippet byte-for-byte, and the token in it is
34
+ * the same one the edge was injecting.
35
+ *
36
+ * Neither value is a secret: the token is served to every visitor inside every page's HTML,
37
+ * which is the whole mechanism. It is an identifier, not a credential.
38
+ */
39
+
40
+ /** The host the beacon is fetched from — the origin a CSP would have to admit. */
41
+ export const WEB_ANALYTICS_BEACON_ORIGIN = "https://static.cloudflareinsights.com";
42
+
43
+ /** The beacon itself. Manual setup serves the unversioned path; the edge served a pinned one. */
44
+ export const WEB_ANALYTICS_BEACON_SRC = `${WEB_ANALYTICS_BEACON_ORIGIN}/beacon.min.js`;
45
+
46
+ /**
47
+ * The `cursedalchemy.com` site's id in the RUM API. **Not** what goes in the tag — see the
48
+ * module note. Kept beside the token so the next reader cannot pick the wrong one by accident.
49
+ */
50
+ export const WEB_ANALYTICS_SITE_TAG = "d1bea8562544421fbd2db5f11b74d1cc";
51
+
52
+ /** The `cursedalchemy.com` site's `data-cf-beacon` token. This is what the tag carries. */
53
+ export const WEB_ANALYTICS_SITE_TOKEN = "bd88d63678b64bc89f9702f48846bc88";
54
+
55
+ /**
56
+ * The snippet, exactly as Cloudflare's own `site_info` endpoint spells it.
57
+ *
58
+ * 🔴 The single-quoted attributes and the space after `"token":` are Cloudflare's, not a
59
+ * style choice, and they are kept because this string is COMPARED against what an app's
60
+ * shell contains. `data-cf-beacon`'s value is JSON containing double quotes, so the attribute
61
+ * quoting cannot be flipped without escaping; leaving it identical to the vendor's text means
62
+ * a future reader can diff it against the dashboard in one glance.
63
+ *
64
+ * `type='module'` rather than `defer`: that is what the endpoint returns today and what the
65
+ * edge was injecting, so switching install methods changes nothing about how the page loads.
66
+ */
67
+ export function webAnalyticsTag(token: string = WEB_ANALYTICS_SITE_TOKEN): string {
68
+ return (
69
+ "<!-- Cloudflare Web Analytics -->" +
70
+ `<script type='module' src='${WEB_ANALYTICS_BEACON_SRC}' ` +
71
+ `data-cf-beacon='{"token": "${token}"}'></script>` +
72
+ "<!-- End Cloudflare Web Analytics -->"
73
+ );
74
+ }
75
+
76
+ /** The fleet's tag, for the one site this generation serves. */
77
+ export const WEB_ANALYTICS_TAG = webAnalyticsTag();
78
+
79
+ /** The zone. A page served from anywhere else must not load the beacon — see below. */
80
+ export const WEB_ANALYTICS_PUBLIC_HOST = "cursedalchemy.com";
81
+
82
+ /**
83
+ * What a static shell actually pastes: the tag, behind a HOSTNAME GUARD.
84
+ *
85
+ * ## 🔴 Why the bare snippet cannot go in an `index.html`
86
+ *
87
+ * Measured 2026-09-18, the first time the eight shells carried it. The beacon posts its
88
+ * pageview to `https://cloudflareinsights.com/cdn-cgi/rum`, and Cloudflare answers that
89
+ * preflight with `Access-Control-Allow-Origin: http://127.0.0.1` — no port. So on every LOCAL
90
+ * page load the browser prints:
91
+ *
92
+ * > Access to XMLHttpRequest at 'https://cloudflareinsights.com/cdn-cgi/rum' from origin
93
+ * > 'http://127.0.0.1:57845' has been blocked by CORS policy … Failed to load resource
94
+ *
95
+ * Under Automatic Setup this never happened: the injection is done by the EDGE, so it existed
96
+ * only on the zone and a developer never saw it. Pasting the raw snippet into the source moves
97
+ * it to every `bun run dev` and every browser test — `apps/music` lost 5 route-render checks and
98
+ * `apps/desk` lost 24, both asserting the console is empty, and the owner's own local console
99
+ * would have gained a red line on every page.
100
+ *
101
+ * That is the exact cost he asked to be rid of, one environment over. So the guard: the beacon
102
+ * is appended only when the page is being served from {@link WEB_ANALYTICS_PUBLIC_HOST}, which
103
+ * is the only place it can report anyway.
104
+ *
105
+ * ## Why an inline script rather than a build-time injection
106
+ *
107
+ * A Vite plugin would mean ten `vite.config.ts` edits and a frontend build depending on a
108
+ * server package — and it would not even work: `apps/desk`'s browser suite runs against a
109
+ * production `dist` served from `127.0.0.1`, so a production-only injection is still a console
110
+ * error there. The hostname is the honest discriminator, not the build mode.
111
+ *
112
+ * 🔴 It needs inline script to be permitted on the page. Every shell that carries it already
113
+ * ships one; `apps/vault` does not, serves `script-src 'self'`, and is exempt from the beacon
114
+ * for that reason — see `tools/check-web-analytics.ts`.
115
+ */
116
+ export function webAnalyticsBootstrap(token: string = WEB_ANALYTICS_SITE_TOKEN): string {
117
+ return [
118
+ "<script>",
119
+ `\tvar host = location.hostname;`,
120
+ `\tif (host === "${WEB_ANALYTICS_PUBLIC_HOST}" || host.endsWith(".${WEB_ANALYTICS_PUBLIC_HOST}")) {`,
121
+ `\t\tvar beacon = document.createElement("script");`,
122
+ `\t\tbeacon.type = "module";`,
123
+ `\t\tbeacon.src = "${WEB_ANALYTICS_BEACON_SRC}";`,
124
+ `\t\tbeacon.setAttribute("data-cf-beacon", '{"token": "${token}"}');`,
125
+ `\t\tdocument.head.appendChild(beacon);`,
126
+ "\t}",
127
+ "</script>",
128
+ ].join("\n");
129
+ }
130
+
131
+ /**
132
+ * Does `html` carry the beacon for this site?
133
+ *
134
+ * Deliberately NOT a substring test against {@link WEB_ANALYTICS_TAG}: a shell is authored by
135
+ * hand and a formatter is allowed to re-wrap the tag across lines or re-order its attributes.
136
+ * What must be true is that the beacon's source is there AND that it is carrying the right
137
+ * token — the two halves that decide whether a pageview is recorded at all.
138
+ */
139
+ export function htmlCarriesWebAnalytics(
140
+ html: string,
141
+ token: string = WEB_ANALYTICS_SITE_TOKEN,
142
+ ): boolean {
143
+ return html.includes(WEB_ANALYTICS_BEACON_SRC) && html.includes(token);
144
+ }