@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyphusion/create-prism",
3
- "version": "1.0.0",
3
+ "version": "1.0.4",
4
4
  "description": "Scaffold a new prism deployment: a multimodal AI playground on Cloudflare Workers.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Conrad Rockenhaus",
@@ -0,0 +1,58 @@
1
+ -- 0004: CSP violation collector (fleet-chezmoi#1646).
2
+ --
3
+ -- Two tables, and the split is the point. `csp_report_buckets` is a rate-limit
4
+ -- counter and could have reused `auth_attempts`, which already has exactly this
5
+ -- shape and a prefixed bucket-key namespace. It deliberately does not.
6
+ --
7
+ -- WHY: the collector's write endpoint is UNAUTHENTICATED by construction, because
8
+ -- browsers post CSP reports without credentials. Pointing an unauthenticated
9
+ -- public write path at the same table the LOGIN limiter depends on means a flood
10
+ -- against the collector contends with sign-in. One extra table is a cheap price
11
+ -- for not coupling a public write path to the auth path.
12
+ --
13
+ -- Apply to an existing database with:
14
+ -- npx wrangler d1 execute skyphusion-llm --remote --file=migrations/0004_csp_reports.sql
15
+ -- Fresh databases get this from schema.sql.
16
+
17
+ -- Collected violations. Every column is a BOUNDED projection of an
18
+ -- attacker-controlled report body; nothing is stored verbatim.
19
+ --
20
+ -- NOT STORED, deliberately: `script-sample`. It can carry fragments of inline
21
+ -- script from a page that handles a credential, and a violation is diagnosable
22
+ -- from the directive plus the blocked URI without it.
23
+ CREATE TABLE IF NOT EXISTS csp_reports (
24
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
25
+ received_at TEXT NOT NULL DEFAULT (datetime('now')),
26
+ -- document_uri is stored with query and fragment STRIPPED. The SPA puts
27
+ -- nothing in URLs (measured), so this costs nothing today and stops the
28
+ -- collector becoming the first place a URL-borne value is persisted.
29
+ document_uri TEXT,
30
+ referrer TEXT,
31
+ violated_directive TEXT,
32
+ effective_directive TEXT,
33
+ blocked_uri TEXT,
34
+ disposition TEXT,
35
+ status_code INTEGER,
36
+ source_file TEXT,
37
+ line_number INTEGER,
38
+ column_number INTEGER
39
+ );
40
+
41
+ -- Read path is operator-only and deliberately has no HTTP endpoint: there is no
42
+ -- admin role on this product, so an authenticated read route would let any
43
+ -- signed-up user read operator diagnostics from a credential-handling page.
44
+ -- Operators query with:
45
+ -- npx wrangler d1 execute skyphusion-llm --remote \
46
+ -- --command "SELECT received_at, effective_directive, blocked_uri, document_uri
47
+ -- FROM csp_reports ORDER BY id DESC LIMIT 50;"
48
+ CREATE INDEX IF NOT EXISTS idx_csp_reports_received ON csp_reports(received_at);
49
+
50
+ -- Rate-limit buckets for the collector, isolated from auth_attempts per the note
51
+ -- above. `dropped` is what makes shedding VISIBLE: without it a rate-limited
52
+ -- estate and a quiet one produce an identical empty table.
53
+ CREATE TABLE IF NOT EXISTS csp_report_buckets (
54
+ bucket_key TEXT PRIMARY KEY,
55
+ count INTEGER NOT NULL DEFAULT 0,
56
+ dropped INTEGER NOT NULL DEFAULT 0,
57
+ window_start TEXT NOT NULL DEFAULT (datetime('now'))
58
+ );
@@ -21,12 +21,12 @@
21
21
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
22
22
  },
23
23
  "devDependencies": {
24
- "@cloudflare/vitest-pool-workers": "^0.20.1",
25
- "@cloudflare/workers-types": "^5.20260804.1",
26
- "@types/node": "^26.1.2",
24
+ "@cloudflare/vitest-pool-workers": "^0.20.3",
25
+ "@cloudflare/workers-types": "^5.20260809.1",
26
+ "@types/node": "^26.2.0",
27
27
  "@vitest/coverage-v8": "^4.1.10",
28
28
  "typescript": "^7.0.2",
29
29
  "vitest": "^4.1.8",
30
- "wrangler": "^4.118.0"
30
+ "wrangler": "^4.120.0"
31
31
  }
