erickjmenezes/policyman

v0.5.0 2024-09-07 20:02 UTC

This package is auto-updated.

Last update: 2025-03-07 21:18:20 UTC


README

A Content-Security-Policy (CSP) header parser and builder.

Instalation

composer install erickjmenezes/policyman

Building a CSP header:

use ErickJMenezes\Policyman\Policyman;
use ErickJMenezes\Policyman\Keyword;

$header = Policyman::builder()
    ->defaultSrc([Keyword::Self])
    ->scriptSrc([Keyword::Self, Keyword::UnsafeEval, Keyword::UnsafeInline, 'trusted-cdn.com'])
    ->styleSrc([Keyword::Self, 'trusted-cdn.com'])
    ->toString();

// Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' trusted-cdn.com; style-src 'self' trusted-cdn.com

Parsing and editing an existing CSP header string:

use ErickJMenezes\Policyman\Policyman;
use ErickJMenezes\Policyman\ContentSecurityPolicy;
use ErickJMenezes\Policyman\Policy;
use ErickJMenezes\Policyman\Keyword;
use ErickJMenezes\Policyman\Directive;

// Example header.
$header = "Content-Security-Policy: img-src 'self' data:; object-src 'none'";

// Parsing to an object.
/** @var ContentSecurityPolicy $csp */
$csp = Policyman::parse($header);

// Adding script-src directive.
$csp->add(new Policy(Directive::ScriptSrc, [Keyword::Self, 'example.com']));
$csp->find(Directive::ImgSrc)->add('example.com');

// Convert it back to a string.
$newHeader = Policyman::serialize($csp);

// Content-Security-Policy: img-src 'self' data: example.com; object-src 'none'; script-src 'self' example.com

Validation:

use ErickJMenezes\Policyman\Policyman;

Policyman::validate("Content-Security-Policy: default_src 'self'"); // false
Policyman::validate("Content-Security-Policy: default-src 'self'"); // true