hk2/csp
Composer 安装命令:
composer require hk2/csp
包简介
Magento 2 module to manage CSP whitelisted URLs
README 文档
README
HK2 CSP Whitelisting — Magento 2 Module
Manage Content Security Policy (CSP) whitelists in Magento 2 with zero overhead. Ships with a pre-built whitelist of 80+ trusted hosts and a flexible admin interface for adding custom origins.
Overview
Magento 2.4.x ships with a strict CSP mode that blocks inline scripts, external resources, and cross-origin requests by default. Extensions integrating third-party services (analytics, payment gateways, CDNs, social widgets) routinely violate these policies, causing broken checkout flows, missing assets, and console errors.
HK2 CSP Whitelisting solves this by providing a maintainable, audit-friendly CSP management layer — no core hacks, no compilation steps, no deployment pipelines required.
Problem Statement
- Magento CSP violations break payment iframes, analytics scripts, and CDN assets silently.
- Default CSP configuration requires manual XML editing or compilation.
- Hardcoding hosts into
etc/csp_whitelist.xmlmakes per-store or per-environment customisation impossible. - Merchant-specific host additions are lost on module updates.
Solution Approach
Three-layer CSP architecture:
- Safe-report-only defaults — broad but safe directive coverage (
CSP.xml), violations logged, nothing blocked. - Pre-built whitelist (
csp_whitelist.xml) — 80+ verified hosts across 7 directives, updated per release. - Admin custom whitelist — 6 textarea fields per store view, persisted in DB, survives updates.
A plugin intercepts Magento\Csp\Model\Policy\PolicyList::getAllPolicies and merges all three layers into a single policy object. No template overrides, no layout handles, no public assets — purely server-side policy assembly.
Alternatives Considered
| Approach | Trade-off |
|---|---|
.htaccess / nginx headers |
Ignores Magento CSP framework; breaks GraphQL and AJAX routes |
Template-level <meta> tags |
Unsafe, client-side only, bypasses Magento CSP reporting |
etc/csp_whitelist.xml only |
Per-store overrides impossible; lost on update |
| Third-party CSP gateway (e.g. Sentry) | Adds latency, cost, and another dependency |
| Disabling CSP entirely | Security regression |
Who is this for?
- Magento 2 merchants using third-party integrations (analytics, payments, CDNs, social media).
- Agencies managing multi-store deployments with different CSP requirements per store.
- Developers needing a predictable, code-reviewed allowlist that doesn't break on module updates.
- Store owners preparing for PCI DSS 4.0 compliance (CSP requirements).
Use Cases
- Payment gateways — whitelist Stripe, PayPal, or Braintree script & frame sources.
- Analytics & tracking — Google Analytics, Tag Manager, Facebook Pixel, Hotjar, Klaviyo.
- CDN assets — jsDelivr, cdnjs, Cloudflare, Fontsource, Tailwind CSS.
- Third-party widgets — YouTube/Vimeo embeds, Trustpilot reviews, TikTok pixels.
- Monitoring — Sentry error tracking, Contentsquare session replay.
- Social media — Facebook, Instagram, Twitter/X, Pinterest, LinkedIn pixels & SDKs.
Key Features
- 80+ trusted hosts pre-loaded across 7 CSP directives
- Admin custom fields — script-src, style-src, img-src, connect-src, font-src, frame-src
- Per-store-view configuration — different whitelists per website/store
- One-click reset — clears all custom entries from DB
- Zero frontend impact — no layout XML, no block rewrites, no JS
- No compilation step — policies assembled at runtime via plugin
- Report-only by default — violations logged, nothing blocked out of the box
- Marketplace-friendly — no
ObjectManager, no preferences, no core rewrites
Architecture Overview
┌─────────────────────────────────────────────────────┐
│ HTTP Response │
│ Content-Security-Policy-Report-Only │
└──────────────────────┬──────────────────────────────┘
│
┌──────────────────────▼──────────────────────────────┐
│ PolicyList::getAllPolicies (Magento\Csp) │
│ ┌────────────────────────────────────────────────┐ │
│ │ Plugin: afterGetAllPolicies │ │
│ │ ┌──────────────────┐ ┌──────────────┐ ┌─────┐ │ │
│ │ │ etc/csp.xml │ │ csp_whitelist │ │ DB │ │ │
│ │ │ (9 directives, │ │ .xml │ │custom│ │ │
│ │ │ report-only) │ │ (80+ hosts, │ │(6 │ │ │
│ │ │ │ │ 7 directives)│ │fields│ │ │
│ │ └──────────────────┘ └──────────────┘ └─────┘ │ │
│ └────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
Layer 1 — Base CSP (etc/csp.xml)
Safe-report-only defaults for 9 directives. No hosts blocked — only logged. Provides immediate visibility into all policy violations without breaking storefront functionality.
Directives covered: script-src, style-src, img-src, connect-src, font-src, media-src, object-src, base-uri, child-src.
Layer 2 — Pre-built Whitelist (etc/csp_whitelist.xml)
Curated set of 80+ hosts across the most commonly needed directives. Sources verified for correctness — no wildcard entries, no redundant allowances.
| Category | Examples | Directives Covered |
|---|---|---|
| Google Services | analytics, tagmanager, gstatic, googleapis, googleusercontent | script-src, style-src, img-src, connect-src, font-src |
| Facebook / Instagram | connect.facebook.net, <www.facebook.com>, graph.facebook.com | script-src, img-src, connect-src |
| Twitter / X | platform.twitter.com, cdn.syndication.twimg.com, abs.twimg.com | script-src, img-src |
| assets.pinterest.com, s.pinimg.com | script-src, img-src | |
| platform.linkedin.com, <www.linkedin.com> | script-src, img-src, connect-src | |
| TikTok | sdk.tt.io, analytics.tiktok.com | script-src, img-src |
| Cloudflare | cdnjs.cloudflare.com, ajax.cloudflare.com | script-src, style-src, img-src, connect-src |
| jsDelivr | cdn.jsdelivr.net | script-src, style-src, img-src, connect-src, font-src |
| Tailwind | cdn.tailwindcss.com | script-src, style-src |
| cdnjs | cdnjs.cloudflare.com | script-src, style-src, img-src, connect-src, font-src |
| Fontsource | cdn.fontsource.org, api.fontsource.org | font-src, style-src |
| Stripe | js.stripe.com, checkout.stripe.com, api.stripe.com | script-src, img-src, connect-src, frame-src |
| PayPal | <www.paypal.com>, api.paypal.com, <www.paypalobjects.com> | script-src, img-src, connect-src, frame-src |
| Hotjar | static.hotjar.com, script.hotjar.com, vars.hotjar.com | script-src, img-src, connect-src |
| Klaviyo | static.klaviyo.com, a.klaviyo.com | script-src, img-src, connect-src |
| Contentsquare | tag.contentsquare.com, unsecure.contentsquare.com | script-src, img-src, connect-src |
| Trustpilot | widget.trustpilot.com, api.trustpilot.com | script-src, img-src, connect-src |
| Sentry | js.sentry-cdn.com, o*.ingest.sentry.io | script-src, connect-src |
| YouTube / Vimeo | <www.youtube.com>, <www.youtube-nocookie.com>, player.vimeo.com | script-src, img-src, connect-src, frame-src |
Layer 3 — Admin Custom Whitelist
Six multi-line textarea fields under Stores → Configuration → CSP Whitelisting:
| Field | Config Path | Directive |
|---|---|---|
| Script Sources | Csp/policies/script_src |
script-src |
| Style Sources | Csp/policies/style_src |
style-src |
| Image Sources | Csp/policies/img_src |
img-src |
| Connect Sources | Csp/policies/connect_src |
connect-src |
| Font Sources | Csp/policies/font_src |
font-src |
| Frame Sources | Csp/policies/frame_src |
frame-src |
System Requirements
| Requirement | Version |
|---|---|
| Magento | 2.4.x (Open Source / Commerce) |
| PHP | 8.1 — 8.4 |
| Magento Framework | ^103.0.0 |
| HK2 Core | ^1.0 |
| Magento_Csp | Bundled with Magento |
| Browser | CSP-supporting (all modern browsers) |
Installation
composer require hk2/csp php bin/magento module:enable HK2_Csp php bin/magento setup:upgrade php bin/magento cache:clean config
See docs/installation.md for full instructions including verification steps.
Configuration
- Navigate to Stores → Configuration → CSP Whitelisting.
- Select the store view (website/store level).
- Enter one host per line in the desired directive field(s).
- Save config.
- Flush the Magento cache (
php bin/magento cache:flush config).
Reset Custom Whitelist
Click Reset Custom CSP Whitelist to clear all six custom fields from the database for the current scope. This does not affect the pre-built csp_whitelist.xml or the base csp.xml.
CSP in Magento 2
By default Magento ships with Content-Security-Policy headers in Report-Only mode. This module follows the same approach — violations are logged but never blocked.
- Production: switch to enforcement mode by editing
etc/csp.xml(changereport-onlytoenforce). - Development: monitor violations in browser console and at the configured report-uri endpoint.
- Testing: use Chrome DevTools or Firefox CSP Inspector to validate directive coverage.
Privacy & GDPR
This module does not:
- Collect, transmit, or store personal data.
- Set cookies or access browser storage.
- Load external resources on its own (whitelist is security metadata, not executable code).
The CSP whitelist only allows — it does not fetch. Any data collection is performed solely by the third-party services whose hosts you whitelist, and is subject to their respective privacy policies.
Documentation
| Document | Description |
|---|---|
| README.md | This file |
| docs/installation.md | Installation & verification |
| docs/usage.md | Architecture, admin guide, best practices |
| docs/compatibility.md | Platform & browser support |
| CHANGELOG.md | Version history |
| SECURITY.md | Vulnerability reporting |
Known Limitations
- No CSP reporting endpoint — Magento expects you to configure your own report-uri (e.g.
report-uri.com, a self-hosted collector, or Sentry). This module respects whatever reporting configuration you set inetc/csp.xml. - No
report-toheader support — Magento's CSP framework uses the olderreport-uridirective. - Wildcard sources — not included in the pre-built whitelist by design; use admin custom fields if you need them.
strict-dynamic— not enabled; Magento's CSP framework does not natively support thestrict-dynamictoken.
Contributing
Contributions are welcome. Please open an issue or pull request on the GitHub repository.
Guidelines
- Follow PSR-12 and Magento 2 coding standards.
- Add or update tests for any new whitelist entries.
- Verify hosts serve content over HTTPS.
- Avoid wildcard (
*) entries in the pre-built whitelist. - Keep
csp_whitelist.xmlentries alphabetically sorted by host.
License
OSL-3.0 — Open Software License 3.0
This license requires that any derivative work distributed as a whole must be made available under the same license terms. See LICENSE for full text.
AFL-3.0 — Academic Free License 3.0 (alternate license for certain jurisdictions).
Disclaimer
THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. The authors and Super Market Depot shall not be held liable for any damages arising from the use of this software. The pre-built CSP whitelist is provided as a convenience and may not cover all third-party hosts used by your store. Always audit CSP policies in a staging environment before deploying to production.
hk2/csp 适用场景与选型建议
hk2/csp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 686 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 06 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「extension」 「csp」 「magento2」 「HK2」 「HK2_Csp」 「Whitelist URL CSP」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hk2/csp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hk2/csp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hk2/csp 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Russian Language Pack for Magento 2
DPD Magento2 Shipping extension
Setup CSP Headers for a website
Middleware to add the Content-Security-Policy header to the response
A custom URL rule class for Yii 2 which allows to create translated URL rules
SilverStripe Content Security Policy module
统计信息
- 总下载量: 686
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 34
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: OSL-3.0
- 更新时间: 2022-06-16