@stacksjs/stx
Version:
A performant UI Framework. Powered by Bun.
229 lines • 7.15 kB
TypeScript
import type { CspConfig, CspDirectives, CspPreset, CustomDirective, StxOptions } from './types';
/**
* Generate a cryptographically secure nonce for CSP
*
* @param length - Length of nonce in bytes (default 16)
* @returns Base64-encoded nonce string
*
* @example
* ```typescript
* const nonce = generateNonce()
* // Returns something like: "4AiRXmSkM+XRG3E2Y1fO9Q=="
* ```
*/
export declare function generateNonce(length?: number): string;
/**
* Get or create a nonce for the current request context
*
* Uses WeakMap to ensure nonce is request-scoped and can be garbage collected.
* If no context is provided, generates a new nonce each time.
*
* @param context - Request context object for nonce scoping
* @param config - CSP configuration (may include custom nonce generator)
* @returns The nonce for the current context
*
* @example
* ```typescript
* // In a request handler
* const ctx = { requestId: '123' }
* const nonce = getNonce(ctx, cspConfig)
* // Same nonce returned for same context object
* const sameNonce = getNonce(ctx, cspConfig)
* ```
*/
export declare function getNonce(context?: object, config?: CspConfig): string;
/**
* Clear the nonce for a context (useful for testing or manual cleanup)
*
* @param context - Request context to clear nonce for
*/
export declare function clearNonce(context: object): void;
/**
* Generate a CSP header string from directive configuration
*
* @param directives - CSP directive configuration
* @param nonce - Optional nonce to inject into script-src and style-src
* @returns CSP header string
*
* @example
* ```typescript
* const header = generateCspHeader({
* 'default-src': ["'self'"],
* 'script-src': ["'self'", 'https://cdn.example.com'],
* 'upgrade-insecure-requests': true,
* })
* // Returns: "default-src 'self'; script-src 'self' https://cdn.example.com; upgrade-insecure-requests"
* ```
*/
export declare function generateCspHeader(directives: CspDirectives, nonce?: string): string;
/**
* Generate CSP meta tag HTML
*
* @param directives - CSP directive configuration
* @param nonce - Optional nonce to inject
* @returns HTML meta tag string
*
* @example
* ```typescript
* const metaTag = generateCspMetaTag({
* 'default-src': ["'self'"],
* })
* // Returns: '<meta http-equiv="Content-Security-Policy" content="default-src \'self\'">'
* ```
*/
export declare function generateCspMetaTag(directives: CspDirectives, nonce?: string): string;
/**
* Get a CSP preset configuration by name
*
* @param preset - Name of the preset
* @returns CSP configuration object
*
* @example
* ```typescript
* const config = getCspPreset('strict')
* // Returns full CspConfig with strict directives
* ```
*/
export declare function getCspPreset(preset: CspPreset): CspConfig;
/**
* Merge two CSP directive configurations
*
* Sources from the second config are added to the first.
* Boolean directives are OR'd together.
*
* @param base - Base CSP directives
* @param override - Override/additional directives
* @returns Merged CSP directives
*
* @example
* ```typescript
* const merged = mergeCspDirectives(
* { 'default-src': ["'self'"], 'script-src': ["'self'"] },
* { 'script-src': ['https://cdn.example.com'], 'img-src': ['https:'] }
* )
* // Result: {
* // 'default-src': ["'self'"],
* // 'script-src': ["'self'", "https://cdn.example.com"],
* // 'img-src': ["https:"]
* // }
* ```
*/
export declare function mergeCspDirectives(base: CspDirectives, override: CspDirectives): CspDirectives;
/**
* Inject CSP meta tag into HTML head
*
* @param html - HTML content
* @param config - CSP configuration
* @param context - Request context for nonce scoping
* @returns HTML with CSP meta tag injected
*/
export declare function injectCspMetaTag(html: string, config: CspConfig, context?: object): string;
/**
* Add nonce attribute to all inline script and style tags
*
* @param html - HTML content
* @param nonce - Nonce value to add
* @returns HTML with nonce attributes added
*/
export declare function addNonceToInlineContent(html: string, nonce: string): string;
/**
* Process CSP-related directives in templates
*
* Handles:
* - @csp - Insert CSP meta tag
* - @cspNonce - Output current nonce value
*
* @param template - Template content
* @param context - Template context
* @param _filePath - Source file path
* @param options - STX options
* @returns Processed template
*/
export declare function processCspDirectives(template: string, context: Record<string, any>, _filePath: string, options: StxOptions): string;
/**
* Register CSP-related custom directives
*
* @returns Array of custom directives for CSP
*/
export declare function registerCspDirectives(): CustomDirective[];
/**
* Validate CSP directive configuration
*
* @param directives - CSP directives to validate
* @returns Array of validation warnings
*
* @example
* ```typescript
* const warnings = validateCspDirectives({
* 'script-src': ["'unsafe-inline'", "'unsafe-eval'"],
* })
* // Returns warnings about unsafe usage
* ```
*/
export declare function validateCspDirectives(directives: CspDirectives): string[];
/**
* Get the appropriate CSP header name based on configuration
*
* @param reportOnly - Whether to use report-only mode
* @returns Header name string
*/
export declare function getCspHeaderName(reportOnly?: boolean): string;
/**
* Create CSP headers object for HTTP response
*
* @param config - CSP configuration
* @param context - Request context for nonce scoping
* @returns Headers object ready to spread into response
*
* @example
* ```typescript
* const headers = createCspHeaders(cspConfig, requestContext)
* return new Response(body, { headers: { ...headers } })
* ```
*/
export declare function createCspHeaders(config: CspConfig, context?: object): Record<string, string>;
/**
* Strict CSP preset - Maximum security, may require nonces for inline content
*
* - No unsafe-inline or unsafe-eval
* - Uses strict-dynamic for scripts
* - Blocks object/embed
* - Restricts form actions to same origin
*/
export declare const strictCspPreset: CspDirectives;
/**
* Moderate CSP preset - Balanced security and compatibility
*
* - Allows unsafe-inline for styles (common requirement)
* - Blocks unsafe-eval
* - Allows data: URIs for images
*/
export declare const moderateCspPreset: CspDirectives;
/**
* Relaxed CSP preset - Basic protection, maximum compatibility
*
* - Allows unsafe-inline for both scripts and styles
* - Still blocks unsafe-eval and object embeds
*/
export declare const relaxedCspPreset: CspDirectives;
/**
* API-only CSP preset - For JSON API responses
*
* - Blocks all content loading (APIs shouldn't render HTML)
* - Prevents framing
*/
export declare const apiCspPreset: CspDirectives;
/**
* CSP meta tag directive
* Usage: @csp
*/
export declare const cspDirective: CustomDirective;
/**
* CSP nonce directive
* Usage: @cspNonce
*/
export declare const cspNonceDirective: CustomDirective;
/**
* Default CSP configuration - moderate preset
*/
export declare const defaultCspConfig: CspConfig;