Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 9 min read

Stop Trusting Third-Party JavaScript by Default: Add a Blast-Radius Limit

A page loads a familiar analytics or experimentation script. The browser connects to the provider's legitimate CDN, receives a file over HTTPS, and runs it with access to the page. Nothing in that sequence looks unusual.

A page loads a familiar analytics or experimentation script. The browser connects to the provider's legitimate CDN, receives a file over HTTPS, and runs it with access to the page. Nothing in that sequence looks unusual. That is precisely why a compromised third-party script is such a powerful delivery path.

On November 16, 2026, Report URI reported that malicious JavaScript reached visitors to 178 organizations through Optimizely Web. It found malicious code in 188 snippets among 1,611 distinct snippets it examined. The modified snippets still came from Optimizely's CDN, and the injected code appeared in customer Project JavaScript. Report URI said the payload could skim payment cards, replace cryptocurrency addresses, steal cookies and screenshots, and deliver iOS exploit kits.[1]

This is not a claim that every third-party script is unsafe, or that one browser header would have prevented every part of this incident. It is a reminder that a trusted vendor URL is not the same thing as trusted, unchanged code. Your page gives every script it runs a powerful position in the user's browser.

This guide turns that risk into a practical engineering task: inventory external scripts, detect unexpected changes, reduce what the browser will execute, and plan a safe path to enforcement. The examples are starting points, not drop-in policies. Test them against your own pages and vendors.

First, understand the boundary

A script executing in a page can generally read and change that page's DOM, interact with browser storage available to the page, and make authenticated requests as the user.[2] A content security policy (CSP) can limit some resource loads and script execution, but it does not turn a script you trust into a sandbox.[2]

Third-party tags can execute with the user's granted privileges, and unmanaged changes may alter the host application's data flows.[5] That distinction matters in the Optimizely report.[1] The attack did not need a malicious-looking domain in the page's original markup. Customer pages already loaded a vendor snippet from a domain they trusted. The reported malicious code was added to the snippet's project-specific JavaScript, while the delivered file still came from the expected CDN.[1]

Think of this as a supply-chain boundary with three separate questions:

  • Who may change the code? Vendor accounts, project editors, CI jobs, and administrators.
  • What code reaches the browser? The exact bytes, including dynamic or account-managed configuration.
  • What can that code do? The page data, network destinations, user actions, and browser APIs available to it.

A host allowlist answers only a slice of the second question. It says where a browser may fetch code from, not whether the bytes at that location are safe today.[2]

Step 1: Build a real inventory

Start with the browser-facing artifacts, not a vendor spreadsheet. A useful inventory records each script's page scope, owner, business purpose, source, loading method, data access, and change process.[5]

For each entry, capture:

  • The exact URL or the code that constructs it.[5]
  • Whether it is static HTML, inserted by a tag manager, or loaded by another script.[5]
  • Which routes load it, and whether it appears on login, checkout, or account pages.[5]
  • The internal team and vendor account responsible for approving changes.[5]
  • The browser data it can access and the network destinations it contacts.[5]
  • How you learn about a change, and how quickly you can disable it.[5]

A simple source search is a useful first pass, though reviewing third-party code can be difficult when it is obfuscated or updated outside your release process.[5]

rg -n 'script|src' src public

This will not discover every runtime-loaded script. A tag manager, application code, or a vendor loader may insert more scripts after page load.[5] Inspect representative pages in browser developer tools, including checkout and logged-in flows. Record the network requests and initiator chain. Treat scripts added by another script as part of that loader's authority, not as unrelated noise.[5]

Next, turn the list into a decision register. Put each script in one of three groups, with a documented defense for the risk it creates.[5]

  • Required and controlled: code you own, built and deployed through your normal release process.[5]
  • Required but externally controlled: vendor code that has a named owner, a documented purpose, and a tested removal path.[5]
  • Unowned or unnecessary: unknown, duplicated, abandoned, or unapproved code. Remove it or identify an accountable owner before leaving it in place.[5]

This is not a one-time audit. Re-run the inventory when a tag manager changes, a vendor is added, a route is redesigned, or a third-party script starts loading new children.[5]

Step 2: Detect changes, not just new domains

A host allowlist can miss a compromise when an approved vendor serves changed JavaScript from its already-approved domain.[5] You need a way to notice material changes in the code and behavior.

For scripts that you can vendor or serve yourself, pin the artifact to a reviewed version. Store its checksum with the release and fail a build if the content changes without an update to the reviewed reference. For an external script that supports stable versioned assets, Subresource Integrity (SRI) lets the browser compare downloaded bytes with a declared cryptographic hash.[3] If the bytes do not match, the browser rejects the resource.[3]

A static SRI example looks like this:

<script
  src="https://cdn.example.test/library/4.2.1/library.min.js"
  integrity="sha384-REPLACE_WITH_THE_VERIFIED_HASH"
  crossorigin="anonymous"></script>

The placeholder is deliberately not a working hash. Generate the value from the exact artifact you reviewed, and verify the provider's cross-origin requirements.[3] Do not copy an integrity value from an unrelated version or treat a hash as proof that the code itself is benign. SRI answers, "Are these the expected bytes?" It does not answer, "Were these bytes safe when we approved them?"[3]

