@skyphusion/create-prism 1.0.0 → 1.0.4

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,444 @@
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
376
+ // the `.seo-skip` rule in styles.css; the element and its behaviour are
377
+ // unchanged, and it is still the first focusable element in the body.
378
+ it("index.html has no inline style attribute", () => {
379
+ expect(INLINE_STYLE_ATTR.test(pub("index.html"))).toBe(false);
380
+ });
381
+
382
+ it("index.html has no inline <style> element", () => {
383
+ expect(INLINE_STYLE_ELEM.test(pub("index.html"))).toBe(false);
384
+ });
385
+
386
+ // stt.html carried a 19-rule inline <style> block. It never reported, because
387
+ // the STT document was serving with no policy header at all (see below), so
388
+ // an enforcing promotion would have taken the whole page layout with nothing
389
+ // in the collector having predicted it.
390
+ it("stt.html has no inline <style> element", () => {
391
+ expect(INLINE_STYLE_ELEM.test(pub("stt.html"))).toBe(false);
392
+ });
393
+
394
+ it("stt.html has no inline style attribute", () => {
395
+ expect(INLINE_STYLE_ATTR.test(pub("stt.html"))).toBe(false);
396
+ });
397
+
398
+ it("the rules stt.html used to inline are still served, from stt.css", () => {
399
+ const css = pub("stt.css");
400
+ expect(pub("stt.html")).toContain('<link rel="stylesheet" href="/stt.css">');
401
+ for (const sel of [".stt-layout", ".stt-controls", "#stt-start", ".stt-live", ".stt-debug"]) {
402
+ expect(css).toContain(sel);
403
+ }
404
+ });
405
+
406
+ it("the offscreen positioning the skip link lost is present in styles.css", () => {
407
+ const css = pub("styles.css");
408
+ expect(css).toMatch(/\.seo-skip\s*\{[^}]*position:\s*absolute/);
409
+ expect(css).toMatch(/\.seo-skip\s*\{[^}]*left:\s*-9999px/);
410
+ expect(pub("index.html")).toContain('class="seo-skip"');
411
+ });
412
+ });
413
+
414
+ // WHAT THIS GUARD CANNOT SEE, stated here rather than in a PR comment: it reads
415
+ // the TEMPLATE. `wrangler.toml` is gitignored and per-deployer, so a green run
416
+ // says the template is right and says nothing about any live deploy. Confirming
417
+ // the header on the wire is a separate act and stays one.
418
+ describe("run_worker_first names the paths the documents are actually served at", () => {
419
+ const toml = readFileSync(
420
+ join(dirname(fileURLToPath(import.meta.url)), "../wrangler.example.toml"),
421
+ "utf8",
422
+ );
423
+
424
+ it("control: the setting is present in the template at all", () => {
425
+ expect(toml).toContain("run_worker_first");
426
+ });
427
+
428
+ // MEASURED on a local dev server, not reasoned: `/stt.html` answers
429
+ // `307 -> /stt`, and `/stt` answered `200 text/html` with NO policy header
430
+ // while only the redirecting spelling was listed. Workers Assets drops the
431
+ // `.html` by default, so the extensionless path is the one a browser holds
432
+ // the document at. A listed path that only redirects fails silently: the page
433
+ // carries no policy, reports nothing, and an empty collector reads as clean.
434
+ it("covers the extensionless STT path, not only the redirecting one", () => {
435
+ const line = toml.split("\n").find((l) => l.trim().startsWith("run_worker_first"));
436
+ expect(line, "run_worker_first line not found in the template").toBeDefined();
437
+ expect(line).toContain('"/stt"');
438
+ });
439
+
440
+ it("still covers the root document", () => {
441
+ const line = toml.split("\n").find((l) => l.trim().startsWith("run_worker_first"));
442
+ expect(line).toContain('"/"');
443
+ });
444
+ });