@celestia-island/hikari 0.55.510 → 0.55.511

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.
@@ -575,3 +575,5 @@ export { useRemoteTouchGestures } from "./composables/useRemoteTouchGestures";
575
575
  export type { TouchGestureHandlers } from "./composables/useRemoteTouchGestures";
576
576
  export { useOrientationLock } from "./composables/useOrientationLock";
577
577
  export { attachOverviewRuler, type OverviewRulerAxis, type OverviewRulerBand, type OverviewRulerCursorMode, type OverviewRulerHandle, type OverviewRulerOptions, } from "./composables/useOverviewRuler";
578
+ export { BEIAN_TAG_ID, GA_TAG_ID, isValidGaMeasurementId, readBeianLines, readGaMeasurementId, readSiteMeta, parseBeianLines, } from "./siteMeta";
579
+ export type { SiteBeianLine, SiteMeta } from "./siteMeta";
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Site meta — the ONE place the family reads deployment-injected site
3
+ * metadata (GA measurement id boot tag, compliance/beian footer lines).
4
+ *
5
+ * Hosts used to duplicate this logic per repo (erp
6
+ * `packages/webui/src/analytics.ts`, chest `packages/webui/src/analytics.ts`,
7
+ * chest `packages/chest-app/src/static_files.rs`, erp
8
+ * `packages/core/src/routes/auth.rs`); the user ruling (2026-11-27) lifted
9
+ * the shared, cross-host site variables into hikari — names and parsing are
10
+ * defined once here.
11
+ *
12
+ * This module is pure functions/constants only (no Vue reactivity, no
13
+ * loader injection) — the `useSiteMeta` composable builds on it in a later
14
+ * slice.
15
+ */
16
+ /**
17
+ * DOM id of the JSON boot tag carrying the GA4 measurement id. Both hosts
18
+ * inject `<script type="application/json" id="celestia-ga-measurement-id">`
19
+ * into the served SPA shell (erp: `CELESTIA_GA_MEASUREMENT_ID` via
20
+ * `packages/core/src/main.rs`; chest: `CHEST_GA_MEASUREMENT_ID` via
21
+ * `packages/chest-app/src/static_files.rs`) — the constant is the
22
+ * intersection of both repos' `GA_TAG_ID` and is the single definition now.
23
+ */
24
+ export declare const GA_TAG_ID = "celestia-ga-measurement-id";
25
+ /**
26
+ * Strict GA4 measurement-id shape: `G-` prefix + 1..=32 uppercase
27
+ * alphanumerics. Rule sourced from chest
28
+ * `packages/chest-app/src/static_files.rs` (`G-` + 1..=32 A-Z0-9), which
29
+ * matches the erp core gate on `CELESTIA_GA_MEASUREMENT_ID`; both webui
30
+ * `analytics.ts` copies implement the identical regex. Defensive by design:
31
+ * the value is echoed back into served HTML, so anything outside the issued
32
+ * shape counts as absent.
33
+ */
34
+ export declare function isValidGaMeasurementId(raw: string): boolean;
35
+ /**
36
+ * Read the GA measurement id from the served document's boot tag. Returns
37
+ * null on every failure mode (tag missing, empty/whitespace content,
38
+ * envsubst leftover `$VAR` / `__VAR__` placeholder, malformed id) — every
39
+ * failure means "tracking disabled", never a throw.
40
+ *
41
+ * Read/placeholder semantics mirror the two hosts' `resolveMeasurementId`
42
+ * (their common intersection): `textContent` is trimmed, and a raw `$…` or
43
+ * `__…` prefix means the injection channel never ran. A malformed
44
+ * non-placeholder value silently returns null so a misconfigured deployment is
45
+ * discoverable in the console without polluting the page.
46
+ */
47
+ export declare function readGaMeasurementId(doc?: Document): string | null;
48
+ /** One compliance footer line: a title and an optional http(s) link. */
49
+ export interface SiteBeianLine {
50
+ title: string;
51
+ url?: string;
52
+ }
53
+ /**
54
+ * Parse the `beian_lines` setting (a JSON array of `{title, url?}`) into
55
+ * footer lines. Semantics aligned line-by-line with erp
56
+ * `packages/core/src/routes/auth.rs::sanitize_beian_lines` (the only
57
+ * backend that ships beian lines; chest's `CHEST_FOOTER_EXTRA` is a
58
+ * different shape and NOT handled here):
59
+ *
60
+ * - Non-JSON input, JSON that is not an array (`"null"`, objects, …) → `[]`.
61
+ * - An entry survives only as an object with a non-empty string `title`
62
+ * after trim; the title is capped at 64 characters (code points).
63
+ * - `url` absent or JSON null → plain-text line (`url` undefined).
64
+ * - A present string `url` is trimmed; empty after trim → plain-text line;
65
+ * otherwise it must start with `https://` or `http://` — a present but
66
+ * malformed url (relative, `javascript:`) drops the WHOLE entry, per the
67
+ * erp contract (half-rendered filing lines are worse than absent ones).
68
+ * - A non-string `url` drops the entry.
69
+ * - Output is capped at the first 4 surviving entries.
70
+ */
71
+ export declare function parseBeianLines(raw: string): Array<SiteBeianLine>;
72
+ /**
73
+ * DOM id of the JSON boot tag carrying the raw `beian_lines` value (the
74
+ * JSON array `parseBeianLines` consumes). This is the ONE build-time channel
75
+ * this repo defines — but NO host emits it yet (2026-11-28 audit):
76
+ *
77
+ * - erp and chest both resolve the setting server-side and never emit it
78
+ * (erp serves the already-parsed array on `/api/auth/login-methods`; chest
79
+ * ships `CHEST_FOOTER_EXTRA` → `/health.footer_extra`, a different shape).
80
+ * - `celestia.ac.cn` still uses its own `celestia-footer-extra` tag, whose
81
+ * schema is WIDER than ours (it also accepts string arrays and a bare HTML
82
+ * string). Moving that site onto this channel is a host-side task, not a
83
+ * property of this module.
84
+ *
85
+ * Absence therefore reads as an empty footer everywhere today — which is the
86
+ * intended degradation, never an error.
87
+ */
88
+ export declare const BEIAN_TAG_ID = "celestia-beian-lines";
89
+ /**
90
+ * Read the beian lines from the served document's boot tag. Every failure
91
+ * mode (no document, tag absent, blank content) reads as "no compliance
92
+ * lines"; a present but malformed value also reads as `[]` rather than
93
+ * throwing, because a misconfigured deployment must not break the shell's
94
+ * footer render.
95
+ *
96
+ * The `$…` / `__…` placeholder guard is DEFENSIVE REDUNDANCY, and the honest
97
+ * statement of what it is worth: it is unobservable from outside. Any
98
+ * placeholder prefix makes the value fail `JSON.parse`, so `parseBeianLines`
99
+ * alone already answers `[]` — no behavioural assertion can distinguish "the
100
+ * guard rejected it" from "the parser rejected it" (mutation evidence: both
101
+ * deleting the guard and neutering it to a literal comparison leave the
102
+ * end-to-end assertions green). Its presence is therefore pinned
103
+ * structurally in `siteMeta.test.ts` (a text pin scoped to this function's
104
+ * body), which catches deletion / move / rename but does NOT prove the
105
+ * guard runs. It is kept — rather than deleted — for one reason only:
106
+ * parity with the two hosts' `analytics.ts`, which carry the same branch.
107
+ */
108
+ export declare function readBeianLines(doc?: Document): Array<SiteBeianLine>;
109
+ /** What one site's deployment injected: the GA id and the compliance lines. */
110
+ export interface SiteMeta {
111
+ /** GA4 measurement id, or null when this deployment ships no tracking. */
112
+ gaMeasurementId: string | null;
113
+ /** Compliance/beian footer lines, already sanitized; empty when absent. */
114
+ beianLines: Array<SiteBeianLine>;
115
+ }
116
+ /**
117
+ * Read every host-injected site variable in one call. Deliberately NOT a
118
+ * Vue composable: nothing here is reactive (the boot tags are written once
119
+ * into the served document before any script runs, and never change for
120
+ * the life of the page), so wrapping it in `ref`s would only add weight.
121
+ * Hosts call it once at boot — erp/chest pass the result into their
122
+ * analytics + footer, static sites read it in the same place.
123
+ *
124
+ * `doc` is injectable so tests (and prerender contexts) never touch the
125
+ * ambient `document`.
126
+ */
127
+ export declare function readSiteMeta(doc?: Document): SiteMeta;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celestia-island/hikari",
3
- "version": "0.55.510",
3
+ "version": "0.55.511",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Hikari UI library, Vue 3 runtime — one design system for Vue 3 and Rust/WASM applications",
@@ -1,7 +1,7 @@
1
1
  <!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
