@skyphusion/create-prism 0.175.6 → 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 +1 -1
- package/template/README.md +192 -25
- package/template/migrations/0003_conversation_compact.sql +24 -0
- package/template/migrations/0004_csp_reports.sql +58 -0
- package/template/package.json +4 -4
- package/template/public/app.js +107 -4
- package/template/public/index.html +5 -1
- package/template/public/stt.css +25 -0
- package/template/public/stt.html +1 -21
- package/template/public/styles.css +27 -2
- package/template/public/url-safety.js +66 -0
- package/template/schema.sql +75 -0
- package/template/src/conversation-context.ts +126 -0
- package/template/src/csp.ts +253 -0
- package/template/src/index.ts +85 -2
- package/template/src/routes/chat.ts +62 -78
- package/template/src/routes/conversations.ts +285 -3
- package/template/src/routes/csp-report.ts +163 -0
- package/template/src/routes/health.ts +6 -1
- package/template/src/routes/rag.ts +25 -3
- package/template/src/stt-session.ts +17 -1
- package/template/src/version.ts +18 -0
- package/template/tests/conversation-compact.test.ts +103 -0
- package/template/tests/csp.test.ts +444 -0
- package/template/tests/public-url-safety.test.ts +360 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
- package/template/tests/version.test.ts +47 -0
- package/template/tests-integration/csp-report.test.ts +232 -0
- package/template/tests-integration/worker.test.ts +154 -0
- package/template/vitest.workers.config.ts +19 -4
- package/template/wrangler.example.toml +33 -0
|
@@ -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;
|
|
@@ -1693,10 +1704,24 @@ body::before {
|
|
|
1693
1704
|
.conversation { flex: 1 1 auto; overflow-y: auto; min-height: 0; }
|
|
1694
1705
|
.conv-head {
|
|
1695
1706
|
max-width: 820px; margin: 0 auto; padding: 1rem 1.25rem 0;
|
|
1696
|
-
display: flex; align-items:
|
|
1707
|
+
display: flex; align-items: center; flex-wrap: wrap; gap: 0.5rem 0.75rem; color: var(--fg-dim);
|
|
1697
1708
|
}
|
|
1698
1709
|
#conv-title { font-size: 0.9rem; font-weight: 600; color: var(--fg); }
|
|
1699
|
-
|
|
1710
|
+
.conv-compact-badge {
|
|
1711
|
+
font-size: 0.65rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;
|
|
1712
|
+
padding: 0.15rem 0.45rem; border-radius: 999px;
|
|
1713
|
+
background: color-mix(in srgb, var(--accent) 18%, transparent);
|
|
1714
|
+
color: var(--accent); border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
|
1715
|
+
}
|
|
1716
|
+
.conv-compact-btn {
|
|
1717
|
+
font-size: 0.72rem; font-weight: 500; padding: 0.2rem 0.55rem;
|
|
1718
|
+
border-radius: 999px; border: 1px solid var(--border); background: var(--bg-elev);
|
|
1719
|
+
color: var(--fg-dim); cursor: pointer;
|
|
1720
|
+
}
|
|
1721
|
+
.conv-compact-btn:hover { border-color: var(--accent); color: var(--fg); }
|
|
1722
|
+
.conv-compact-btn:disabled { opacity: 0.5; cursor: wait; }
|
|
1723
|
+
.conv-uncompact-btn { border-style: dashed; }
|
|
1724
|
+
#output-meta { font-size: 0.75rem; margin-left: auto; }
|
|
1700
1725
|
.transcript { max-width: 820px; margin: 0 auto; padding: 0.75rem 1.25rem 1.5rem; }
|
|
1701
1726
|
|
|
1702
1727
|
/* floating composer */
|
|
@@ -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
|
+
})();
|
package/template/schema.sql
CHANGED
|
@@ -50,6 +50,23 @@ CREATE TABLE IF NOT EXISTS chats (
|
|
|
50
50
|
CREATE INDEX IF NOT EXISTS idx_chats_conversation
|
|
51
51
|
ON chats(conversation_id, turn_index);
|
|
52
52
|
|
|
53
|
+
-- Compact state for multi-turn context (v0.175.7). Full transcript stays in
|
|
54
|
+
-- chats; this row holds a summary of older turns so the model path does not
|
|
55
|
+
-- re-send them. See src/conversation-context.ts.
|
|
56
|
+
CREATE TABLE IF NOT EXISTS conversation_compact (
|
|
57
|
+
conversation_id TEXT NOT NULL,
|
|
58
|
+
user_email TEXT NOT NULL,
|
|
59
|
+
summary TEXT NOT NULL,
|
|
60
|
+
through_turn_index INTEGER NOT NULL,
|
|
61
|
+
keep_recent INTEGER NOT NULL DEFAULT 2,
|
|
62
|
+
model TEXT NOT NULL,
|
|
63
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
64
|
+
PRIMARY KEY (conversation_id, user_email)
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
CREATE INDEX IF NOT EXISTS idx_conversation_compact_user
|
|
68
|
+
ON conversation_compact(user_email);
|
|
69
|
+
|
|
53
70
|
CREATE INDEX IF NOT EXISTS idx_chats_user_created
|
|
54
71
|
ON chats(user_email, created_at DESC);
|
|
55
72
|
|
|
@@ -281,3 +298,61 @@ CREATE TABLE IF NOT EXISTS auth_attempts (
|
|
|
281
298
|
count INTEGER NOT NULL DEFAULT 0,
|
|
282
299
|
window_start TEXT NOT NULL DEFAULT (datetime('now'))
|
|
283
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,126 @@
|
|
|
1
|
+
// Conversation context for multi-turn chat: prior turns + optional compact
|
|
2
|
+
// summary (v0.175.7). Pure helpers live here so chat routes and the compact
|
|
3
|
+
// endpoint share one assembly rule, and so unit tests cover it without D1.
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_KEEP_RECENT = 2;
|
|
6
|
+
/** Soft cap on stored / injected summary text (chars). */
|
|
7
|
+
export const COMPACT_SUMMARY_MAX_CHARS = 12_000;
|
|
8
|
+
/** Minimum completed chat turns before compact is useful (keep_recent + 1). */
|
|
9
|
+
export const MIN_TURNS_TO_COMPACT = DEFAULT_KEEP_RECENT + 1;
|
|
10
|
+
|
|
11
|
+
export type ChatTurnRow = {
|
|
12
|
+
user_input: string;
|
|
13
|
+
output: string;
|
|
14
|
+
turn_index: number;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type ConversationCompactState = {
|
|
18
|
+
summary: string;
|
|
19
|
+
through_turn_index: number;
|
|
20
|
+
keep_recent: number;
|
|
21
|
+
model: string;
|
|
22
|
+
updated_at: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type PriorContext = {
|
|
26
|
+
/** Raw user/assistant pairs to put on the wire after any compact block. */
|
|
27
|
+
priorTurns: Array<{ user_input: string; output: string }>;
|
|
28
|
+
/** Next turn_index for persistChat. */
|
|
29
|
+
turnIndex: number;
|
|
30
|
+
/** System-prompt block for compacted earlier turns, or null. */
|
|
31
|
+
compactBlock: string | null;
|
|
32
|
+
compact: ConversationCompactState | null;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Split turns into those summarized vs kept raw. */
|
|
36
|
+
export function splitTurnsForCompact(
|
|
37
|
+
turns: ChatTurnRow[],
|
|
38
|
+
keepRecent: number,
|
|
39
|
+
): { summarize: ChatTurnRow[]; keep: ChatTurnRow[] } {
|
|
40
|
+
const k = Math.max(0, Math.floor(keepRecent));
|
|
41
|
+
if (turns.length === 0) return { summarize: [], keep: [] };
|
|
42
|
+
if (k === 0) return { summarize: turns.slice(), keep: [] };
|
|
43
|
+
if (turns.length <= k) return { summarize: [], keep: turns.slice() };
|
|
44
|
+
return {
|
|
45
|
+
summarize: turns.slice(0, turns.length - k),
|
|
46
|
+
keep: turns.slice(turns.length - k),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Flatten turns into a plain transcript the summarizer model can read. */
|
|
51
|
+
export function formatTurnsForSummary(turns: ChatTurnRow[]): string {
|
|
52
|
+
const parts: string[] = [];
|
|
53
|
+
for (const t of turns) {
|
|
54
|
+
const u = (t.user_input ?? "").trim();
|
|
55
|
+
const a = (t.output ?? "").trim();
|
|
56
|
+
if (!u && !a) continue;
|
|
57
|
+
parts.push(`User:\n${u || "(empty)"}\n\nAssistant:\n${a || "(empty)"}`);
|
|
58
|
+
}
|
|
59
|
+
return parts.join("\n\n---\n\n");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** System-prompt block injected when a conversation is compacted. */
|
|
63
|
+
export function buildCompactSystemBlock(summary: string): string {
|
|
64
|
+
const s = summary.trim();
|
|
65
|
+
if (!s) return "";
|
|
66
|
+
return (
|
|
67
|
+
"[Compacted earlier conversation]\n" +
|
|
68
|
+
"The following is a summary of earlier turns in this thread. Treat it as " +
|
|
69
|
+
"authoritative context. Recent turns (if any) follow as normal messages.\n\n" +
|
|
70
|
+
s +
|
|
71
|
+
"\n\n[End compacted context]"
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Apply compact state to a full ordered turn list.
|
|
77
|
+
* - priorTurns: only turns AFTER through_turn_index (raw recent context)
|
|
78
|
+
* - compactBlock: summary system block when state is present
|
|
79
|
+
* - turnIndex: max(turn_index)+1 or 0
|
|
80
|
+
*/
|
|
81
|
+
export function applyCompactToPriorTurns(
|
|
82
|
+
allTurns: ChatTurnRow[],
|
|
83
|
+
state: ConversationCompactState | null,
|
|
84
|
+
): PriorContext {
|
|
85
|
+
const usable = allTurns.filter((t) => t.user_input && t.output);
|
|
86
|
+
// Next index must clear every stored turn_index, including empty/failed rows
|
|
87
|
+
// that were filtered out of the wire history.
|
|
88
|
+
const turnIndex = allTurns.length
|
|
89
|
+
? Math.max(...allTurns.map((t) => t.turn_index)) + 1
|
|
90
|
+
: 0;
|
|
91
|
+
|
|
92
|
+
if (!state?.summary?.trim()) {
|
|
93
|
+
return {
|
|
94
|
+
priorTurns: usable.map((t) => ({ user_input: t.user_input, output: t.output })),
|
|
95
|
+
turnIndex,
|
|
96
|
+
compactBlock: null,
|
|
97
|
+
compact: null,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const through = state.through_turn_index;
|
|
102
|
+
const recent = usable.filter((t) => t.turn_index > through);
|
|
103
|
+
const block = buildCompactSystemBlock(state.summary);
|
|
104
|
+
return {
|
|
105
|
+
priorTurns: recent.map((t) => ({ user_input: t.user_input, output: t.output })),
|
|
106
|
+
turnIndex,
|
|
107
|
+
compactBlock: block || null,
|
|
108
|
+
compact: state,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Clamp and normalize a model-produced summary for storage / injection. */
|
|
113
|
+
export function normalizeSummary(raw: string): string {
|
|
114
|
+
let s = (raw ?? "").trim();
|
|
115
|
+
if (s.length > COMPACT_SUMMARY_MAX_CHARS) {
|
|
116
|
+
s = s.slice(0, COMPACT_SUMMARY_MAX_CHARS) + "\n[summary truncated]";
|
|
117
|
+
}
|
|
118
|
+
return s;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export const COMPACT_SYSTEM_PROMPT =
|
|
122
|
+
"You compress multi-turn chat history into a continuity brief for another " +
|
|
123
|
+
"assistant that will continue the conversation. Preserve: decisions, facts, " +
|
|
124
|
+
"names, constraints, open questions, and anything the user asked to remember. " +
|
|
125
|
+
"Drop chit-chat and repeated boilerplate. Write in neutral third person or " +
|
|
126
|
+
"tight bullet form. No preamble like 'Here is a summary'.";
|
|
@@ -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
|
+
}
|