32
32
  }
@@ -886,7 +886,7 @@ function renderRetrievedChunksHTML(chunks) {
886
886
  <span class="rc-file">${escapeHtml(c.title || "?")}</span>
887
887
  <span class="rc-meta">${escapeHtml(sourceLabel)}${score}</span>
888
888
  </summary>
889
- <pre class="rc-text"><a href="${escapeHtml(c.url || "#")}" target="_blank" rel="noopener noreferrer">${escapeHtml(c.url || "")}</a>
889
+ <pre class="rc-text"><a href="${escapeHtml(window.safeHref(c.url))}" target="_blank" rel="noopener noreferrer">${escapeHtml(c.url || "")}</a>
890
890
 
891
891
  ${escapeHtml(c.snippet || "")}</pre>
892
892
  </details>`;
@@ -2392,6 +2392,17 @@ async function openGatewayModal() {
2392
2392
 
2393
2393
  function closeGatewayModal() {
2394
2394
  if (gatewayModal) gatewayModal.hidden = true;
2395
+ // Drop the plaintext credentials out of the DOM on the way out, so no
2396
+ // client-side copy of either secret outlives the modal that collected
2397
+ // it. The clear lives HERE rather than at the call sites because every
2398
+ // dismissal already routes through this function (save success, the
2399
+ // cancel button, the backdrop, the X affordance, Escape): one clear on
2400
+ // the single chokepoint holds by construction, where five clears hold
2401
+ // only while all five stay correct. Adding a sixth dismissal path gets
2402
+ // this for free; tests/public-url-safety.test.ts asserts the routing
2403
+ // stays true so that stops being an assumption.
2404
+ if (gatewayModalToken) gatewayModalToken.value = "";
2405
+ if (gatewayModalCpKey) gatewayModalCpKey.value = "";
2395
2406
  }
2396
2407
 
2397
2408
  function showGatewayModalError(msg) {
@@ -2848,6 +2859,17 @@ function openAccountDeleteModal() {
2848
2859
  }
2849
2860
  function closeAccountDeleteModal() {
2850
2861
  if (accountDeleteModal) accountDeleteModal.hidden = true;
2862
+ // Drop the password out of the DOM on the way out, matching the AI Gateway
2863
+ // modal. All four dismissal paths route through here (the backdrop and the
2864
+ // close affordance via data-modal-close, Escape, and the cancel button), and
2865
+ // the success path calls location.reload(), so the value cannot outlive the
2866
+ // modal by either route.
2867
+ //
2868
+ // Deliberately NOT cleared on a failed delete: a wrong password leaves the
2869
+ // modal open with the value intact so the user can correct it. Clearing on
2870
+ // dismissal and clearing on every error are different rules, and only the
2871
+ // first one is wanted here.
2872
+ if (accountDeletePassword) accountDeletePassword.value = "";
2851
2873
  }
2852
2874
  async function submitAccountDelete() {
2853
2875
  const password = accountDeletePassword ? accountDeletePassword.value : "";
@@ -44,7 +44,7 @@
44
44
  </script>
45
45
  </head>
46
46
  <body>
47
- <a class="seo-skip" href="#auth-screen" style="position:absolute;left:-9999px">Prism multimodal AI playground: sign up or log in</a>
47
+ <a class="seo-skip" href="#auth-screen">Prism multimodal AI playground: sign up or log in</a>
48
48
  <!-- #80 public-mode first-party auth. Hidden by default; the boot probe
49
49
  (GET /api/session) reveals it only when mode=public and no session.
50
50
  Access / self-host deploys report mode=access and never show it. -->
@@ -369,6 +369,7 @@
369
369
  </div>
370
370
  </div>
371
371
 
372
+ <script src="/url-safety.js"></script>
372
373
  <script src="/voice-widget.js"></script>
373
374
  <script src="/app.js"></script>
374
375
  </body>
@@ -0,0 +1,25 @@
1
+ /* Conversational STT page chrome. Loaded by stt.html alongside styles.css.
2
+ These rules lived in an inline <style> block in stt.html until fc#1646.
3
+ An enforcing `style-src 'self'` blocks an inline <style> element, which
4
+ would have taken the entire layout of this page; an external sheet needs
5
+ no policy exception. Rules are unchanged, only relocated and dedented. */
6
+
7
+ .stt-layout { max-width: 820px; margin: 0 auto; padding: 1rem; }
8
+ .stt-controls { display: flex; align-items: center; gap: 1rem; margin: 1rem 0; }
9
+ #stt-start { font-size: 1rem; padding: 0.6rem 1.4rem; border-radius: 999px; cursor: pointer; }
10
+ #stt-start.is-live { background: #b3122c; color: #fff; }
11
+ .stt-status { opacity: 0.8; font-size: 0.9rem; }
12
+ .stt-live { min-height: 3.5rem; font-size: 1.25rem; line-height: 1.5; padding: 0.75rem 1rem;
13
+ border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; margin-bottom: 1rem; }
14
+ .stt-live-interim { opacity: 0.55; font-style: italic; }
15
+ .stt-turns { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 1.5rem; }
16
+ .stt-turn { padding: 0.5rem 0.75rem; border-radius: 8px; background: rgba(255,255,255,0.05); }
17
+ .stt-meta { font-size: 0.78rem; opacity: 0.6; }
18
+ .stt-debug { font-family: ui-monospace, monospace; font-size: 0.72rem; white-space: pre-wrap;
19
+ max-height: 220px; overflow-y: auto; background: rgba(0,0,0,0.25); padding: 0.5rem;
20
+ border-radius: 8px; }
21
+ .stt-debug-row { padding: 1px 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
22
+ summary { cursor: pointer; opacity: 0.8; }
23
+ .stt-page-header { margin-bottom: 0.5rem; }
24
+ .stt-back { font-size: 0.85rem; opacity: 0.7; text-decoration: none; }
25
+ .stt-back:hover { opacity: 1; }
@@ -11,27 +11,7 @@
11
11
  <link rel="manifest" href="/manifest.webmanifest">
12
12
  <meta name="theme-color" content="#0E1730">
13
13
  <link rel="stylesheet" href="/styles.css">
14
- <style>
15
- .stt-layout { max-width: 820px; margin: 0 auto; padding: 1rem; }
16
- .stt-controls { display: flex; align-items: center; gap: 1rem; margin: 1rem 0; }
17
- #stt-start { font-size: 1rem; padding: 0.6rem 1.4rem; border-radius: 999px; cursor: pointer; }
18
- #stt-start.is-live { background: #b3122c; color: #fff; }
19
- .stt-status { opacity: 0.8; font-size: 0.9rem; }
20
- .stt-live { min-height: 3.5rem; font-size: 1.25rem; line-height: 1.5; padding: 0.75rem 1rem;
21
- border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; margin-bottom: 1rem; }
22
- .stt-live-interim { opacity: 0.55; font-style: italic; }
23
- .stt-turns { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 1.5rem; }
24
- .stt-turn { padding: 0.5rem 0.75rem; border-radius: 8px; background: rgba(255,255,255,0.05); }
25
- .stt-meta { font-size: 0.78rem; opacity: 0.6; }
26
- .stt-debug { font-family: ui-monospace, monospace; font-size: 0.72rem; white-space: pre-wrap;
27
- max-height: 220px; overflow-y: auto; background: rgba(0,0,0,0.25); padding: 0.5rem;
28
- border-radius: 8px; }
29
- .stt-debug-row { padding: 1px 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
30
- summary { cursor: pointer; opacity: 0.8; }
31
- .stt-page-header { margin-bottom: 0.5rem; }
32
- .stt-back { font-size: 0.85rem; opacity: 0.7; text-decoration: none; }
33
- .stt-back:hover { opacity: 1; }
34
- </style>
14
+ <link rel="stylesheet" href="/stt.css">
35
15
  </head>
36
16
  <body class="stt-body">
37
17
  <!-- Conversational STT is a skyphusion-llm playground feature; standalone
@@ -25,6 +25,17 @@
25
25
 
26
26
  * { box-sizing: border-box; }
27
27
 
28
+ /* Offscreen SEO/skip anchor, first focusable element in the body.
29
+ The declarations below were an inline `style` attribute on the element
30
+ until fc#1646: a report-only CSP observed it as the collector's first
31
+ real finding (style-src-attr / blocked_uri inline), and an enforcing
32
+ policy would drop the positioning and render the link on the page.
33
+ Same two declarations, same computed result, no `unsafe-inline` needed. */
34
+ .seo-skip {
35
+ position: absolute;
36
+ left: -9999px;
37
+ }
38
+
28
39
  html, body {
29
40
  margin: 0;
30
41
  padding: 0;
@@ -0,0 +1,66 @@
1
+ // URL safety for values this app did not construct.
2
+ //
3
+ // Web-search results reach the transcript carrying a `url` field that
4
+ // originates off-box. SearXNG hands upstream engine results through with a
5
+ // truthiness filter only (src/searxng.ts filters on `r.url && r.title` and
6
+ // never parses), src/routes/rag.ts maps them to source_type:"web", and the
7
+ // value is persisted in retrieved_context and replayed on every subsequent
8
+ // transcript render. So the string in an href there is not ours.
9
+ //
10
+ // WHY ESCAPING IS THE WRONG TOOL HERE. escapeHtml() replaces & < > " ' and is
11
+ // exactly right for stopping attribute injection. It does nothing whatever to
12
+ // a scheme: `javascript:alert(1)` contains none of those five characters and
13
+ // passes through escaping byte for byte. Escaping answers "can this break out
14
+ // of the attribute", and the question an href also has to answer is "what does
15
+ // this navigate to". Two different questions, two different guards, and both
16
+ // call sites keep both.
17
+ //
18
+ // PARSE, DO NOT PATTERN-MATCH. The URL parser strips leading and trailing
19
+ // C0/space, and removes embedded tab, LF and CR, before it resolves the
20
+ // scheme. So " JavaScript:x", "java\nscript:x" and "JAVASCRIPT:x" all
21
+ // normalise to protocol "javascript:" and are refused by the check below,
22
+ // while a hand-written regex sees three unrelated strings and will miss at
23
+ // least one of them. Delegating to the parser is what makes the guard
24
+ // complete rather than a list of the variants someone happened to think of.
25
+ //
26
+ // ALLOWLIST, NOT BLOCKLIST. An allowlist of the two schemes a web result can
27
+ // legitimately use cannot be outgrown; a blocklist of the dangerous ones has
28
+ // to be extended every time a browser ships a new scheme.
29
+ //
30
+ // Its own file, loaded as a classic script before app.js, the same shape
31
+ // voice-widget.js already uses for shared browser helpers. It is separate so
32
+ // that the SHIPPED function is addressable from a test: app.js touches the DOM
33
+ // at top level and cannot be evaluated outside a browser, so a guard living
34
+ // inside it could only ever be tested by a copy, and a copy is a second thing
35
+ // that drifts. tests/public-url-safety.test.ts evaluates THIS file and refuses
36
+ // to run at all if the function is missing or renamed, so the suite cannot
37
+ // pass vacuously against a guard that is no longer there.
38
+ (function () {
39
+ "use strict";
40
+
41
+ var ALLOWED_PROTOCOLS = ["http:", "https:"];
42
+
43
+ // Returns a value safe to place in an href attribute, or "#" when the input
44
+ // is not a plain web URL.
45
+ //
46
+ // On success it returns the ORIGINAL string rather than the parser's
47
+ // normalised form, so the href and the visible link text next to it stay
48
+ // byte-identical. That is deliberate: a link whose text and destination
49
+ // differ is its own problem, and normalisation would introduce one. The
50
+ // caller still passes the result through escapeHtml, which is what handles
51
+ // a quote inside an otherwise legitimate https URL.
52
+ window.safeHref = function safeHref(raw) {
53
+ if (typeof raw !== "string" || !raw.trim()) return "#";
54
+ var parsed;
55
+ try {
56
+ parsed = new URL(raw);
57
+ } catch (_) {
58
+ // Not an absolute URL. Every caller here passes an absolute one, so a
59
+ // parse failure is a refusal rather than a case to resolve against a
60
+ // base: guessing a base for an unparseable string is how you turn "I do
61
+ // not know what this is" into a confident wrong destination.
62
+ return "#";
63
+ }
64
+ return ALLOWED_PROTOCOLS.indexOf(parsed.protocol) === -1 ? "#" : raw;
65
+ };
66
+ })();
@@ -298,3 +298,61 @@ CREATE TABLE IF NOT EXISTS auth_attempts (
298
298
  count INTEGER NOT NULL DEFAULT 0,
299
299
  window_start TEXT NOT NULL DEFAULT (datetime('now'))
300
300
  );
301
+ -- 0004: CSP violation collector (fleet-chezmoi#1646).
302
+ --
303
+ -- Two tables, and the split is the point. `csp_report_buckets` is a rate-limit
304
+ -- counter and could have reused `auth_attempts`, which already has exactly this
305
+ -- shape and a prefixed bucket-key namespace. It deliberately does not.
306
+ --
307
+ -- WHY: the collector's write endpoint is UNAUTHENTICATED by construction, because
308
+ -- browsers post CSP reports without credentials. Pointing an unauthenticated
309
+ -- public write path at the same table the LOGIN limiter depends on means a flood
310
+ -- against the collector contends with sign-in. One extra table is a cheap price
311
+ -- for not coupling a public write path to the auth path.
312
+ --
313
+ -- Apply to an existing database with:
314
+ -- npx wrangler d1 execute skyphusion-llm --remote --file=migrations/0004_csp_reports.sql
315
+ -- Fresh databases get this from schema.sql.
316
+
317
+ -- Collected violations. Every column is a BOUNDED projection of an
318
+ -- attacker-controlled report body; nothing is stored verbatim.
319
+ --
320
+ -- NOT STORED, deliberately: `script-sample`. It can carry fragments of inline
321
+ -- script from a page that handles a credential, and a violation is diagnosable
322
+ -- from the directive plus the blocked URI without it.
323
+ CREATE TABLE IF NOT EXISTS csp_reports (
324
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
325
+ received_at TEXT NOT NULL DEFAULT (datetime('now')),
326
+ -- document_uri is stored with query and fragment STRIPPED. The SPA puts
327
+ -- nothing in URLs (measured), so this costs nothing today and stops the
328
+ -- collector becoming the first place a URL-borne value is persisted.
329
+ document_uri TEXT,
330
+ referrer TEXT,
331
+ violated_directive TEXT,
332
+ effective_directive TEXT,
333
+ blocked_uri TEXT,
334
+ disposition TEXT,
335
+ status_code INTEGER,
336
+ source_file TEXT,
337
+ line_number INTEGER,
338
+ column_number INTEGER
339
+ );
340
+
341
+ -- Read path is operator-only and deliberately has no HTTP endpoint: there is no
342
+ -- admin role on this product, so an authenticated read route would let any
343
+ -- signed-up user read operator diagnostics from a credential-handling page.
344
+ -- Operators query with:
345
+ -- npx wrangler d1 execute skyphusion-llm --remote \
346
+ -- --command "SELECT received_at, effective_directive, blocked_uri, document_uri
347
+ -- FROM csp_reports ORDER BY id DESC LIMIT 50;"
348
+ CREATE INDEX IF NOT EXISTS idx_csp_reports_received ON csp_reports(received_at);
349
+
350
+ -- Rate-limit buckets for the collector, isolated from auth_attempts per the note
351
+ -- above. `dropped` is what makes shedding VISIBLE: without it a rate-limited
352
+ -- estate and a quiet one produce an identical empty table.
353
+ CREATE TABLE IF NOT EXISTS csp_report_buckets (
354
+ bucket_key TEXT PRIMARY KEY,
355
+ count INTEGER NOT NULL DEFAULT 0,
356
+ dropped INTEGER NOT NULL DEFAULT 0,
357
+ window_start TEXT NOT NULL DEFAULT (datetime('now'))
358
+ );
@@ -0,0 +1,253 @@
1
+ // Content-Security-Policy: the policy string, and the pure projection of a
2
+ // violation report into the bounded row we persist (fleet-chezmoi#1646).
3
+ //
4
+ // Everything here is a pure function so it is testable in the fast node suite
5
+ // without booting workerd or D1. The DB layer lives in routes/csp-report.ts and
6
+ // does nothing but the rate-limit window and the insert.
7
+ //
8
+ // THE POLICY IS NOW ENFORCING. Phase one shipped it report-only and
9
+ // deliberately stricter than the page was believed to need, so that every
10
+ // exception would be established by an OBSERVED violation rather than by a
11
+ // directive list derived from reading app.js. That phase is over and its
12
+ // output is the two grants in buildCspPolicy below.
13
+ //
14
+ // WORTH KEEPING: phase one's author predicted, in this comment, exactly two
15
+ // violations -- an inline style attribute on the skip link, and a data: image
16
+ // preview. The measurement found FOUR distinct ones. The skip link and the
17
+ // data: image were both real. A blob: URL on TTS playback was not predicted,
18
+ // and an inline <style> block on the STT page was not only unpredicted but
19
+ // could not have reported at all, because that document was being served
20
+ // outside `run_worker_first` and carried no policy header.
21
+ //
22
+ // So a careful reading of the source got 2 of 4, and the two it missed are the
23
+ // ones that would have hurt: one silences voice chat, and the other was
24
+ // invisible to the very instrument that was supposed to find it. That is the
25
+ // argument for the report-only phase, made by the phase itself, and it is the
26
+ // reason a future directive change owes an observation rather than a reading.
27
+
28
+ /** Max accepted request body, in bytes. A CSP report is small; this is generous. */
29
+ export const CSP_REPORT_MAX_BYTES = 8192;
30
+
31
+ /** Per-field character caps. Every value here is attacker-controlled. */
32
+ export const CSP_FIELD_CAPS = {
33
+ document_uri: 512,
34
+ referrer: 512,
35
+ violated_directive: 128,
36
+ effective_directive: 128,
37
+ blocked_uri: 512,
38
+ disposition: 32,
39
+ source_file: 512,
40
+ } as const;
41
+
42
+ /** Reports accepted per window, per client. */
43
+ export const CSP_RATE_LIMIT = 60;
44
+ /** Rate-limit window, seconds. */
45
+ export const CSP_RATE_WINDOW_SECONDS = 300;
46
+ /** Rows older than this are pruned on write. Deletion path, not an intention. */
47
+ export const CSP_RETENTION_DAYS = 30;
48
+
49
+ export interface CspReportRow {
50
+ document_uri: string | null;
51
+ referrer: string | null;
52
+ violated_directive: string | null;
53
+ effective_directive: string | null;
54
+ blocked_uri: string | null;
55
+ disposition: string | null;
56
+ status_code: number | null;
57
+ source_file: string | null;
58
+ line_number: number | null;
59
+ column_number: number | null;
60
+ }
61
+
62
+ /** The response header name. ENFORCING, not `-Report-Only`.
63
+ *
64
+ * Exported so the name and the mode cannot drift apart in a caller: a policy
65
+ * built as enforcing and emitted under the report-only name is a strictly
66
+ * decorative control, and nothing about either string announces the mismatch.
67
+ */
68
+ export const CSP_HEADER = "content-security-policy";
69
+
70
+ /** The header name phase one used. Kept ONLY so tests can assert it is gone.
71
+ *
72
+ * A retired name is a live hazard rather than trivia: a check that looks for
73
+ * the old header keeps passing after promotion by finding nothing, which is
74
+ * indistinguishable from the header being correctly absent. Asserting on this
75
+ * constant makes "the report-only header is no longer emitted" a claim a test
76
+ * can actually make.
77
+ */
78
+ export const CSP_HEADER_REPORT_ONLY = "content-security-policy-report-only";
79
+
80
+ /**
81
+ * The ENFORCING policy served on HTML responses.
82
+ *
83
+ * PROMOTED FROM REPORT-ONLY on mackaye's ruling, fleet-chezmoi#1646 comment
84
+ * 5281677490, after the report-only phase measured what the page genuinely
85
+ * needs. Every exception below was established by a violation that was
86
+ * OBSERVED, never by reading app.js and deciding what looked necessary. That
87
+ * ordering is the whole point of having had a report-only phase, and it is
88
+ * cheap to quietly invert later, so the provenance of each grant is recorded
89
+ * here rather than in a merged PR nobody re-reads.
90
+ *
91
+ * ONLY `report-uri`, DELIBERATELY, AND THIS WAS MEASURED RATHER THAN REASONED.
92
+ *
93
+ * The obvious shape is to emit both: `report-uri` for browsers that never
94
+ * implemented the replacement, plus `report-to` with a companion
95
+ * `Reporting-Endpoints` header for those that did. That is what this shipped
96
+ * first, and it delivered NOTHING.
97
+ *
98
+ * Measured, with the two states separated rather than inferred. A
99
+ * `securitypolicyviolation` listener in the page proved violations were being
100
+ * REGISTERED by the browser while the collector received zero rows, so the
101
+ * violation was real and the DELIVERY was the failure. Removing `report-to`
102
+ * and the `Reporting-Endpoints` header, changing nothing else, made the
103
+ * identical violations arrive immediately. Re-adding `report-to` is a change
104
+ * that must be justified by watching a report arrive over it, not by noting
105
+ * that it is the modern directive.
106
+ *
107
+ * THE COLLECTOR STAYS WIRED UNDER ENFORCEMENT, and that is not leftovers. The
108
+ * stored `disposition` column now distinguishes `enforce` from `report`, so a
109
+ * directive this policy gets wrong shows up as a row naming the thing that was
110
+ * actually broken, instead of as a user reporting that a feature stopped
111
+ * working. Dropping `report-uri` at promotion would retire the instrument at
112
+ * the exact moment it starts describing real refusals.
113
+ *
114
+ * THE TWO GRANTS, each with the observation that produced it. Both were
115
+ * measured violating in a browser run whose off-origin positive control fired
116
+ * in the same run, so neither rests on a zero from an instrument that might
117
+ * simply have been blind.
118
+ *
119
+ * `img-src 'self' data:`
120
+ * Attachment thumbnails, extracted video-frame previews, and the downscale
121
+ * path that feeds them all render a `data:` URL the page produced itself
122
+ * from a local file. Observed as `img-src | data`.
123
+ *
124
+ * `media-src 'self' blob:`
125
+ * TTS playback constructs an `Audio` around a `blob:` URL minted from a
126
+ * same-origin response. Observed as `media-src | blob`.
127
+ *
128
+ * WHY GRANT RATHER THAN REWORK, since the rework reads as the more rigorous
129
+ * option and is the worse one: making the previews same-origin means uploading
130
+ * a user's local image to a server in order to show it back to them in their
131
+ * own browser. Prism is BYOK and privacy-primary. The policy exists to serve
132
+ * that posture, not to outrank it. And promoting with the two features broken
133
+ * is worse still, because a control that fires during healthy operation
134
+ * teaches everyone that its red means nothing, so the next red arrives
135
+ * pre-discounted and the policy eventually gets switched off.
136
+ *
137
+ * WHAT THE GRANTS DO NOT BUY, stated so a later reader does not have to
138
+ * re-derive the blast radius: neither admits script execution. `blob:` is
139
+ * same-origin-created by construction. `data:` here is scoped to `img-src`
140
+ * alone, whose realistic downside is UI spoofing rather than code execution.
141
+ *
142
+ * NOTHING ELSE WIDENED. `script-src` and `connect-src` are unchanged from the
143
+ * measured baseline, `object-src` stays `'none'`, and no `unsafe-inline` or
144
+ * `unsafe-eval` appears anywhere. Adding a directive to make a violation stop
145
+ * arriving is the inversion this whole exercise exists to prevent; tests assert
146
+ * each of those absences by name so a future grant has to be deliberate.
147
+ */
148
+ export function buildCspPolicy(reportPath = "/api/csp-report"): string {
149
+ return [
150
+ "default-src 'self'",
151
+ "script-src 'self'",
152
+ "style-src 'self'",
153
+ // GRANTED: local file previews, never uploaded. Observed `img-src | data`.
154
+ "img-src 'self' data:",
155
+ "font-src 'self'",
156
+ "connect-src 'self'",
157
+ // GRANTED: TTS playback of a same-origin response. Observed `media-src | blob`.
158
+ "media-src 'self' blob:",
159
+ "object-src 'none'",
160
+ "base-uri 'self'",
161
+ "form-action 'self'",
162
+ "frame-ancestors 'self'",
163
+ `report-uri ${reportPath}`,
164
+ ].join("; ");
165
+ }
166
+
167
+
168
+ function capped(v: unknown, max: number): string | null {
169
+ if (typeof v !== "string") return null;
170
+ const t = v.trim();
171
+ if (!t) return null;
172
+ return t.slice(0, max);
173
+ }
174
+
175
+ function intOrNull(v: unknown): number | null {
176
+ if (typeof v !== "number" || !Number.isFinite(v)) return null;
177
+ // Bound it: these are line/column/status numbers, not arbitrary integers.
178
+ const n = Math.trunc(v);
179
+ if (n < 0 || n > 100_000_000) return null;
180
+ return n;
181
+ }
182
+
183
+ /**
184
+ * Strip query and fragment from a document URI before storage.
185
+ *
186
+ * The SPA puts nothing in URLs, which was measured rather than assumed, so this
187
+ * changes nothing today. It exists so the collector cannot become the first
188
+ * place a URL-borne value gets persisted if that ever stops being true. An
189
+ * unparseable value is returned capped rather than dropped, because knowing a
190
+ * violation happened somewhere unrecognisable is still worth more than a null.
191
+ */
192
+ export function stripUrlNoise(raw: unknown): string | null {
193
+ const s = capped(raw, CSP_FIELD_CAPS.document_uri);
194
+ if (s === null) return null;
195
+ try {
196
+ const u = new URL(s);
197
+ u.search = "";
198
+ u.hash = "";
199
+ return u.toString().slice(0, CSP_FIELD_CAPS.document_uri);
200
+ } catch {
201
+ return s;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Project a parsed report body into the bounded row.
207
+ *
208
+ * Accepts BOTH wire shapes and returns null when neither is present:
209
+ * - `report-uri`: {"csp-report": {...}} with hyphenated keys
210
+ * - `report-to`: [{"type":"csp-violation","body":{...}}] with underscored keys
211
+ *
212
+ * Returning null rather than an empty row matters: an empty row is a record
213
+ * that a violation occurred with no detail, which is indistinguishable from a
214
+ * collector that is mangling its input.
215
+ */
216
+ export function extractCspReport(parsed: unknown): CspReportRow | null {
217
+ let b: Record<string, unknown> | null = null;
218
+
219
+ if (Array.isArray(parsed)) {
220
+ const entry = parsed.find(
221
+ (e) => e && typeof e === "object" && (e as Record<string, unknown>).type === "csp-violation",
222
+ ) as Record<string, unknown> | undefined;
223
+ const body = entry?.body;
224
+ if (body && typeof body === "object") b = body as Record<string, unknown>;
225
+ } else if (parsed && typeof parsed === "object") {
226
+ const legacy = (parsed as Record<string, unknown>)["csp-report"];
227
+ if (legacy && typeof legacy === "object") b = legacy as Record<string, unknown>;
228
+ }
229
+
230
+ if (!b) return null;
231
+
232
+ // Hyphenated (report-uri) first, underscored (Reporting API) second.
233
+ const pick = (a: string, z: string): unknown => (b![a] !== undefined ? b![a] : b![z]);
234
+
235
+ return {
236
+ document_uri: stripUrlNoise(pick("document-uri", "documentURL")),
237
+ referrer: capped(pick("referrer", "referrer"), CSP_FIELD_CAPS.referrer),
238
+ violated_directive: capped(
239
+ pick("violated-directive", "violatedDirective"),
240
+ CSP_FIELD_CAPS.violated_directive,
241
+ ),
242
+ effective_directive: capped(
243
+ pick("effective-directive", "effectiveDirective"),
244
+ CSP_FIELD_CAPS.effective_directive,
245
+ ),
246
+ blocked_uri: capped(pick("blocked-uri", "blockedURL"), CSP_FIELD_CAPS.blocked_uri),
247
+ disposition: capped(pick("disposition", "disposition"), CSP_FIELD_CAPS.disposition),
248
+ status_code: intOrNull(pick("status-code", "statusCode")),
249
+ source_file: capped(pick("source-file", "sourceFile"), CSP_FIELD_CAPS.source_file),
250
+ line_number: intOrNull(pick("line-number", "lineNumber")),
251
+ column_number: intOrNull(pick("column-number", "columnNumber")),
252
+ };
253
+ }