### Quick Setup Navigation Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/COMPLETION-SUMMARY.md Follow these steps for a quick setup of the project. This includes starting with the README, configuring options, building the project, and deploying. ```bash START → README.md (Quick Start) → Configuration.md (your specific options) → astro build → deploy ``` -------------------------------- ### Integration Setup Logging Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Logs output during the setup phase of the integration. ```log [astro-cloudflare-pages-headers] Setting up integration ``` -------------------------------- ### Informational Logging During Setup Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md This snippet shows the informational log message that appears when the integration starts its setup phase. It indicates that the integration is initializing and does not signify an error. ```log [astro-cloudflare-pages-headers] Setting up integration ``` -------------------------------- ### Usage Example - Basic Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Example of how to integrate astroCloudflarePagesHeaders with basic server headers configuration. ```APIDOC ## Usage Example - Basic Configuration ```typescript import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders({ workers: false, csp: { autoHashes: true, hashStyleElements: true, hashStyleAttributes: true, hashInlineScripts: true, stripUnsafeInline: true, mode: 'route', maxHeaderLineLength: 2000, overflow: 'error', }, }), ], server: { headers: { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', }, }, }); ``` ``` -------------------------------- ### Install astro-cloudflare-pages-headers Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/README.md Use the `astro add` command to install the integration. This command handles adding the necessary dependencies and configuration. ```bash astro add astro-cloudflare-pages-headers ``` -------------------------------- ### Route Matching Order Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Demonstrates the top-to-bottom, first-match behavior of route patterns in the _headers file. More specific routes should be listed first. ```text /api/v1/status Cache-Control: max-age=60 /api/* Cache-Control: max-age=3600 /* Cache-Control: max-age=300 ``` -------------------------------- ### Usage Example - Nested Headers Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Example demonstrating the use of nested headers for route-specific configurations. ```APIDOC ## Usage Example - Nested Headers ```typescript import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders(), ], server: { headers: { '/api': { 'Cache-Control': 'max-age=3600', 'Content-Type': 'application/json', }, '/static': { 'Cache-Control': 'max-age=31536000', }, }, }, }); ``` ``` -------------------------------- ### Astro Build Command Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md This command builds the Astro project, which in turn generates the _headers file in the specified output directory. ```bash astro build # Creates: ./dist/_headers ``` -------------------------------- ### Production-Grade Setup for astro-cloudflare-pages-headers Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/configuration.md A comprehensive setup with route-based CSP auto-hashing, multiple security headers, and route-specific caching strategies. Includes conservative max line length and error on overflow for strict validation. ```javascript export default defineConfig({ integrations: [ astroCloudflarePagesHeaders({ workers: false, csp: { autoHashes: true, mode: 'route', hashStyleElements: true, hashStyleAttributes: true, hashInlineScripts: true, stripUnsafeInline: true, maxHeaderLineLength: 1800, overflow: 'error', }, }), ], server: { headers: { '/': { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-no-referrer', 'Permissions-Policy': 'geolocation=(), microphone=(), camera=()', 'Content-Security-Policy': "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:", }, '/api': { 'Cache-Control': 'public, max-age=3600', 'Content-Type': 'application/json', }, '/static': { 'Cache-Control': 'public, max-age=31536000, immutable', }, }, }, }); ``` -------------------------------- ### Routes Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/types.md Provides an example of the Routes type, demonstrating its structure for internal route management. This object is subject to mutation during header processing and normalization. ```typescript const routes: Routes = { '/*': { 'X-Frame-Options': 'DENY' }, '/api': { 'Cache-Control': 'max-age=3600' } }; ``` -------------------------------- ### Common Header Examples Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Provides examples of commonly used HTTP headers and their values, such as Cache-Control, X-Frame-Options, and Content-Security-Policy. ```plaintext Cache-Control: max-age=3600 X-Frame-Options: DENY Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline' ``` -------------------------------- ### Example Header Line Calculation Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Illustrates how to calculate the total length of a header line for validation against the maximum limit. ```text Content-Security-Policy: script-src 'self' 'sha256-abc...' 'sha256-def...' ... ``` -------------------------------- ### Minimal Setup for astro-cloudflare-pages-headers Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/configuration.md Applies flat headers to all routes. Generates a `_headers` file with the specified headers. ```javascript import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders(), ], server: { headers: { 'X-Frame-Options': 'DENY', }, }, }); ``` -------------------------------- ### Setup Hook for Astro Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md This hook is called during Astro's configuration phase. It logs a setup message and stores any server headers defined in the Astro configuration for later use. ```typescript "astro:config:setup": ({ config, logger }: { config: AstroConfig; logger: AstroIntegrationLogger }) => { logger.info(`[${NAME}] Setting up integration`); if (config.server?.headers) { astroHeaders = config.server.headers as AstroHeaders; } } ``` -------------------------------- ### Astro Integration Order Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md Demonstrates where to place the astroCloudflarePagesHeaders integration within the Astro configuration file. It can typically be placed anywhere in the integrations array. ```javascript export default defineConfig({ integrations: [ // Other integrations... astroCloudflarePagesHeaders(), // Can be anywhere ], }); ``` -------------------------------- ### Global Mode Example Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md Shows a server header configuration for 'global' mode. A wildcard '/*' is used to apply a single CSP header to all routes, which will include all merged script hashes. ```javascript server: { headers: { '/*': { 'Content-Security-Policy': "script-src 'self' 'unsafe-inline'", } } } ``` -------------------------------- ### Run Unit Tests with npm Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/README.md Execute unit tests for the project using npm. Ensure you have npm installed and the project dependencies are set up. ```bash npm test ``` -------------------------------- ### Run Unit Tests with pnpm Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/README.md Execute unit tests for the project using pnpm. Ensure you have pnpm installed and the project dependencies are set up. ```bash pnpm test ``` -------------------------------- ### HeadersNested Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/types.md Illustrates the usage of the HeadersNested type with example routes and their corresponding headers. This structure mirrors the format expected in _headers files for route-specific configurations. ```typescript const nestedHeaders: HeadersNested = { '/api': { 'Cache-Control': 'max-age=3600', 'Content-Type': 'application/json' }, '/static': { 'Cache-Control': 'max-age=31536000' } }; ``` -------------------------------- ### Configure Nested Headers with astroCloudflarePagesHeaders Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Example demonstrating how to configure route-specific headers using the nested format with the astroCloudflarePagesHeaders integration. ```typescript export default defineConfig({ integrations: [ astroCloudflarePagesHeaders(), ], server: { headers: { '/api': { 'Cache-Control': 'max-age=3600', 'Content-Type': 'application/json', }, '/static': { 'Cache-Control': 'max-age=31536000', }, }, }, }); ``` -------------------------------- ### Route Mode Example Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md Illustrates server header configuration for 'route' mode. Specific routes receive their own CSP headers, while wildcard routes like '/*' have CSP headers removed, retaining only other specified headers. ```javascript server: { headers: { '/': { 'Content-Security-Policy': "script-src 'self' 'unsafe-inline'", }, '/blog/': { 'Content-Security-Policy': "script-src 'self' 'unsafe-inline'", }, '/*': { 'X-Frame-Options': 'DENY', } } } ``` -------------------------------- ### Run Unit Tests with yarn Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/README.md Execute unit tests for the project using yarn. Ensure you have yarn installed and the project dependencies are set up. ```bash yarn test ``` -------------------------------- ### Deep Dive Navigation Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/COMPLETION-SUMMARY.md For a deep dive into the project, follow this navigation sequence. It starts with an overview and progresses through all documents. ```bash START → INDEX.md (overview) → All documents in sequence → README.md for context → Specific docs for details ``` -------------------------------- ### Cloudflare Pages Build Command Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Example of a typical build command used in `wrangler.toml` or Cloudflare Pages settings to generate static assets and the _headers file. ```bash npm run build ``` -------------------------------- ### CSP Directive Preservation Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Shows how the order of CSP directives is maintained after patching, ensuring compatibility with browser parsing. ```text default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' ``` ```text default-src 'self'; script-src 'self' 'sha256-abc...'; style-src 'self' 'sha256-def...' ``` -------------------------------- ### Configure Wildcard Headers in Astro Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/configuration.md Example of configuring wildcard headers in Astro's server configuration. This will be automatically remapped to '/*' when the workers option is enabled. ```javascript server: { headers: { '*': { 'X-Frame-Options': 'DENY', }, }, } ``` -------------------------------- ### Route Pattern Examples Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Illustrates various route patterns supported by Cloudflare Pages _headers files, including root path, universal wildcard, directory wildcard, and exact path matching. ```plaintext / /* /api/* /static ``` -------------------------------- ### Cloudflare Pages _headers File Format Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md This is an example of the `_headers` file format generated by the integration. It specifies custom headers for different routes. ```plaintext /* X-Frame-Options: DENY X-Content-Type-Options: nosniff /api Cache-Control: max-age=3600 ``` -------------------------------- ### CSP Hash Format Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md CSP hashes are formatted as CSP source expressions, prefixed with single quotes and the algorithm, followed by a Base-64 encoded SHA-256 digest. ```text 'sha256-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcd+/==' ``` -------------------------------- ### Example CSP Auto-Hash Patch Log Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md This log message indicates the completion of the CSP auto-hash patching process. It provides counts of various hashes generated and CSP headers updated. This message is logged at the info level during the build process. ```text [astro-cloudflare-pages-headers] CSP auto-hash patch completed: 5 inline style hashes, 3 style attribute hashes, 8 inline script hashes, 4 updated CSP headers. ``` -------------------------------- ### Integration Hooks Structure Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md Demonstrates the structure for defining integration hooks, including the `astro:config:setup` for initial configuration and `astro:build:done` for post-build actions. It shows how a closure variable `astroHeaders` is used to persist data between hooks. ```typescript let astroHeaders: AstroHeaders | undefined; // ... return { name: "astroCloudflarePagesHeaders", hooks: { "astro:config:setup": ({ config, logger }) => { // Populate astroHeaders }, "astro:build:done": async ({ dir, logger }) => { // Use astroHeaders }, }, }; ``` -------------------------------- ### Basic _headers File Structure Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Defines the general structure of a _headers file. Route patterns are at the start of a line, followed by indented header key-value pairs. Sections are separated by empty lines. ```plaintext route-pattern Header-Name: header-value Another-Header: another-value another-pattern Header-Name: value ``` -------------------------------- ### Handling Non-Fatal CSP Patching Errors Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md This example shows how to catch and log errors during CSP patching without halting the build process. It's useful for I/O or parsing errors related to HTML files. ```typescript try { const report = await patchRoutesCsp(routes, buildDir, cspOptions); logger.info(/* success message */); } catch (err) { logger.error(`[${NAME}] Failed to patch CSP hashes: ${err}`); } // Build continues ``` -------------------------------- ### Replacing 'none' Directive with Hashes Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md The 'none' directive is incompatible with hash sources and will be replaced when hashes are added to the CSP. For example, 'style-src \'none\'' becomes 'style-src \'sha256-abc...\'' ```csp style-src 'none' ``` ```csp style-src 'sha256-abc...' ``` -------------------------------- ### Hash Style Attributes Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md This example shows an inline `style` attribute on an HTML element. The attribute's content is hashed and added to the `style-src-attr` directive, automatically including `'unsafe-hashes'`. ```html
Content
``` -------------------------------- ### Integration State Management with Closure Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md This snippet demonstrates how the integration uses a closure variable to maintain state across Astro build hooks. The `astroHeaders` variable is initialized once per build and updated during `astro:config:setup`, then read in `astro:build:done`. ```typescript export default function astroCloudflarePagesHeaders( options: AstroCloudflarePagesHeadersOptions = {}, ) { let astroHeaders: AstroHeaders | undefined; // ← State const cspOptions = resolveCspOptions(options); const workersEnabled = options.workers === true; return { name: "astroCloudflarePagesHeaders", hooks: { "astro:config:setup": ({ config, logger }) => { // Access and modify astroHeaders }, "astro:build:done": async ({ dir, logger }) => { // Read astroHeaders (set by setup hook) }, }, }; } ``` -------------------------------- ### HeadersFlat Type Alias Example Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/types.md Type alias for flat header format where all headers apply globally. Each key is a header name and each value is a header value string. These headers apply to all routes via `/*` in the `_headers` file. ```typescript const flatHeaders: HeadersFlat = { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'max-age=3600' }; ``` -------------------------------- ### Understanding Navigation Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/COMPLETION-SUMMARY.md Navigate through these documents to understand the project's concepts and features. This path is recommended for a deeper comprehension. ```bash START → README.md (Key Concepts) → Integration-lifecycle.md (how it works) → CSP-auto-hashing.md (if using that feature) → Headers-file-format.md (what gets generated) ``` -------------------------------- ### Build and Inspect _headers File Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Build your Astro project and then view the generated _headers file to verify its content and format. ```bash astro build cat dist/_headers ``` -------------------------------- ### astro-cloudflare-pages-headers with Nested Headers Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/configuration.md Applies different headers to specific routes. Each route gets its own CSP header section. ```javascript export default defineConfig({ integrations: [ astroCloudflarePagesHeaders(), ], server: { headers: { '/api': { 'Cache-Control': 'max-age=3600', 'Content-Type': 'application/json', }, '/static': { 'Cache-Control': 'max-age=31536000', }, '/*': { 'X-Frame-Options': 'DENY', }, }, }, }); ``` -------------------------------- ### Preserving Whitespace in Header Values Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Demonstrates how leading and trailing whitespace in header values is preserved. The integration does not trim values, as shown in this example. ```javascript headers: { 'X-Custom': ' spaced value ' } ``` ```text X-Custom: spaced value ``` -------------------------------- ### Typical Usage Import Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/EXPORT-INDEX.md Shows how to import the main integration function and relevant types from the package. ```typescript import astroCloudflarePagesHeaders, { AstroCloudflarePagesHeadersOptions, CspAutoHashesOptions, } from 'astro-cloudflare-pages-headers'; ``` -------------------------------- ### API Usage Navigation Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/COMPLETION-SUMMARY.md Access these entry points for API usage information. This includes understanding exports, type definitions, function signatures, and option types. ```bash START → EXPORT-INDEX.md (what's exported) → Types.md (type definitions) → API-reference.md (function signatures) → Configuration.md (option types) ``` -------------------------------- ### CSP Header Line Length Overflow Error Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md Example of an error message indicating that a CSP header line has exceeded the maximum allowed length. ```text Header line length overflow: 2450 characters for "/" -> "Content-Security-Policy". Max allowed is 2000. Found 2 overflowing line(s). ``` -------------------------------- ### Secure Headers for All Routes Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Apply security headers like X-Frame-Options, X-Content-Type-Options, and Referrer-Policy to all routes. Ensure these headers are configured within the server configuration. ```javascript server: { headers: { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-no-referrer', } } ``` -------------------------------- ### Integration Build Warnings Logging Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Logs output for various warnings that may occur during the build phase. ```log [astro-cloudflare-pages-headers] No headers configuration found. Skipping _headers generation. [astro-cloudflare-pages-headers] Both "*" and "/*" routes were found. Merged into "/*". [astro-cloudflare-pages-headers] CSP auto-hashes enabled but no hash categories enabled. Skipping CSP patch. [astro-cloudflare-pages-headers] Header line length overflow: N characters. Max allowed is M. ``` -------------------------------- ### CSP Hash Source Format Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/csp-auto-hashing.md CSP hashes are formatted as a string literal enclosed in single quotes, starting with the algorithm prefix 'sha256-' followed by a base-64 encoded digest. ```text 'sha256-K8ioM1wDenlaTmwvf64lO7OWgoQ4FywwhKoBeWecw8c=' ``` -------------------------------- ### Collect HTML Files Recursively Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Recursively walks the build directory and returns all .html file paths. Accepts a root directory string and returns a Promise of absolute paths. ```typescript async function collectHtmlFiles(rootDir: string): Promise ``` -------------------------------- ### Integration Build Success Logging Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Logs output indicating a successful build phase for the integration. ```log [astro-cloudflare-pages-headers] Running build hook [astro-cloudflare-pages-headers] CSP auto-hash patch completed: X style hashes, Y attr hashes, Z script hashes, N updated headers. [astro-cloudflare-pages-headers] Successfully created _headers at /path/to/dist/_headers ``` -------------------------------- ### Resolve Build Directory and Headers File Path Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md Determines the file system path for the build output directory and resolves the absolute path for the _headers file. ```typescript const buildDir = getBuildDir(dir); const headersFilePath = path.resolve(buildDir, "_headers"); ``` -------------------------------- ### Configure Flat Headers in Astro Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/README.md Add the integration to your `astro.config.mjs` and define flat headers in the `server.headers` property. This configuration will be used to generate the `_headers` file. ```js,ts import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders(), ], server: { headers: { 'X-Custom-Header': 'my-value', 'X-Another-Header': 'another-value' }, }, }); ``` -------------------------------- ### Basic Header Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Configure basic headers like X-Frame-Options and X-Content-Type-Options in your astro.config.mjs. These headers will be applied to all routes. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders(), ], server: { headers: { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', }, }, }); ``` -------------------------------- ### Collect CSP Hashes from Build Output Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Scans all HTML files in the build directory and returns merged hashes across all routes in global mode. Requires the build directory and CSP configuration options. ```typescript async function collectCspHashesFromBuild( buildDir: string, cspOptions: ResolvedCspOptions ): Promise ``` -------------------------------- ### Secure Headers for All Routes Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Applies security headers like X-Frame-Options, X-Content-Type-Options, and Referrer-Policy to all routes. ```APIDOC ## Secure Headers for All Routes ### Description Applies security headers to all routes. ### Configuration ```javascript server: { headers: { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-no-referrer', } } ``` ``` -------------------------------- ### Integration Build Errors Logging Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Logs output for errors encountered during the build phase. ```log [astro-cloudflare-pages-headers] Failed to patch CSP hashes: [astro-cloudflare-pages-headers] Failed to write _headers file: ``` -------------------------------- ### Patch Routes with CSP Headers Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Main entry point for applying CSP hashes to headers. It supports both global and route-specific CSP modes and respects directive-specific options. Ensure the build directory is correctly specified. ```typescript async function patchRoutesCsp( routes: Routes, buildDir: string, cspOptions: ResolvedCspOptions ): Promise ``` -------------------------------- ### Configure Flat Headers in Astro Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Use this configuration for applying the same set of headers to all routes. Ensure headers are indented and followed by a blank line in the generated file. ```javascript server: { headers: { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', } } ``` ```text /* X-Frame-Options: DENY X-Content-Type-Options: nosniff ``` -------------------------------- ### astroCloudflarePagesHeaders Function Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md The main entry point function for the astroCloudflarePagesHeaders integration. It accepts an optional configuration object and returns an Astro integration. ```APIDOC ## astroCloudflarePagesHeaders ### Function Signature ```typescript export default function astroCloudflarePagesHeaders( options?: AstroCloudflarePagesHeadersOptions ): AstroIntegration ``` ### Parameters #### options - **options** (`AstroCloudflarePagesHeadersOptions`) - Optional - Configuration object for the integration. ### Returns - `AstroIntegration` — An Astro integration object with two lifecycle hooks: `astro:config:setup` and `astro:build:done`. ### Description This function initializes the Astro integration. It reads header configurations from `config.server.headers` and generates a `_headers` file for Cloudflare Pages during the build process. It supports various features like flat and nested header formats, workers mode, CSP auto-hashing, and header line length validation. ``` -------------------------------- ### Check Headers Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/integration-lifecycle.md Warns and exits early if no headers configuration is found or if it's an empty object. This prevents the creation of an empty _headers file. ```typescript if (!astroHeaders || (typeof astroHeaders === "object" && isEmptyObject(astroHeaders))) { logger.warn(`[${NAME}] No headers configuration found in Astro config. Skipping _headers generation.`); return; } ``` -------------------------------- ### astroCloudflarePagesHeaders Integration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/EXPORT-INDEX.md The main function to initialize the astro-cloudflare-pages-headers integration. It accepts an optional configuration object. ```APIDOC ## astroCloudflarePagesHeaders ### Description Initializes the astro-cloudflare-pages-headers integration for Astro projects. This function allows you to configure custom headers for Cloudflare Pages. ### Signature ```typescript function astroCloudflarePagesHeaders(options?: AstroCloudflarePagesHeadersOptions): AstroIntegration ``` ### Parameters #### Options (`AstroCloudflarePagesHeadersOptions`) - **workers** (boolean) - Optional. If true, enables worker-specific header configurations. - **csp** (`CspAutoHashesOptions`) - Optional. Configuration object for Content Security Policy (CSP) auto-hashing. ### See [API Reference — astroCloudflarePagesHeaders](./api-reference.md#astrocloudfarepagesheaders) ``` -------------------------------- ### collectCspHashesByRouteFromBuild Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Scans all HTML files within a specified build directory and groups CSP hashes by route. This is useful for implementing route-specific CSP headers. ```APIDOC ## collectCspHashesByRouteFromBuild ### Description Scans all HTML files and groups hashes by route (route mode), for route-specific CSP headers. ### Method async function ### Parameters #### Path Parameters - `buildDir` (string) - Required - Build output directory #### Request Body - `cspOptions` (ResolvedCspOptions) - Required - Configuration for hashing ### Returns `Promise` - Object with `sourcesByRoute` map and aggregated `totals` ``` -------------------------------- ### Flat Header Format Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Configure headers that apply to all routes using the flat format in astro.config.mjs. This is useful for global security headers. ```javascript server: { headers: { 'X-Header': 'value', } } ``` -------------------------------- ### Regex for Style Tag Matching Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Regular expression to match ` ``` -------------------------------- ### Configure astroCloudflarePagesHeaders Integration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/api-reference.md Use this snippet to integrate astro-cloudflare-pages-headers into your Astro project. Configure CSP options and server headers for all routes. ```typescript import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders({ workers: false, csp: { autoHashes: true, hashStyleElements: true, hashStyleAttributes: true, hashInlineScripts: true, stripUnsafeInline: true, mode: 'route', maxHeaderLineLength: 2000, overflow: 'error', }, }), ], server: { headers: { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', }, }, }); ``` -------------------------------- ### Configure CSP Auto-Hashing in Astro Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/README.md Enable optional CSP auto-hashing by passing a `csp` configuration object to the integration. This is useful when using CSP integrations to automatically add hashes for inline styles and scripts. ```js,ts import { defineConfig } from 'astro/config'; import astroCloudflarePagesHeaders from 'astro-cloudflare-pages-headers'; export default defineConfig({ integrations: [ astroCloudflarePagesHeaders({ csp: { autoHashes: true, hashStyleElements: true, hashStyleAttributes: true, hashInlineScripts: true, stripUnsafeInline: true, maxHeaderLineLength: 2000, overflow: 'error', }, }), ], }); ``` -------------------------------- ### Package.json Exports Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/EXPORT-INDEX.md Defines the main export point for the package, which is the index.ts file. ```json { "exports": { ".": "./index.ts" } } ``` -------------------------------- ### CspAutoHashesOptions Interface Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/types.md Configuration for automatic CSP hash generation and patching. Enables hashing of style elements, style attributes, and inline scripts. Control the hash collection strategy with `mode` and header line length with `maxHeaderLineLength`. ```typescript export interface CspAutoHashesOptions { autoHashes?: boolean; hashStyleElements?: boolean; hashStyleAttributes?: boolean; hashInlineScripts?: boolean; stripUnsafeInline?: boolean; mode?: "global" | "route"; maxHeaderLineLength?: number; overflow?: "error" | "warn"; } ``` -------------------------------- ### Configure CSP Auto-Hashing for Route Mode in Astro Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Enable `csp.autoHashes` to automatically generate SHA-256 hashes for inline CSP content. This replaces `'unsafe-inline'` with specific hashes for improved security. ```javascript server: { headers: { '/': { 'Content-Security-Policy': "style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'", } } } ``` ```html ``` ```text / Content-Security-Policy: style-src 'self' 'sha256-abc123def456...'; script-src 'self' 'sha256-xyz789uvw012...' ``` -------------------------------- ### Configure Nested Headers in Astro Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/headers-file-format.md Configure headers for specific routes using a nested structure. Each route section in the generated file is separated by an empty line. ```javascript server: { headers: { '/api': { 'Cache-Control': 'max-age=3600', 'Content-Type': 'application/json', }, '/static': { 'Cache-Control': 'max-age=31536000', }, '/*': { 'X-Frame-Options': 'DENY', } } } ``` ```text /api Cache-Control: max-age=3600 Content-Type: application/json /static Cache-Control: max-age=31536000 /* X-Frame-Options: DENY ``` -------------------------------- ### CSP Auto-Hashing Configuration Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/README.md Enable Content-Security-Policy with auto-hashing to automatically generate hashes for inline scripts and styles. This enhances security by allowing the removal of 'unsafe-inline'. ```javascript export default defineConfig({ integrations: [ astroCloudflarePagesHeaders({ csp: { autoHashes: true, }, }), ], server: { headers: { '/*': { 'Content-Security-Policy': "style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'", }, }, }, }); ``` -------------------------------- ### CspRoute Interface Source: https://github.com/martinsilha/astro-cloudflare-pages-headers/blob/main/_autodocs/types.md Represents a parsed CSP route entry extracted from routes. Includes the route pattern, headers, and the exact CSP header key. ```typescript interface CspRoute { route: string; headers: Record; headerKey: string; } ```