@skyphusion/create-prism 1.0.0 → 1.2.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.
Files changed (54) hide show
  1. package/README.md +7 -4
  2. package/index.js +1 -0
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +18 -3
  5. package/template/MIGRATIONS.md +52 -0
  6. package/template/README.md +50 -16
  7. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
  8. package/template/docs/legal/INSTANCE-PRIVACY.md +127 -27
  9. package/template/migrations/0004_csp_reports.sql +58 -0
  10. package/template/migrations/0005_auth_attempts_retention.sql +23 -0
  11. package/template/package.json +6 -6
  12. package/template/public/app.js +42 -7
  13. package/template/public/index.html +24 -9
  14. package/template/public/stt.css +25 -0
  15. package/template/public/stt.html +1 -21
  16. package/template/public/styles.css +49 -0
  17. package/template/public/url-safety.js +66 -0
  18. package/template/schema.sql +64 -0
  19. package/template/src/ai-binding.ts +125 -3
  20. package/template/src/auth.ts +6 -0
  21. package/template/src/csp.ts +253 -0
  22. package/template/src/env.ts +11 -0
  23. package/template/src/gateway-credentials.ts +118 -22
  24. package/template/src/index.ts +79 -2
  25. package/template/src/providers/anthropic.ts +4 -4
  26. package/template/src/providers/openai-image.ts +10 -0
  27. package/template/src/providers/xai.ts +4 -4
  28. package/template/src/rate-limit.ts +26 -0
  29. package/template/src/routes/chat.ts +29 -16
  30. package/template/src/routes/csp-report.ts +163 -0
  31. package/template/src/routes/health.ts +6 -1
  32. package/template/src/routes/prefs.ts +46 -5
  33. package/template/src/routes/rag.ts +53 -15
  34. package/template/src/routes/shared.ts +22 -9
  35. package/template/src/routes/workflow.ts +2 -5
  36. package/template/src/stt-session.ts +16 -0
  37. package/template/src/user-prefs.ts +16 -3
  38. package/template/src/version.ts +18 -0
  39. package/template/tests/ai-binding-rest.test.ts +154 -0
  40. package/template/tests/csp.test.ts +449 -0
  41. package/template/tests/gateway-credentials.test.ts +101 -3
  42. package/template/tests/openai-image.test.ts +21 -1
  43. package/template/tests/public-url-safety.test.ts +360 -0
  44. package/template/tests/rag-metadata-filter.test.ts +135 -0
  45. package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
  46. package/template/tests/skip-link.test.ts +164 -0
  47. package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
  48. package/template/tests/version.test.ts +47 -0
  49. package/template/tests-integration/auth.test.ts +346 -2
  50. package/template/tests-integration/csp-report.test.ts +232 -0
  51. package/template/tests-integration/pdf-extract.test.ts +71 -0
  52. package/template/tests-integration/worker.test.ts +154 -0
  53. package/template/vitest.workers.config.ts +19 -4
  54. package/template/wrangler.example.toml +45 -2
@@ -1,10 +1,16 @@
1
1
  // Per-user preferences stored in D1 (v0.164.0).
2
2
  //
3
- // JSON blob keyed by Cloudflare Access email. Gateway fields are the first
4
- // use case for a public demo deployment where each visitor brings their own
5
- // AI Gateway slug and CF_AIG_TOKEN.
3
+ // JSON blob keyed by the caller's identity (Access email or public account
4
+ // id). Gateway fields are the first use case for a public demo deployment
5
+ // where each visitor brings their own AI Gateway.
6
+ //
7
+ // v1.1.0: account_id added. Being a key in the JSON blob, it needs no DDL;
8
+ // pre-v1.1.0 rows simply lack it and resolve as "account id required" in
9
+ // public mode (see resolveGateway in gateway-credentials.ts).
6
10
 
