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/README.md CHANGED
@@ -1,3 +1,294 @@
1
- # Temporary Holding Version
1
+ # astro-apache-headers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **English** · [Français](./README.fr.md)
4
+
5
+ An Astro integration for **static sites hosted on Apache shared hosting** (OVH, o2switch, Hostinger, Infomaniak…). At build time it writes a `.htaccess` that sends:
6
+
7
+ - a real **`Content-Security-Policy` HTTP header**, with the SHA-256 hashes of every inline script computed automatically;
8
+ - the usual **security headers**, all configurable: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy, and removal of `X-Powered-By`;
9
+ - **long-term caching** for `/_astro/` (fingerprinted files) and revalidation for HTML pages.
10
+
11
+ Before writing anything, it checks the policy and the `.htaccess` files against the built HTML: the scripts, styles and attributes it finds, and the ways it knows a `.htaccess` can remove or narrow the CSP. A problem it detects stops the build (see [Strict checks](#strict-checks) for what is covered).
12
+
13
+ ```js
14
+ // astro.config.mjs
15
+ import { defineConfig } from 'astro/config';
16
+ import apacheHeaders from 'astro-apache-headers';
17
+
18
+ export default defineConfig({
19
+ site: 'https://example.com',
20
+ integrations: [apacheHeaders()],
21
+ });
22
+ ```
23
+
24
+ ## Why
25
+
26
+ On a static build with no adapter, Astro's `security.csp` can only put the policy in a `<meta>` tag. A `<meta>` policy has limits:
27
+
28
+ - it cannot use `frame-ancestors`, `report-uri` or `sandbox`;
29
+ - it does not protect anything that comes before the tag, or non-HTML responses.
30
+
31
+ Shared hosts have no adapter to set headers, but they all run Apache with `.htaccess` files. Writing that file by hand means keeping a list of hashes in sync with every inline script on every page. This integration does it for you on each build and checks the result.
32
+
33
+ ## Install
34
+
35
+ ```sh
36
+ npm install astro-apache-headers
37
+ ```
38
+
39
+ Then add it to `integrations` as shown above. Requirements:
40
+
41
+ - Astro 5, 6 or 7 with `output: 'static'`;
42
+ - Node 20.19 or later for this package. Your Astro version may ask for more: Astro checks Node itself and stops if it is too old. For example, Astro 6.0 needs Node 22.12 and Astro 7.4.14 needs Node 22.23.4;
43
+ - Apache 2.4 with `mod_headers` and `AllowOverride` allowing `FileInfo` (the default on shared hosting).
44
+
45
+ Versions tested before release: Astro 5.0.9, 5.18.2, 6.0.8, 6.4.8, 7.0.9 and 7.4.14 (installed from the packed `.tgz`), on Node 22.23 and, for Astro 5, Node 20.19.0. The test site, Apache and Chromium checks run with Astro 7.4.
46
+
47
+ ## What you get
48
+
49
+ `dist/.htaccess` (your own rules from `public/.htaccess` are kept, see below):
50
+
51
+ ```apache
52
+ # BEGIN astro-apache-headers
53
+ # Generated at build time by astro-apache-headers 0.1.6.
54
+ # Anything between these two markers is overwritten on every build.
55
+ <IfModule mod_headers.c>
56
+ Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'sha256-glJu…' 'sha256-yOX5…'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
57
+ Header always set Strict-Transport-Security "max-age=31536000"
58
+ Header always set X-Frame-Options "DENY"
59
+ Header always set X-Content-Type-Options "nosniff"
60
+ Header always set Referrer-Policy "strict-origin-when-cross-origin"
61
+ Header always set Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()"
62
+ Header always set Cross-Origin-Opener-Policy "same-origin"
63
+ # Do not advertise the PHP version
64
+ Header always unset X-Powered-By
65
+ Header unset X-Powered-By
66
+ # HTML pages: always revalidate, so a new deployment is seen at once
67
+ <FilesMatch "\.html?$">
68
+ Header set Cache-Control "no-cache"
69
+ </FilesMatch>
70
+ </IfModule>
71
+ # END astro-apache-headers
72
+ ```
73
+
74
+ `dist/_astro/.htaccess`:
75
+
76
+ ```apache
77
+ <IfModule mod_headers.c>
78
+ Header set Cache-Control "public, max-age=31536000, immutable"
79
+ </IfModule>
80
+ ```
81
+
82
+ The cache rule lives in its own `.htaccess` inside the assets folder. It therefore works whatever your `base` and `build.assets` settings are. The assets folder must be a subfolder of the build output: `.`, `..` or an absolute path stop the build before anything is written.
83
+
84
+ ## Your existing `.htaccess`
85
+
86
+ Put your own rules (redirects, `ErrorDocument`, `mod_expires`, compression…) in `public/.htaccess`. Astro copies it to `dist/`, then the integration:
87
+
88
+ - **replaces** the content between `# BEGIN astro-apache-headers` and `# END astro-apache-headers`, if you placed these two markers in your file (to choose where the block goes). They must be at the top level of the file, not inside a `<Files>`, `<If>`, `<IfModule>`… section, otherwise the headers would not apply to the whole site and the build stops;
89
+ - otherwise **appends** the block at the end of the file.
90
+
91
+ Everything outside the markers is left untouched. Running the build again gives the same file.
92
+
93
+ If your own rules also touch a header that the integration manages, the build stops and names the line, with its number in your `public/.htaccess`. This covers a hand-written `Content-Security-Policy` or `X-Frame-Options`, and also `Header unset`, `edit` or `append` on the generated CSP, with or without a final colon after the name: placed after the block, an `unset` removes the CSP in Apache. Remove that line or turn off the matching option.
94
+
95
+ `.htaccess` files in subfolders (copied from `public/blog/.htaccess`, for example) apply on top of the root one. The same rule holds there for the CSP, and every line is checked, markers included, since the integration does not rewrite these files. For the other managed headers, a per-folder override is reported as a warning.
96
+
97
+ To keep a CSP you write yourself, set `csp: false`: your lines are then left alone and the other headers are still generated.
98
+
99
+ ## Options
100
+
101
+ All options are optional. Use `false` to turn a header off.
102
+
103
+ ```js
104
+ apacheHeaders({
105
+ csp: {
106
+ directives: {
107
+ 'img-src': ["'self'", 'data:', 'https://images.example.com'],
108
+ 'connect-src': "'self' https://api.example.com",
109
+ 'upgrade-insecure-requests': false, // remove a default directive
110
+ },
111
+ hashScripts: true, // hash inline <script> elements (default)
112
+ hashStyles: false, // hash inline <style> elements (see "Styles")
113
+ algorithm: 'sha256', // or 'sha384', 'sha512'
114
+ reportOnly: false, // send Content-Security-Policy-Report-Only
115
+ allowUnsafeEval: false, // accept 'unsafe-eval' in strict mode
116
+ replaceDefaults: false, // start from an empty policy instead of the defaults
117
+ },
118
+ hsts: { maxAge: 31536000, includeSubDomains: false, preload: false },
119
+ frameOptions: 'DENY', // or 'SAMEORIGIN'
120
+ contentTypeOptions: true, // X-Content-Type-Options: nosniff
121
+ referrerPolicy: 'strict-origin-when-cross-origin',
122
+ permissionsPolicy: { camera: [], microphone: [], geolocation: [], payment: [], usb: [] },
123
+ crossOriginOpenerPolicy: 'same-origin',
124
+ removePoweredBy: true,
125
+ headers: { 'Cross-Origin-Resource-Policy': 'same-origin' }, // any other header (false = unset)
126
+ cache: { immutableAssets: true, html: 'no-cache' },
127
+ strict: true,
128
+ onGenerated(result) { /* result.policy, result.scriptHashes, result.issues… */ },
129
+ });
130
+ ```
131
+
132
+ ### Default policy
133
+
134
+ | Directive | Default value |
135
+ | --- | --- |
136
+ | `default-src` | `'self'` |
137
+ | `script-src` | `'self'` + hashes of inline scripts |
138
+ | `style-src` | `'self' 'unsafe-inline'` |
139
+ | `img-src` | `'self' data:` |
140
+ | `font-src`, `connect-src` | `'self'` |
141
+ | `object-src` | `'none'` |
142
+ | `base-uri`, `form-action` | `'self'` |
143
+ | `frame-ancestors` | `'none'` |
144
+ | `upgrade-insecure-requests` | (on) |
145
+
146
+ Hashes are added to `script-src-elem` instead if you define that directive. If you remove `script-src`, it is created from `default-src`.
147
+
148
+ ### Permissions-Policy
149
+
150
+ Give an object; each feature takes a list of allowed origins:
151
+
152
+ ```js
153
+ permissionsPolicy: { geolocation: ["'self'", 'https://maps.example.com'], camera: [], fullscreen: '*' }
154
+ // → geolocation=(self "https://maps.example.com"), camera=(), fullscreen=*
155
+ ```
156
+
157
+ You can also give a raw header string.
158
+
159
+ ## Strict checks
160
+
161
+ The integration checks the policy against the HTML it has to protect: every inline script, `<style>` element, `style="…"` attribute, event handler and external script or stylesheet found in the built pages. It reports the incompatibilities it knows how to detect (listed below); it cannot prove that a policy will never break anything, so still browse the site once with the developer tools open.
162
+
163
+ With `strict: true` (the default), the build stops if any of these checks fails, and nothing is written. With `strict: false`, they are reported as warnings and the files are written.
164
+
165
+ **Always fatal, even with `strict: false`** (writing would be unsafe or impossible): unusable options, an assets folder that is not a subfolder of the build output, broken markers, and a `.htaccess` to write that is a symbolic link or has several hard links.
166
+
167
+ **Policy syntax**
168
+
169
+ - Unknown directive names (catches typos such as `scrpit-src`).
170
+ - Invalid or missing values for directives that are not source lists: `require-trusted-types-for` (needs `'script'`), `report-to` (needs one endpoint name), `report-uri` (needs URL references that Node's URL parser accepts, absolute or relative such as `/csp-report`), `webrtc` (needs `'allow'` or `'block'`), `sandbox` flags, `trusted-types` names.
171
+ - An array item that contains a space (`['\'self\' data:']`): it would be written as several values.
172
+ - Keywords written without quotes: `self` instead of `'self'` is read as a host name.
173
+ - `'none'` combined with other sources (it is then ignored).
174
+ - Commas, semicolons, double quotes or control characters inside a source.
175
+
176
+ **Script safety**
177
+
178
+ - `'unsafe-inline'`, `'unsafe-eval'`, `*`, `http:`, `https:` or `data:` in `script-src`.
179
+ - No `script-src` and no `default-src` at all.
180
+
181
+ **What the browser would block**
182
+
183
+ - Each inline `<script>` must be allowed by the directive that applies to it (`script-src-elem`, then `script-src`, then `default-src`): by its hash (in any algorithm), its nonce, or `'unsafe-inline'` when no hash or nonce makes browsers ignore it. Inline speculation rules (`<script type="speculationrules">`) are also allowed by `'inline-speculation-rules'`. This is checked even with `hashScripts: false`, for hashes written by hand.
184
+ - Each `<style>` element likewise (`style-src-elem`, then `style-src`, then `default-src`).
185
+ - Each `style="…"` attribute (`style-src-attr`, then `style-src`, then `default-src`) and each event handler such as `onclick="…"` (`script-src-attr`, then `script-src`, then `default-src`): allowed by `'unsafe-inline'`, or by `'unsafe-hashes'` together with the hash of that exact value. Only real event handler attributes count (the list comes from Chromium, plus touch and SVG animation events): an attribute such as `once="…"` is not one.
186
+ - `javascript:` URLs.
187
+ - `sandbox` without `allow-scripts` while the site has scripts: no script would run.
188
+ - External scripts and stylesheets from a source the policy does not allow, for example an analytics script left out of `script-src`. Relative URLs are resolved from the address of each page (`docs/index.html` is served at `/docs/`), taking Astro's `base` into account. Paths are compared case-sensitively. With `'strict-dynamic'`, hosts and `'self'` are not enough for a script written in the HTML: the validator checks its nonce or its `integrity` hashes.
189
+ - A `<base href>` refused by `base-uri`: browsers ignore it, so URLs are then resolved from the page address.
190
+
191
+ **The `.htaccess` files**
192
+
193
+ - Outside the generated block, any `Header` directive on the generated CSP header (`set`, `unset`, `edit`, `append`…), in the root `.htaccess` or in a subfolder one, and a second policy. `Header echo` takes a regular expression and copies the matching headers sent by the client into the response: a pattern that can match a managed header is refused. Only a simple subset of the PCRE syntax is analysed (literals, `.`, `^`, `$`, `|`, groups, character classes, ranges between two single characters, `\d \w \s`, ordinary quantifiers); any other construct, such as POSIX classes like `[[:alpha:]]`, is reported as unverifiable, since its meaning could not be reproduced with certainty. Because the client chooses the case of the header names it sends, patterns are tested without case; a negated class containing letters (`[^x]`) would then match less than in Apache, so it is reported as unverifiable too. Header names are compared like Apache does: without case, and with or without a final colon (`Content-Security-Policy:`).
194
+ - In the root `.htaccess`, another managed header set outside the block. In a subfolder `.htaccess`, the same is only a warning (a per-folder override can be intended).
195
+ - Markers inside a section (`<Files>`, `<If>`, `<IfModule>`…): the headers would only apply to part of the site, or not at all.
196
+ - In subfolder `.htaccess` files, which the integration does not rewrite, markers have no special meaning: every line is checked.
197
+ - A `.htaccess` that is a symbolic link, and folders or pages that are symbolic links (they are not scanned).
198
+ - The CSP value read back from the file differs from the computed one.
199
+ - A line longer than 8,191 bytes. Apache answers every request with a 500 error ("Line too long") beyond that limit, which was measured on Apache 2.4.58.
200
+ - Invalid values for HSTS preload, Referrer-Policy and Cross-Origin-Opener-Policy.
201
+
202
+ Warnings, which never stop the build:
203
+
204
+ - Astro's own `security.csp` is enabled too (two policies would apply, and a resource must pass both).
205
+ - Report-only mode.
206
+ - `object-src` or `base-uri` missing.
207
+ - An empty source list (it blocks everything; `'none'` says so explicitly).
208
+ - Hashes or nonces next to `'unsafe-inline'` (browsers then ignore `'unsafe-inline'`).
209
+ - An external script allowed only by the hashes of its `integrity` attribute: CSP Level 3 allows it when *every* recognised hash of the attribute is in the policy, and Chromium does it, but other browsers may not. If one hash is missing, it is an error (Chromium blocks the script).
210
+ - An encoded character such as `%2F` in a path that browsers treat differently: blocked under the CSP Level 3 rule, allowed by Chromium.
211
+
212
+ **Known limit:** event handlers and `style` attributes are checked value by value, but whatever JavaScript inserts at run time is not visible to a build-time check.
213
+
214
+ ### Apache details handled for you
215
+
216
+ - `%` is written as `%%`: `mod_headers` reads `%` as a format specifier, and a single `%` (from a percent-encoded URL, for example) makes Apache answer every request with a 500 error.
217
+ - Values that contain double quotes, such as Permissions-Policy origins, are wrapped in single quotes.
218
+ - Security headers use `Header always`, so error pages (404, 403…) are protected too.
219
+ - `X-Powered-By` is removed from both of Apache's header tables, because PHP adds it to the "on success" table.
220
+
221
+ ## Styles
222
+
223
+ Astro may put inline `<style>` elements in pages, depending on `build.inlineStylesheets`. The default `style-src 'self' 'unsafe-inline'` allows them. To hash them instead:
224
+
225
+ ```js
226
+ apacheHeaders({
227
+ csp: { hashStyles: true, directives: { 'style-src': "'self'" } },
228
+ });
229
+ ```
230
+
231
+ Remove `'unsafe-inline'` from `style-src` when you do this: browsers ignore it as soon as a hash is present, so keeping both is misleading (the checks warn about it). `style="…"` attributes are not covered by these hashes. To allow a few known values, use `'style-src-attr': "'unsafe-hashes' 'sha256-…'"` with the hash of each exact value; to allow any, use `'style-src-attr': "'unsafe-inline'"`.
232
+
233
+ ## Post-processing the HTML after `astro build`
234
+
235
+ If another script changes the HTML after Astro (minification, renaming, comment removal), the hashes must be computed after it. Use the command line at the end of that script instead of the integration:
236
+
237
+ ```sh
238
+ astro build && node scripts/postbuild.mjs && astro-apache-headers dist --site https://example.com
239
+ ```
240
+
241
+ If the site is served under a path, add `--base /blog/` (by default, the path of `--site`). The CLI reads its options from `apache-headers.config.mjs` (default export) or `--config <file>`. `--check` computes and checks without writing. It exits with code 1 when a check fails.
242
+
243
+ The same function is available from JavaScript:
244
+
245
+ ```js
246
+ import { generateApacheHeaders } from 'astro-apache-headers';
247
+ await generateApacheHeaders({ outDir: 'dist', site: 'https://example.com', options: { /* … */ } });
248
+ ```
249
+
250
+ ## Things to know
251
+
252
+ - **One policy for the whole site.** It contains the hashes of all inline scripts of all pages. This is what makes `<ClientRouter />` navigations work, because the first page's policy stays in force when the next page's scripts run.
253
+ - **Static output only.** HTML rendered on demand cannot be hashed at build time. In strict mode, the build stops if the project uses `output: 'server'`.
254
+ - **The package does not generate nonces.** A nonce must change on every response, which a static file cannot do. Nonces already present in the HTML are recognised during validation, but for a static site, prefer hashes.
255
+ - **Many different inline scripts make a long line.** The policy holds one hash per *distinct* script content: the same script on 100 pages counts once, and a long script takes no more room than a short one. With SHA-256, each hash takes about 54 bytes, so around 140 distinct inline scripts fill a 8,191-byte line (SHA-384 and SHA-512 take about 74 and 98 bytes). The check stops the build before that happens. If you get close, move to files the scripts whose content changes from page to page, such as scripts that embed page-specific data.
256
+ - **`mod_headers` missing?** The block is wrapped in `<IfModule mod_headers.c>`, so the site keeps working, but no header is sent. Check once after deploying:
257
+ ```sh
258
+ curl -sI https://example.com/ | grep -i content-security-policy
259
+ ```
260
+ - **HSTS.** Only set `includeSubDomains` if every subdomain works over HTTPS. Only set `preload` if you mean it: leaving the browsers' preload list takes months.
261
+ - **Rolling out.** Start with `csp: { reportOnly: true }`, browse the site with the developer tools open, then remove `reportOnly`.
262
+
263
+ ## Development
264
+
265
+ ```sh
266
+ npm install
267
+ npm test # unit tests + builds of the fixture Astro site
268
+ npm run test:apache # same site served by a real Apache 2.4, checked with HTTP requests and Chromium,
269
+ # plus each validator verdict compared with what Chromium really blocks
270
+ npm run test:pack # npm pack, then install the .tgz in fresh Astro 5, 6 and 7 sites outside the repo, build, run the CLI
271
+ npm run test:pack -- --astro 5.0.9,7.4.14 # same, for chosen Astro versions
272
+ ```
273
+
274
+ The scripts run on Windows, macOS and Linux (no shell commands, no shell spawned). `npm pack` builds `dist/` by itself (`prepack`). For each major version, `test:pack` installs the newest Astro that supports your Node. The test site itself uses Astro 7.4, which needs Node 22.23.4 or later; with an older Node, the Astro tests stop with one message saying so.
275
+
276
+ `test:apache` needs Apache 2.4 (`apache2` or `httpd`; set `APACHE_BIN` and `APACHE_MODULES` to use a specific install). The browser tests also need a Chromium that `playwright-core` can launch (`CHROMIUM_PATH`). Without them, these tests are reported as skipped; set `AAH_REQUIRE_APACHE=1` and `AAH_REQUIRE_BROWSER=1` to make a missing Apache or Chromium fail the run instead. On Windows with Laragon, for example (adjust the version folder):
277
+
278
+ ```powershell
279
+ $env:APACHE_BIN = "C:\laragon\bin\apache\httpd-2.4.62-240904-win64-VS17\bin\httpd.exe"
280
+ $env:APACHE_MODULES = "C:\laragon\bin\apache\httpd-2.4.62-240904-win64-VS17\modules"
281
+ npm run test:apache
282
+ ```
283
+
284
+ These tests check that:
285
+
286
+ - every header arrives as computed, on pages, directory URLs, assets and 404 pages;
287
+ - every inline and bundled script runs with no CSP violation, including after `<ClientRouter />` navigations;
288
+ - a script injected after the build is blocked;
289
+ - an `unset` after the generated block really removes the CSP in Apache, and the build refuses it;
290
+ - the 8,191-byte line limit matches the real Apache.
291
+
292
+ ## License
293
+
294
+ [MIT](./LICENSE)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * astro-apache-headers [dir] [--config file] [--site url] [--assets name] [--check]
4
+ *
5
+ * Runs the same generation as the integration on an existing build folder.
6
+ * Useful when another script changes the HTML after `astro build`.
7
+ */
8
+ import { existsSync } from 'node:fs';
9
+ import { resolve } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ import { parseArgs } from 'node:util';
12
+ import { ApacheHeadersError, generateApacheHeaders } from './generate.js';
13
+ const HELP = `Usage: astro-apache-headers [dir] [options]
14
+
15
+ Generates dir/.htaccess (default dir: dist) with a Content-Security-Policy header
16
+ hashing the inline scripts of every HTML file, plus security and cache headers.
17
+
18
+ Options:
19
+ --config <file> ES module whose default export is the options object
20
+ (default: apache-headers.config.mjs if it exists)
21
+ --site <url> Public URL of the site (counts as 'self' for absolute URLs)
22
+ --base <path> Path the site is served under (Astro base; default: path of --site)
23
+ --assets <name> Hashed assets folder (default: _astro), "false" to skip
24
+ --check Compute and check only, write nothing
25
+ -h, --help Show this help
26
+ `;
27
+ async function main() {
28
+ const { values, positionals } = parseArgs({
29
+ allowPositionals: true,
30
+ options: {
31
+ config: { type: 'string' },
32
+ site: { type: 'string' },
33
+ base: { type: 'string' },
34
+ assets: { type: 'string' },
35
+ check: { type: 'boolean', default: false },
36
+ help: { type: 'boolean', short: 'h', default: false },
37
+ },
38
+ });
39
+ if (values.help) {
40
+ process.stdout.write(HELP);
41
+ return 0;
42
+ }
43
+ if (positionals.length > 1) {
44
+ process.stderr.write(HELP);
45
+ return 2;
46
+ }
47
+ const outDir = resolve(positionals[0] ?? 'dist');
48
+ let configPath = values.config ? resolve(values.config) : resolve('apache-headers.config.mjs');
49
+ let options = {};
50
+ if (values.config || existsSync(configPath)) {
51
+ if (!existsSync(configPath)) {
52
+ process.stderr.write(`Config file not found: ${configPath}\n`);
53
+ return 2;
54
+ }
55
+ const mod = (await import(pathToFileURL(configPath).href));
56
+ options = mod.default ?? {};
57
+ }
58
+ else {
59
+ configPath = '';
60
+ }
61
+ const logger = {
62
+ info: (m) => process.stdout.write(`astro-apache-headers: ${m}\n`),
63
+ warn: (m) => process.stderr.write(`⚠ ${m}\n`),
64
+ error: (m) => process.stderr.write(`✖ ${m}\n`),
65
+ };
66
+ try {
67
+ await generateApacheHeaders({
68
+ outDir,
69
+ options,
70
+ site: values.site,
71
+ base: values.base,
72
+ assetsDir: values.assets === 'false' ? false : (values.assets ?? '_astro'),
73
+ write: !values.check,
74
+ logger,
75
+ });
76
+ return 0;
77
+ }
78
+ catch (e) {
79
+ if (e instanceof ApacheHeadersError) {
80
+ for (const i of e.issues)
81
+ logger.error(`[${i.code}] ${i.message}`);
82
+ process.stderr.write(`astro-apache-headers: ${e.issues.length} problem(s), nothing written.\n`);
83
+ return 1;
84
+ }
85
+ process.stderr.write(`astro-apache-headers: ${e.message}\n`);
86
+ return 1;
87
+ }
88
+ }
89
+ main().then((code) => { process.exitCode = code; });
package/dist/csp.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Building and checking the Content-Security-Policy.
3
+ */
4
+ import type { ResolvedCspOptions } from './options.js';
5
+ import { type HtmlScan, type Item } from './html.js';
6
+ export type Directives = Map<string, string[] | true>;
7
+ export interface Issue {
8
+ level: 'error' | 'warning';
9
+ code: string;
10
+ message: string;
11
+ }
12
+ /** Directives defined by CSP Level 3 and related specs (used to catch typos). */
13
+ export declare const KNOWN_DIRECTIVES: Set<string>;
14
+ /** Where inline script/style hashes must go: the `-elem` directive if present, else the base one. */
15
+ export declare function hashTarget(directives: Directives, kind: 'script' | 'style'): string;
16
+ /**
17
+ * Effective source list, following the CSP fallback chain:
18
+ * elements: `<kind>-src-elem` → `<kind>-src` → `default-src`;
19
+ * attributes (`style="…"`, `onclick="…"`): `<kind>-src-attr` → `<kind>-src` → `default-src`.
20
+ */
21
+ export declare function effectiveSources(directives: Directives, kind: 'script' | 'style', target?: 'elem' | 'attr'): {
22
+ name: string;
23
+ sources: string[];
24
+ } | undefined;
25
+ /**
26
+ * Adds hashes to the directives. When the target directive does not exist, it is created
27
+ * from `default-src` so that the fallback behaviour is preserved.
28
+ */
29
+ export declare function addHashes(directives: Directives, kind: 'script' | 'style', hashes: Iterable<string>): void;
30
+ export declare function serialisePolicy(directives: Directives): string;
31
+ /** Parses a serialised policy back into directives (first occurrence wins, like browsers). */
32
+ export declare function parsePolicy(policy: string): Directives;
33
+ /** Builds the policy from resolved options and the HTML scan. */
34
+ export declare function buildPolicy(csp: ResolvedCspOptions, scan: HtmlScan): {
35
+ directives: Directives;
36
+ policy: string;
37
+ };
38
+ /** Is an inline <script>/<style> element allowed? (nonce, hash in any algorithm, or effective 'unsafe-inline') */
39
+ export declare function inlineElementAllowed(item: Item, sources: string[], kind: 'script' | 'style'): boolean;
40
+ /** Is an attribute (style="…", onclick="…") allowed? Hashes count only with 'unsafe-hashes'; nonces never. */
41
+ export declare function attributeAllowed(value: string, sources: string[], kind: 'script' | 'style'): boolean;
42
+ /**
43
+ * Path matching. `spec` follows CSP3 "path-part matching": split on "/" first, then
44
+ * percent-decode each segment, so "/a%2Fb.js" (one segment) does not match "/a/b.js".
45
+ * `decoded` decodes the whole path first, which is what Chromium does (checked with
46
+ * Chromium 158): there "/a%2Fb.js" matches "/a/b.js".
47
+ */
48
+ export type PathMode = 'spec' | 'decoded';
49
+ export declare function pathMatches(sourcePath: string, urlPath: string, mode?: PathMode): boolean;
50
+ /**
51
+ * Does `url` match the source list, for a document served from `self`?
52
+ * Schemes and hosts are compared case-insensitively, paths case-sensitively (as in CSP Level 3).
53
+ */
54
+ export declare function urlMatchesSources(url: URL, sources: string[], self: URL | undefined, mode?: PathMode): boolean;
55
+ /**
56
+ * URL a built file is served at: `docs/index.html` → `<root>docs/` (Apache's DirectoryIndex
57
+ * and DirectorySlash), `docs/intro.html` → `<root>docs/intro.html`.
58
+ */
59
+ export declare function pageUrl(file: string, root: URL): URL;
60
+ export interface CheckContext {
61
+ csp: ResolvedCspOptions;
62
+ directives: Directives;
63
+ policy: string;
64
+ scan: HtmlScan;
65
+ /** Site origin (Astro `site`), used to decide what `'self'` covers. */
66
+ site?: URL | undefined;
67
+ /** Path the site is served under (Astro `base`). Default `/`. */
68
+ base?: string | undefined;
69
+ }
70
+ /** Checks the produced policy against itself and against the HTML it must protect. */
71
+ export declare function checkPolicy(ctx: CheckContext): Issue[];