astro-apache-headers 0.0.0-stage → 0.1.6

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/dist/csp.js ADDED
@@ -0,0 +1,552 @@
1
+ import { hashSource } from './html.js';
2
+ /** Directives defined by CSP Level 3 and related specs (used to catch typos). */
3
+ export const KNOWN_DIRECTIVES = new Set([
4
+ 'base-uri', 'block-all-mixed-content', 'child-src', 'connect-src', 'default-src', 'fenced-frame-src',
5
+ 'font-src', 'form-action', 'frame-ancestors', 'frame-src', 'img-src', 'manifest-src', 'media-src',
6
+ 'object-src', 'prefetch-src', 'report-to', 'report-uri', 'require-trusted-types-for', 'sandbox',
7
+ 'script-src', 'script-src-attr', 'script-src-elem', 'style-src', 'style-src-attr', 'style-src-elem',
8
+ 'trusted-types', 'upgrade-insecure-requests', 'webrtc', 'worker-src',
9
+ ]);
10
+ /** Directives whose value is not a source list. */
11
+ const NON_SOURCE_LIST = new Set([
12
+ 'sandbox', 'report-uri', 'report-to', 'trusted-types', 'require-trusted-types-for', 'webrtc',
13
+ 'upgrade-insecure-requests', 'block-all-mixed-content',
14
+ ]);
15
+ const VALUELESS = new Set(['upgrade-insecure-requests', 'block-all-mixed-content']);
16
+ const DEPRECATED = {
17
+ 'block-all-mixed-content': 'it is deprecated; use upgrade-insecure-requests',
18
+ 'prefetch-src': 'it is deprecated and ignored by browsers',
19
+ };
20
+ const KEYWORDS = [
21
+ 'self', 'none', 'unsafe-inline', 'unsafe-eval', 'strict-dynamic', 'unsafe-hashes', 'report-sample',
22
+ 'wasm-unsafe-eval', 'unsafe-allow-redirects', 'inline-speculation-rules', 'trusted-types-eval',
23
+ 'report-sha256', 'report-sha384', 'report-sha512',
24
+ ];
25
+ const QUOTED_KEYWORDS = new Set(KEYWORDS.map((k) => `'${k}'`));
26
+ const HASH_RE = /^'(sha256|sha384|sha512)-[A-Za-z0-9+/_-]+={0,2}'$/i;
27
+ const NONCE_RE = /^'nonce-[A-Za-z0-9+/_-]+={0,2}'$/;
28
+ const SCHEME_RE = /^[a-z][a-z0-9+.-]*:$/i;
29
+ const HOST_RE = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d+|\*))?(\/[^\s;,]*)?$/i;
30
+ /** Where inline script/style hashes must go: the `-elem` directive if present, else the base one. */
31
+ export function hashTarget(directives, kind) {
32
+ return directives.has(`${kind}-src-elem`) ? `${kind}-src-elem` : `${kind}-src`;
33
+ }
34
+ /**
35
+ * Effective source list, following the CSP fallback chain:
36
+ * elements: `<kind>-src-elem` → `<kind>-src` → `default-src`;
37
+ * attributes (`style="…"`, `onclick="…"`): `<kind>-src-attr` → `<kind>-src` → `default-src`.
38
+ */
39
+ export function effectiveSources(directives, kind, target = 'elem') {
40
+ for (const name of [`${kind}-src-${target}`, `${kind}-src`, 'default-src']) {
41
+ const v = directives.get(name);
42
+ if (v !== undefined)
43
+ return { name, sources: v === true ? [] : v };
44
+ }
45
+ return undefined;
46
+ }
47
+ /**
48
+ * Adds hashes to the directives. When the target directive does not exist, it is created
49
+ * from `default-src` so that the fallback behaviour is preserved.
50
+ */
51
+ export function addHashes(directives, kind, hashes) {
52
+ const list = [...hashes];
53
+ if (list.length === 0)
54
+ return;
55
+ const target = hashTarget(directives, kind);
56
+ let current = directives.get(target);
57
+ if (current === undefined) {
58
+ const fallback = directives.get('default-src');
59
+ current = fallback === undefined || fallback === true ? [] : [...fallback];
60
+ }
61
+ // 'none' is kept on purpose: combined with hashes it is ignored, and the checks report it.
62
+ const sources = current === true ? [] : [...current];
63
+ for (const h of list)
64
+ if (!sources.includes(h))
65
+ sources.push(h);
66
+ directives.set(target, sources);
67
+ }
68
+ export function serialisePolicy(directives) {
69
+ return [...directives].map(([name, v]) => (v === true || v.length === 0 ? name : `${name} ${v.join(' ')}`)).join('; ');
70
+ }
71
+ /** Parses a serialised policy back into directives (first occurrence wins, like browsers). */
72
+ export function parsePolicy(policy) {
73
+ const out = new Map();
74
+ for (const part of policy.split(';')) {
75
+ const tokens = part.trim().split(/\s+/).filter(Boolean);
76
+ if (tokens.length === 0)
77
+ continue;
78
+ const name = tokens[0].toLowerCase();
79
+ if (out.has(name))
80
+ continue;
81
+ out.set(name, tokens.length === 1 && VALUELESS.has(name) ? true : tokens.slice(1));
82
+ }
83
+ return out;
84
+ }
85
+ /** Builds the policy from resolved options and the HTML scan. */
86
+ export function buildPolicy(csp, scan) {
87
+ const directives = new Map([...csp.directives].map(([k, v]) => [k, v === true ? true : [...v]]));
88
+ if (csp.hashScripts)
89
+ addHashes(directives, 'script', scan.scriptHashes.keys());
90
+ if (csp.hashStyles)
91
+ addHashes(directives, 'style', scan.styleHashes.keys());
92
+ return { directives, policy: serialisePolicy(directives) };
93
+ }
94
+ // ---------------------------------------------------------------------------
95
+ // Values of directives that are not source lists
96
+ // ---------------------------------------------------------------------------
97
+ /** Directives that are meaningless without a value, and what they need. */
98
+ const REQUIRES_VALUE = {
99
+ 'require-trusted-types-for': "it needs 'script', otherwise the Trusted Types protection is not enabled.",
100
+ 'report-to': 'it needs the name of a reporting endpoint (declared in a Reporting-Endpoints header).',
101
+ 'report-uri': 'it needs at least one URL to send reports to.',
102
+ webrtc: "it needs 'allow' or 'block'.",
103
+ };
104
+ const SANDBOX_FLAGS = new Set([
105
+ 'allow-downloads', 'allow-forms', 'allow-modals', 'allow-orientation-lock', 'allow-pointer-lock', 'allow-popups',
106
+ 'allow-popups-to-escape-sandbox', 'allow-presentation', 'allow-same-origin', 'allow-scripts',
107
+ 'allow-storage-access-by-user-activation', 'allow-top-navigation', 'allow-top-navigation-by-user-activation',
108
+ 'allow-top-navigation-to-custom-protocols',
109
+ ]);
110
+ /** Returns why the value of a non-source-list directive is invalid, or undefined. */
111
+ function invalidValueMessage(name, value) {
112
+ const lower = value.map((t) => t.toLowerCase());
113
+ switch (name) {
114
+ case 'require-trusted-types-for':
115
+ return lower.length === 1 && lower[0] === "'script'" ? undefined
116
+ : `the only valid value is 'script' (with single quotes); got ${value.join(' ')}.`;
117
+ case 'sandbox': {
118
+ const bad = value.filter((t) => !SANDBOX_FLAGS.has(t.toLowerCase()));
119
+ return bad.length ? `unknown sandbox flag(s) ${bad.join(', ')}. Valid flags: ${[...SANDBOX_FLAGS].join(', ')}.` : undefined;
120
+ }
121
+ case 'webrtc':
122
+ return lower.length === 1 && (lower[0] === "'allow'" || lower[0] === "'block'") ? undefined
123
+ : `the value must be 'allow' or 'block' (with single quotes); got ${value.join(' ')}.`;
124
+ case 'trusted-types': {
125
+ const bad = value.filter((t) => !/^('none'|'allow-duplicates'|\*|[A-Za-z0-9\-#=_/@.%]+)$/i.test(t));
126
+ return bad.length ? `invalid policy name(s) ${bad.join(', ')}.` : undefined;
127
+ }
128
+ case 'report-uri': {
129
+ // URI references: absolute or relative (/csp-report). Resolved against a dummy base.
130
+ const bad = value.filter((t) => { try {
131
+ new URL(t, 'https://site.invalid/');
132
+ return false;
133
+ }
134
+ catch {
135
+ return true;
136
+ } });
137
+ return bad.length ? `${bad.map((b) => JSON.stringify(b)).join(', ')} ${bad.length > 1 ? 'are not valid URLs' : 'is not a valid URL'}; reports could not be sent.` : undefined;
138
+ }
139
+ case 'report-to':
140
+ if (value.length !== 1)
141
+ return `expects a single reporting endpoint name; got ${value.length}.`;
142
+ return /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(value[0]) ? undefined
143
+ : `${JSON.stringify(value[0])} is not a valid endpoint name (letters, digits and - _ . ! # $ % & ' * + ^ \` | ~ only).`;
144
+ default:
145
+ return undefined;
146
+ }
147
+ }
148
+ // ---------------------------------------------------------------------------
149
+ // Inline content matching (CSP3 "does element match source list for type and source")
150
+ // ---------------------------------------------------------------------------
151
+ const ALGORITHMS = ['sha256', 'sha384', 'sha512'];
152
+ /** Canonical form of a hash source: algorithm in lower case, base64url mapped to base64. */
153
+ function canonicalHash(source) {
154
+ const m = /^'(sha256|sha384|sha512)-([A-Za-z0-9+/_-]+={0,2})'$/i.exec(source);
155
+ return m ? `'${m[1].toLowerCase()}-${m[2].replace(/-/g, '+').replace(/_/g, '/')}'` : undefined;
156
+ }
157
+ function listedHashes(sources) {
158
+ return new Set(sources.map(canonicalHash).filter((h) => h !== undefined));
159
+ }
160
+ function textHashes(text) {
161
+ return ALGORITHMS.map((a) => hashSource(text, a));
162
+ }
163
+ /** Inline-allowing keywords are ignored as soon as a hash or a nonce is present (and, for scripts, with 'strict-dynamic'). */
164
+ function unsafeInlineEffective(sources, kind) {
165
+ const lower = sources.map((s) => s.toLowerCase());
166
+ if (!lower.includes("'unsafe-inline'"))
167
+ return false;
168
+ if (sources.some((s) => HASH_RE.test(s) || NONCE_RE.test(s)))
169
+ return false;
170
+ return !(kind === 'script' && lower.includes("'strict-dynamic'"));
171
+ }
172
+ /** Is an inline <script>/<style> element allowed? (nonce, hash in any algorithm, or effective 'unsafe-inline') */
173
+ export function inlineElementAllowed(item, sources, kind) {
174
+ if (item.nonce && sources.includes(`'nonce-${item.nonce}'`))
175
+ return true;
176
+ // 'inline-speculation-rules' allows inline speculation rules, and nothing else.
177
+ if (kind === 'script' && item.type === 'speculationrules' && sources.some((s) => s.toLowerCase() === "'inline-speculation-rules'"))
178
+ return true;
179
+ const listed = listedHashes(sources);
180
+ if (textHashes(item.text ?? '').some((h) => listed.has(h)))
181
+ return true;
182
+ return unsafeInlineEffective(sources, kind);
183
+ }
184
+ /** Is an attribute (style="…", onclick="…") allowed? Hashes count only with 'unsafe-hashes'; nonces never. */
185
+ export function attributeAllowed(value, sources, kind) {
186
+ const lower = sources.map((s) => s.toLowerCase());
187
+ if (lower.includes("'unsafe-hashes'")) {
188
+ const listed = listedHashes(sources);
189
+ if (textHashes(value).some((h) => listed.has(h)))
190
+ return true;
191
+ }
192
+ return unsafeInlineEffective(sources, kind);
193
+ }
194
+ function fmtLocations(list, max = 5) {
195
+ const shown = list.slice(0, max).map((l) => ` - ${l.file}: ${l.detail}`);
196
+ if (list.length > max)
197
+ shown.push(` - … and ${list.length - max} more`);
198
+ return shown.join('\n');
199
+ }
200
+ // ---------------------------------------------------------------------------
201
+ // Source matching (simplified CSP Level 3 "does url match source list")
202
+ // ---------------------------------------------------------------------------
203
+ function defaultPort(scheme) {
204
+ return scheme === 'https:' || scheme === 'wss:' ? '443' : scheme === 'http:' || scheme === 'ws:' ? '80' : '';
205
+ }
206
+ function decodeSegment(p) {
207
+ try {
208
+ return decodeURIComponent(p);
209
+ }
210
+ catch {
211
+ return p;
212
+ }
213
+ }
214
+ export function pathMatches(sourcePath, urlPath, mode = 'spec') {
215
+ if (mode === 'decoded') {
216
+ const p = decodeSegment(urlPath);
217
+ const want = decodeSegment(sourcePath);
218
+ return want.endsWith('/') ? p.startsWith(want) : p === want;
219
+ }
220
+ const exact = !sourcePath.endsWith('/');
221
+ const src = sourcePath.split('/');
222
+ const url = urlPath.split('/');
223
+ if (!exact)
224
+ src.pop();
225
+ if (src.length > url.length)
226
+ return false;
227
+ for (let i = 0; i < src.length; i++) {
228
+ if (decodeSegment(src[i]) !== decodeSegment(url[i]))
229
+ return false;
230
+ }
231
+ return !exact || src.length === url.length;
232
+ }
233
+ /**
234
+ * Does `url` match the source list, for a document served from `self`?
235
+ * Schemes and hosts are compared case-insensitively, paths case-sensitively (as in CSP Level 3).
236
+ */
237
+ export function urlMatchesSources(url, sources, self, mode = 'spec') {
238
+ const lowerAll = sources.map((s) => s.toLowerCase());
239
+ if (lowerAll.includes("'none'") && lowerAll.length === 1)
240
+ return false;
241
+ for (const raw of sources) {
242
+ const lower = raw.toLowerCase();
243
+ if (lower === "'self'") {
244
+ if (self && url.host === self.host && (url.protocol === self.protocol || (self.protocol === 'http:' && url.protocol === 'https:')))
245
+ return true;
246
+ continue;
247
+ }
248
+ if (lower === '*') {
249
+ if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol) || (self && url.protocol === self.protocol))
250
+ return true;
251
+ continue;
252
+ }
253
+ if (SCHEME_RE.test(lower)) {
254
+ if (url.protocol === lower || (lower === 'http:' && url.protocol === 'https:') || (lower === 'ws:' && url.protocol === 'wss:'))
255
+ return true;
256
+ continue;
257
+ }
258
+ const m = raw.startsWith("'") ? null : HOST_RE.exec(raw);
259
+ if (!m)
260
+ continue;
261
+ const scheme = m[1]?.toLowerCase();
262
+ const host = m[2].toLowerCase();
263
+ const port = m[3];
264
+ const path = m[4];
265
+ if (scheme) {
266
+ const s = `${scheme}:`;
267
+ const ok = url.protocol === s || (s === 'http:' && url.protocol === 'https:') || (s === 'ws:' && url.protocol === 'wss:');
268
+ if (!ok)
269
+ continue;
270
+ }
271
+ else {
272
+ const base = self?.protocol ?? 'https:';
273
+ const ok = url.protocol === base || (base === 'http:' && url.protocol === 'https:');
274
+ if (!ok)
275
+ continue;
276
+ }
277
+ const h = url.hostname;
278
+ if (host === '*') { /* any host */ }
279
+ else if (host.startsWith('*.')) {
280
+ if (!h.endsWith(host.slice(1)))
281
+ continue;
282
+ }
283
+ else if (h !== host)
284
+ continue;
285
+ if (port !== '*') {
286
+ const urlPort = url.port || defaultPort(url.protocol);
287
+ const wanted = port ?? defaultPort(scheme ? `${scheme}:` : url.protocol);
288
+ if (urlPort !== wanted && !(port === undefined && wanted === '80' && urlPort === '443'))
289
+ continue;
290
+ }
291
+ if (path && path !== '/' && !pathMatches(path, url.pathname, mode))
292
+ continue;
293
+ return true;
294
+ }
295
+ return false;
296
+ }
297
+ /**
298
+ * URL a built file is served at: `docs/index.html` → `<root>docs/` (Apache's DirectoryIndex
299
+ * and DirectorySlash), `docs/intro.html` → `<root>docs/intro.html`.
300
+ */
301
+ export function pageUrl(file, root) {
302
+ const path = file.replace(/(^|\/)index\.html?$/i, '$1');
303
+ return new URL(path.split('/').map(encodeURIComponent).join('/'), root);
304
+ }
305
+ /** Checks the produced policy against itself and against the HTML it must protect. */
306
+ export function checkPolicy(ctx) {
307
+ const { csp, directives, policy, scan } = ctx;
308
+ const issues = [];
309
+ const err = (code, message) => issues.push({ level: 'error', code, message });
310
+ const warn = (code, message) => issues.push({ level: 'warning', code, message });
311
+ // --- 1. Syntax of every directive -------------------------------------------------
312
+ for (const [name, value] of directives) {
313
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
314
+ err('csp-directive-name', `"${name}" is not a valid CSP directive name.`);
315
+ continue;
316
+ }
317
+ if (!KNOWN_DIRECTIVES.has(name))
318
+ err('csp-unknown-directive', `unknown CSP directive "${name}" (typo?). Known directives: ${[...KNOWN_DIRECTIVES].join(', ')}.`);
319
+ if (DEPRECATED[name])
320
+ warn('csp-deprecated-directive', `CSP directive "${name}": ${DEPRECATED[name]}.`);
321
+ if (VALUELESS.has(name)) {
322
+ if (value !== true && value.length > 0)
323
+ err('csp-valueless', `CSP directive "${name}" takes no value.`);
324
+ continue;
325
+ }
326
+ if (value === true || value.length === 0) {
327
+ const required = REQUIRES_VALUE[name];
328
+ if (required)
329
+ err('csp-invalid-value', `CSP directive "${name}" has no value: ${required}`);
330
+ else if (!['sandbox', 'trusted-types'].includes(name))
331
+ warn('csp-empty-directive', `CSP directive "${name}" has an empty source list, which blocks everything; writing "'none'" says so explicitly.`);
332
+ continue;
333
+ }
334
+ for (const token of value) {
335
+ if (/\s/.test(token)) {
336
+ err('csp-forbidden-character', `CSP directive "${name}": ${JSON.stringify(token)} contains a space, so it would be written as several values. Give each value as its own array item.`);
337
+ continue;
338
+ }
339
+ if (/[;,"\\\u0000-\u001f\u007f]/.test(token)) {
340
+ err('csp-forbidden-character', `CSP directive "${name}": source ${JSON.stringify(token)} contains a forbidden character (; , " \\ or a control character).`);
341
+ continue;
342
+ }
343
+ if (NON_SOURCE_LIST.has(name))
344
+ continue; // checked as a whole below
345
+ const lower = token.toLowerCase();
346
+ if (KEYWORDS.includes(lower) || /^(sha256|sha384|sha512|nonce)-/.test(lower)) {
347
+ err('csp-unquoted-keyword', `CSP directive "${name}": "${token}" must be written with single quotes ('${token}'); without them it is read as a host name.`);
348
+ continue;
349
+ }
350
+ if (token.startsWith("'")) {
351
+ if (!QUOTED_KEYWORDS.has(lower) && !HASH_RE.test(token) && !NONCE_RE.test(token)) {
352
+ err('csp-invalid-keyword', `CSP directive "${name}": unknown keyword ${token}.`);
353
+ }
354
+ continue;
355
+ }
356
+ if (!SCHEME_RE.test(token) && token !== '*' && !HOST_RE.test(token)) {
357
+ err('csp-invalid-source', `CSP directive "${name}": "${token}" is not a valid source expression.`);
358
+ }
359
+ }
360
+ const invalid = invalidValueMessage(name, value);
361
+ if (invalid)
362
+ err('csp-invalid-value', `CSP directive "${name}": ${invalid}`);
363
+ if (!NON_SOURCE_LIST.has(name) && value.some((t) => t.toLowerCase() === "'none'") && value.length > 1) {
364
+ err('csp-none-combined', `CSP directive "${name}": 'none' is ignored when combined with other sources; remove one of them.`);
365
+ }
366
+ }
367
+ if (/,/.test(policy))
368
+ err('csp-comma', 'the policy contains a comma, which would split it into several policies.');
369
+ // --- 2. Dangerous script sources ------------------------------------------------------
370
+ const script = effectiveSources(directives, 'script');
371
+ if (!script) {
372
+ err('csp-no-script-src', 'the policy has neither script-src nor default-src: any script would be allowed.');
373
+ }
374
+ else {
375
+ for (const name of ['script-src', 'script-src-elem', 'default-src']) {
376
+ const v = directives.get(name);
377
+ if (v === undefined || v === true)
378
+ continue;
379
+ if (name === 'default-src' && (directives.has('script-src') || directives.has('script-src-elem')))
380
+ continue;
381
+ for (const t of v) {
382
+ const l = t.toLowerCase();
383
+ if (l === "'unsafe-inline'")
384
+ err('csp-unsafe-inline', `${name} must not allow 'unsafe-inline': it defeats the purpose of hashing inline scripts.`);
385
+ else if (l === "'unsafe-eval'" && !csp.allowUnsafeEval)
386
+ err('csp-unsafe-eval', `${name} must not allow 'unsafe-eval' (set csp.allowUnsafeEval: true if a library really needs it).`);
387
+ else if (l === '*' || l === 'http:' || l === 'https:' || l === 'data:')
388
+ err('csp-script-wildcard', `${name} must not allow "${t}": it lets any site (or data: URL) provide scripts.`);
389
+ }
390
+ }
391
+ const defaultSrc = directives.get('default-src');
392
+ if (!directives.has('object-src') && !(Array.isArray(defaultSrc) && defaultSrc.some((s) => s.toLowerCase() === "'none'"))) {
393
+ warn('csp-object-src', "object-src is not set to 'none': plugins (<object>, <embed>) fall back to default-src.");
394
+ }
395
+ }
396
+ if (!directives.has('base-uri'))
397
+ warn('csp-base-uri', "base-uri is not set: an injected <base> tag could redirect relative script URLs. Use base-uri 'self'.");
398
+ // --- 3. Every inline script is allowed by the directive that applies to it -----------
399
+ // Checked even with hashScripts: false (hashes may be written by hand).
400
+ const inlineDetail = (i) => ({ file: i.file, detail: `${i.detail} ${hashSource(i.text ?? '', 'sha256')}` });
401
+ const uniqueBy = (items) => {
402
+ const seen = new Set();
403
+ return items.filter((i) => { const k = `${i.file}\u0000${i.text}\u0000${i.nonce ?? ''}`; if (seen.has(k))
404
+ return false; seen.add(k); return true; });
405
+ };
406
+ if (script) {
407
+ const blocked = uniqueBy(scan.inlineScripts.filter((i) => !inlineElementAllowed(i, script.sources, 'script')));
408
+ if (blocked.length > 0) {
409
+ err('csp-inline-script-blocked', `${blocked.length} inline script(s) are not allowed by ${script.name} and will be blocked${csp.hashScripts ? '' : ' (csp.hashScripts is false: add their hashes yourself, or turn it back on)'}:\n${fmtLocations(blocked.map(inlineDetail))}`);
410
+ }
411
+ }
412
+ // --- 3b. sandbox without allow-scripts runs no script at all ------------------------------
413
+ const sandbox = directives.get('sandbox');
414
+ if (sandbox !== undefined) {
415
+ const flags = sandbox === true ? [] : sandbox.map((t) => t.toLowerCase());
416
+ const hasScripts = scan.inlineScripts.length + scan.externalScripts.length + scan.eventHandlers.length > 0;
417
+ if (!flags.includes('allow-scripts') && hasScripts) {
418
+ err('csp-sandbox-scripts', `the sandbox directive has no allow-scripts flag, so no script will run, although the site has ${scan.inlineScripts.length} inline and ${scan.externalScripts.length} external script(s). Add allow-scripts to sandbox, or remove sandbox.`);
419
+ }
420
+ }
421
+ // --- 4. Inline handlers and javascript: URLs ----------------------------------------------
422
+ const scriptAttr = effectiveSources(directives, 'script', 'attr');
423
+ if (scriptAttr) {
424
+ const blocked = scan.eventHandlers.filter((h) => !attributeAllowed(h.text ?? '', scriptAttr.sources, 'script'));
425
+ if (blocked.length > 0) {
426
+ err('csp-event-handlers', `${blocked.length} inline event handler attribute(s) (onclick=… etc.) will be blocked by ${scriptAttr.name}. Move them to a <script> with addEventListener, or allow these exact values with 'unsafe-hashes' and their hashes in script-src-attr:\n${fmtLocations(blocked)}`);
427
+ }
428
+ }
429
+ if (scan.javascriptUrls.length > 0) {
430
+ err('csp-javascript-urls', `${scan.javascriptUrls.length} javascript: URL(s) will be blocked by the CSP:\n${fmtLocations(scan.javascriptUrls)}`);
431
+ }
432
+ // --- 5. Styles: each <style> element and each style attribute ------------------------------
433
+ const style = effectiveSources(directives, 'style');
434
+ if (style) {
435
+ const unsafeInline = style.sources.some((s) => s.toLowerCase() === "'unsafe-inline'");
436
+ const hasHashOrNonce = style.sources.some((s) => HASH_RE.test(s) || NONCE_RE.test(s));
437
+ if (unsafeInline && hasHashOrNonce) {
438
+ warn('csp-style-unsafe-inline-ignored', `${style.name} contains both hashes or nonces and 'unsafe-inline': browsers then ignore 'unsafe-inline'. Remove it from ${style.name} to make the policy say what it does.`);
439
+ }
440
+ const blocked = uniqueBy(scan.inlineStyles.filter((i) => !inlineElementAllowed(i, style.sources, 'style')));
441
+ if (blocked.length > 0) {
442
+ err('csp-inline-style-blocked', `${blocked.length} inline <style> element(s) are not allowed by ${style.name} and will be blocked. Enable csp.hashStyles, add their hashes, or allow 'unsafe-inline':\n${fmtLocations(blocked.map(inlineDetail))}`);
443
+ }
444
+ }
445
+ // Attributes follow style-src-attr → style-src → default-src (never style-src-elem).
446
+ const styleAttr = effectiveSources(directives, 'style', 'attr');
447
+ if (styleAttr) {
448
+ const blocked = scan.styleAttributes.filter((a) => !attributeAllowed(a.text ?? '', styleAttr.sources, 'style'));
449
+ if (blocked.length > 0) {
450
+ err('csp-style-attributes', `${blocked.length} style="…" attribute(s) will be blocked by ${styleAttr.name}. Add "style-src-attr": "'unsafe-inline'", allow these exact values with 'unsafe-hashes' and their hashes, or remove them:\n${fmtLocations(blocked)}`);
451
+ }
452
+ }
453
+ // --- 6. <base> and external scripts/stylesheets ---------------------------------------------
454
+ const origin = ctx.site ? new URL(ctx.site.origin) : new URL('https://self.invalid/');
455
+ let basePath = ctx.base ?? '/';
456
+ if (!basePath.startsWith('/'))
457
+ basePath = `/${basePath}`;
458
+ if (!basePath.endsWith('/'))
459
+ basePath += '/';
460
+ const root = new URL(basePath, origin);
461
+ const baseUri = directives.get('base-uri');
462
+ const blockedBases = [];
463
+ const documentBase = new Map();
464
+ for (const file of scan.files) {
465
+ const page = pageUrl(file, root);
466
+ const href = scan.baseHrefs.get(file);
467
+ let base = page;
468
+ if (href !== undefined) {
469
+ try {
470
+ const candidate = new URL(href, page);
471
+ // base-uri has no fallback: when absent, any base is allowed.
472
+ if (Array.isArray(baseUri) && !urlMatchesSources(candidate, baseUri, origin)) {
473
+ blockedBases.push({ file, detail: `<base href="${href}">` });
474
+ }
475
+ else {
476
+ base = candidate;
477
+ }
478
+ }
479
+ catch { /* invalid base: the browser ignores it too */ }
480
+ }
481
+ documentBase.set(file, base);
482
+ }
483
+ if (blockedBases.length > 0) {
484
+ err('csp-blocked-base', `${blockedBases.length} <base> element(s) are not allowed by base-uri: the browser ignores them, so relative URLs resolve from the page address instead. Remove the <base> or allow its URL in base-uri:\n${fmtLocations(blockedBases)}`);
485
+ }
486
+ const integrityOnly = [];
487
+ const encodingDependent = [];
488
+ const checkExternal = (kind, list, label) => {
489
+ const eff = effectiveSources(directives, kind);
490
+ if (!eff)
491
+ return;
492
+ const strictDynamic = kind === 'script' && eff.sources.some((s) => s.toLowerCase() === "'strict-dynamic'");
493
+ const listed = listedHashes(eff.sources);
494
+ const blocked = [];
495
+ const seen = new Set();
496
+ for (const item of list) {
497
+ let url;
498
+ try {
499
+ url = new URL(item.detail, documentBase.get(item.file) ?? root);
500
+ }
501
+ catch {
502
+ continue;
503
+ }
504
+ const key = `${url.href}\u0000${item.nonce ?? ''}\u0000${item.integrity ?? ''}`;
505
+ if (seen.has(key))
506
+ continue;
507
+ seen.add(key);
508
+ const shown = { file: item.file, detail: item.detail === url.href ? item.detail : `${item.detail} (${url.href})` };
509
+ if (item.nonce && eff.sources.includes(`'nonce-${item.nonce}'`))
510
+ continue;
511
+ // With 'strict-dynamic', host, scheme and 'self' sources are ignored for parser-inserted scripts.
512
+ if (!strictDynamic && urlMatchesSources(url, eff.sources, origin))
513
+ continue;
514
+ // Blocked by the CSP3 path rule but allowed by browsers that decode the whole path: say so.
515
+ if (!strictDynamic && urlMatchesSources(url, eff.sources, origin, 'decoded')) {
516
+ encodingDependent.push(shown);
517
+ continue;
518
+ }
519
+ // CSP3: an external script matches by integrity only if EVERY recognised SRI hash is listed
520
+ // (checked in Chromium 158: with sha256+sha384 in integrity and only sha256 listed, it is blocked).
521
+ // Unsupported algorithms and "?options" are ignored, as SRI parsing does.
522
+ const sri = (item.integrity ?? '').split(/\s+/).filter(Boolean).map((t) => canonicalHash(`'${t.replace(/\?.*$/, '')}'`)).filter((h) => !!h);
523
+ if (kind === 'script' && sri.length > 0 && sri.every((h) => listed.has(h))) {
524
+ integrityOnly.push(shown);
525
+ continue;
526
+ }
527
+ blocked.push(shown);
528
+ }
529
+ if (blocked.length > 0) {
530
+ const hint = strictDynamic
531
+ ? `${eff.name} uses 'strict-dynamic': scripts written in the HTML need a nonce, or must be inserted by an allowed script.`
532
+ : `Add their origin to ${eff.name}${ctx.site ? '' : ' (or set `site` in astro.config so that same-site absolute URLs count as \'self\')'}.`;
533
+ err(`csp-blocked-${kind}`, `${blocked.length} external ${label}(s) are not allowed by ${eff.name} and will be blocked:\n${fmtLocations(blocked)}\n${hint}`);
534
+ }
535
+ };
536
+ checkExternal('script', scan.externalScripts, 'script');
537
+ checkExternal('style', scan.externalStylesheets, 'stylesheet');
538
+ if (encodingDependent.length > 0) {
539
+ warn('csp-path-encoding', `${encodingDependent.length} external resource(s) have an encoded character in their path (such as %2F) that browsers treat differently: blocked under the CSP Level 3 rule, allowed by Chromium. Use the plain path, or allow the folder:\n${fmtLocations(encodingDependent)}`);
540
+ }
541
+ if (integrityOnly.length > 0) {
542
+ warn('csp-integrity-only', `${integrityOnly.length} external script(s) are allowed only through the hash of their integrity attribute. CSP Level 3 allows this, but browsers that do not implement it will block them; also allowing their origin is safer:\n${fmtLocations(integrityOnly)}`);
543
+ }
544
+ // --- 7. Two policies at once ---------------------------------------------------------------
545
+ if (scan.metaCsp.length > 0) {
546
+ warn('csp-meta-tag', `${scan.metaCsp.length} page(s) also carry a <meta http-equiv="Content-Security-Policy"> (Astro's security.csp?). The browser enforces both policies: a resource must pass both. Disable one of them to avoid surprises.\n${fmtLocations(scan.metaCsp.map((m) => ({ file: m.file, detail: m.detail.slice(0, 80) + (m.detail.length > 80 ? '…' : '') })), 3)}`);
547
+ }
548
+ if (csp.reportOnly) {
549
+ warn('csp-report-only', 'the policy is sent as Content-Security-Policy-Report-Only: nothing is blocked' + (directives.has('report-uri') || directives.has('report-to') ? '.' : ', and without report-uri/report-to violations only appear in the browser console.'));
550
+ }
551
+ return issues;
552
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Event handler content attributes: the only `on…` attributes a browser runs as script.
3
+ * Taken from Chromium 158 (every `on…` property of HTML elements, <body>, <frameset>,
4
+ * <video>, <svg>, window and document), plus handlers that this list cannot show:
5
+ * touch events (exposed only on touch devices) and SVG animation events.
6
+ * An `on…` attribute that is not listed (`once`, `online-id`…) is plain data.
7
+ */
8
+ export declare const EVENT_HANDLER_ATTRIBUTES: ReadonlySet<string>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Event handler content attributes: the only `on…` attributes a browser runs as script.
3
+ * Taken from Chromium 158 (every `on…` property of HTML elements, <body>, <frameset>,
4
+ * <video>, <svg>, window and document), plus handlers that this list cannot show:
5
+ * touch events (exposed only on touch devices) and SVG animation events.
6
+ * An `on…` attribute that is not listed (`once`, `online-id`…) is plain data.
7
+ */
8
+ export const EVENT_HANDLER_ATTRIBUTES = new Set([
9
+ // Chromium 158
10
+ 'onabort', 'onafterprint', 'onanimationcancel', 'onanimationend', 'onanimationiteration', 'onanimationstart',
11
+ 'onappinstalled', 'onauxclick', 'onbeforecopy', 'onbeforecut', 'onbeforeinput', 'onbeforeinstallprompt',
12
+ 'onbeforematch', 'onbeforepaste', 'onbeforeprint', 'onbeforetoggle', 'onbeforeunload', 'onbeforexrselect',
13
+ 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncommand',
14
+ 'oncontentvisibilityautostatechange', 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy',
15
+ 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover',
16
+ 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onencrypted', 'onended', 'onenterpictureinpicture',
17
+ 'onerror', 'onfocus', 'onformdata', 'onfreeze', 'onfullscreenchange', 'onfullscreenerror',
18
+ 'ongamepadconnected', 'ongamepaddisconnected', 'ongotpointercapture', 'onhashchange', 'oninput',
19
+ 'oninstallresult', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onlanguagechange',
20
+ 'onleavepictureinpicture', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart',
21
+ 'onlostpointercapture', 'onmessage', 'onmessageerror', 'onmousedown', 'onmouseenter', 'onmouseleave',
22
+ 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onoffline', 'ononline',
23
+ 'onpagehide', 'onpagereveal', 'onpageshow', 'onpageswap', 'onpaste', 'onpause', 'onplay', 'onplaying',
24
+ 'onpointercancel', 'onpointerdown', 'onpointerenter', 'onpointerleave', 'onpointerlockchange',
25
+ 'onpointerlockerror', 'onpointermove', 'onpointerout', 'onpointerover', 'onpointerup', 'onpopstate',
26
+ 'onprerenderingchange', 'onprogress', 'onratechange', 'onreadystatechange', 'onrejectionhandled',
27
+ 'onreset', 'onresize', 'onresume', 'onscroll', 'onscrollend', 'onscrollsnapchange', 'onscrollsnapchanging',
28
+ 'onsearch', 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 'onselectionchange',
29
+ 'onselectstart', 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 'ontimeupdate',
30
+ 'ontoggle', 'ontransitioncancel', 'ontransitionend', 'ontransitionrun', 'ontransitionstart',
31
+ 'onunhandledrejection', 'onunload', 'onvisibilitychange', 'onvolumechange', 'onwaiting', 'onwaitingforkey',
32
+ 'onwebkitanimationend', 'onwebkitanimationiteration', 'onwebkitanimationstart', 'onwebkitfullscreenchange',
33
+ 'onwebkitfullscreenerror', 'onwebkittransitionend', 'onwheel',
34
+ // Touch events (only on touch-capable devices)
35
+ 'ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel',
36
+ // SVG animation (SMIL) and legacy SVG events
37
+ 'onbegin', 'onend', 'onrepeat', 'onfocusin', 'onfocusout', 'onactivate', 'onzoom',
38
+ ]);
@@ -0,0 +1,57 @@
1
+ import { type Issue } from './csp.js';
2
+ import { type HeaderLine } from './htaccess.js';
3
+ import { type ApacheHeadersOptions, type ResolvedOptions } from './options.js';
4
+ export interface Logger {
5
+ info(message: string): void;
6
+ warn(message: string): void;
7
+ error(message: string): void;
8
+ }
9
+ export declare const VERSION: string;
10
+ export interface GenerateInput {
11
+ /** Build output directory (Astro's `dist`). */
12
+ outDir: string;
13
+ options?: ApacheHeadersOptions;
14
+ /** Public URL of the site (Astro `site`), used to tell same-origin URLs from third-party ones. */
15
+ site?: string | URL | undefined;
16
+ /**
17
+ * Path the build is served under (Astro `base`), used to resolve relative URLs in pages.
18
+ * Default: the path of `site`, or `/`.
19
+ */
20
+ base?: string | undefined;
21
+ /** Folder of hashed assets, relative to outDir (Astro `build.assets`). Default `_astro`. `false` to skip. */
22
+ assetsDir?: string | false;
23
+ /** Write the files. Default `true`; `false` only computes and checks. */
24
+ write?: boolean;
25
+ logger?: Logger;
26
+ }
27
+ export interface WrittenFile {
28
+ path: string;
29
+ content: string;
30
+ mode: 'created' | 'replaced' | 'appended';
31
+ }
32
+ export interface GenerateResult {
33
+ /** Header name used for the policy, if CSP is enabled. */
34
+ cspHeader?: string;
35
+ policy?: string;
36
+ scriptHashes: string[];
37
+ styleHashes: string[];
38
+ pages: number;
39
+ htaccess: WrittenFile;
40
+ assetsHtaccess?: WrittenFile;
41
+ issues: Issue[];
42
+ written: boolean;
43
+ }
44
+ /** Thrown in strict mode when at least one check fails. Nothing has been written. */
45
+ export declare class ApacheHeadersError extends Error {
46
+ readonly issues: Issue[];
47
+ name: string;
48
+ constructor(issues: Issue[]);
49
+ }
50
+ /** Lists the headers to emit, and reports invalid values. */
51
+ export declare function headerLines(o: ResolvedOptions, policy: string | undefined, issues: Issue[]): HeaderLine[];
52
+ /**
53
+ * Resolves the hashed-assets folder and makes sure it is a real subfolder of outDir:
54
+ * not outDir itself (its .htaccess would replace the root one), not outside it.
55
+ */
56
+ export declare function resolveAssetsDir(outDir: string, assetsDir: string): string;
57
+ export declare function generateApacheHeaders(input: GenerateInput): Promise<GenerateResult>;