Content Security Policy (CSP)

XyPriss provides advanced Content Security Policy configuration with flexible directive support through the Helmet middleware. This allows developers to create comprehensive security policies to prevent XSS and data injection attacks.

Basic Configuration

Configure CSP directives globally in your server options. XyPriss supports strings, arrays, and boolean directives.

typescript
import { createServer } from "xypriss";

const app = createServer({
    security: {
        helmet: {
            contentSecurityPolicy: {
                directives: {
                    defaultSrc: ["'self'"],
                    scriptSrc: ["'self'", "'unsafe-inline'"],
                    styleSrc: ["'self'", "'unsafe-inline'"],
                    imgSrc: ["'self'", "data:", "https:"],
                },
            },
        },
    },
});

Advanced Multi-Source Policy

For complex applications, you can define granular sources for different resource types:

typescript
const app = createServer({
    security: {
        helmet: {
            contentSecurityPolicy: {
                directives: {
                    defaultSrc: ["'self'"],
                    scriptSrc: [
                        "'self'",
                        "'unsafe-inline'",
                        "https://cdn.example.com",
                        "https://dll.nehonix.com"
                    ],
                    fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
                    connectSrc: ["'self'", "https://dll.nehonix.com"],
                    frameSrc: ["'none'"],
                    objectSrc: ["'none'"],
                    upgradeInsecureRequests: [] // Boolean directive
                }
            }
        }
    }
});

Nonces and Hashes

Nonce Support

Generate per-request nonces to allow specific inline scripts while maintaining a strict policy.

Hash Support

Whiltelist specific inline script contents using their SHA-256 cryptographic hashes.

Report-Only Mode

Test new policies without blocking resources by enabling reportOnly mode. Violations will be logged to the specified URI.

typescript
const app = createServer({
    security: {
        helmet: {
            contentSecurityPolicy: {
                reportOnly: true, 
                directives: { /* directives */ },
                reportUri: "/api/security/csp-report",
            },
        },
    },
});

Security Best Practices

Avoid unsafe-inline: Whenever possible, avoid using 'unsafe-inline'. Use Nonces or Hashes instead to maintain a strong security posture.
  • Principle of Least Privilege: Only allow necessary sources and start with restrictive defaults.
  • Use HTTPS: Always prefer and enforce HTTPS sources for all directives.
CORS Policy

Configure cross-origin resource sharing for your API with wildcard and pattern support.