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.
@@ -0,0 +1,477 @@
1
+ export const BEGIN_MARKER = '# BEGIN astro-apache-headers';
2
+ export const END_MARKER = '# END astro-apache-headers';
3
+ /**
4
+ * Apache reads configuration lines into a buffer of MAX_STRING_LEN (8192) bytes,
5
+ * terminating NUL included: 8191 bytes pass, 8192 make every request of the folder
6
+ * fail with "500 — Line too long" (checked against Apache 2.4.58).
7
+ */
8
+ export const APACHE_MAX_LINE_BYTES = 8191;
9
+ export class HtaccessError extends Error {
10
+ name = 'HtaccessError';
11
+ }
12
+ /**
13
+ * Quotes a header value as an Apache directive argument, for mod_headers:
14
+ * `%` is doubled (mod_headers would read `%x` as a format specifier) and the value
15
+ * is wrapped in double quotes, or single quotes when it contains double quotes.
16
+ */
17
+ export function quoteHeaderValue(value) {
18
+ if (/[\u0000-\u001f\u007f]/.test(value))
19
+ throw new HtaccessError(`header value ${JSON.stringify(value)} contains a control character or a line break.`);
20
+ if (value.includes('\\'))
21
+ throw new HtaccessError(`header value ${JSON.stringify(value)} contains a backslash, which Apache may read as an escape.`);
22
+ const v = value.replace(/%/g, '%%');
23
+ if (!v.includes('"'))
24
+ return `"${v}"`;
25
+ if (!v.includes("'"))
26
+ return `'${v}'`;
27
+ throw new HtaccessError(`header value ${JSON.stringify(value)} contains both single and double quotes.`);
28
+ }
29
+ function header(h, indent) {
30
+ if (h.value === false)
31
+ return [`${indent}Header always unset ${h.name}`, `${indent}Header unset ${h.name}`];
32
+ return [`${indent}Header ${h.always ? 'always ' : ''}set ${h.name} ${quoteHeaderValue(h.value)}`];
33
+ }
34
+ export function renderRootBlock(input, eol = '\n') {
35
+ const lines = [
36
+ BEGIN_MARKER,
37
+ `# Generated at build time by astro-apache-headers ${input.version}.`,
38
+ '# Anything between these two markers is overwritten on every build.',
39
+ '<IfModule mod_headers.c>',
40
+ ];
41
+ for (const h of input.headers)
42
+ lines.push(...header(h, ' '));
43
+ if (input.removePoweredBy)
44
+ lines.push(' # Do not advertise the PHP version', ...header({ name: 'X-Powered-By', value: false, always: true }, ' '));
45
+ if (input.htmlCacheControl !== false) {
46
+ lines.push(' # HTML pages: always revalidate, so a new deployment is seen at once', ' <FilesMatch "\\.html?$">', ...header({ name: 'Cache-Control', value: input.htmlCacheControl, always: false }, ' '), ' </FilesMatch>');
47
+ }
48
+ lines.push('</IfModule>', END_MARKER);
49
+ return lines.join(eol);
50
+ }
51
+ export function renderAssetsBlock(version, eol = '\n') {
52
+ return [
53
+ BEGIN_MARKER,
54
+ `# Generated at build time by astro-apache-headers ${version}.`,
55
+ '# Files in this folder have a content hash in their name: they can be cached forever.',
56
+ '<IfModule mod_headers.c>',
57
+ ' Header set Cache-Control "public, max-age=31536000, immutable"',
58
+ '</IfModule>',
59
+ END_MARKER,
60
+ ].join(eol);
61
+ }
62
+ export function detectEol(text) {
63
+ return text && /\r\n/.test(text) ? '\r\n' : '\n';
64
+ }
65
+ /**
66
+ * Inserts the block into an existing .htaccess:
67
+ * - between existing markers if present (exactly one pair, in order);
68
+ * - otherwise appended at the end (later `Header set` directives win in Apache).
69
+ */
70
+ export function mergeBlock(existing, block) {
71
+ const eol = detectEol(existing);
72
+ if (existing === undefined || existing.trim() === '')
73
+ return { content: block + eol, mode: 'created' };
74
+ const lines = existing.split(/\r?\n/);
75
+ const begins = lines.flatMap((l, i) => (l.trim() === BEGIN_MARKER ? [i] : []));
76
+ const ends = lines.flatMap((l, i) => (l.trim() === END_MARKER ? [i] : []));
77
+ if (begins.length === 0 && ends.length === 0) {
78
+ const body = existing.replace(/(\r?\n)*$/, '');
79
+ return { content: body + eol + eol + block + eol, mode: 'appended' };
80
+ }
81
+ if (begins.length !== 1 || ends.length !== 1 || begins[0] > ends[0]) {
82
+ throw new HtaccessError(`the existing .htaccess must contain the markers "${BEGIN_MARKER}" and "${END_MARKER}" exactly once each, in that order (found ${begins.length} BEGIN and ${ends.length} END).`);
83
+ }
84
+ const before = lines.slice(0, begins[0]);
85
+ const after = lines.slice(ends[0] + 1);
86
+ return { content: [...before, ...block.split(/\r?\n/), ...after].join(eol), mode: 'replaced' };
87
+ }
88
+ // ---------------------------------------------------------------------------
89
+ // Reading the result back
90
+ // ---------------------------------------------------------------------------
91
+ /** Splits a directive line into arguments like Apache's ap_getword_conf. */
92
+ export function splitApacheArgs(line) {
93
+ const args = [];
94
+ let i = 0;
95
+ while (i < line.length) {
96
+ while (i < line.length && /\s/.test(line[i]))
97
+ i++;
98
+ if (i >= line.length)
99
+ break;
100
+ const q = line[i];
101
+ if (q === '"' || q === "'") {
102
+ let j = i + 1;
103
+ let out = '';
104
+ while (j < line.length && line[j] !== q) {
105
+ if (line[j] === '\\' && line[j + 1] === q) {
106
+ out += q;
107
+ j += 2;
108
+ }
109
+ else {
110
+ out += line[j];
111
+ j++;
112
+ }
113
+ }
114
+ args.push(out);
115
+ i = j + 1;
116
+ }
117
+ else {
118
+ let j = i;
119
+ while (j < line.length && !/\s/.test(line[j]))
120
+ j++;
121
+ args.push(line.slice(i, j));
122
+ i = j;
123
+ }
124
+ }
125
+ return args;
126
+ }
127
+ /** Header name as Apache compares it: case-insensitive, optional trailing colon ("Name:"). */
128
+ export function normaliseHeaderName(name) {
129
+ return name.replace(/:$/, '').toLowerCase();
130
+ }
131
+ /**
132
+ * Lists the active (non-comment) mod_headers `Header` directives of a .htaccess.
133
+ * With `trustMarkers: false` (files the generator does not rewrite), lines between
134
+ * the markers are treated like any other line.
135
+ */
136
+ export function readHeaderDirectives(content, opts = {}) {
137
+ const trust = opts.trustMarkers ?? true;
138
+ const physical = content.split(/\r?\n/);
139
+ const directives = [];
140
+ let inBlock = false;
141
+ let block;
142
+ const sections = [];
143
+ let longest = { lineNumber: 0, bytes: 0 };
144
+ for (let i = 0; i < physical.length; i++) {
145
+ const start = i;
146
+ let line = physical[i];
147
+ // Apache joins lines ending with a backslash.
148
+ while (line.endsWith('\\') && i + 1 < physical.length)
149
+ line = line.slice(0, -1) + physical[++i];
150
+ const bytes = Buffer.byteLength(line, 'utf8');
151
+ if (bytes > longest.bytes)
152
+ longest = { lineNumber: start + 1, bytes };
153
+ const trimmed = line.trim();
154
+ if (trimmed === BEGIN_MARKER) {
155
+ if (!block)
156
+ block = { lineNumber: start + 1, enclosing: [...sections] };
157
+ if (trust)
158
+ inBlock = true;
159
+ continue;
160
+ }
161
+ if (trimmed === END_MARKER) {
162
+ inBlock = false;
163
+ continue;
164
+ }
165
+ if (trimmed === '' || trimmed.startsWith('#'))
166
+ continue;
167
+ // Track Apache sections (<Files …>, <If …>, <IfModule …>…) to know where the block sits.
168
+ const close = /^<\/\s*([A-Za-z]+)\s*>/.exec(trimmed);
169
+ if (close) {
170
+ sections.pop();
171
+ continue;
172
+ }
173
+ const open = /^<\s*([A-Za-z]+)\b[^>]*>/.exec(trimmed);
174
+ if (open) {
175
+ sections.push(trimmed);
176
+ continue;
177
+ }
178
+ const args = splitApacheArgs(trimmed);
179
+ if (args[0]?.toLowerCase() !== 'header')
180
+ continue;
181
+ let k = 1;
182
+ if (/^(always|onsuccess)$/i.test(args[k] ?? ''))
183
+ k++;
184
+ const action = (args[k] ?? '').toLowerCase();
185
+ const name = (args[k + 1] ?? '').replace(/:$/, '');
186
+ const value = args[k + 2];
187
+ directives.push({
188
+ lineNumber: start + 1,
189
+ inBlock,
190
+ action,
191
+ name,
192
+ value: value === undefined ? undefined : value.replace(/%%/g, '%'),
193
+ rawLength: bytes,
194
+ });
195
+ }
196
+ return { directives, longestLine: longest, ...(block ? { block } : {}) };
197
+ }
198
+ /**
199
+ * Does a PCRE pattern use only constructs that mean the same thing in JavaScript?
200
+ * A whitelist: literals, escaped punctuation, `.`, `^`, `$`, `|`, groups `( )` and `(?: )`,
201
+ * classes `[...]` with ranges, `\d \w \s` (and upper-case), `\b \B` outside classes,
202
+ * greedy or lazy quantifiers `* + ? {n} {n,} {n,m}`. Everything else (POSIX classes,
203
+ * possessive quantifiers, \Q…\E, \x{…}, \p{…}, back-references, other (?…) groups,
204
+ * verbs…) is refused, because JavaScript may compile it with a different meaning.
205
+ */
206
+ export function isPortablePattern(p) {
207
+ let i = 0;
208
+ let depth = 0;
209
+ let atom = false; // is there something a quantifier can apply to?
210
+ const SHORTHAND = /[dDwWsS]/;
211
+ while (i < p.length) {
212
+ const c = p[i];
213
+ if (c === '\\') {
214
+ const n = p[i + 1];
215
+ if (n === undefined)
216
+ return false;
217
+ if (SHORTHAND.test(n)) {
218
+ atom = true;
219
+ i += 2;
220
+ continue;
221
+ }
222
+ if (n === 'b' || n === 'B') {
223
+ atom = false;
224
+ i += 2;
225
+ continue;
226
+ }
227
+ if (/[A-Za-z0-9]/.test(n))
228
+ return false; // \Q \x \p \k \1 \R \h \K \c \0 \N \t…
229
+ atom = true;
230
+ i += 2;
231
+ continue; // escaped punctuation: a literal in both engines
232
+ }
233
+ if (c === '[') {
234
+ let j = i + 1;
235
+ const negated = p[j] === '^';
236
+ if (negated)
237
+ j++;
238
+ if (p[j] === ']')
239
+ return false; // PCRE: literal "]"; JavaScript: empty class
240
+ let closed = false;
241
+ let hasLetter = false;
242
+ const literals = []; // literal characters, in order, to detect ranges
243
+ while (j < p.length) {
244
+ const d = p[j];
245
+ if (d === ']') {
246
+ closed = true;
247
+ break;
248
+ }
249
+ if (d === '[')
250
+ return false; // [:alpha:], [=a=], [.x.] in PCRE
251
+ if (d === '\\') {
252
+ const n = p[j + 1];
253
+ if (n === undefined)
254
+ return false;
255
+ if (!SHORTHAND.test(n) && /[A-Za-z0-9]/.test(n))
256
+ return false; // \b, \x, \p… inside a class
257
+ if (SHORTHAND.test(n) && p[j + 2] === '-' && p[j + 3] !== undefined && p[j + 3] !== ']')
258
+ return false; // [\w-0]
259
+ literals.push(SHORTHAND.test(n) ? '' : n);
260
+ j += 2;
261
+ continue;
262
+ }
263
+ if (d === '-' && literals.length > 0 && p[j + 1] !== undefined && p[j + 1] !== ']') {
264
+ // Range a-b. Both bounds must be single characters: PCRE2 refuses "[0-\w]"
265
+ // ("invalid range", Apache answers 500) while JavaScript reads it differently.
266
+ const left = literals[literals.length - 1];
267
+ if (!left)
268
+ return false; // left bound is \d, \w… or the end of another range
269
+ let right;
270
+ if (p[j + 1] === '\\') {
271
+ const n = p[j + 2];
272
+ if (n === undefined || /[A-Za-z0-9]/.test(n))
273
+ return false; // \w, \d, \x41…
274
+ right = n;
275
+ j += 3;
276
+ }
277
+ else {
278
+ if (p[j + 1] === '[')
279
+ return false;
280
+ right = p[j + 1];
281
+ j += 2;
282
+ }
283
+ const from = left.charCodeAt(0);
284
+ const to = right.charCodeAt(0);
285
+ if (from > to)
286
+ return false; // reversed range: compile error in both engines
287
+ if (from <= 122 && to >= 65 && !(to < 97 && from > 90))
288
+ hasLetter = true;
289
+ literals.push('');
290
+ continue;
291
+ }
292
+ if (/[A-Za-z]/.test(d))
293
+ hasLetter = true;
294
+ literals.push(d);
295
+ j++;
296
+ }
297
+ if (!closed)
298
+ return false;
299
+ // The pattern is tested without case (request header names come in any case). For a
300
+ // negated class with letters, that REDUCES the matches ([^A] would also exclude "a"):
301
+ // the over-approximation no longer holds, so the pattern is not analysed.
302
+ if (negated && hasLetter)
303
+ return false;
304
+ atom = true;
305
+ i = j + 1;
306
+ continue;
307
+ }
308
+ if (c === '(') {
309
+ if (p[i + 1] === '?') {
310
+ if (p[i + 2] !== ':')
311
+ return false; // (?>…) (?=…) (?<n>…) (?i:…) (?#…) (?s)…
312
+ i += 3;
313
+ }
314
+ else if (p[i + 1] === '*') {
315
+ return false; // (*UTF), (*SKIP)…
316
+ }
317
+ else {
318
+ i += 1;
319
+ }
320
+ depth++;
321
+ atom = false;
322
+ continue;
323
+ }
324
+ if (c === ')') {
325
+ if (depth === 0)
326
+ return false;
327
+ depth--;
328
+ atom = true;
329
+ i++;
330
+ continue;
331
+ }
332
+ if (c === '|') {
333
+ atom = false;
334
+ i++;
335
+ continue;
336
+ }
337
+ if (c === '^' || c === '$') {
338
+ atom = false;
339
+ i++;
340
+ continue;
341
+ }
342
+ if (c === '*' || c === '+' || c === '?' || c === '{') {
343
+ if (!atom)
344
+ return false;
345
+ if (c === '{') {
346
+ const q = /^\{(\d+)(,(\d*))?\}/.exec(p.slice(i));
347
+ if (!q)
348
+ return false; // "{,2}", "{2" … are read differently
349
+ i += q[0].length;
350
+ }
351
+ else {
352
+ i++;
353
+ }
354
+ if (p[i] === '+')
355
+ return false; // possessive
356
+ if (p[i] === '?')
357
+ i++; // lazy: same set of matches
358
+ atom = false;
359
+ continue;
360
+ }
361
+ if (c === ']' || c === '}')
362
+ return false; // literal in both, but avoid ambiguity
363
+ atom = true;
364
+ i++;
365
+ }
366
+ return depth === 0;
367
+ }
368
+ /**
369
+ * `Header echo <regex>` copies every REQUEST header whose name matches into the response.
370
+ * The name is chosen by the client, in any case, so the pattern is tested without case
371
+ * (a safe over-approximation). Patterns outside the portable subset are reported as
372
+ * unverifiable (returns undefined).
373
+ */
374
+ export function echoMatcher(pattern) {
375
+ let p = pattern;
376
+ const inline = /^\(\?([a-zA-Z]+)\)/.exec(p);
377
+ if (inline) {
378
+ if (!/^i+$/.test(inline[1]))
379
+ return undefined;
380
+ p = p.slice(inline[0].length);
381
+ }
382
+ if (!isPortablePattern(p))
383
+ return undefined;
384
+ try {
385
+ const re = new RegExp(p, 'i');
386
+ return (name) => re.test(name);
387
+ }
388
+ catch {
389
+ return undefined;
390
+ }
391
+ }
392
+ const isCspName = (name) => /^content-security-policy(-report-only)?$/i.test(normaliseHeaderName(name));
393
+ const ADDING_ACTIONS = new Set(['set', 'append', 'add', 'merge', 'setifempty']);
394
+ /**
395
+ * Checks a .htaccess after merging:
396
+ * - nothing outside the generated block may touch the managed CSP header (set, unset, edit…);
397
+ * - no second policy outside the block;
398
+ * - the root file contains exactly one CSP directive, equal to the computed policy;
399
+ * - no conflicting directive for the other managed headers;
400
+ * - no line too long for Apache.
401
+ */
402
+ export function checkHtaccess(content, expected) {
403
+ const issues = [];
404
+ const label = expected.label ?? '.htaccess';
405
+ const add = (level, code, message) => issues.push({ level, code, message });
406
+ const { directives, longestLine, block: blockPos } = readHeaderDirectives(content, { trustMarkers: expected.trustMarkers ?? true });
407
+ const lines = content.split(/\r?\n/);
408
+ const quote = (d) => `"${(lines[d.lineNumber - 1] ?? '').trim()}"`;
409
+ const scope = expected.scope ?? 'all';
410
+ const outside = scope !== 'block';
411
+ const block = scope !== 'outside';
412
+ if (block && (expected.trustMarkers ?? true) && blockPos && blockPos.enclosing.length > 0) {
413
+ add('error', 'htaccess-block-scope', `the "${BEGIN_MARKER}" marker of ${label} (line ${blockPos.lineNumber}) is inside ${blockPos.enclosing.map((x) => `"${x}"`).join(' > ')}: the generated headers would only apply to part of the site, or not at all. Move the markers to the top level of the file, outside any <…> section.`);
414
+ }
415
+ if (block && longestLine.bytes > APACHE_MAX_LINE_BYTES) {
416
+ add('error', 'htaccess-line-too-long', `line ${longestLine.lineNumber} of ${label} is ${longestLine.bytes} bytes long; Apache rejects lines over ${APACHE_MAX_LINE_BYTES} bytes and would answer every request with a 500 error. Reduce the number of distinct inline scripts (move them to files) or shorten the policy.`);
417
+ }
418
+ const ourCsp = expected.cspHeader ? normaliseHeaderName(expected.cspHeader) : undefined;
419
+ // Header echo: the "name" is a regular expression over request header names.
420
+ for (const d of outside ? directives : []) {
421
+ if (d.inBlock || d.action !== 'echo')
422
+ continue;
423
+ const matches = echoMatcher(d.name);
424
+ if (!matches) {
425
+ add('error', 'htaccess-unverifiable', `line ${d.lineNumber} of ${label}, ${quote(d)}: this Header echo pattern cannot be checked (it uses regular expression syntax that this check cannot interpret with certainty, such as POSIX classes like [[:alpha:]]). It could copy request headers over the headers astro-apache-headers sets. Rewrite it with a simpler pattern, or remove it.`);
426
+ continue;
427
+ }
428
+ const cspNames = ['content-security-policy', 'content-security-policy-report-only'];
429
+ if (ourCsp && matches(ourCsp)) {
430
+ add('error', 'htaccess-csp-conflict', `line ${d.lineNumber} of ${label}, ${quote(d)}, copies a ${expected.cspHeader} header sent by the client into the response, next to the generated one (Apache checked: the client's value is added). Remove that line or narrow its pattern.`);
431
+ }
432
+ else if (ourCsp && cspNames.some((n) => matches(n))) {
433
+ add('error', 'htaccess-duplicate-csp', `line ${d.lineNumber} of ${label}, ${quote(d)}, copies a client-supplied policy header into the response. Remove that line or narrow its pattern.`);
434
+ }
435
+ for (const h of expected.managed) {
436
+ if (isCspName(h.name) || !matches(normaliseHeaderName(h.name)))
437
+ continue;
438
+ add(expected.conflictLevel ?? 'error', 'htaccess-header-conflict', `line ${d.lineNumber} of ${label}, ${quote(d)}, copies a "${h.name}" header sent by the client into the response, next to the value astro-apache-headers sets (Apache checked: "X-Frame-Options: DENY, ALLOWALL"). Remove that line or narrow its pattern.`);
439
+ }
440
+ }
441
+ if (ourCsp) {
442
+ for (const d of outside ? directives : []) {
443
+ if (d.inBlock || d.action === 'echo' || !isCspName(d.name))
444
+ continue;
445
+ if (normaliseHeaderName(d.name) === ourCsp) {
446
+ add('error', 'htaccess-csp-conflict', `line ${d.lineNumber} of ${label}, ${quote(d)}, ${d.action === 'unset' ? 'removes' : 'changes'} the ${expected.cspHeader} header generated by astro-apache-headers. Remove that line, or set csp: false to manage the CSP yourself.`);
447
+ }
448
+ else if (ADDING_ACTIONS.has(d.action)) {
449
+ add('error', 'htaccess-duplicate-csp', `line ${d.lineNumber} of ${label}, ${quote(d)}, sends a second policy (${d.name}) next to the generated ${expected.cspHeader}. Remove that line, or set csp: false.`);
450
+ }
451
+ }
452
+ if (block && (expected.requireBlock ?? true)) {
453
+ const ours = directives.filter((d) => d.inBlock && normaliseHeaderName(d.name) === ourCsp);
454
+ if (ours.length !== 1)
455
+ add('error', 'htaccess-csp-missing', `the generated block of ${label} should contain exactly one ${expected.cspHeader} directive (found ${ours.length}).`);
456
+ else if (ours[0].action !== 'set')
457
+ add('error', 'htaccess-csp-action', `the ${expected.cspHeader} directive must use "set" (found "${ours[0].action}").`);
458
+ else if (ours[0].value !== expected.policy)
459
+ add('error', 'htaccess-csp-mismatch', `the ${expected.cspHeader} value read back from ${label} differs from the computed policy (quoting problem?).`);
460
+ }
461
+ }
462
+ const managed = new Map(expected.managed.map((h) => [normaliseHeaderName(h.name), h]));
463
+ for (const d of outside ? directives : []) {
464
+ if (d.inBlock || d.action === 'echo')
465
+ continue;
466
+ const name = normaliseHeaderName(d.name);
467
+ if (isCspName(name))
468
+ continue;
469
+ const ours = managed.get(name);
470
+ if (!ours)
471
+ continue;
472
+ if (ours.value === false && d.action === 'unset')
473
+ continue; // unsetting twice is harmless
474
+ add(expected.conflictLevel ?? 'error', 'htaccess-header-conflict', `line ${d.lineNumber} of ${label}, ${quote(d)}, also handles "${d.name}", which astro-apache-headers sets. Remove that line, or disable the corresponding option, so that only one value is sent.`);
475
+ }
476
+ return issues;
477
+ }
package/dist/html.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { HashAlgorithm } from './options.js';
2
+ /** Inline script types that the browser checks against `script-src`. Others are inert data blocks. */
3
+ export declare function isCspCheckedScriptType(type: string | undefined): boolean;
4
+ export declare function hashSource(text: string, algorithm: HashAlgorithm): string;
5
+ export interface Location {
6
+ file: string;
7
+ detail: string;
8
+ }
9
+ /** An inline element, attribute or external resource, kept with what CSP matching needs. */
10
+ export interface Item extends Location {
11
+ /** Script/style text, or attribute value. */
12
+ text?: string;
13
+ /** `nonce` attribute, if any. */
14
+ nonce?: string;
15
+ /** `integrity` attribute of an external script, if any. */
16
+ integrity?: string;
17
+ /** `type` attribute of a script, lower-cased, if any (e.g. `module`, `speculationrules`). */
18
+ type?: string;
19
+ }
20
+ export interface HtmlScan {
21
+ files: string[];
22
+ /** Hash source expression → files where the inline script appears. */
23
+ scriptHashes: Map<string, string[]>;
24
+ styleHashes: Map<string, string[]>;
25
+ inlineStyleElements: number;
26
+ /** Every inline executable `<script>` (non-empty), with its text and nonce. */
27
+ inlineScripts: Item[];
28
+ /** Every inline `<style>` (non-empty), with its text and nonce. */
29
+ inlineStyles: Item[];
30
+ styleAttributes: Item[];
31
+ eventHandlers: Item[];
32
+ javascriptUrls: Location[];
33
+ externalScripts: Item[];
34
+ externalStylesheets: Item[];
35
+ metaCsp: Location[];
36
+ /** First `<base href>` of each file, when present. */
37
+ baseHrefs: Map<string, string>;
38
+ }
39
+ /** Recursively lists `.html` / `.htm` files, sorted for deterministic output. */
40
+ export declare function listHtmlFiles(dir: string): Promise<string[]>;
41
+ export declare function emptyScan(): HtmlScan;
42
+ /** Scans one HTML document and accumulates findings into `scan`. */
43
+ export declare function scanHtml(html: string, file: string, algorithm: HashAlgorithm, scan: HtmlScan): void;
44
+ /** Scans every HTML file of a build output directory. File names in the result are relative, with `/`. */
45
+ export declare function scanDirectory(dir: string, algorithm: HashAlgorithm): Promise<HtmlScan>;
package/dist/html.js ADDED
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Scans built HTML files with a spec-compliant parser (parse5), so that the text
3
+ * we hash is exactly the text the browser hashes (newline normalisation included).
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import { readdir, readFile } from 'node:fs/promises';
7
+ import { join, relative, sep } from 'node:path';
8
+ import { parse } from 'parse5';
9
+ import { EVENT_HANDLER_ATTRIBUTES } from './event-handlers.js';
10
+ /** JavaScript MIME type essences, from the HTML standard. */
11
+ const JS_MIME = new Set([
12
+ 'application/ecmascript', 'application/javascript', 'application/x-ecmascript', 'application/x-javascript',
13
+ 'text/ecmascript', 'text/javascript', 'text/javascript1.0', 'text/javascript1.1', 'text/javascript1.2',
14
+ 'text/javascript1.3', 'text/javascript1.4', 'text/javascript1.5', 'text/jscript', 'text/livescript',
15
+ 'text/x-ecmascript', 'text/x-javascript',
16
+ ]);
17
+ /** Inline script types that the browser checks against `script-src`. Others are inert data blocks. */
18
+ export function isCspCheckedScriptType(type) {
19
+ if (type === undefined)
20
+ return true;
21
+ const t = type.trim().toLowerCase();
22
+ if (t === '' || t === 'module' || t === 'importmap' || t === 'speculationrules')
23
+ return true;
24
+ const essence = t.split(';')[0].trim();
25
+ return JS_MIME.has(essence);
26
+ }
27
+ export function hashSource(text, algorithm) {
28
+ return `'${algorithm}-${createHash(algorithm).update(text, 'utf8').digest('base64')}'`;
29
+ }
30
+ const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href', 'data']);
31
+ function attr(node, name) {
32
+ return node.attrs?.find((a) => (a.prefix ? `${a.prefix}:${a.name}` : a.name) === name)?.value;
33
+ }
34
+ function textOf(node) {
35
+ let out = '';
36
+ for (const c of node.childNodes ?? [])
37
+ if (c.nodeName === '#text')
38
+ out += c.value ?? '';
39
+ return out;
40
+ }
41
+ function optional(o) {
42
+ const out = {};
43
+ for (const [k, v] of Object.entries(o))
44
+ if (v !== undefined)
45
+ out[k] = v;
46
+ return out;
47
+ }
48
+ function add(map, key, file) {
49
+ const list = map.get(key);
50
+ if (!list)
51
+ map.set(key, [file]);
52
+ else if (!list.includes(file))
53
+ list.push(file);
54
+ }
55
+ /** Recursively lists `.html` / `.htm` files, sorted for deterministic output. */
56
+ export async function listHtmlFiles(dir) {
57
+ const out = [];
58
+ async function walk(d) {
59
+ const entries = await readdir(d, { withFileTypes: true });
60
+ for (const e of entries) {
61
+ const p = join(d, e.name);
62
+ if (e.isDirectory())
63
+ await walk(p);
64
+ else if (e.isFile() && /\.html?$/i.test(e.name))
65
+ out.push(p);
66
+ }
67
+ }
68
+ await walk(dir);
69
+ return out.sort();
70
+ }
71
+ export function emptyScan() {
72
+ return {
73
+ files: [], scriptHashes: new Map(), styleHashes: new Map(), inlineStyleElements: 0,
74
+ inlineScripts: [], inlineStyles: [], styleAttributes: [], eventHandlers: [], javascriptUrls: [], externalScripts: [],
75
+ externalStylesheets: [], metaCsp: [], baseHrefs: new Map(),
76
+ };
77
+ }
78
+ /** Scans one HTML document and accumulates findings into `scan`. */
79
+ export function scanHtml(html, file, algorithm, scan) {
80
+ const doc = parse(html);
81
+ scan.files.push(file);
82
+ const visit = (node) => {
83
+ const tag = node.tagName?.toLowerCase();
84
+ if (tag) {
85
+ for (const a of node.attrs ?? []) {
86
+ const name = (a.prefix ? `${a.prefix}:${a.name}` : a.name).toLowerCase();
87
+ if (EVENT_HANDLER_ATTRIBUTES.has(name))
88
+ scan.eventHandlers.push({ file, detail: `<${tag} ${name}="…">`, text: a.value });
89
+ else if (name === 'style')
90
+ scan.styleAttributes.push({ file, detail: `<${tag} style="…">`, text: a.value });
91
+ else if (URL_ATTRS.has(name) && /^javascript:/i.test(a.value.replace(/[\u0000- ]/g, ''))) {
92
+ scan.javascriptUrls.push({ file, detail: `<${tag} ${name}="javascript:…">` });
93
+ }
94
+ }
95
+ if (tag === 'script') {
96
+ const src = attr(node, 'src');
97
+ const extra = optional({ nonce: attr(node, 'nonce'), integrity: attr(node, 'integrity') });
98
+ if (src !== undefined) {
99
+ if (isCspCheckedScriptType(attr(node, 'type')))
100
+ scan.externalScripts.push({ file, detail: src, ...extra });
101
+ }
102
+ else if (isCspCheckedScriptType(attr(node, 'type'))) {
103
+ const text = textOf(node);
104
+ // An inline script with empty source text is never executed nor checked.
105
+ if (text !== '') {
106
+ add(scan.scriptHashes, hashSource(text, algorithm), file);
107
+ const type = attr(node, 'type')?.trim().toLowerCase();
108
+ scan.inlineScripts.push({ file, detail: type ? `<script type="${type}">` : '<script>', text, ...extra, ...(type ? { type } : {}) });
109
+ }
110
+ }
111
+ }
112
+ else if (tag === 'style') {
113
+ scan.inlineStyleElements++;
114
+ const text = textOf(node);
115
+ if (text !== '') {
116
+ add(scan.styleHashes, hashSource(text, algorithm), file);
117
+ scan.inlineStyles.push({ file, detail: '<style>', text, ...optional({ nonce: attr(node, 'nonce') }) });
118
+ }
119
+ }
120
+ else if (tag === 'link') {
121
+ const rel = (attr(node, 'rel') ?? '').toLowerCase().split(/\s+/);
122
+ const href = attr(node, 'href');
123
+ if (rel.includes('stylesheet') && href)
124
+ scan.externalStylesheets.push({ file, detail: href, ...optional({ nonce: attr(node, 'nonce'), integrity: attr(node, 'integrity') }) });
125
+ }
126
+ else if (tag === 'base') {
127
+ const href = attr(node, 'href');
128
+ if (href !== undefined && !scan.baseHrefs.has(file))
129
+ scan.baseHrefs.set(file, href);
130
+ }
131
+ else if (tag === 'meta') {
132
+ if ((attr(node, 'http-equiv') ?? '').trim().toLowerCase() === 'content-security-policy') {
133
+ scan.metaCsp.push({ file, detail: attr(node, 'content') ?? '' });
134
+ }
135
+ }
136
+ }
137
+ for (const child of node.childNodes ?? [])
138
+ visit(child);
139
+ if (node.content)
140
+ visit(node.content); // <template> contents
141
+ };
142
+ visit(doc);
143
+ }
144
+ /** Scans every HTML file of a build output directory. File names in the result are relative, with `/`. */
145
+ export async function scanDirectory(dir, algorithm) {
146
+ const scan = emptyScan();
147
+ for (const path of await listHtmlFiles(dir)) {
148
+ const rel = relative(dir, path).split(sep).join('/');
149
+ scanHtml(await readFile(path, 'utf8'), rel, algorithm, scan);
150
+ }
151
+ return scan;
152
+ }