7
11
  export interface UserPrefsJson {
12
+ /** v1.1.0: Cloudflare account id (32 hex) that owns gateway_id. */
13
+ account_id?: string;
8
14
  gateway_id?: string;
9
15
  cf_aig_token?: string;
10
16
  /**
@@ -43,6 +49,13 @@ export async function saveUserPrefs(
43
49
  const existing = (await loadUserPrefs(db, userEmail)) ?? {};
44
50
  const merged: UserPrefsJson = { ...existing };
45
51
 
52
+ if (patch.account_id !== undefined) {
53
+ // Callers validate before saving; stored lowercase so comparisons and
54
+ // the URL builder see one canonical form.
55
+ const trimmed = patch.account_id.trim().toLowerCase();
56
+ if (trimmed) merged.account_id = trimmed;
57
+ else delete merged.account_id;
58
+ }
46
59
  if (patch.gateway_id !== undefined) {
47
60
  const trimmed = patch.gateway_id.trim();
48
61
  if (trimmed) merged.gateway_id = trimmed;
@@ -0,0 +1,18 @@
1
+ // The version this Worker advertises on its unauthenticated health surfaces.
2
+ //
3
+ // WHY THIS FILE EXISTS: a green deploy workflow proves the UPLOAD succeeded, not that the
4
+ // running Worker is the code you think it is. Without a version on the wire, "is the fix
5
+ // actually serving?" is answerable only with an account-scoped Cloudflare token, from a
6
+ // system separate from the one serving traffic (fleet-chezmoi#1641).
7
+ //
8
+ // WHY A GUARDED LITERAL AND NOT `import pkg from "../package.json"`: importing package.json
9
+ // would bundle the dependency list into a Worker whose whole point here is to disclose one
10
+ // short string, and it would put the manifest on the deployed surface. The literal is a copy
11
+ // -- but it is a copy that CANNOT SHIP WRONG, because tests/version.test.ts reads package.json
12
+ // off disk and derives the expected value from it rather than carrying a second hand-typed
13
+ // copy of the same string.
14
+ //
15
+ // That distinction is the entire point. In prism-mcp the advertised version was a literal and
16
+ // the test asserting it carried a TRANSCRIBED duplicate, so the assertion only ever proved
17
+ // that someone had typed the same thing twice, and a correct version bump went red.
18
+ export const VERSION = "1.2.0";
@@ -0,0 +1,154 @@
1
+ // Unit tests for the account-scoped transport in src/ai-binding.ts (v1.1.0).
2
+ //
3
+ // The AI binding is pinned to the worker's own Cloudflare account, so a user's
4
+ // gateway is only reachable over HTTP. These pin the request each transport
5
+ // builds and prove an account-scoped context never touches the binding.
6
+
7
+ import { afterEach, describe, expect, it, vi } from "vitest";
8
+ import {
9
+ aiLogId,
10
+ aiRun,
11
+ buildRestRunRequest,
12
+ gatewayProviderUrl,
13
+ unwrapRestResponse,
14
+ type AiContext,
15
+ } from "../src/ai-binding";
16
+ import type { Env } from "../src/env";
17
+
18
+ const ACCT = "0123456789abcdef0123456789abcdef";
19
+
20
+ // A binding that fails the test if anything reaches it.
21
+ function trapBinding(): Env["AI"] {
22
+ const trap = () => { throw new Error("host AI binding was called"); };
23
+ return { run: trap, gateway: trap, aiGatewayLogId: "host-log" } as unknown as Env["AI"];
24
+ }
25
+
26
+ function userCtx(): AiContext {
27
+ return {
28
+ env: { AI: trapBinding() } as Env,
29
+ gateway: { gatewayId: "user-gw", cfAigToken: "user-token", accountId: ACCT },
30
+ };
31
+ }
32
+
33
+ afterEach(() => { vi.unstubAllGlobals(); });
34
+
35
+ describe("buildRestRunRequest", () => {
36
+ it("partner models use the /ai/run envelope on the user's account", () => {
37
+ const { url, init } = buildRestRunRequest(ACCT, userCtx().gateway, "openai/gpt-5.5", { messages: [] });
38
+ expect(url).toBe(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/ai/run`);
39
+ const h = init.headers as Record<string, string>;
40
+ expect(h.authorization).toBe("Bearer user-token");
41
+ expect(h["cf-aig-gateway-id"]).toBe("user-gw");
42
+ expect(JSON.parse(init.body as string)).toEqual({ model: "openai/gpt-5.5", input: { messages: [] } });
43
+ });
44
+
45
+ it("Workers AI models use the model-in-path endpoint with bare params", () => {
46
+ const { url, init } = buildRestRunRequest(ACCT, userCtx().gateway, "@cf/baai/bge-base-en-v1.5", { text: ["a"] });
47
+ expect(url).toBe(`https://api.cloudflare.com/client/v4/accounts/${ACCT}/ai/run/@cf/baai/bge-base-en-v1.5`);
48
+ expect(JSON.parse(init.body as string)).toEqual({ text: ["a"] });
49
+ });
50
+ });
51
+
52
+ describe("aiRun transport selection", () => {
53
+ it("account-scoped: fetches the user's account and never touches the binding", async () => {
54
+ const fetchMock = vi.fn(async () => new Response(
55
+ JSON.stringify({ success: true, result: { response: "hi" }, errors: [] }),
56
+ { headers: { "content-type": "application/json", "cf-aig-log-id": "user-log" } },
57
+ ));
58
+ vi.stubGlobal("fetch", fetchMock);
59
+ const ctx = userCtx();
60
+ const out = await aiRun(ctx, "openai/gpt-5.5", { messages: [] });
61
+ expect(out).toEqual({ response: "hi" });
62
+ expect(fetchMock).toHaveBeenCalledTimes(1);
63
+ expect(aiLogId(ctx)).toBe("user-log");
64
+ });
65
+
66
+ it("account-scoped aiLogId never reads the host binding's log id", () => {
67
+ expect(aiLogId(userCtx())).toBeNull();
68
+ });
69
+
70
+ it("host context (accountId null) still uses the binding with the gateway id", async () => {
71
+ const run = vi.fn(async () => ({ ok: 1 }));
72
+ const ctx: AiContext = {
73
+ env: { AI: { run } } as unknown as Env,
74
+ gateway: { gatewayId: "host-gw", cfAigToken: "", accountId: null },
75
+ };
76
+ await aiRun(ctx, "@cf/x/y", { a: 1 });
77
+ expect(run).toHaveBeenCalledWith("@cf/x/y", { a: 1 }, { gateway: { id: "host-gw" } });
78
+ });
79
+ });
80
+
81
+ describe("gatewayProviderUrl", () => {
82
+ it("builds the provider-native URL from the user's account", async () => {
83
+ expect(await gatewayProviderUrl(userCtx(), "anthropic"))
84
+ .toBe(`https://gateway.ai.cloudflare.com/v1/${ACCT}/user-gw/anthropic`);
85
+ });
86
+
87
+ it("encodes a hostile stored slug rather than letting it rewrite the path", async () => {
88
+ const ctx = userCtx();
89
+ ctx.gateway.gatewayId = "../evil";
90
+ expect(await gatewayProviderUrl(ctx, "grok"))
91
+ .toBe(`https://gateway.ai.cloudflare.com/v1/${ACCT}/..%2Fevil/grok`);
92
+ });
93
+
94
+ it("host context delegates to the binding's getUrl", async () => {
95
+ const getUrl = vi.fn(async (p: string) => `https://gateway.ai.cloudflare.com/v1/host/host-gw/${p}`);
96
+ const ctx: AiContext = {
97
+ env: { AI: { gateway: () => ({ getUrl }) } } as unknown as Env,
98
+ gateway: { gatewayId: "host-gw", cfAigToken: "t", accountId: null },
99
+ };
100
+ expect(await gatewayProviderUrl(ctx, "anthropic")).toContain("/host/host-gw/anthropic");
101
+ });
102
+ });
103
+
104
+ describe("unwrapRestResponse", () => {
105
+ it("unwraps the Cloudflare API envelope", async () => {
106
+ const r = new Response(JSON.stringify({ success: true, result: { data: [[1]] } }), {
107
+ headers: { "content-type": "application/json" },
108
+ });
109
+ expect(await unwrapRestResponse(r, ACCT, false)).toEqual({ data: [[1]] });
110
+ });
111
+
112
+ it("passes non-envelope JSON through untouched", async () => {
113
+ const r = new Response(JSON.stringify({ type: "message", content: [] }), {
114
+ headers: { "content-type": "application/json" },
115
+ });
116
+ expect(await unwrapRestResponse(r, ACCT, false)).toEqual({ type: "message", content: [] });
117
+ });
118
+
119
+ it("throws on success:false with the API's message", async () => {
120
+ const r = new Response(JSON.stringify({ success: false, errors: [{ message: "no credits" }] }), {
121
+ headers: { "content-type": "application/json" },
122
+ });
123
+ await expect(unwrapRestResponse(r, ACCT, false)).rejects.toThrow(/no credits/);
124
+ });
125
+
126
+ it("a 401 names the permissions and the account, so the failure is actionable", async () => {
127
+ const r = new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: "Authentication error" }] }), {
128
+ status: 401,
129
+ headers: { "content-type": "application/json" },
130
+ });
131
+ await expect(unwrapRestResponse(r, ACCT, false))
132
+ .rejects.toThrow(new RegExp(`401: 10000 Authentication error.*Workers AI Read.*${ACCT}`));
133
+ });
134
+
135
+ it("returns the body stream for SSE", async () => {
136
+ const r = new Response("data: {}\n\n", { headers: { "content-type": "text/event-stream" } });
137
+ expect(await unwrapRestResponse(r, ACCT, false)).toBeInstanceOf(ReadableStream);
138
+ });
139
+
140
+ it("raw mode returns binary responses as-is", async () => {
141
+ const r = new Response(new Uint8Array([1, 2]), { headers: { "content-type": "audio/mpeg" } });
142
+ const out = await unwrapRestResponse(r, ACCT, true) as Response;
143
+ expect(new Uint8Array(await out.arrayBuffer())).toEqual(new Uint8Array([1, 2]));
144
+ });
145
+
146
+ it("raw mode turns a JSON { audio: base64 } result into audio bytes", async () => {
147
+ const r = new Response(JSON.stringify({ success: true, result: { audio: "AQI=" } }), {
148
+ headers: { "content-type": "application/json" },
149
+ });
150
+ const out = await unwrapRestResponse(r, ACCT, true) as Response;
151
+ expect(out.headers.get("content-type")).toBe("audio/mpeg");
152
+ expect(new Uint8Array(await out.arrayBuffer())).toEqual(new Uint8Array([1, 2]));
153
+ });
154
+ });
@@ -0,0 +1,449 @@
1
+ // Pure-logic tests for the CSP policy string and the violation projection
2
+ // (fleet-chezmoi#1646). The DB half is covered against the real fetch handler
3
+ // and real local D1 in tests-integration/worker.test.ts; these two suites cover
4
+ // different failure modes and neither substitutes for the other.
5
+
6
+ import { readFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { describe, expect, it } from "vitest";
10
+ import {
11
+ CSP_FIELD_CAPS,
12
+ CSP_HEADER,
13
+ CSP_HEADER_REPORT_ONLY,
14
+ CSP_REPORT_MAX_BYTES,
15
+ buildCspPolicy,
16
+ extractCspReport,
17
+ stripUrlNoise,
18
+ } from "../src/csp";
19
+
20
+ describe("the header name is the enforcing one", () => {
21
+ // The mode lives in the header NAME, not in the policy string, so a correct
22
+ // policy under the wrong name is a control that refuses nothing while every
23
+ // assertion about its directives keeps passing. Both names are asserted:
24
+ // the live one by value, the retired one by NOT being the live one, because
25
+ // "the report-only header is absent" is otherwise satisfied by a typo.
26
+ it("emits the enforcing header and not the report-only one", () => {
27
+ expect(CSP_HEADER).toBe("content-security-policy");
28
+ expect(CSP_HEADER).not.toBe(CSP_HEADER_REPORT_ONLY);
29
+ });
30
+
31
+ // Separate fact, and the one that actually decides the mode on the wire: the
32
+ // Worker must SET the constant rather than a literal typed a second time. A
33
+ // hand-typed header name in index.ts satisfies every assertion above while
34
+ // emitting whatever that literal happens to say.
35
+ it("the worker sets the header from the shared constant, not a literal", () => {
36
+ const src = readFileSync(
37
+ join(dirname(fileURLToPath(import.meta.url)), "../src/index.ts"),
38
+ "utf8",
39
+ );
40
+ expect(src).toContain("headers.set(CSP_HEADER, buildCspPolicy())");
41
+ expect(src).not.toContain('"content-security-policy-report-only"');
42
+ });
43
+
44
+ // Control: the retired constant really does hold the report-only spelling,
45
+ // so the assertion above is comparing against the right thing rather than
46
+ // against a value that could never have matched.
47
+ it("control: the retired constant is the report-only spelling", () => {
48
+ expect(CSP_HEADER_REPORT_ONLY).toBe("content-security-policy-report-only");
49
+ });
50
+ });
51
+
52
+ describe("enforcing policy string", () => {
53
+ const p = buildCspPolicy();
54
+
55
+ it("names the collector on the only transport a report has been seen to arrive over", () => {
56
+ expect(p).toContain("report-uri /api/csp-report");
57
+ });
58
+
59
+ // The collector is deliberately KEPT under enforcement. Dropping report-uri
60
+ // at promotion retires the instrument at the moment it starts describing
61
+ // real refusals, and the stored `disposition` is what separates an enforced
62
+ // block from a phase-one observation.
63
+ it("keeps reporting wired at whatever path the caller passes, not just the default", () => {
64
+ expect(buildCspPolicy("/elsewhere/collect")).toContain("report-uri /elsewhere/collect");
65
+ expect(buildCspPolicy("/elsewhere/collect")).not.toContain("report-uri /api/csp-report");
66
+ });
67
+
68
+ // REGRESSION GUARD, and it is the opposite of what it looks like. Adding
69
+ // `report-to` is the obvious modernisation and it is what this shipped first;
70
+ // measured, it SUPPRESSED delivery entirely while violations were still being
71
+ // registered by the browser. Whoever re-adds it owes a report observed
72
+ // ARRIVING over that transport.
73
+ it("does not declare report-to, which was measured to suppress delivery", () => {
74
+ expect(p).not.toContain("report-to");
75
+ });
76
+
77
+ it("carries the directives that make a strict baseline strict", () => {
78
+ for (const d of [
79
+ "default-src 'self'",
80
+ "script-src 'self'",
81
+ "style-src 'self'",
82
+ "connect-src 'self'",
83
+ "font-src 'self'",
84
+ "object-src 'none'",
85
+ "base-uri 'self'",
86
+ "form-action 'self'",
87
+ "frame-ancestors 'self'",
88
+ ]) {
89
+ expect(p).toContain(d);
90
+ }
91
+ });
92
+ });
93
+
94
+ describe("the two granted exceptions, and only those two", () => {
95
+ const p = buildCspPolicy();
96
+ // Each directive is read as its own segment. Substring matching cannot tell
97
+ // `img-src 'self' data:` from a `data:` that leaked into some other
98
+ // directive, and the whole value of this suite is that distinction.
99
+ const seg = (name: string): string => {
100
+ const found = p.split("; ").find((d) => d.startsWith(`${name} `));
101
+ if (!found) throw new Error(`directive ${name} absent from policy`);
102
+ return found;
103
+ };
104
+
105
+ it("control: the segment reader finds a directive that is definitely present", () => {
106
+ expect(seg("default-src")).toBe("default-src 'self'");
107
+ });
108
+
109
+ it("control: the segment reader throws rather than returning empty for an absent directive", () => {
110
+ expect(() => seg("child-src")).toThrow(/absent/);
111
+ });
112
+
113
+ // GRANT 1. Observed as `img-src | data` in the report-only phase: attachment
114
+ // thumbnails, video-frame previews, and the downscale path, all rendering a
115
+ // data: URL the page produced from a local file that is never uploaded.
116
+ it("grants data: to img-src, which was observed violating", () => {
117
+ expect(seg("img-src")).toBe("img-src 'self' data:");
118
+ });
119
+
120
+ // GRANT 2. Observed as `media-src | blob`: TTS playback wraps an Audio around
121
+ // a blob: URL minted from a same-origin response.
122
+ it("grants blob: to media-src, which was observed violating", () => {
123
+ expect(seg("media-src")).toBe("media-src 'self' blob:");
124
+ });
125
+
126
+ // THE SCOPE OF THE RULING. Exactly two directives widened. Each of these is
127
+ // asserted on its OWN directive rather than on the whole policy string, so a
128
+ // failure names which directive drifted instead of reporting that something
129
+ // somewhere contains "data:".
130
+ it("does not leak data: into script-src", () => {
131
+ expect(seg("script-src")).toBe("script-src 'self'");
132
+ });
133
+
134
+ it("does not leak blob: or data: into connect-src", () => {
135
+ expect(seg("connect-src")).toBe("connect-src 'self'");
136
+ });
137
+
138
+ it("does not widen style-src, whose violations were fixed in the page instead", () => {
139
+ expect(seg("style-src")).toBe("style-src 'self'");
140
+ });
141
+
142
+ it("does not widen font-src, which was measured to need nothing", () => {
143
+ expect(seg("font-src")).toBe("font-src 'self'");
144
+ });
145
+
146
+ it("keeps object-src at none", () => {
147
+ expect(seg("object-src")).toBe("object-src 'none'");
148
+ });
149
+
150
+ // The absences that make the grants a grant rather than a relaxation pass.
151
+ it("admits no inline or eval execution anywhere in the policy", () => {
152
+ expect(p).not.toContain("unsafe-inline");
153
+ expect(p).not.toContain("unsafe-eval");
154
+ expect(p).not.toContain("unsafe-hashes");
155
+ expect(p).not.toContain("*");
156
+ });
157
+
158
+ // Counting is the guard a later reader is least likely to think of: it goes
159
+ // red when a THIRD grant is added, even one this file never anticipated and
160
+ // therefore has no named assertion for.
161
+ it("exactly two directives carry a scheme source, and they are the two granted", () => {
162
+ const widened = p
163
+ .split("; ")
164
+ .filter((d) => /(^|\s)(data|blob|https?|ws|wss|filesystem|mediastream):/.test(d));
165
+ expect(widened.sort()).toEqual(["img-src 'self' data:", "media-src 'self' blob:"]);
166
+ });
167
+
168
+ it("control: the scheme matcher fires on a policy that carries a third grant", () => {
169
+ const widened = "default-src 'self'; img-src 'self' data:; font-src 'self' https:"
170
+ .split("; ")
171
+ .filter((d) => /(^|\s)(data|blob|https?|ws|wss|filesystem|mediastream):/.test(d));
172
+ expect(widened).toHaveLength(2);
173
+ expect(widened).toContain("font-src 'self' https:");
174
+ });
175
+ });
176
+
177
+ // ROUTE ORDERING, asserted here because the integration suite structurally
178
+ // cannot see it. That pool binds no AUTH_MODE, so `authMode(env)` is never
179
+ // "public" and the public-mode gate never executes there; an "unauthenticated
180
+ // access works" test would pass identically whether the collector sat above or
181
+ // below the gate. This is a source assertion and it says so, but it is a source
182
+ // assertion about the one property that decides whether the collector collects
183
+ // anything at all: browsers post violation reports WITHOUT credentials, so a
184
+ // session-gated collector is an empty table forever.
185
+ describe("the collector is routed above the public-mode auth gate", () => {
186
+ const indexSrc = readFileSync(
187
+ join(dirname(fileURLToPath(import.meta.url)), "../src/index.ts"),
188
+ "utf8",
189
+ );
190
+
191
+ const gateMarker = 'authMode(env) === "public" &&';
192
+ const routeMarker = 'url.pathname === "/api/csp-report"';
193
+
194
+ // Controls first, so a matcher that has stopped matching fails as a broken
195
+ // instrument rather than as a passing ordering claim.
196
+ it("both markers are present (control)", () => {
197
+ expect(indexSrc).toContain(gateMarker);
198
+ expect(indexSrc).toContain(routeMarker);
199
+ });
200
+
201
+ it("the collector route appears before the gate", () => {
202
+ const routeAt = indexSrc.indexOf(routeMarker);
203
+ const gateAt = indexSrc.indexOf(gateMarker);
204
+ expect(routeAt).toBeGreaterThan(-1);
205
+ expect(gateAt).toBeGreaterThan(-1);
206
+ expect(
207
+ routeAt,
208
+ "the CSP collector must be routed ABOVE the public-mode gate; browsers " +
209
+ "post violation reports with no credentials, so a gated collector " +
210
+ "silently collects nothing",
211
+ ).toBeLessThan(gateAt);
212
+ });
213
+ });
214
+
215
+ describe("stripUrlNoise", () => {
216
+ it("removes query and fragment", () => {
217
+ expect(stripUrlNoise("https://play.skyphusion.org/x?a=1&b=2#frag")).toBe(
218
+ "https://play.skyphusion.org/x",
219
+ );
220
+ });
221
+
222
+ it("leaves a clean URL alone", () => {
223
+ expect(stripUrlNoise("https://play.skyphusion.org/")).toBe("https://play.skyphusion.org/");
224
+ });
225
+
226
+ it("returns an unparseable value capped rather than dropping it", () => {
227
+ // Knowing a violation happened somewhere unrecognisable beats a null.
228
+ expect(stripUrlNoise("not a url")).toBe("not a url");
229
+ });
230
+
231
+ it("caps length", () => {
232
+ const long = "https://x.example/" + "a".repeat(5000);
233
+ expect(stripUrlNoise(long)!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.document_uri);
234
+ });
235
+
236
+ it("returns null for non-strings and blanks", () => {
237
+ expect(stripUrlNoise(null)).toBeNull();
238
+ expect(stripUrlNoise(42)).toBeNull();
239
+ expect(stripUrlNoise(" ")).toBeNull();
240
+ });
241
+ });
242
+
243
+ describe("extractCspReport", () => {
244
+ it("reads the legacy report-uri shape", () => {
245
+ const r = extractCspReport({
246
+ "csp-report": {
247
+ "document-uri": "https://play.skyphusion.org/?x=1",
248
+ "violated-directive": "style-src 'self'",
249
+ "effective-directive": "style-src-attr",
250
+ "blocked-uri": "inline",
251
+ disposition: "report",
252
+ "status-code": 200,
253
+ "line-number": 47,
254
+ },
255
+ });
256
+ expect(r).not.toBeNull();
257
+ expect(r!.document_uri).toBe("https://play.skyphusion.org/");
258
+ expect(r!.effective_directive).toBe("style-src-attr");
259
+ expect(r!.blocked_uri).toBe("inline");
260
+ expect(r!.status_code).toBe(200);
261
+ expect(r!.line_number).toBe(47);
262
+ });
263
+
264
+ it("reads the Reporting API shape", () => {
265
+ const r = extractCspReport([
266
+ {
267
+ type: "csp-violation",
268
+ body: {
269
+ documentURL: "https://play.skyphusion.org/",
270
+ effectiveDirective: "img-src",
271
+ blockedURL: "data:image/png;base64,AAAA",
272
+ disposition: "report",
273
+ },
274
+ },
275
+ ]);
276
+ expect(r).not.toBeNull();
277
+ expect(r!.effective_directive).toBe("img-src");
278
+ expect(r!.blocked_uri).toBe("data:image/png;base64,AAAA");
279
+ });
280
+
281
+ // Returning null rather than an all-null row is load-bearing: an empty row
282
+ // records "a violation happened with no detail", which is indistinguishable
283
+ // from a collector mangling its input.
284
+ it("returns null when neither wire shape is present", () => {
285
+ expect(extractCspReport({})).toBeNull();
286
+ expect(extractCspReport([])).toBeNull();
287
+ expect(extractCspReport({ nonsense: 1 })).toBeNull();
288
+ expect(extractCspReport([{ type: "deprecation", body: {} }])).toBeNull();
289
+ expect(extractCspReport("a string")).toBeNull();
290
+ expect(extractCspReport(null)).toBeNull();
291
+ });
292
+
293
+ it("never persists script-sample under any key", () => {
294
+ // Privacy call: script-sample can carry inline-script fragments from a page
295
+ // that handles a credential. A violation is diagnosable without it.
296
+ const r = extractCspReport({
297
+ "csp-report": {
298
+ "document-uri": "https://play.skyphusion.org/",
299
+ "script-sample": "const token = 'SUPER SECRET VALUE'",
300
+ "effective-directive": "script-src",
301
+ },
302
+ });
303
+ expect(r).not.toBeNull();
304
+ expect(JSON.stringify(r)).not.toContain("SUPER SECRET");
305
+ expect(Object.keys(r!)).not.toContain("script_sample");
306
+ });
307
+
308
+ it("caps every string field against a hostile oversized report", () => {
309
+ const huge = "z".repeat(9000);
310
+ const r = extractCspReport({
311
+ "csp-report": {
312
+ "document-uri": huge,
313
+ referrer: huge,
314
+ "violated-directive": huge,
315
+ "effective-directive": huge,
316
+ "blocked-uri": huge,
317
+ disposition: huge,
318
+ "source-file": huge,
319
+ },
320
+ })!;
321
+ expect(r.referrer!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.referrer);
322
+ expect(r.violated_directive!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.violated_directive);
323
+ expect(r.effective_directive!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.effective_directive);
324
+ expect(r.blocked_uri!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.blocked_uri);
325
+ expect(r.disposition!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.disposition);
326
+ expect(r.source_file!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.source_file);
327
+ expect(r.document_uri!.length).toBeLessThanOrEqual(CSP_FIELD_CAPS.document_uri);
328
+ });
329
+
330
+ it("refuses non-numeric and out-of-range numerics rather than coercing", () => {
331
+ const r = extractCspReport({
332
+ "csp-report": {
333
+ "document-uri": "https://x.example/",
334
+ "status-code": "200",
335
+ "line-number": -5,
336
+ "column-number": 1e12,
337
+ },
338
+ })!;
339
+ expect(r.status_code).toBeNull();
340
+ expect(r.line_number).toBeNull();
341
+ expect(r.column_number).toBeNull();
342
+ });
343
+
344
+ it("exports a body cap that is bounded and non-trivial", () => {
345
+ expect(CSP_REPORT_MAX_BYTES).toBeGreaterThan(1024);
346
+ expect(CSP_REPORT_MAX_BYTES).toBeLessThanOrEqual(65536);
347
+ });
348
+ });
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // SOURCE GUARDS FOR THE INLINE-CSS SURFACES (fleet-chezmoi#1646).
352
+ //
353
+ // The report-only collector observed exactly one of these, because it can only
354
+ // observe a page somebody loaded. These assert on the served files themselves,
355
+ // so a re-introduced inline style is a red test rather than a violation nobody
356
+ // happens to trip. Every matcher runs its positive control FIRST: a matcher
357
+ // that has stopped matching returns zero, and zero reads exactly like clean.
358
+ // ---------------------------------------------------------------------------
359
+ describe("the served documents carry no inline CSS", () => {
360
+ const pub = (f: string) =>
361
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../public/", f), "utf8");
362
+
363
+ const INLINE_STYLE_ATTR = /<[a-z][^>]*\sstyle\s*=\s*["']/i;
364
+ const INLINE_STYLE_ELEM = /<style[\s>]/i;
365
+
366
+ it("control: both matchers fire on a subject known to contain the thing", () => {
367
+ expect(INLINE_STYLE_ATTR.test('<a class="x" style="left:-1px">y</a>')).toBe(true);
368
+ expect(INLINE_STYLE_ELEM.test("<head>\n <style>\n .a { color: red; }\n </style>")).toBe(true);
369
+ // Negative half: neither may fire on the shape that must be allowed through.
370
+ expect(INLINE_STYLE_ATTR.test('<link rel="stylesheet" href="/stt.css">')).toBe(false);
371
+ expect(INLINE_STYLE_ELEM.test('<link rel="stylesheet" href="/styles.css">')).toBe(false);
372
+ });
373
+
374
+ // index.html:47 was the collector's first genuine finding:
375
+ // style-src-attr | inline | line 47. The offscreen positioning moved to a
376
+ // stylesheet rule, where it stays. fc#1700 then renamed that rule from
377
+ // `.seo-skip` to `.skip-link` and gave it the `:focus` reveal it never had;
378
+ // the CSP invariant asserted here is unchanged by that, and the element is
379
+ // still the first focusable element in the body. The accessibility half is
380
+ // asserted in tests/skip-link.test.ts, not here.
381
+ it("index.html has no inline style attribute", () => {
382
+ expect(INLINE_STYLE_ATTR.test(pub("index.html"))).toBe(false);
383
+ });
384
+
385
+ it("index.html has no inline <style> element", () => {
386
+ expect(INLINE_STYLE_ELEM.test(pub("index.html"))).toBe(false);
387
+ });
388
+
389
+ // stt.html carried a 19-rule inline <style> block. It never reported, because
390
+ // the STT document was serving with no policy header at all (see below), so
391
+ // an enforcing promotion would have taken the whole page layout with nothing
392
+ // in the collector having predicted it.
393
+ it("stt.html has no inline <style> element", () => {
394
+ expect(INLINE_STYLE_ELEM.test(pub("stt.html"))).toBe(false);
395
+ });
396
+
397
+ it("stt.html has no inline style attribute", () => {
398
+ expect(INLINE_STYLE_ATTR.test(pub("stt.html"))).toBe(false);
399
+ });
400
+
401
+ it("the rules stt.html used to inline are still served, from stt.css", () => {
402
+ const css = pub("stt.css");
403
+ expect(pub("stt.html")).toContain('<link rel="stylesheet" href="/stt.css">');
404
+ for (const sel of [".stt-layout", ".stt-controls", "#stt-start", ".stt-live", ".stt-debug"]) {
405
+ expect(css).toContain(sel);
406
+ }
407
+ });
408
+
409
+ it("the offscreen positioning the skip link lost is present in styles.css", () => {
410
+ const css = pub("styles.css");
411
+ expect(css).toMatch(/\.skip-link\s*\{[^}]*position:\s*absolute/);
412
+ expect(css).toMatch(/\.skip-link\s*\{[^}]*left:\s*-9999px/);
413
+ expect(pub("index.html")).toContain('class="skip-link"');
414
+ // No inline style attribute crept back onto the element itself.
415
+ expect(pub("index.html")).not.toMatch(/<a class="skip-link"[^>]*\sstyle\s*=/);
416
+ });
417
+ });
418
+
419
+ // WHAT THIS GUARD CANNOT SEE, stated here rather than in a PR comment: it reads
420
+ // the TEMPLATE. `wrangler.toml` is gitignored and per-deployer, so a green run
421
+ // says the template is right and says nothing about any live deploy. Confirming
422
+ // the header on the wire is a separate act and stays one.
423
+ describe("run_worker_first names the paths the documents are actually served at", () => {
424
+ const toml = readFileSync(
425
+ join(dirname(fileURLToPath(import.meta.url)), "../wrangler.example.toml"),
426
+ "utf8",
427
+ );
428
+
429
+ it("control: the setting is present in the template at all", () => {
430
+ expect(toml).toContain("run_worker_first");
431
+ });
432
+
433
+ // MEASURED on a local dev server, not reasoned: `/stt.html` answers
434
+ // `307 -> /stt`, and `/stt` answered `200 text/html` with NO policy header
435
+ // while only the redirecting spelling was listed. Workers Assets drops the
436
+ // `.html` by default, so the extensionless path is the one a browser holds
437
+ // the document at. A listed path that only redirects fails silently: the page
438
+ // carries no policy, reports nothing, and an empty collector reads as clean.
439
+ it("covers the extensionless STT path, not only the redirecting one", () => {
440
+ const line = toml.split("\n").find((l) => l.trim().startsWith("run_worker_first"));
441
+ expect(line, "run_worker_first line not found in the template").toBeDefined();
442
+ expect(line).toContain('"/stt"');
443
+ });
444
+
445
+ it("still covers the root document", () => {
446
+ const line = toml.split("\n").find((l) => l.trim().startsWith("run_worker_first"));
447
+ expect(line).toContain('"/"');
448
+ });
449
+ });