- <meta name="hk-error-landing" content="v1 0.55.510 <dev>">
4
+ <meta name="hk-error-landing" content="v1 0.55.511 <dev>">
5
5
  <meta charset="utf-8" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1" />
7
7
  <meta name="robots" content="noindex" />
package/src/index.ts CHANGED
@@ -1358,3 +1358,16 @@ export {
1358
1358
  type OverviewRulerHandle,
1359
1359
  type OverviewRulerOptions,
1360
1360
  } from "./composables/useOverviewRuler";
1361
+
1362
+ // Site meta — the single upstream definition of host-injected site variables
1363
+ // (GA measurement id boot tag, compliance/beian footer lines).
1364
+ export {
1365
+ BEIAN_TAG_ID,
1366
+ GA_TAG_ID,
1367
+ isValidGaMeasurementId,
1368
+ readBeianLines,
1369
+ readGaMeasurementId,
1370
+ readSiteMeta,
1371
+ parseBeianLines,
1372
+ } from "./siteMeta";
1373
+ export type { SiteBeianLine, SiteMeta } from "./siteMeta";
@@ -0,0 +1,263 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ import { describe, expect, it, vi } from "vitest";
6
+
7
+ import {
8
+ BEIAN_TAG_ID,
9
+ GA_TAG_ID,
10
+ isValidGaMeasurementId,
11
+ parseBeianLines,
12
+ readBeianLines,
13
+ readGaMeasurementId,
14
+ readSiteMeta,
15
+ } from "./siteMeta";
16
+
17
+ // MUT:site-meta-ga-tag-id — renaming the boot-tag id would silently detach
18
+ // the reader from both hosts' injected `<script id>` (erp core main.rs and
19
+ // chest static_files.rs both emit this exact id).
20
+ describe("GA_TAG_ID", () => {
21
+ it("is the boot tag id both hosts inject", () => {
22
+ expect(GA_TAG_ID).toBe("celestia-ga-measurement-id");
23
+ });
24
+ });
25
+
26
+ // MUT:site-meta-ga-id-shape — the validator mirrors chest
27
+ // packages/chest-app/src/static_files.rs: `G-` + 1..=32 uppercase
28
+ // alphanumerics; loosening any branch lets a hostile id reach served HTML.
29
+ describe("isValidGaMeasurementId truth table", () => {
30
+ it.each([
31
+ ["G-A1B2C3", true],
32
+ ["G-" + "A".repeat(32), true], // at the upper cap
33
+ ["G-" + "A".repeat(33), false], // over the cap
34
+ ["A1B2C3", false], // missing G- prefix
35
+ ["g-abc", false], // lowercase prefix
36
+ ["G-abc", false], // lowercase body
37
+ ["G-", false], // empty body
38
+ ["", false],
39
+ ["G-AB C", false], // whitespace is not alphanumeric
40
+ ])("isValidGaMeasurementId(%j) === %j", (raw, expected) => {
41
+ expect(isValidGaMeasurementId(raw)).toBe(expected);
42
+ });
43
+ });
44
+
45
+ function docWithBootTag(content: string | null): Document {
46
+ const doc = document.implementation.createHTMLDocument("");
47
+ if (content !== null) {
48
+ const tag = doc.createElement("script");
49
+ tag.id = GA_TAG_ID;
50
+ tag.type = "application/json";
51
+ tag.textContent = content;
52
+ doc.head.appendChild(tag);
53
+ }
54
+ return doc;
55
+ }
56
+
57
+ // MUT:site-meta-ga-read-branches — every failure mode must resolve to null
58
+ // ("tracking disabled") rather than throwing or returning a malformed id;
59
+ // the placeholder branches pin the shared envsubst-leftover convention.
60
+ describe("readGaMeasurementId boot-tag branches", () => {
61
+ it("reads a well-formed id, trimming surrounding whitespace", () => {
62
+ expect(readGaMeasurementId(docWithBootTag(" G-TESTID01 \n"))).toBe("G-TESTID01");
63
+ });
64
+
65
+ it("returns null when the tag is absent", () => {
66
+ expect(readGaMeasurementId(docWithBootTag(null))).toBeNull();
67
+ });
68
+
69
+ // MUT:site-meta-beian-codepoints — the 64 limit is CODE POINTS (Rust
70
+ // chars().count() in erp), not UTF-16 units: astral characters must count
71
+ // as one. A `.length`-based mutation reddens the first assertion here.
72
+ it("counts astral code points, not UTF-16 units, against the 64 limit", () => {
73
+ const fortyAstral = "😀".repeat(40); // 40 code points / 80 UTF-16 units
74
+ expect(parseBeianLines(JSON.stringify([{ title: fortyAstral }]))).toHaveLength(1);
75
+ // 65 astral code points are over the limit — and a `.length`-based
76
+ // implementation would see 130 UTF-16 units and keep the line, so this
77
+ // is the mutation-sensitive half.
78
+ const sixtyFiveAstral = "😀".repeat(65);
79
+ expect(parseBeianLines(JSON.stringify([{ title: sixtyFiveAstral }]))).toHaveLength(0);
80
+ });
81
+
82
+ // MUT:site-meta-beian-https-case — the protocol check is case-sensitive by
83
+ // alignment with erp (`HTTPS://` is NOT a valid url → the entry is DROPPED,
84
+ // not downgraded to plain text). A `.toLowerCase()`-style normalization
85
+ // mutation would keep the entry and redden this.
86
+ it("drops entries whose url uses an uppercase-scheme form", () => {
87
+ expect(
88
+ parseBeianLines(JSON.stringify([{ title: "x", url: "HTTPS://beian.example" }]))
89
+ ).toHaveLength(0);
90
+ });
91
+
92
+ it("returns null for malformed JSON-ish junk, silently like the hosts", () => {
93
+ // MUT:site-meta-ga-silent-reject — a warn on the invalid id (R2's S2:
94
+ // the module originally warned per call) reddens THIS silent-null test.
95
+ // The hosts' analytics.ts never warn on an invalid id (the boot tag is
96
+ // our own deploy payload); this module must not either.
97
+ expect(readGaMeasurementId(docWithBootTag("not-an-id"))).toBeNull();
98
+ });
99
+
100
+ it("returns null for envsubst leftovers", () => {
101
+ expect(readGaMeasurementId(docWithBootTag("$CELESTIA_GA_MEASUREMENT_ID"))).toBeNull();
102
+ expect(readGaMeasurementId(docWithBootTag("__CHEST_GA_MEASUREMENT_ID__"))).toBeNull();
103
+ expect(readGaMeasurementId(docWithBootTag(""))).toBeNull();
104
+ });
105
+ });
106
+
107
+ // MUT:site-meta-beian-sanitize — line-by-line port of erp
108
+ // packages/core/src/routes/auth.rs::sanitize_beian_lines; any divergence
109
+ // re-opens the XSS / layout-breaker hole the backend contract closes.
110
+ describe("parseBeianLines (erp sanitize_beian_lines semantics)", () => {
111
+ it("keeps well-formed entries, drops malformed ones, plain text has no url", () => {
112
+ const raw = JSON.stringify([
113
+ { title: "京ICP备00000000号-1", url: "https://beian.miit.gov.cn/" },
114
+ { title: " plain line " },
115
+ { title: "" },
116
+ { title: 42 },
117
+ { url: "https://x/" },
118
+ { title: "bad url", url: "javascript:alert(1)" },
119
+ { title: "relative", url: "/relative" },
120
+ "just a string",
121
+ ]);
122
+ expect(parseBeianLines(raw)).toEqual([
123
+ { title: "京ICP备00000000号-1", url: "https://beian.miit.gov.cn/" },
124
+ { title: "plain line" },
125
+ ]);
126
+ });
127
+
128
+ it("maps null and empty-string urls to plain-text lines (erp url-absence rule)", () => {
129
+ const raw = JSON.stringify([
130
+ { title: "nulled", url: null },
131
+ { title: "blanked", url: " " },
132
+ ]);
133
+ expect(parseBeianLines(raw)).toEqual([{ title: "nulled" }, { title: "blanked" }]);
134
+ });
135
+
136
+ it("returns [] for non-JSON, non-array JSON, and empty arrays", () => {
137
+ expect(parseBeianLines("not json")).toEqual([]);
138
+ expect(parseBeianLines('{"title":"x"}')).toEqual([]);
139
+ expect(parseBeianLines("null")).toEqual([]);
140
+ expect(parseBeianLines("[]")).toEqual([]);
141
+ });
142
+
143
+ it("caps the output at four lines (erp footer cap)", () => {
144
+ const raw = JSON.stringify(
145
+ Array.from({ length: 8 }, (_, i) => ({ title: `line ${i}` })),
146
+ );
147
+ const out = parseBeianLines(raw);
148
+ expect(out).toHaveLength(4);
149
+ expect(out[3]?.title).toBe("line 3");
150
+ });
151
+
152
+ it("drops overlong titles at 64 code points, keeping the at-cap one", () => {
153
+ expect(parseBeianLines(`[{"title":"${"x".repeat(65)}"}]`)).toEqual([]);
154
+ expect(parseBeianLines(`[{"title":"${"x".repeat(64)}"}]`)).toEqual([
155
+ { title: "x".repeat(64) },
156
+ ]);
157
+ });
158
+
159
+ it("drops entries whose url is a non-string JSON value (erp Some(_) => None)", () => {
160
+ expect(parseBeianLines('[{"title":"ok","url":42}]')).toEqual([]);
161
+ });
162
+ });
163
+
164
+ // MUT:site-meta-beian-tag-read — the beian boot tag is a SECOND injection
165
+ // channel (build-time hosts); deleting its reader while keeping
166
+ // parseBeianLines green would silently empty every static site's footer.
167
+ describe("readBeianLines", () => {
168
+ const docWith = (id: string, text: string): Document => {
169
+ const doc = document.implementation.createHTMLDocument("t");
170
+ const tag = doc.createElement("script");
171
+ tag.type = "application/json";
172
+ tag.id = id;
173
+ tag.textContent = text;
174
+ doc.head.appendChild(tag);
175
+ return doc;
176
+ };
177
+
178
+ it("reads and sanitizes the tag payload", () => {
179
+ const doc = docWith(
180
+ BEIAN_TAG_ID,
181
+ JSON.stringify([{ title: "京ICP备00000000号-1", url: "https://beian.miit.gov.cn/" }]),
182
+ );
183
+ expect(readBeianLines(doc)).toEqual([
184
+ { title: "京ICP备00000000号-1", url: "https://beian.miit.gov.cn/" },
185
+ ]);
186
+ });
187
+
188
+ it("treats a missing tag and blank content as no lines", () => {
189
+ expect(readBeianLines(docWith("some-other-id", '[{"title":"x"}]'))).toEqual([]);
190
+ expect(readBeianLines(docWith(BEIAN_TAG_ID, " "))).toEqual([]);
191
+ });
192
+
193
+ // MUT:site-meta-beian-guard-pin — deleting the guard branch reddens this
194
+ // test (R4 mutation evidence); the claims below document what the pin does
195
+ // NOT cover.
196
+ // The placeholder guard CANNOT be pinned behaviourally from the outside:
197
+ // ANY prefix (`$…` / `__…`) makes the value fail `JSON.parse`, so
198
+ // `parseBeianLines` would already answer [] and no assertion could tell
199
+ // "guard rejected it" from "parser rejected it" (R2 mutation evidence:
200
+ // deleting the guard left a placeholder-only test green). It is pinned
201
+ // structurally instead — the source of this module must still carry the
202
+ // placeholder branch — and the placeholder assertions stay as the
203
+ // end-to-end contract (whatever rejects them, the answer is []).
204
+ //
205
+ // KNOWN BLIND SPOT of this text pin, stated so nobody mistakes it for a
206
+ // behavioural guarantee: it catches DELETION, MOVING and RENAMING, but it // comment-gate-ok: 该钉只声明抓删除/移动/改名,R4 已实证
207
+ // does not prove the guard executes. Two deliberately hostile shapes pass // comment-gate-ok: 两种敌意形状实测仍绿,见下行与 R4 记录
208
+ // green — `false && (guard)`, and computing the predicate into an unused
209
+ // variable — both were mutation-tested in R4 and the runs are in the PR // comment-gate-ok: 此句引用 R4 已归档的变异运行记录(PR 轮次账),非本测试的新行为声称
210
+ // ledger. Accepting that is cheaper than deleting the guard, which exists
211
+ // for parity with both hosts' analytics.ts.
212
+ it("keeps the envsubst placeholder guard in the reader", () => {
213
+ // Scope the assertion to THIS reader's body: the GA reader carries an
214
+ // identical guard string, so a whole-file `toContain` would stay green
215
+ // even after the beian guard was deleted (R2 follow-up mutation proof).
216
+ const here = dirname(fileURLToPath(import.meta.url));
217
+ const src = readFileSync(join(here, "siteMeta.ts"), "utf8");
218
+ const start = src.indexOf("export function readBeianLines");
219
+ expect(start).toBeGreaterThan(-1);
220
+ const body = src.slice(start, src.indexOf("return parseBeianLines(raw);", start));
221
+ expect(body).toContain('raw.startsWith("$") || raw.startsWith("__")');
222
+ expect(readBeianLines(docWith(BEIAN_TAG_ID, "$BEIAN_LINES"))).toEqual([]);
223
+ expect(readBeianLines(docWith(BEIAN_TAG_ID, "__BEIAN_LINES__"))).toEqual([]);
224
+ });
225
+
226
+ it("returns [] rather than throwing on malformed JSON", () => {
227
+ expect(readBeianLines(docWith(BEIAN_TAG_ID, "{not json"))).toEqual([]);
228
+ expect(readBeianLines(docWith(BEIAN_TAG_ID, '"just a string"'))).toEqual([]);
229
+ });
230
+ });
231
+
232
+ // MUT:site-meta-aggregate — readSiteMeta is the single call hosts make at
233
+ // boot; dropping either half (or reading the wrong tag) has to redden here,
234
+ // because a host test that only asserts "it returned an object" would not.
235
+ describe("readSiteMeta", () => {
236
+ const docWithBoth = (ga: string, beian: string): Document => {
237
+ const doc = document.implementation.createHTMLDocument("t");
238
+ for (const [id, text] of [
239
+ [GA_TAG_ID, ga],
240
+ [BEIAN_TAG_ID, beian],
241
+ ]) {
242
+ const tag = doc.createElement("script");
243
+ tag.type = "application/json";
244
+ tag.id = id;
245
+ tag.textContent = text;
246
+ doc.head.appendChild(tag);
247
+ }
248
+ return doc;
249
+ };
250
+
251
+ it("reads both halves in one call", () => {
252
+ const doc = docWithBoth("G-ABCDEF1234", JSON.stringify([{ title: "备案" }]));
253
+ expect(readSiteMeta(doc)).toEqual({
254
+ gaMeasurementId: "G-ABCDEF1234",
255
+ beianLines: [{ title: "备案" }],
256
+ });
257
+ });
258
+
259
+ it("reads both halves as absent on a bare document", () => {
260
+ const doc = document.implementation.createHTMLDocument("t");
261
+ expect(readSiteMeta(doc)).toEqual({ gaMeasurementId: null, beianLines: [] });
262
+ });
263
+ });
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Site meta — the ONE place the family reads deployment-injected site
3
+ * metadata (GA measurement id boot tag, compliance/beian footer lines).
4
+ *
5
+ * Hosts used to duplicate this logic per repo (erp
6
+ * `packages/webui/src/analytics.ts`, chest `packages/webui/src/analytics.ts`,
7
+ * chest `packages/chest-app/src/static_files.rs`, erp
8
+ * `packages/core/src/routes/auth.rs`); the user ruling (2026-11-27) lifted
9
+ * the shared, cross-host site variables into hikari — names and parsing are
10
+ * defined once here.
11
+ *
12
+ * This module is pure functions/constants only (no Vue reactivity, no
13
+ * loader injection) — the `useSiteMeta` composable builds on it in a later
14
+ * slice.
15
+ */
16
+
17
+ /**
18
+ * DOM id of the JSON boot tag carrying the GA4 measurement id. Both hosts
19
+ * inject `<script type="application/json" id="celestia-ga-measurement-id">`
20
+ * into the served SPA shell (erp: `CELESTIA_GA_MEASUREMENT_ID` via
21
+ * `packages/core/src/main.rs`; chest: `CHEST_GA_MEASUREMENT_ID` via
22
+ * `packages/chest-app/src/static_files.rs`) — the constant is the
23
+ * intersection of both repos' `GA_TAG_ID` and is the single definition now.
24
+ */
25
+ export const GA_TAG_ID = "celestia-ga-measurement-id";
26
+
27
+ /**
28
+ * Strict GA4 measurement-id shape: `G-` prefix + 1..=32 uppercase
29
+ * alphanumerics. Rule sourced from chest
30
+ * `packages/chest-app/src/static_files.rs` (`G-` + 1..=32 A-Z0-9), which
31
+ * matches the erp core gate on `CELESTIA_GA_MEASUREMENT_ID`; both webui
32
+ * `analytics.ts` copies implement the identical regex. Defensive by design:
33
+ * the value is echoed back into served HTML, so anything outside the issued
34
+ * shape counts as absent.
35
+ */
36
+ export function isValidGaMeasurementId(raw: string): boolean {
37
+ return raw.startsWith("G-") && /^[A-Z0-9]{1,32}$/.test(raw.slice(2));
38
+ }
39
+
40
+ /**
41
+ * Read the GA measurement id from the served document's boot tag. Returns
42
+ * null on every failure mode (tag missing, empty/whitespace content,
43
+ * envsubst leftover `$VAR` / `__VAR__` placeholder, malformed id) — every
44
+ * failure means "tracking disabled", never a throw.
45
+ *
46
+ * Read/placeholder semantics mirror the two hosts' `resolveMeasurementId`
47
+ * (their common intersection): `textContent` is trimmed, and a raw `$…` or
48
+ * `__…` prefix means the injection channel never ran. A malformed
49
+ * non-placeholder value silently returns null so a misconfigured deployment is
50
+ * discoverable in the console without polluting the page.
51
+ */
52
+ export function readGaMeasurementId(doc: Document = document): string | null {
53
+ let raw: string | null;
54
+ try {
55
+ raw = doc.getElementById(GA_TAG_ID)?.textContent?.trim() ?? null;
56
+ } catch {
57
+ return null; // doc-less context (prerender / workers)
58
+ }
59
+ if (raw === null || raw.length === 0 || raw.startsWith("$") || raw.startsWith("__")) {
60
+ return null;
61
+ }
62
+ if (!isValidGaMeasurementId(raw)) {
63
+ // Silent, exactly like both hosts' analytics.ts: the boot tag is our own
64
+ // deployment's payload, so an invalid id is a deploy-time mistake that
65
+ // other signals already surface — per-call warnings here would only spam
66
+ // re-renders.
67
+ return null;
68
+ }
69
+ return raw;
70
+ }
71
+
72
+ /** One compliance footer line: a title and an optional http(s) link. */
73
+ export interface SiteBeianLine {
74
+ title: string;
75
+ url?: string;
76
+ }
77
+
78
+ /**
79
+ * Parse the `beian_lines` setting (a JSON array of `{title, url?}`) into
80
+ * footer lines. Semantics aligned line-by-line with erp
81
+ * `packages/core/src/routes/auth.rs::sanitize_beian_lines` (the only
82
+ * backend that ships beian lines; chest's `CHEST_FOOTER_EXTRA` is a
83
+ * different shape and NOT handled here):
84
+ *
85
+ * - Non-JSON input, JSON that is not an array (`"null"`, objects, …) → `[]`.
86
+ * - An entry survives only as an object with a non-empty string `title`
87
+ * after trim; the title is capped at 64 characters (code points).
88
+ * - `url` absent or JSON null → plain-text line (`url` undefined).
89
+ * - A present string `url` is trimmed; empty after trim → plain-text line;
90
+ * otherwise it must start with `https://` or `http://` — a present but
91
+ * malformed url (relative, `javascript:`) drops the WHOLE entry, per the
92
+ * erp contract (half-rendered filing lines are worse than absent ones).
93
+ * - A non-string `url` drops the entry.
94
+ * - Output is capped at the first 4 surviving entries.
95
+ */
96
+ export function parseBeianLines(raw: string): Array<SiteBeianLine> {
97
+ let parsed: unknown;
98
+ try {
99
+ parsed = JSON.parse(raw) as unknown;
100
+ } catch {
101
+ return [];
102
+ }
103
+ if (!Array.isArray(parsed)) return [];
104
+ const lines: Array<SiteBeianLine> = [];
105
+ for (const entry of parsed) {
106
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
107
+ const record = entry as Record<string, unknown>;
108
+ const titleRaw = record["title"];
109
+ if (typeof titleRaw !== "string") continue;
110
+ const title = titleRaw.trim();
111
+ if (title.length === 0 || [...title].length > 64) continue;
112
+ const urlRaw = record["url"];
113
+ let url: string | undefined;
114
+ if (urlRaw !== undefined && urlRaw !== null) {
115
+ if (typeof urlRaw !== "string") continue;
116
+ const trimmed = urlRaw.trim();
117
+ if (trimmed.length === 0) {
118
+ url = undefined;
119
+ } else if (trimmed.startsWith("https://") || trimmed.startsWith("http://")) {
120
+ url = trimmed;
121
+ } else {
122
+ continue; // present-but-malformed url drops the whole entry
123
+ }
124
+ }
125
+ const line: SiteBeianLine = { title };
126
+ if (url !== undefined) line.url = url;
127
+ lines.push(line);
128
+ if (lines.length === 4) break;
129
+ }
130
+ return lines;
131
+ }
132
+
133
+ /**
134
+ * DOM id of the JSON boot tag carrying the raw `beian_lines` value (the
135
+ * JSON array `parseBeianLines` consumes). This is the ONE build-time channel
136
+ * this repo defines — but NO host emits it yet (2026-11-28 audit):
137
+ *
138
+ * - erp and chest both resolve the setting server-side and never emit it
139
+ * (erp serves the already-parsed array on `/api/auth/login-methods`; chest
140
+ * ships `CHEST_FOOTER_EXTRA` → `/health.footer_extra`, a different shape).
141
+ * - `celestia.ac.cn` still uses its own `celestia-footer-extra` tag, whose
142
+ * schema is WIDER than ours (it also accepts string arrays and a bare HTML
143
+ * string). Moving that site onto this channel is a host-side task, not a
144
+ * property of this module.
145
+ *
146
+ * Absence therefore reads as an empty footer everywhere today — which is the
147
+ * intended degradation, never an error.
148
+ */
149
+ export const BEIAN_TAG_ID = "celestia-beian-lines";
150
+
151
+ /**
152
+ * Read the beian lines from the served document's boot tag. Every failure
153
+ * mode (no document, tag absent, blank content) reads as "no compliance
154
+ * lines"; a present but malformed value also reads as `[]` rather than
155
+ * throwing, because a misconfigured deployment must not break the shell's
156
+ * footer render.
157
+ *
158
+ * The `$…` / `__…` placeholder guard is DEFENSIVE REDUNDANCY, and the honest
159
+ * statement of what it is worth: it is unobservable from outside. Any
160
+ * placeholder prefix makes the value fail `JSON.parse`, so `parseBeianLines`
161
+ * alone already answers `[]` — no behavioural assertion can distinguish "the
162
+ * guard rejected it" from "the parser rejected it" (mutation evidence: both
163
+ * deleting the guard and neutering it to a literal comparison leave the
164
+ * end-to-end assertions green). Its presence is therefore pinned
165
+ * structurally in `siteMeta.test.ts` (a text pin scoped to this function's
166
+ * body), which catches deletion / move / rename but does NOT prove the
167
+ * guard runs. It is kept — rather than deleted — for one reason only:
168
+ * parity with the two hosts' `analytics.ts`, which carry the same branch.
169
+ */
170
+ export function readBeianLines(doc: Document = document): Array<SiteBeianLine> {
171
+ let raw: string | null;
172
+ try {
173
+ raw = doc.getElementById(BEIAN_TAG_ID)?.textContent?.trim() ?? null;
174
+ } catch {
175
+ return []; // doc-less context (prerender / workers)
176
+ }
177
+ if (raw === null || raw.length === 0 || raw.startsWith("$") || raw.startsWith("__")) {
178
+ return [];
179
+ }
180
+ return parseBeianLines(raw);
181
+ }
182
+
183
+ /** What one site's deployment injected: the GA id and the compliance lines. */
184
+ export interface SiteMeta {
185
+ /** GA4 measurement id, or null when this deployment ships no tracking. */
186
+ gaMeasurementId: string | null;
187
+ /** Compliance/beian footer lines, already sanitized; empty when absent. */
188
+ beianLines: Array<SiteBeianLine>;
189
+ }
190
+
191
+ /**
192
+ * Read every host-injected site variable in one call. Deliberately NOT a
193
+ * Vue composable: nothing here is reactive (the boot tags are written once
194
+ * into the served document before any script runs, and never change for
195
+ * the life of the page), so wrapping it in `ref`s would only add weight.
196
+ * Hosts call it once at boot — erp/chest pass the result into their
197
+ * analytics + footer, static sites read it in the same place.
198
+ *
199
+ * `doc` is injectable so tests (and prerender contexts) never touch the
200
+ * ambient `document`.
201
+ */
202
+ export function readSiteMeta(doc: Document = document): SiteMeta {
203
+ return {
204
+ gaMeasurementId: readGaMeasurementId(doc),
205
+ beianLines: readBeianLines(doc),
206
+ };
207
+ }