hk2 / csp
Magento 2 module to manage CSP whitelisted URLs
Package info
github.com/basantmandal/magento2-csp-whitelisting-module
Type:magento2-module
pkg:composer/hk2/csp
Requires
- php: ^8.1 || ^8.2 || ^8.3 || ^8.4
- hk2/core: ^1.0
- magento/framework: ^103.0.0
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.