decodelabs / sanctum
在您的PHP应用程序中定义和部署内容安全策略
v0.2.0
2024-08-22 02:25 UTC
Requires
- php: ^8.1
- decodelabs/archetype: ^0.3
- decodelabs/exceptional: ^0.4
- decodelabs/glitch-support: ^0.4
- psr/http-message: ^2.0
Requires (Dev)
README
为您的PHP应用程序创建内容安全策略。
Sanctum允许您轻松创建和部署内容安全策略。消除这一重要安全特性中的猜测。
在DecodeLabs博客上获取新闻和更新。
安装
composer require decodelabs/sanctum
使用方法
创建您的定义
use DecodeLabs\Sanctum\Definition; class MyCsp extends Definition { // These items can be reused in other directives const SharedSrc = [ '@self', // Resolves to 'self' '*.myotherdomain.com' ]; // These items create the default-src directive const DefaultSrc = [ '@shared-src', // Import items from SharedSrc ]; // These define script sources const ScriptSrc = [ '@nonce', // Creates a unique nonce to be used in markup '@unsafe-inline', // Resolves to 'unsafe-inline' '@strict-dynamic', '@https', '@http' ]; // These define image sources const ImgSrc = [ '@shared', // Import items from SharedSrc '@data', // Resolves to data: for data URLs '*.myimagecdn.net', '!*.myotherdomain.com' // Exclude importing from SharedSrc ]; // Report endpoint const ReportUri = 'https://mydomain.com/report'; }
有关指令的完整列表,请参阅https://content-security-policy.com/
然后在您的HTTP处理器中
$csp = new MyCsp(); foreach($csp->exportHeaders() as $header => $value) { $response->setHeader($header, $value); } /* Reporting-Endpoints => sanctum-csp-report="https://mydomain.com/report" Content-Security-Policy => default-src 'self' *.myotherdomain.com; script-src nonce-98b88fa48f23911d6fc1f5092efb2e36d76423ce4f5d7ef42765a2c2501d57c9' 'unsafe-inline' 'strict-dynamic' https: http:; img-src 'self' data: *.myimagecdn.net; report-uri https://mydomain.com/report; report-to sanctum-csp-report */
散列
利用散列功能来处理脚本 - 请参阅https://content-security-policy.com/hash/以了解说明
/* HTML: <script>doSomething();</script> */ $script = 'doSomething();'; // Your JS // Adds sha256-xxx hash to CSP directive $hash = $csp->hashContent($script, 'script-src');
构型加载器
Sanctum还提供了一个可选的构型加载器
namespace DecodeLabs\Sanctum\Definition; use DecodeLabs\Sanctum\Definition; class MyCsp extends Definition {} $csp = Definition::load('MyCsp'); $csp->exportHeaders();
默认情况下,构型将在根命名空间(DecodeLabs\Sanctum\Definition
)中查找实现。如果您希望在不同命名空间中托管实现,您应创建并注册一个新的构型解析器来查找它们。
许可协议
Sanctum采用MIT许可协议。请参阅LICENSE以获取完整的许可协议文本。