SRI also has limits. It is a poor fit for a vendor script whose contents vary by account, project, or experiment, because legitimate changes alter the hash.[3] It does not automatically pin scripts that the initial script creates dynamically.[3] Do not invent a hash workaround for a changing vendor bundle. Instead, ask whether the vendor provides a stable versioned asset, a self-hosting option, or a way to remove custom executable code from the managed project.

For dynamic scripts, monitor the properties that matter: content hashes where meaningful, script additions, changes to loaded destinations, and changes to the page's sensitive data flows.[5] Alert on a new destination or an unexpected change, then have a clear owner decide whether it is expected. Preserve enough evidence to compare what changed and when. Monitoring is detection, not prevention, so pair it with the browser controls and the ability to disable a script quickly.[5]

Step 3: Add CSP in report-only mode

CSP is a browser-enforced policy that can restrict where scripts and other resources load from, and can block classes of inline JavaScript and risky evaluation.[2] MDN recommends testing a policy with Content-Security-Policy-Report-Only before enforcing it, so teams can see violations without breaking users.[2]

A deliberately narrow example for an application that serves scripts only from its own origin might begin like this:

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; report-uri /csp-report

This is an illustration, not a universal production header. Real applications often need styles, images, API connections, fonts, payments, and embedded content from specific origins.[2] Add only the sources that the application actually requires. Keep script-src and default-src focused; do not make the policy meaningless by adding broad schemes or unsafe-inline simply to silence violations.[2]

For a nonce-based strict policy, the server generates a fresh, unpredictable nonce for each response, places it in the CSP header, and adds the same value only to approved script elements.[2] A conceptual policy might look like:

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-PER_RESPONSE_RANDOM_VALUE'; object-src 'none'; base-uri 'none'

The nonce must be generated securely and must not be reused across responses. The HTML and header must share the same value. A static site cannot safely paste one fixed nonce into every page.[2] If your pages are static, discuss a hash-based policy or another architecture with your platform team instead.[2]

Be especially careful with strict-dynamic. It allows a nonce- or hash-trusted root script to pass trust to scripts it loads.[4] That can make a strict policy practical when a loader has legitimate dynamic children, but it also means the trusted loader can expand the set of executable scripts. If the loader is compromised, the policy may trust its children too.[4] Use it only when you understand and accept that trust chain.[4]

Send reports to an endpoint you control, or a service approved for your data. CSP reports can include page and blocked-resource details.[2] Filter noise, avoid collecting unnecessary user data, and alert on meaningful new script sources or policy violations. A report-only policy is a measurement phase. It does not block the reported action.[2]

Step 4: Enforce gradually and rehearse removal

After reviewing report-only violations, group them by route and owner. Some violations will be genuine features; others may be old tags that nobody remembers. Fix the application or document a narrowly scoped exception. Then enforce the policy for a low-risk route or a small rollout before expanding it.[2]

Before enforcement, test the user journeys that depend on browser scripts: sign-in, checkout, support widgets, analytics consent, and any embedded payment flow. Verify both successful behavior and failure behavior.[2] If a vendor script is blocked, the page should fail safely rather than silently granting broader permissions.

Also rehearse the operational response. Know who can disable a vendor tag, revoke project access, rotate credentials, and remove a script from a high-risk route. Keep an emergency change path that does not depend on the same vendor account you may need to contain.[5] Record the expected rollback action and test it before an incident.

What these controls do not promise

No single control eliminates the risk of third-party JavaScript. CSP can limit sources and execution patterns, but a malicious script already admitted as trusted may still have meaningful access.[2] SRI can detect changed bytes for supported static resources, but may not work for project-specific dynamic scripts.[3] Monitoring can surface unexpected changes, but someone must respond. Vendor review can reduce exposure, but cannot guarantee that a provider's infrastructure or account will never be compromised.

Layering matters because the controls answer different questions:

  • Inventory: Do we know which scripts run and who owns them?
  • Review and integrity: Did the artifact change from the version we approved?
  • CSP: Which script-loading and execution behaviors does the browser permit?
  • Monitoring: What changed in the browser's runtime behavior?
  • Response: Can we disable the integration before more users are exposed?

The useful target is not "trust nothing." It is to make trust explicit, scoped, observable, and reversible.

A checklist to save

Before adding or renewing a third-party script, ask:

  • Does it need to run on every page, especially pages with account or payment data?[5]
  • Is there a stable version or integrity mechanism, or does the vendor generate project-specific code?[5]
  • Which people and systems can change its delivered code?[5]
  • What other scripts and network destinations can it load?[5]
  • Is it covered by a tested CSP and a change-monitoring process?[5]
  • Who can disable it, and how quickly can the change reach production?[5]
  • Have we tested the page when the vendor is unavailable or blocked?[5]

The Optimizely incident is a strong reminder that a familiar CDN hostname is not a security review. Start with the scripts your browser actually executes, narrow their access where practical, and make unexpected changes visible before users have to tell you something is wrong.

I write about practical software engineering, security, and developer tools. Subscribe for more guides focused on concrete implementation trade-offs.

Have you inventoried the third-party scripts on your highest-risk pages? Which control has been hardest to put in place: stable integrity checks, CSP, or a reliable removal path?

Sources

[1] Report URI: World’s Largest Brands Infected With Malware Via Optimizely
[2] MDN: Content Security Policy implementation
[3] MDN: Subresource Integrity implementation
[4] MDN: Content Security Policy
[5] OWASP: Third-Party JavaScript Management Cheat Sheet

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.