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,298 @@
1
+ /**
2
+ * Framework-independent entry point: scans a build output folder and writes
3
+ * the .htaccess file(s). Used by the Astro integration and the CLI.
4
+ */
5
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
6
+ import { readdir, readFile, writeFile } from 'node:fs/promises';
7
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
8
+ import { buildPolicy, checkPolicy } from './csp.js';
9
+ import { scanDirectory } from './html.js';
10
+ import { checkHtaccess, detectEol, HtaccessError, mergeBlock, renderAssetsBlock, renderRootBlock, } from './htaccess.js';
11
+ import { resolveOptions } from './options.js';
12
+ const silentLogger = { info() { }, warn() { }, error() { } };
13
+ export const VERSION = (() => {
14
+ try {
15
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
16
+ }
17
+ catch {
18
+ return '0.0.0';
19
+ }
20
+ })();
21
+ /** Thrown in strict mode when at least one check fails. Nothing has been written. */
22
+ export class ApacheHeadersError extends Error {
23
+ issues;
24
+ name = 'ApacheHeadersError';
25
+ constructor(issues) {
26
+ super(`astro-apache-headers: ${issues.length} problem(s) found, .htaccess not written:\n` +
27
+ issues.map((i) => `✖ [${i.code}] ${i.message}`).join('\n'));
28
+ this.issues = issues;
29
+ }
30
+ }
31
+ const REFERRER_POLICIES = new Set([
32
+ 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin',
33
+ 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url',
34
+ ]);
35
+ const COOP_VALUES = new Set(['same-origin', 'same-origin-allow-popups', 'unsafe-none', 'noopener-allow-popups']);
36
+ function toUrl(site) {
37
+ if (!site)
38
+ return undefined;
39
+ try {
40
+ return new URL(String(site));
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ /** Lists the headers to emit, and reports invalid values. */
47
+ export function headerLines(o, policy, issues) {
48
+ const err = (code, message) => issues.push({ level: 'error', code, message });
49
+ const lines = [];
50
+ if (o.csp && policy !== undefined) {
51
+ lines.push({ name: o.csp.reportOnly ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy', value: policy, always: true });
52
+ }
53
+ if (o.hsts) {
54
+ const { maxAge, includeSubDomains, preload } = o.hsts;
55
+ if (preload && (!includeSubDomains || maxAge < 31536000)) {
56
+ err('hsts-preload', 'hsts.preload requires includeSubDomains: true and maxAge >= 31536000 (hstspreload.org requirements).');
57
+ }
58
+ lines.push({
59
+ name: 'Strict-Transport-Security',
60
+ value: [`max-age=${maxAge}`, includeSubDomains && 'includeSubDomains', preload && 'preload'].filter(Boolean).join('; '),
61
+ always: true,
62
+ });
63
+ }
64
+ if (o.frameOptions)
65
+ lines.push({ name: 'X-Frame-Options', value: o.frameOptions, always: true });
66
+ if (o.contentTypeOptions)
67
+ lines.push({ name: 'X-Content-Type-Options', value: 'nosniff', always: true });
68
+ if (o.referrerPolicy !== false) {
69
+ const bad = o.referrerPolicy.split(',').map((s) => s.trim()).filter((s) => !REFERRER_POLICIES.has(s));
70
+ if (bad.length)
71
+ err('referrer-policy', `referrerPolicy: unknown value(s) ${bad.map((b) => JSON.stringify(b)).join(', ')}. Valid: ${[...REFERRER_POLICIES].join(', ')}.`);
72
+ lines.push({ name: 'Referrer-Policy', value: o.referrerPolicy, always: true });
73
+ }
74
+ if (o.permissionsPolicy !== false && o.permissionsPolicy !== '') {
75
+ lines.push({ name: 'Permissions-Policy', value: o.permissionsPolicy, always: true });
76
+ }
77
+ if (o.crossOriginOpenerPolicy !== false) {
78
+ const token = o.crossOriginOpenerPolicy.split(';')[0].trim();
79
+ if (!COOP_VALUES.has(token))
80
+ err('coop', `crossOriginOpenerPolicy: unknown value ${JSON.stringify(token)}. Valid: ${[...COOP_VALUES].join(', ')}.`);
81
+ lines.push({ name: 'Cross-Origin-Opener-Policy', value: o.crossOriginOpenerPolicy, always: true });
82
+ }
83
+ for (const [name, value] of o.headers) {
84
+ const dup = lines.find((l) => l.name.toLowerCase() === name.toLowerCase());
85
+ if (dup) {
86
+ err('header-duplicate', `headers['${name}'] duplicates a header already produced by another option; set that option instead.`);
87
+ continue;
88
+ }
89
+ lines.push({ name, value, always: true });
90
+ }
91
+ return lines;
92
+ }
93
+ async function readIfExists(path) {
94
+ return existsSync(path) ? readFile(path, 'utf8') : undefined;
95
+ }
96
+ const assetsIssue = (message) => new ApacheHeadersError([{ level: 'error', code: 'assets-dir', message }]);
97
+ /**
98
+ * Resolves the hashed-assets folder and makes sure it is a real subfolder of outDir:
99
+ * not outDir itself (its .htaccess would replace the root one), not outside it.
100
+ */
101
+ export function resolveAssetsDir(outDir, assetsDir) {
102
+ const shown = JSON.stringify(assetsDir);
103
+ if (typeof assetsDir !== 'string' || assetsDir.trim() === '')
104
+ throw assetsIssue(`the assets folder must be a non-empty relative path (got ${shown}).`);
105
+ if (isAbsolute(assetsDir) || /^[a-zA-Z]:/.test(assetsDir) || /^[\\/]/.test(assetsDir)) {
106
+ throw assetsIssue(`the assets folder must be relative to the build output directory (got ${shown}).`);
107
+ }
108
+ const abs = resolve(outDir, assetsDir);
109
+ const rel = relative(resolve(outDir), abs);
110
+ if (rel === '')
111
+ throw assetsIssue(`the assets folder ${shown} is the build output directory itself: its .htaccess would replace the main one.`);
112
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
113
+ throw assetsIssue(`the assets folder ${shown} is outside the build output directory.`);
114
+ if (existsSync(abs)) {
115
+ const realOut = realpathSync(outDir);
116
+ const realRel = relative(realOut, realpathSync(abs));
117
+ if (realRel === '' || realRel === '..' || realRel.startsWith(`..${sep}`) || isAbsolute(realRel)) {
118
+ throw assetsIssue(`the assets folder ${shown} resolves (through a link) outside the build output directory.`);
119
+ }
120
+ }
121
+ return abs;
122
+ }
123
+ /** Every .htaccess below outDir (root excluded), and every symbolic link met on the way. */
124
+ async function walkOutput(dir, root = dir, acc = { htaccess: [], links: [] }) {
125
+ for (const e of await readdir(dir, { withFileTypes: true })) {
126
+ const p = join(dir, e.name);
127
+ if (e.isSymbolicLink()) {
128
+ let isDir = false;
129
+ try {
130
+ isDir = statSync(p).isDirectory();
131
+ }
132
+ catch { /* broken link */ }
133
+ acc.links.push({ path: p, isDir });
134
+ }
135
+ else if (e.isDirectory())
136
+ await walkOutput(p, root, acc);
137
+ else if (e.isFile() && e.name === '.htaccess' && dir !== root)
138
+ acc.htaccess.push(p);
139
+ }
140
+ acc.htaccess.sort();
141
+ return acc;
142
+ }
143
+ /**
144
+ * A file the generator writes must be a plain file of its own: writing through a symbolic
145
+ * link, or into a file with another hard link, would change a file elsewhere.
146
+ */
147
+ function assertWritableTarget(path, label) {
148
+ if (!existsSync(path) && !isDanglingLink(path))
149
+ return;
150
+ const st = lstatSync(path);
151
+ if (st.isSymbolicLink())
152
+ throw new ApacheHeadersError([{ level: 'error', code: 'htaccess-link', message: `${label} is a symbolic link: writing it would change another file. Replace it with a regular file.` }]);
153
+ if (st.nlink > 1)
154
+ throw new ApacheHeadersError([{ level: 'error', code: 'htaccess-link', message: `${label} has ${st.nlink} hard links: writing it would change the other copies too (is it the same file as another .htaccess?). Replace it with a regular file.` }]);
155
+ }
156
+ function isDanglingLink(path) {
157
+ try {
158
+ return lstatSync(path).isSymbolicLink();
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ }
164
+ function resolveBase(base, site) {
165
+ let b = base ?? site?.pathname ?? '/';
166
+ if (!b.startsWith('/'))
167
+ b = `/${b}`;
168
+ return b.endsWith('/') ? b : `${b}/`;
169
+ }
170
+ export async function generateApacheHeaders(input) {
171
+ const logger = input.logger ?? silentLogger;
172
+ const o = resolveOptions(input.options);
173
+ const outDir = input.outDir;
174
+ if (!existsSync(outDir) || !statSync(outDir).isDirectory()) {
175
+ throw new Error(`astro-apache-headers: build output directory not found: ${outDir}`);
176
+ }
177
+ const site = toUrl(input.site);
178
+ const base = resolveBase(input.base, site);
179
+ const issues = [];
180
+ // 0. Where the assets .htaccess would go: validated before anything is read or written.
181
+ const assetsDirOption = input.assetsDir === undefined ? '_astro' : input.assetsDir;
182
+ const assetsPath = o.cache.immutableAssets && assetsDirOption !== false ? resolveAssetsDir(outDir, assetsDirOption) : undefined;
183
+ // 1. Scan HTML and build the policy.
184
+ const scan = await scanDirectory(outDir, o.csp ? o.csp.algorithm : 'sha256');
185
+ if (scan.files.length === 0)
186
+ issues.push({ level: 'warning', code: 'no-html', message: `no .html file found in ${outDir}.` });
187
+ let policy;
188
+ if (o.csp) {
189
+ const built = buildPolicy(o.csp, scan);
190
+ policy = built.policy;
191
+ issues.push(...checkPolicy({ csp: o.csp, directives: built.directives, policy, scan, site, base }));
192
+ }
193
+ // 2. Root .htaccess.
194
+ const headers = headerLines(o, policy, issues);
195
+ const rootPath = join(outDir, '.htaccess');
196
+ assertWritableTarget(rootPath, '.htaccess');
197
+ const existingRoot = await readIfExists(rootPath);
198
+ const eol = detectEol(existingRoot);
199
+ let root;
200
+ try {
201
+ const block = renderRootBlock({ headers, removePoweredBy: o.removePoweredBy, htmlCacheControl: o.cache.html, version: VERSION }, eol);
202
+ root = { path: rootPath, ...mergeBlock(existingRoot, block) };
203
+ }
204
+ catch (e) {
205
+ if (e instanceof HtaccessError)
206
+ throw new ApacheHeadersError([{ level: 'error', code: 'htaccess', message: e.message }]);
207
+ throw e;
208
+ }
209
+ const managed = [...headers];
210
+ if (o.removePoweredBy)
211
+ managed.push({ name: 'X-Powered-By', value: false, always: true });
212
+ if (o.cache.html !== false)
213
+ managed.push({ name: 'Cache-Control', value: o.cache.html, always: false });
214
+ const cspHeader = headers.find((h) => /^content-security-policy/i.test(h.name))?.name;
215
+ // Generated block on the merged file; the user's own lines on the file they wrote (same line numbers).
216
+ issues.push(...checkHtaccess(root.content, { cspHeader, policy, managed, scope: 'block' }));
217
+ if (existingRoot !== undefined)
218
+ issues.push(...checkHtaccess(existingRoot, { cspHeader, managed, scope: 'outside' }));
219
+ // 3. Hashed assets folder.
220
+ let assets;
221
+ const assetsDir = assetsDirOption === false ? '' : relative(outDir, assetsPath ?? outDir).split(sep).join('/');
222
+ if (assetsPath) {
223
+ const dir = assetsPath;
224
+ if (existsSync(dir) && statSync(dir).isDirectory()) {
225
+ const p = join(dir, '.htaccess');
226
+ assertWritableTarget(p, `${assetsDir}/.htaccess`);
227
+ const existing = await readIfExists(p);
228
+ try {
229
+ assets = { path: p, ...mergeBlock(existing, renderAssetsBlock(VERSION, detectEol(existing))) };
230
+ }
231
+ catch (e) {
232
+ if (e instanceof HtaccessError)
233
+ throw new ApacheHeadersError([{ level: 'error', code: 'htaccess', message: `${assetsDir}/.htaccess: ${e.message}` }]);
234
+ throw e;
235
+ }
236
+ const assetsCheck = { cspHeader, managed: [{ name: 'Cache-Control', value: '', always: false }], requireBlock: false, label: `${assetsDir}/.htaccess` };
237
+ issues.push(...checkHtaccess(assets.content, { ...assetsCheck, scope: 'block' }));
238
+ if (existing !== undefined)
239
+ issues.push(...checkHtaccess(existing, { ...assetsCheck, scope: 'outside' }));
240
+ }
241
+ else {
242
+ logger.info(`no ${assetsDir}/ folder in the build output: no immutable caching rule needed.`);
243
+ }
244
+ }
245
+ // 4. Other .htaccess files copied from public/ into subfolders: they apply on top of the root one.
246
+ // The generator does not rewrite them, so markers there mean nothing: every line is checked.
247
+ const walked = await walkOutput(outDir);
248
+ for (const link of walked.links) {
249
+ const label = relative(outDir, link.path).split(sep).join('/');
250
+ if (link.path.endsWith(`${sep}.htaccess`)) {
251
+ issues.push({ level: 'error', code: 'htaccess-link', message: `${label} is a symbolic link: its content cannot be verified. Replace it with a regular file.` });
252
+ }
253
+ else if (link.isDir) {
254
+ issues.push({ level: 'error', code: 'linked-folder', message: `${label} is a symbolic link to a folder: its pages and .htaccess files are not scanned, so their scripts are not hashed and their headers not verified. Copy the files instead.` });
255
+ }
256
+ else if (/\.html?$/i.test(link.path)) {
257
+ issues.push({ level: 'error', code: 'linked-file', message: `${label} is a symbolic link: this page is not scanned, so its inline scripts are not hashed. Copy the file instead.` });
258
+ }
259
+ }
260
+ for (const p of walked.htaccess) {
261
+ if (assets && p === assets.path) {
262
+ // already checked above for Cache-Control; check the other managed headers as warnings
263
+ issues.push(...checkHtaccess(await readFile(p, 'utf8'), { managed, requireBlock: false, conflictLevel: 'warning', label: `${assetsDir}/.htaccess`, scope: 'outside' }));
264
+ continue;
265
+ }
266
+ const label = relative(outDir, p).split(sep).join('/');
267
+ issues.push(...checkHtaccess(await readFile(p, 'utf8'), { cspHeader, managed, requireBlock: false, conflictLevel: 'warning', label, trustMarkers: false }));
268
+ }
269
+ // 5. Report, then write (or stop).
270
+ const errors = issues.filter((i) => i.level === 'error');
271
+ if (o.strict && errors.length > 0)
272
+ throw new ApacheHeadersError(errors);
273
+ for (const i of issues)
274
+ logger.warn(`[${i.code}] ${i.message}`);
275
+ const write = input.write ?? true;
276
+ if (write) {
277
+ await writeFile(root.path, root.content);
278
+ if (assets)
279
+ await writeFile(assets.path, assets.content);
280
+ }
281
+ const hashes = [...scan.scriptHashes.keys()];
282
+ logger.info(`${write ? 'wrote' : 'computed'} .htaccess (${root.mode})` +
283
+ (assets ? ` and ${assetsDir}/.htaccess` : '') +
284
+ ` — ${scan.files.length} page(s)` +
285
+ (o.csp ? `, ${o.csp.hashScripts ? hashes.length : 0} inline script hash(es) in the CSP${o.csp.reportOnly ? ' (report-only)' : ''}` : ', CSP disabled') +
286
+ '.');
287
+ return {
288
+ ...(cspHeader ? { cspHeader } : {}),
289
+ ...(policy !== undefined ? { policy } : {}),
290
+ scriptHashes: hashes,
291
+ styleHashes: [...scan.styleHashes.keys()],
292
+ pages: scan.files.length,
293
+ htaccess: root,
294
+ ...(assets ? { assetsHtaccess: assets } : {}),
295
+ issues,
296
+ written: write,
297
+ };
298
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Rendering the generated block, merging it into an existing .htaccess,
3
+ * and reading the result back the way Apache does.
4
+ */
5
+ import type { Issue } from './csp.js';
6
+ export declare const BEGIN_MARKER = "# BEGIN astro-apache-headers";
7
+ export declare const END_MARKER = "# END astro-apache-headers";
8
+ /**
9
+ * Apache reads configuration lines into a buffer of MAX_STRING_LEN (8192) bytes,
10
+ * terminating NUL included: 8191 bytes pass, 8192 make every request of the folder
11
+ * fail with "500 — Line too long" (checked against Apache 2.4.58).
12
+ */
13
+ export declare const APACHE_MAX_LINE_BYTES = 8191;
14
+ export declare class HtaccessError extends Error {
15
+ name: string;
16
+ }
17
+ /**
18
+ * Quotes a header value as an Apache directive argument, for mod_headers:
19
+ * `%` is doubled (mod_headers would read `%x` as a format specifier) and the value
20
+ * is wrapped in double quotes, or single quotes when it contains double quotes.
21
+ */
22
+ export declare function quoteHeaderValue(value: string): string;
23
+ export interface HeaderLine {
24
+ name: string;
25
+ value: string | false;
26
+ /** `always` puts the header on every response, error pages included. */
27
+ always: boolean;
28
+ }
29
+ export interface RenderInput {
30
+ headers: HeaderLine[];
31
+ /** Header name used for the CSP (`Content-Security-Policy` or `-Report-Only`), if any. */
32
+ removePoweredBy: boolean;
33
+ htmlCacheControl: string | false;
34
+ version: string;
35
+ }
36
+ export declare function renderRootBlock(input: RenderInput, eol?: string): string;
37
+ export declare function renderAssetsBlock(version: string, eol?: string): string;
38
+ export declare function detectEol(text: string | undefined): string;
39
+ /**
40
+ * Inserts the block into an existing .htaccess:
41
+ * - between existing markers if present (exactly one pair, in order);
42
+ * - otherwise appended at the end (later `Header set` directives win in Apache).
43
+ */
44
+ export declare function mergeBlock(existing: string | undefined, block: string): {
45
+ content: string;
46
+ mode: 'created' | 'replaced' | 'appended';
47
+ };
48
+ /** Splits a directive line into arguments like Apache's ap_getword_conf. */
49
+ export declare function splitApacheArgs(line: string): string[];
50
+ export interface HeaderDirective {
51
+ lineNumber: number;
52
+ inBlock: boolean;
53
+ action: string;
54
+ name: string;
55
+ /** Value with mod_headers `%%` unescaped. */
56
+ value: string | undefined;
57
+ rawLength: number;
58
+ }
59
+ /** Header name as Apache compares it: case-insensitive, optional trailing colon ("Name:"). */
60
+ export declare function normaliseHeaderName(name: string): string;
61
+ export interface ReadResult {
62
+ directives: HeaderDirective[];
63
+ longestLine: {
64
+ lineNumber: number;
65
+ bytes: number;
66
+ };
67
+ /** Where the generated block starts, and the sections (<Files>, <If>…) it is nested in. */
68
+ block?: {
69
+ lineNumber: number;
70
+ enclosing: string[];
71
+ };
72
+ }
73
+ /**
74
+ * Lists the active (non-comment) mod_headers `Header` directives of a .htaccess.
75
+ * With `trustMarkers: false` (files the generator does not rewrite), lines between
76
+ * the markers are treated like any other line.
77
+ */
78
+ export declare function readHeaderDirectives(content: string, opts?: {
79
+ trustMarkers?: boolean;
80
+ }): ReadResult;
81
+ export interface HtaccessCheck {
82
+ /**
83
+ * Name of the CSP header generated by the package (`Content-Security-Policy` or
84
+ * `-Report-Only`), or undefined when `csp: false` (then CSP lines are the user's business).
85
+ */
86
+ cspHeader?: string | undefined;
87
+ /** Expected policy value, checked in the generated block of the root file. */
88
+ policy?: string | undefined;
89
+ /** Headers set by the package: touching them elsewhere is a conflict. */
90
+ managed: HeaderLine[];
91
+ /** The root .htaccess must contain the generated CSP directive. Default: true. */
92
+ requireBlock?: boolean;
93
+ /** Severity of a conflict on a managed header other than the CSP. Default: 'error'. */
94
+ conflictLevel?: 'error' | 'warning';
95
+ /** Shown in messages, e.g. `.htaccess` or `blog/.htaccess`. */
96
+ label?: string;
97
+ /**
98
+ * What to check: `block` = the generated block and line lengths (on the merged file);
99
+ * `outside` = the user's own lines (on the file as written by the user, so that line
100
+ * numbers match it); `all` = both. Default: `all`.
101
+ */
102
+ scope?: 'all' | 'block' | 'outside';
103
+ /**
104
+ * Whether lines between the markers belong to the package (true for files it rewrites).
105
+ * For other .htaccess files (subfolders), set false: every line is checked. Default: true.
106
+ */
107
+ trustMarkers?: boolean;
108
+ }
109
+ /**
110
+ * Does a PCRE pattern use only constructs that mean the same thing in JavaScript?
111
+ * A whitelist: literals, escaped punctuation, `.`, `^`, `$`, `|`, groups `( )` and `(?: )`,
112
+ * classes `[...]` with ranges, `\d \w \s` (and upper-case), `\b \B` outside classes,
113
+ * greedy or lazy quantifiers `* + ? {n} {n,} {n,m}`. Everything else (POSIX classes,
114
+ * possessive quantifiers, \Q…\E, \x{…}, \p{…}, back-references, other (?…) groups,
115
+ * verbs…) is refused, because JavaScript may compile it with a different meaning.
116
+ */
117
+ export declare function isPortablePattern(p: string): boolean;
118
+ /**
119
+ * `Header echo <regex>` copies every REQUEST header whose name matches into the response.
120
+ * The name is chosen by the client, in any case, so the pattern is tested without case
121
+ * (a safe over-approximation). Patterns outside the portable subset are reported as
122
+ * unverifiable (returns undefined).
123
+ */
124
+ export declare function echoMatcher(pattern: string): ((headerName: string) => boolean) | undefined;
125
+ /**
126
+ * Checks a .htaccess after merging:
127
+ * - nothing outside the generated block may touch the managed CSP header (set, unset, edit…);
128
+ * - no second policy outside the block;
129
+ * - the root file contains exactly one CSP directive, equal to the computed policy;
130
+ * - no conflicting directive for the other managed headers;
131
+ * - no line too long for Apache.
132
+ */
133
+ export declare function checkHtaccess(content: string, expected: HtaccessCheck): Issue[];