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,15 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import { type GenerateResult } from './generate.js';
3
+ import { type ApacheHeadersOptions } from './options.js';
4
+ export type IntegrationOptions = ApacheHeadersOptions & {
5
+ /** Called after a successful generation, e.g. to log or archive the policy. */
6
+ onGenerated?: (result: GenerateResult) => void | Promise<void>;
7
+ };
8
+ export default function apacheHeaders(options?: IntegrationOptions): AstroIntegration;
9
+ export { apacheHeaders };
10
+ export { generateApacheHeaders, ApacheHeadersError, VERSION } from './generate.js';
11
+ export type { GenerateInput, GenerateResult, Logger, WrittenFile } from './generate.js';
12
+ export type { ApacheHeadersOptions, CspOptions, CspDirectiveValue, HstsOptions, CacheOptions, PermissionsPolicy, HashAlgorithm, } from './options.js';
13
+ export { DEFAULT_CSP_DIRECTIVES, DEFAULT_PERMISSIONS_POLICY, OptionsError } from './options.js';
14
+ export type { Issue } from './csp.js';
15
+ export { BEGIN_MARKER, END_MARKER } from './htaccess.js';
package/dist/index.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * astro-apache-headers — Astro integration.
3
+ *
4
+ * import apacheHeaders from 'astro-apache-headers';
5
+ * export default defineConfig({ integrations: [apacheHeaders()] });
6
+ */
7
+ import { fileURLToPath } from 'node:url';
8
+ import { ApacheHeadersError, generateApacheHeaders } from './generate.js';
9
+ import { resolveOptions } from './options.js';
10
+ export default function apacheHeaders(options = {}) {
11
+ const { onGenerated, ...headerOptions } = options;
12
+ // Validate options as soon as the config is loaded, not after a full build.
13
+ const resolved = resolveOptions(headerOptions);
14
+ let config;
15
+ let buildOutput = 'static';
16
+ return {
17
+ name: 'astro-apache-headers',
18
+ hooks: {
19
+ 'astro:config:done': ({ config: c, logger, ...rest }) => {
20
+ config = c;
21
+ const bo = rest.buildOutput;
22
+ if (bo)
23
+ buildOutput = bo;
24
+ const security = c.security;
25
+ if (resolved.csp && security?.csp) {
26
+ logger.warn("Astro's security.csp is enabled too: pages will carry a <meta> CSP in addition to the HTTP header, and the browser enforces both. " +
27
+ 'Keep only one (recommended: remove security.csp, the header can also protect against framing).');
28
+ }
29
+ },
30
+ 'astro:build:done': async ({ dir, logger }) => {
31
+ if (buildOutput === 'server') {
32
+ const msg = 'this project renders pages on demand (output: "server" or server islands/routes). Only prerendered HTML can be hashed, ' +
33
+ 'so inline scripts of on-demand pages would be blocked. astro-apache-headers targets fully static sites.';
34
+ if (resolved.strict)
35
+ throw new Error(`astro-apache-headers: ${msg}`);
36
+ logger.warn(`${msg} Skipping.`);
37
+ return;
38
+ }
39
+ const assetsPrefix = config?.build.assetsPrefix;
40
+ try {
41
+ const result = await generateApacheHeaders({
42
+ outDir: fileURLToPath(dir),
43
+ options: headerOptions,
44
+ site: config?.site,
45
+ base: config?.base,
46
+ assetsDir: assetsPrefix ? false : (config?.build.assets ?? '_astro'),
47
+ logger,
48
+ });
49
+ if (assetsPrefix)
50
+ logger.info('build.assetsPrefix is set: hashed assets are served from elsewhere, no immutable caching rule written.');
51
+ await onGenerated?.(result);
52
+ }
53
+ catch (e) {
54
+ if (e instanceof ApacheHeadersError) {
55
+ for (const i of e.issues)
56
+ logger.error(`[${i.code}] ${i.message}`);
57
+ throw new Error(`astro-apache-headers: ${e.issues.length} problem(s) found, build stopped (strict mode). See the messages above.`);
58
+ }
59
+ throw e;
60
+ }
61
+ },
62
+ },
63
+ };
64
+ }
65
+ export { apacheHeaders };
66
+ export { generateApacheHeaders, ApacheHeadersError, VERSION } from './generate.js';
67
+ export { DEFAULT_CSP_DIRECTIVES, DEFAULT_PERMISSIONS_POLICY, OptionsError } from './options.js';
68
+ export { BEGIN_MARKER, END_MARKER } from './htaccess.js';
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Public options of astro-apache-headers and their resolution against defaults.
3
+ *
4
+ * Every security header can be turned off with `false`. Defaults are a strict but
5
+ * practical baseline for a static Astro site (no third-party scripts).
6
+ */
7
+ export type HashAlgorithm = 'sha256' | 'sha384' | 'sha512';
8
+ /**
9
+ * A CSP directive value:
10
+ * - a string (`"'self' data:"`) or an array of sources (`["'self'", 'data:']`)
11
+ * - `true` for directives without a value (`upgrade-insecure-requests`)
12
+ * - `false` to remove a default directive
13
+ */
14
+ export type CspDirectiveValue = string | string[] | boolean;
15
+ export interface CspOptions {
16
+ /**
17
+ * Directives merged over the defaults. Keys are directive names
18
+ * (`'script-src'`, `'img-src'`…). Use `false` to drop a default directive.
19
+ */
20
+ directives?: Record<string, CspDirectiveValue>;
21
+ /**
22
+ * Replace the default directives entirely instead of merging. Default: `false`.
23
+ */
24
+ replaceDefaults?: boolean;
25
+ /** Hash inline `<script>` elements and add the hashes to `script-src`. Default: `true`. */
26
+ hashScripts?: boolean;
27
+ /**
28
+ * Hash inline `<style>` elements and add the hashes to `style-src`.
29
+ * Default: `false` (the default `style-src` allows `'unsafe-inline'`, which hashes would disable).
30
+ */
31
+ hashStyles?: boolean;
32
+ /** Hash algorithm. Default: `'sha256'`. */
33
+ algorithm?: HashAlgorithm;
34
+ /** Send `Content-Security-Policy-Report-Only` instead of an enforced policy. Default: `false`. */
35
+ reportOnly?: boolean;
36
+ /**
37
+ * Allow `'unsafe-eval'` in `script-src` without failing strict mode
38
+ * (some libraries need it). Default: `false`.
39
+ */
40
+ allowUnsafeEval?: boolean;
41
+ }
42
+ export interface HstsOptions {
43
+ /** Seconds. Default: `31536000` (1 year). */
44
+ maxAge?: number;
45
+ /** Default: `false` — only enable if every subdomain is served over HTTPS. */
46
+ includeSubDomains?: boolean;
47
+ /** Default: `false`. Requires `includeSubDomains` and `maxAge >= 31536000`. */
48
+ preload?: boolean;
49
+ }
50
+ export interface CacheOptions {
51
+ /**
52
+ * `Cache-Control: public, max-age=31536000, immutable` for the hashed assets
53
+ * folder (`build.assets`, `_astro` by default). Default: `true`.
54
+ */
55
+ immutableAssets?: boolean;
56
+ /** Cache-Control value for `.html` files, or `false` to leave it alone. Default: `'no-cache'`. */
57
+ html?: string | false;
58
+ }
59
+ export type PermissionsPolicy = Record<string, string[] | string>;
60
+ export interface ApacheHeadersOptions {
61
+ /** Content-Security-Policy, sent as a real HTTP header. `false` to disable. */
62
+ csp?: CspOptions | false;
63
+ /** Strict-Transport-Security. `false` to disable. */
64
+ hsts?: HstsOptions | false;
65
+ /** X-Frame-Options. Default: `'DENY'`. */
66
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
67
+ /** `X-Content-Type-Options: nosniff`. Default: `true`. */
68
+ contentTypeOptions?: boolean;
69
+ /** Referrer-Policy. Default: `'strict-origin-when-cross-origin'`. */
70
+ referrerPolicy?: string | false;
71
+ /**
72
+ * Permissions-Policy, as an object (`{ camera: [], geolocation: ['self'] }`)
73
+ * or a raw header string. Default: camera, microphone, geolocation, payment and usb disabled.
74
+ */
75
+ permissionsPolicy?: PermissionsPolicy | string | false;
76
+ /** Cross-Origin-Opener-Policy. Default: `'same-origin'`. */
77
+ crossOriginOpenerPolicy?: string | false;
78
+ /** Remove `X-Powered-By` (added by PHP on shared hosting). Default: `true`. */
79
+ removePoweredBy?: boolean;
80
+ /** Any other response header to set (`string`) or unset (`false`). */
81
+ headers?: Record<string, string | false>;
82
+ /** Caching rules. `false` to disable all of them. */
83
+ cache?: CacheOptions | false;
84
+ /**
85
+ * Strict mode: any problem found in the produced policy or `.htaccess` stops the build.
86
+ * When `false`, problems are reported as warnings. Default: `true`.
87
+ */
88
+ strict?: boolean;
89
+ }
90
+ export declare const DEFAULT_CSP_DIRECTIVES: Readonly<Record<string, CspDirectiveValue>>;
91
+ export declare const DEFAULT_PERMISSIONS_POLICY: Readonly<PermissionsPolicy>;
92
+ export interface ResolvedCspOptions {
93
+ directives: Map<string, string[] | true>;
94
+ hashScripts: boolean;
95
+ hashStyles: boolean;
96
+ algorithm: HashAlgorithm;
97
+ reportOnly: boolean;
98
+ allowUnsafeEval: boolean;
99
+ }
100
+ export interface ResolvedOptions {
101
+ csp: ResolvedCspOptions | false;
102
+ hsts: Required<HstsOptions> | false;
103
+ frameOptions: 'DENY' | 'SAMEORIGIN' | false;
104
+ contentTypeOptions: boolean;
105
+ referrerPolicy: string | false;
106
+ permissionsPolicy: string | false;
107
+ crossOriginOpenerPolicy: string | false;
108
+ removePoweredBy: boolean;
109
+ headers: Array<[string, string | false]>;
110
+ cache: {
111
+ immutableAssets: boolean;
112
+ html: string | false;
113
+ };
114
+ strict: boolean;
115
+ }
116
+ /** Thrown for invalid options, before anything is generated. */
117
+ export declare class OptionsError extends Error {
118
+ name: string;
119
+ }
120
+ /** Normalises a directive name the same way browsers do (ASCII lower-case). */
121
+ export declare function normaliseDirectiveName(name: string): string;
122
+ /** Serialises a Permissions-Policy object to its structured-header form. */
123
+ export declare function serialisePermissionsPolicy(policy: PermissionsPolicy): string;
124
+ export declare function resolveOptions(options?: ApacheHeadersOptions): ResolvedOptions;
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Public options of astro-apache-headers and their resolution against defaults.
3
+ *
4
+ * Every security header can be turned off with `false`. Defaults are a strict but
5
+ * practical baseline for a static Astro site (no third-party scripts).
6
+ */
7
+ export const DEFAULT_CSP_DIRECTIVES = Object.freeze({
8
+ 'default-src': ["'self'"],
9
+ 'script-src': ["'self'"],
10
+ 'style-src': ["'self'", "'unsafe-inline'"],
11
+ 'img-src': ["'self'", 'data:'],
12
+ 'font-src': ["'self'"],
13
+ 'connect-src': ["'self'"],
14
+ 'object-src': ["'none'"],
15
+ 'base-uri': ["'self'"],
16
+ 'form-action': ["'self'"],
17
+ 'frame-ancestors': ["'none'"],
18
+ 'upgrade-insecure-requests': true,
19
+ });
20
+ export const DEFAULT_PERMISSIONS_POLICY = Object.freeze({
21
+ camera: [],
22
+ microphone: [],
23
+ geolocation: [],
24
+ payment: [],
25
+ usb: [],
26
+ });
27
+ /** Thrown for invalid options, before anything is generated. */
28
+ export class OptionsError extends Error {
29
+ name = 'OptionsError';
30
+ }
31
+ function toSources(name, value) {
32
+ if (value === false)
33
+ return undefined;
34
+ if (value === true)
35
+ return true;
36
+ const list = Array.isArray(value) ? value : value.split(/\s+/);
37
+ const sources = list.map((s) => {
38
+ if (typeof s !== 'string')
39
+ throw new OptionsError(`csp.directives['${name}'] must contain strings only.`);
40
+ return s.trim();
41
+ }).filter(Boolean);
42
+ return sources;
43
+ }
44
+ /** Normalises a directive name the same way browsers do (ASCII lower-case). */
45
+ export function normaliseDirectiveName(name) {
46
+ return name.trim().toLowerCase();
47
+ }
48
+ function resolveCsp(csp) {
49
+ if (csp === false)
50
+ return false;
51
+ const c = csp ?? {};
52
+ const algorithm = c.algorithm ?? 'sha256';
53
+ if (!['sha256', 'sha384', 'sha512'].includes(algorithm)) {
54
+ throw new OptionsError(`csp.algorithm must be 'sha256', 'sha384' or 'sha512' (got ${JSON.stringify(algorithm)}).`);
55
+ }
56
+ const directives = new Map();
57
+ const base = c.replaceDefaults ? {} : DEFAULT_CSP_DIRECTIVES;
58
+ for (const [name, value] of Object.entries(base)) {
59
+ const s = toSources(name, value);
60
+ if (s !== undefined)
61
+ directives.set(name, s);
62
+ }
63
+ for (const [rawName, value] of Object.entries(c.directives ?? {})) {
64
+ const name = normaliseDirectiveName(rawName);
65
+ if (value === undefined)
66
+ continue;
67
+ if (typeof value !== 'boolean' && typeof value !== 'string' && !Array.isArray(value)) {
68
+ throw new OptionsError(`csp.directives['${rawName}'] must be a string, an array of strings or a boolean.`);
69
+ }
70
+ const s = toSources(name, value);
71
+ if (s === undefined)
72
+ directives.delete(name);
73
+ else
74
+ directives.set(name, s);
75
+ }
76
+ return {
77
+ directives,
78
+ hashScripts: c.hashScripts ?? true,
79
+ hashStyles: c.hashStyles ?? false,
80
+ algorithm,
81
+ reportOnly: c.reportOnly ?? false,
82
+ allowUnsafeEval: c.allowUnsafeEval ?? false,
83
+ };
84
+ }
85
+ /** Serialises a Permissions-Policy object to its structured-header form. */
86
+ export function serialisePermissionsPolicy(policy) {
87
+ return Object.entries(policy)
88
+ .map(([feature, allow]) => {
89
+ if (!/^[a-z][a-z0-9-]*$/.test(feature)) {
90
+ throw new OptionsError(`permissionsPolicy: invalid feature name ${JSON.stringify(feature)}.`);
91
+ }
92
+ const list = typeof allow === 'string' ? allow.split(/\s+/).filter(Boolean) : allow;
93
+ if (list.length === 1 && list[0] === '*')
94
+ return `${feature}=*`;
95
+ const items = list.map((item) => {
96
+ const v = item.replace(/^'(self|src)'$/, '$1');
97
+ if (v === 'self' || v === 'src' || v === '*')
98
+ return v;
99
+ if (/^https?:\/\/[^\s"]+$/.test(v))
100
+ return `"${v.replace(/\/$/, '')}"`;
101
+ if (/^"https?:\/\/[^\s"]+"$/.test(v))
102
+ return v;
103
+ throw new OptionsError(`permissionsPolicy.${feature}: ${JSON.stringify(item)} is not 'self', 'src', '*' or an origin like https://example.com.`);
104
+ });
105
+ return `${feature}=(${items.join(' ')})`;
106
+ })
107
+ .join(', ');
108
+ }
109
+ export function resolveOptions(options = {}) {
110
+ if (options === null || typeof options !== 'object')
111
+ throw new OptionsError('options must be an object.');
112
+ let hsts = false;
113
+ if (options.hsts !== false) {
114
+ const h = options.hsts ?? {};
115
+ hsts = {
116
+ maxAge: h.maxAge ?? 31536000,
117
+ includeSubDomains: h.includeSubDomains ?? false,
118
+ preload: h.preload ?? false,
119
+ };
120
+ if (!Number.isInteger(hsts.maxAge) || hsts.maxAge < 0) {
121
+ throw new OptionsError(`hsts.maxAge must be a non-negative integer (got ${String(h.maxAge)}).`);
122
+ }
123
+ }
124
+ const frameOptions = options.frameOptions === undefined ? 'DENY' : options.frameOptions;
125
+ if (frameOptions !== false && frameOptions !== 'DENY' && frameOptions !== 'SAMEORIGIN') {
126
+ throw new OptionsError(`frameOptions must be 'DENY', 'SAMEORIGIN' or false (ALLOW-FROM is obsolete; use CSP frame-ancestors).`);
127
+ }
128
+ let permissionsPolicy;
129
+ const pp = options.permissionsPolicy;
130
+ if (pp === false)
131
+ permissionsPolicy = false;
132
+ else if (typeof pp === 'string')
133
+ permissionsPolicy = pp.trim();
134
+ else
135
+ permissionsPolicy = serialisePermissionsPolicy(pp ?? DEFAULT_PERMISSIONS_POLICY);
136
+ const headers = [];
137
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
138
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) {
139
+ throw new OptionsError(`headers: ${JSON.stringify(name)} is not a valid header name.`);
140
+ }
141
+ if (value !== false && typeof value !== 'string') {
142
+ throw new OptionsError(`headers['${name}'] must be a string or false.`);
143
+ }
144
+ headers.push([name, value]);
145
+ }
146
+ const cache = options.cache === false
147
+ ? { immutableAssets: false, html: false }
148
+ : { immutableAssets: options.cache?.immutableAssets ?? true, html: options.cache?.html ?? 'no-cache' };
149
+ return {
150
+ csp: resolveCsp(options.csp),
151
+ hsts,
152
+ frameOptions,
153
+ contentTypeOptions: options.contentTypeOptions ?? true,
154
+ referrerPolicy: options.referrerPolicy === undefined ? 'strict-origin-when-cross-origin' : options.referrerPolicy,
155
+ permissionsPolicy,
156
+ crossOriginOpenerPolicy: options.crossOriginOpenerPolicy === undefined ? 'same-origin' : options.crossOriginOpenerPolicy,
157
+ removePoweredBy: options.removePoweredBy ?? true,
158
+ headers,
159
+ cache,
160
+ strict: options.strict ?? true,
161
+ };
162
+ }
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "astro-apache-headers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.6",
4
+ "description": "Astro integration for static sites on Apache shared hosting: generates .htaccess with a real Content-Security-Policy header (automatic SHA-256 hashes of inline scripts), security headers and long-term caching for /_astro/, with strict build-time checks.",
5
+ "license": "MIT",
6
+ "author": "Williams Kubiak (https://lezartsduweb.fr)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/williamsiilofofora/astro-apache-headers.git"
10
+ },
11
+ "homepage": "https://github.com/williamsiilofofora/astro-apache-headers#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/williamsiilofofora/astro-apache-headers/issues"
14
+ },
15
+ "type": "module",
16
+ "keywords": [
17
+ "astro",
18
+ "astro-integration",
19
+ "withastro",
20
+ "apache",
21
+ "htaccess",
22
+ "csp",
23
+ "content-security-policy",
24
+ "security-headers",
25
+ "hsts",
26
+ "static-site",
27
+ "shared-hosting"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "main": "./dist/index.js",
37
+ "types": "./dist/index.d.ts",
38
+ "bin": {
39
+ "astro-apache-headers": "./dist/cli.js"
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "README.md",
44
+ "README.fr.md",
45
+ "LICENSE",
46
+ "CHANGELOG.md"
47
+ ],
48
+ "engines": {
49
+ "node": ">=20.19.0"
50
+ },
51
+ "scripts": {
52
+ "build": "node scripts/build.mjs",
53
+ "prepack": "node scripts/build.mjs",
54
+ "typecheck": "tsc -p tsconfig.json --noEmit",
55
+ "test": "vitest run test/unit test/integration",
56
+ "test:apache": "vitest run test/apache",
57
+ "test:all": "vitest run",
58
+ "test:pack": "node scripts/test-pack.mjs",
59
+ "prepublishOnly": "npm run typecheck && npm run test:all"
60
+ },
61
+ "peerDependencies": {
62
+ "astro": "^5.0.0 || ^6.0.0 || ^7.0.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "astro": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "dependencies": {
70
+ "parse5": "^8.0.0"
71
+ },
72
+ "devDependencies": {
73
+ "@types/node": "^22.0.0",
74
+ "astro": "^7.4.0",
75
+ "playwright-core": "1.63.0",
76
+ "typescript": "^5.9.0",
77
+ "vitest": "^5.1.0"
78
+ }
79
+ }