Debian Codegraph @

src/ext/hx-csp.js

raw symbols SCIP
1 //==========================================================
2 // hx-csp.js
3 //
4 // CSP enforcement extension for htmx.
5 //
6 // Provides three layers of Content Security Policy integration:
7 //
8 // 1. Nonce gating — gates htmx attribute processing behind CSP
9 // nonces to prevent HTML injection attacks. Every htmx element
10 // must carry an hx-nonce attribute matching the page nonce or
11 // its htmx attributes are stripped. Fail closed if no page
12 // nonce is found. Also re-checks nonce presence before internal eval
13 // to also cover extension eval use like hx-live.
14 // Nonce source: script[nonce].nonce property on page load.
15 //
16 // 2. Trusted Types — creates an 'htmx' TT policy (passthrough —
17 // trust established by the nonce gate). Add trusted-types htmx
18 // to your CSP to enforce that only htmx touches DOM sinks.
19 // Fail closed if policy creation is blocked by CSP.
20 //
21 // 3. Safe eval — set config.safeEval:true to replace htmx's
22 // Function/AsyncFunction with nonce-based script injection,
23 // enabling hx-on:/hx-vals js:/hx-confirm js: without
24 // unsafe-eval in your CSP.
25 //
26 // Usage:
27 // <meta name="htmx-config" content='extensions:"hx-csp"'>
28 // <meta name="htmx-config" content='extensions:"hx-csp",safeEval:true'>
29 // <script src="hx-csp.js"></script>
30 //
31 // Server stamps hx-nonce on every htmx element:
32 // <button hx-post="/save" hx-nonce="<csp-nonce>">Save</button>
33 //==========================================================
34 (() => {
35
36 let pageNonce = null;
37 let ttPolicy = null;
38 let internalApi = null;
39
40 function getNonce(elt) {
41 return internalApi?.attributeValue(elt, 'hx-nonce');
42 }
43
44 function checkNonce(elt) {
45 if (!pageNonce) return false;
46 let eltNonce = getNonce(elt);
47 if (eltNonce !== pageNonce && stripHxAttributes(elt, eltNonce)) return false;
48 }
49
50 // Anchors to script-src/default-src to avoid matching nonces in other CSP directives
51 function extractNonceFromCSP(csp) {
52 return csp?.match(/(?:script-src|default-src)[^;]*'nonce-([^']+)'/i)?.[1] ?? null;
53 }
54
55 // Fallback: parse raw response HTML and extract nonce from meta CSP tag in <head>.
56 // Only used for full-page responses with no CSP header.
57 function extractNonceFromMetaTag(text) {
58 let doc = Document.parseHTMLUnsafe(ttPolicy.createHTML(text));
59 let meta = doc.head?.querySelector('meta[http-equiv="Content-Security-Policy"]');
60 return extractNonceFromCSP(meta?.content);
61 }
62
63 function escapeRegex(str) {
64 return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
65 }
66
67 // Rewrites responseNonce → replacement in raw HTML before DOM parsing,
68 // covering hx-nonce and script nonce attributes in one pass.
69 // Pass replacement='' to strip nonce attributes entirely (stolen-nonce scrub).
70 function rewriteNoncesInText(text, responseNonce, replacement = pageNonce) {
71 let escaped = escapeRegex(responseNonce);
72 return text.replace(
73 new RegExp(`(nonce=)(["']?)${escaped}\\2`, 'gi'),
74 (_, attr, quote) => replacement ? `${attr}${quote}${replacement}${quote}` : ''
75 );
76 }
77
78 // Strips all hx- attributes, fires htmx:security:strip, returns true if anything stripped.
79 function stripHxAttributes(elt, eltNonce) {
80 let stripped = [];
81 for (let attr of [...elt.attributes]) {
82 if (attr.name.startsWith('hx-') || (htmx.config.prefix && attr.name.startsWith(htmx.config.prefix))) {
83 stripped.push(attr.name);
84 elt.removeAttribute(attr.name);
85 }
86 }
87 if (!stripped.length) return false;
88 let tag = elt.tagName?.toLowerCase();
89 let id = elt.id ? `#${elt.id}` : '';
90 let reason = eltNonce == null ? 'missing-nonce' : 'nonce-mismatch';
91 console.error(`htmx: [hx-csp] blocked <${tag}${id}> — ${eltNonce == null ? 'no hx-nonce attribute' : 'nonce mismatch (possible injection)'}`, { elt, reason });
92 htmx.trigger(elt, 'htmx:security:strip', { reason, stripped });
93 return true;
94 }
95
96 htmx.registerExtension('hx-csp', {
97
98 init: (api) => {
99 internalApi = api;
100
101 // .nonce property stays readable after browsers blank the attribute
102 // to prevent CSS exfiltration attacks.
103 pageNonce = document.querySelector('script[nonce]')?.nonce || null;
104
105 if (!pageNonce) {
106 console.error('htmx: [hx-csp] no page nonce found — blocking all htmx. Add a nonce to your script tags.');
107 return;
108 }
109
110 // Passthrough TT policy — trust established by nonce gate.
111 // Fail closed if 'htmx' is not in the trusted-types CSP whitelist.
112 try {
113 ttPolicy = typeof trustedTypes !== 'undefined'
114 ? trustedTypes.createPolicy('htmx', { createHTML: s => s, createScript: s => s })
115 : { createHTML: s => s, createScript: s => s };
116 } catch (e) {
117 console.error("htmx: [hx-csp] TrustedTypes policy 'htmx' blocked — add 'htmx' to trusted-types CSP directive. Blocking all htmx.");
118 pageNonce = null;
119 return;
120 }
121
122 let counter = 0;
123 let NativeFunction = Function;
124 let NativeAsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
125
126 function makeGatedConstructor(isAsync) {
127 return function(...keys) {
128 let body = keys.pop();
129 return {
130 call: (thisArg, ...values) => {
131 if (getNonce(thisArg) !== pageNonce) {
132 let tag = thisArg?.tagName?.toLowerCase();
133 let id = thisArg?.id ? `#${thisArg.id}` : '';
134 console.error(`htmx: [hx-csp] blocked eval on <${tag}${id}> — nonce mismatch`, { elt: thisArg });
135 htmx.trigger(thisArg, 'htmx:security:violation', { reason: 'nonce-mismatch-at-eval' });
136 return;
137 }
138 if (htmx.config.safeEval) {
139 let fn = `__htmx_eval_${++counter}`;
140 let script = document.createElement('script');
141 script.nonce = pageNonce;
142 script.textContent = ttPolicy.createScript(`window.${fn} = ${isAsync ? 'async ' : ''}function(${keys.join(',')}) { ${body} }`);
143 document.head.appendChild(script);
144 script.remove();
145 let r = window[fn].call(thisArg, ...values);
146 delete window[fn];
147 return r;
148 }
149 let Ctor = isAsync ? NativeAsyncFunction : NativeFunction;
150 return new Ctor(...keys, body).call(thisArg, ...values);
151 }
152 };
153 };
154 }
155
156 api.initSecurity(ttPolicy, makeGatedConstructor(false), makeGatedConstructor(true));
157 },
158
159 htmx_before_init: checkNonce,
160
161 htmx_before_on_init: checkNonce,
162
163 // Rewrites response nonces to pageNonce in raw HTML before fragment parsing.
164 // Always scrubs stolen pageNonce. Only promotes response nonce for verified same-origin.
165 htmx_after_request: (elt, detail) => {
166 if (!pageNonce) return false;
167 let ctx = detail.ctx;
168
169 // Always scrub stolen pageNonce from any response — the server cannot know the
170 // page nonce, so its presence indicates a stolen-nonce injection attempt.
171 ctx.text = rewriteNoncesInText(ctx.text, pageNonce, '');
172
173 // Only promote response nonce for verified same-origin responses
174 let responseURL = ctx?.response?.raw?.url;
175 if (!responseURL) return; // can't verify origin — scrub only, no promotion
176 try { if (new URL(responseURL).origin !== location.origin) return; }
177 catch (_) { return; }
178
179 let responseNonce = extractNonceFromCSP(ctx?.response?.headers?.get('Content-Security-Policy'))
180 ?? extractNonceFromMetaTag(ctx?.text);
181 if (responseNonce && responseNonce !== pageNonce) {
182 ctx.text = rewriteNoncesInText(ctx.text, responseNonce);
183 }
184 },
185
186 // Blocks boosted form submissions where an unnonced submitter overrides formaction.
187 // Also blocks js:/javascript: action URLs — entity encoding doesn't neutralise these
188 // so they may survive template rendering and execute unexpectedly.
189 htmx_config_request: (elt, detail) => {
190 if (!pageNonce) return false;
191 let action = detail.ctx?.request?.action;
192 if (action && /^(js|javascript):/i.test(action)) {
193 console.error(`htmx: [hx-csp] blocked js:/javascript: action URL on <${elt.tagName.toLowerCase()}${elt.id ? '#'+elt.id : ''}>`, { elt });
194 htmx.trigger(elt, 'htmx:security:violation', { reason: 'javascript-url', action, ctx: detail.ctx });
195 detail.cancelled = true;
196 return false;
197 }
198 let submitter = detail.ctx?.sourceEvent?.submitter;
199 if (!elt._htmx?.boosted || !submitter?.getAttribute('formaction')) return;
200 if (getNonce(submitter) !== pageNonce) {
201 let id = submitter?.id ? `#${submitter.id}` : '';
202 console.error(`htmx: [hx-csp] blocked boosted form — unnonced submitter${id} overrode formaction`);
203 htmx.trigger(elt, 'htmx:security:violation', { reason: 'unnonced-submitter', submitter, ctx: detail.ctx });
204 detail.cancelled = true;
205 return false;
206 }
207 }
208 });
209
210 })();