Python MIT License Open Source Project

Third-Party Script Monitor in Python: Detect Website Supply-Chain Attacks with SRI & CSP Alerts (Free Code)

Build a third-party script monitor in Python that hashes website scripts, checks SRI and CSP, and alerts on changes, after the Nov 2026 Optimizely attack.

Project Specifications & Technical Summary

Difficulty Beginner
License MIT License
Advertisement

On 16 November 2026, websites like CNN, the BBC and Zoom served malicious JavaScript to their visitors without being hacked themselves. A script they trusted changed. In this tutorial we build a third-party script monitor in Python: a read-only tool that lists every third-party script and stylesheet on your pages, hashes them, checks Subresource Integrity (SRI) and your Content Security Policy (CSP), and alerts you when anything changes.

It is a practical web security project for BTech, MCA and MTech students, and a useful tool for anyone who runs a website. It has a command-line tool, an optional Flask web UI, an offline demo, a baseline-and-diff engine and 27 automated tests.

The complete code of this third-party script monitor is free and open source on GitHub under the MIT License, so you can download it, run the demo in two minutes and extend it for your final-year project.

What Happened in the Optimizely Supply-Chain Attack

Optimizely Web Experimentation is an A/B testing service. Each customer adds one script tag that loads a per-project “snippet” from cdn.optimizely.com. That snippet includes an optional field called Project JavaScript, which is custom code that runs on every page.

According to Report URI’s investigation by Scott Helme (16 Nov 2026), an attacker added a small loader to the Project JavaScript of many customer projects. The rest of each snippet was untouched, and the file was still served from Optimizely’s own domain with Optimizely’s own certificate. Report URI checked 1,611 snippets and found the loader in 188 of them, belonging to 178 organisations, including Zoom, the BBC, CNN, Salesforce, GitLab, IKEA, HSBC and Equifax. It says the real number is likely higher.

Optimizely’s Security Incident Report (17 Nov 2026) says the attacker exploited a flaw in the Web Experimentation account signup flow that let them act as administrator users without their passwords. It says this was not a credentials breach, and that only Web Experimentation was involved.

Timeline of 16 November 2026

Time (UTC)Time (IST, UTC+5:30)EventSource
04:2109:51First injection seen (BBC snippet)Report URI
07:5113:21First malicious code written, per Optimizely’s investigationOptimizely
13:3419:04Optimizely detects the activityOptimizely
13:4319:13Card-skimming code added to the payloadReport URI
16:1021:40Optimizely closes the vulnerabilityOptimizely
21:5203:22 (17 Nov)Only 1 of 188 infected snippets still carries the codeReport URI
22:2403:54 (17 Nov)Optimizely removes injected code from all affected projectsOptimizely
23:1104:41 (17 Nov)Report URI observes every infected file cleanReport URI

The two first-seen times differ because they come from different sources: Report URI’s crawl data and Optimizely’s internal investigation. We show both rather than pick one.

What the injected code did

We will not reproduce the malware. At a high level, Report URI, BleepingComputer (16 Nov 2026) and The Hacker News (17 Nov 2026) describe a multi-purpose kit that:

  • swapped cryptocurrency wallet addresses on the page and in the clipboard for the attacker’s;
  • skimmed card numbers, expiry dates and CVVs typed into the site’s own forms (cards entered in hosted payment iframes such as Stripe or Adyen were out of reach);
  • sent cookies that were not marked HttpOnly, plus page screenshots, to the attacker;
  • loaded iOS exploit kits (identified as Coruna and DarkSword) on iPhones and iPads running older iOS versions.

Report URI recorded about $7,000 in crypto sent to the attacker’s wallets on 16 November. Nobody has published how many cards or cookies were taken. Malwarebytes (17 Nov 2026) notes that BuiltWith detects Optimizely on roughly 190,000 live websites, which is its overall usage, not the number affected.

“The uncomfortable lesson is that none of the victims were breached. Their own infrastructure was untouched; a vendor’s script turned hostile and their sites served it to every visitor.” — Scott Helme, speaking to TechTarget (17 Nov 2026)

Why SRI Alone Could Not Stop It, and What CSP Did

Subresource Integrity lets you add a hash to a script tag: integrity="sha384-…". If the file changes, the browser refuses to run it. That is perfect for a fixed, versioned library. But an Optimizely snippet changes every time an experiment is published, so, as Mark Stott explains on Optimizely World (17 Nov 2026), pinning it to a fixed hash is not practical.

A Content Security Policy controls where scripts can load from and where data can go. It could not tell that code from a trusted origin was dishonest, but it could block the next steps. Report URI checked the CSPs of the affected organisations’ sites:

CSP situationSites
No CSP at all68
CSP allowed both the payload and the data theft50
Payload ran, but connect-src blocked the data theft17
Restrictive script-src blocked the payload outright24

Two CSP keywords undid otherwise good policies. 'strict-dynamic' passes trust from a trusted script to any script it adds, so the compromised snippet could load the payload from a new host. 'unsafe-eval' let an inline eval() fallback run on one large bank that had blocked the remote file.

So the defence has three layers: SRI where files are static, a strict CSP everywhere, and monitoring for the files you cannot pin. That third layer is exactly what our third-party script monitor does.

What Is a Third-Party Script Monitor?

A third-party script monitor is a tool that regularly loads your web pages, records every external script and stylesheet they include, stores a hash of each file, and compares each new scan with a saved “known good” baseline. When a new domain appears, a trusted file’s hash changes, an integrity attribute disappears or the CSP gets weaker, it raises an alert.

Our version is strictly defensive. It only makes ordinary GET requests, reads files as text and never executes JavaScript.

Features of the Third-Party Script Monitor

  • Resource inventory: external scripts, stylesheets, modulepreload/preload files, WP Rocket lazy-loaded scripts, and hashes of inline scripts.
  • First-party vs third-party classification, with --first-party for your own CDN.
  • Hashing: SHA-256 for change detection and a ready-to-paste sha384-… SRI value.
  • SRI checks: missing, malformed, mismatched and missing crossorigin.
  • CSP review: missing or report-only policy, 'unsafe-inline', 'unsafe-eval', 'strict-dynamic', * and https: sources, missing connect-src, object-src, base-uri and reporting.
  • Baseline diff: new third-party hosts, changed file hashes, new hosts referenced inside a changed script, new risky patterns such as atob or sendBeacon, SRI removed, CSP weakened.
  • Reports in the terminal, JSON and a self-contained HTML file, plus a 0–100 score and a verdict.
  • CI-friendly: --fail-on high exits with code 1, with a ready GitHub Actions example.
  • Optional Flask web UI with an offline demo shop.

Tech Stack and Requirements

PartTechnology
LanguagePython 3.9+ (scanner and CLI use only the standard library)
HTML parsinghtml.parser from the standard library
Hashinghashlib + base64 (SHA-256, SHA-384, SHA-512)
Web UIFlask 3 (optional)
Testingpytest
HardwareAny laptop; no GPU, no paid API. The demo works offline.

New to Flask? Warm up with our Flask web chat application tutorial.

Project Structure

Third-Party-Script-Monitor-Python/
├── script_monitor/
│   ├── cli.py          # scan / demo / csp / sri commands
│   ├── scanner.py      # inventory, hashing, per-file findings
│   ├── htmlparse.py    # finds <script>, <link>, inline scripts, CSP <meta>
│   ├── sri.py          # compute and verify integrity values
│   ├── csp.py          # parse, review and compare policies
│   ├── baseline.py     # save baselines and diff snapshots
│   ├── fetcher.py      # HTTP fetcher + offline fixture fetcher
│   ├── findings.py     # severities, score, verdict
│   └── report.py       # text, JSON and HTML reports
├── app.py              # optional Flask web UI
├── templates/ static/  # web UI files
├── examples/demo-site/ # harmless offline demo shop (v1 and v2)
└── tests/              # 27 pytest tests

How the Third-Party Script Monitor Works

Step 1: Parse the page and collect resources

Python’s built-in HTMLParser walks the HTML. Every <script src>, stylesheet and script preload is recorded with its attributes, and relative URLs are resolved against the page (and any <base> tag).

def handle_starttag(self, tag, attrs):
    a = {k.lower(): (v if v is not None else "") for k, v in attrs}
    if tag == "base" and a.get("href") and self.base_href is None:
        self.base_href = a["href"]
    elif tag == "meta" and a.get("http-equiv", "").lower() == "content-security-policy":
        if a.get("content"):
            self.meta_csp.append(a["content"])
    elif tag == "script":
        # data-rocket-src / data-src: lazy-loaded scripts (WP Rocket and similar plugins)
        src = a.get("src") or a.get("data-rocket-src") or a.get("data-src")
        if src:
            self.resources.append({"kind": "script", "src": src, "attrs": a})
        else:
            self._in_script, self._script_attrs, self._buf = True, a, []
    elif tag == "link":
        rels = set(a.get("rel", "").lower().split())
        if a.get("href") and rels & LINK_RELS:
            if "preload" in rels and a.get("as", "").lower() not in ("script", "style"):
                return
            kind = "stylesheet" if ("stylesheet" in rels or a.get("as") == "style") else "script-preload"
            self.resources.append({"kind": kind, "src": a["href"], "attrs": a})

Step 2: Decide what is third-party

A file is first-party when it comes from the same registrable domain as the page, so static.shop.in belongs to www.shop.in. The helper understands two-level suffixes such as co.in and co.uk.

def site_of(host: str) -> str:
    """Approximate registrable domain: news.bbc.co.uk -> bbc.co.uk, cdn.example.com -> example.com."""
    labels = [x for x in (host or "").lower().strip(".").split(".") if x]
    if len(labels) <= 2:
        return ".".join(labels)
    if len(labels[-1]) == 2 and labels[-2] in TWO_LEVEL_SUFFIXES:
        return ".".join(labels[-3:])
    return ".".join(labels[-2:])


def is_third_party(host: str, page_host: str, first_party: tuple[str, ...] = ()) -> bool:
    site = site_of(host)
    if site == site_of(page_host):
        return False
    return not any(host == fp or host.endswith("." + fp) for fp in first_party)

Step 3: Hash every file and check SRI

Each file is downloaded once (5 MB limit) and hashed. If the tag has an integrity attribute, we verify it the same way a browser does: only the strongest algorithm listed counts.

Advertisement
def check(value: str | None, body: bytes | None) -> str:
    """Return one of: missing, invalid, unfetched, ok, mismatch."""
    if value is None or not value.strip():
        return "missing"
    tokens = parse_integrity(value)
    if not tokens:
        return "invalid"
    if body is None:
        return "unfetched"
    # Browsers only use the strongest algorithm present.
    strongest = max(ALGOS.index(a) for a, _ in tokens)
    wanted = [d for a, d in tokens if ALGOS.index(a) == strongest]
    actual = integrity(body, ALGOS[strongest]).split("-", 1)[1]
    return "ok" if actual in wanted else "mismatch"

Step 4: Review the Content Security Policy

The CSP is read from the Content-Security-Policy header (or a <meta> tag). The default-src fallback is respected, and each risky setting becomes a finding with an explanation.

used, script = effective(d, "script-src")
if script is None:
    f.append(Finding("high", "CSP_NO_SCRIPT_SRC", "No script-src or default-src" + label,
                     "The policy does not restrict where scripts load from."))
else:
    low = [s.lower() for s in script]
    if "*" in low:
        f.append(Finding("high", "CSP_SCRIPT_WILDCARD", f"{used} allows '*'" + label,
                         "Scripts can load from any host, so the policy gives no supply-chain protection."))
    schemes = sorted(set(low) & SCHEME_SOURCES)
    if schemes:
        f.append(Finding("high", "CSP_SCRIPT_SCHEME", f"{used} allows scheme sources {' '.join(schemes)}" + label,
                         "A bare scheme such as https: acts as a wildcard for every host on that scheme."))
    if "'unsafe-inline'" in low and not _has_nonce_or_hash(low) and "'strict-dynamic'" not in low:
        f.append(Finding("high", "CSP_UNSAFE_INLINE", f"{used} allows 'unsafe-inline'" + label,
                         "Inline script injection (XSS) is not blocked. Use nonces or hashes instead."))
    if "'unsafe-eval'" in low:
        f.append(Finding("high", "CSP_UNSAFE_EVAL", f"{used} allows 'unsafe-eval'" + label,
                         "eval() and new Function() are allowed. In the Optimizely incident an inline eval() "
                         "fallback still ran on a site that blocked the remote payload because of this keyword."))
    if "'strict-dynamic'" in low:
        f.append(Finding("medium", "CSP_STRICT_DYNAMIC", f"{used} uses 'strict-dynamic'" + label,
                         "Any script added by a trusted script is also trusted and host allow-lists are ignored. "
                         "If a trusted vendor script is compromised, the scripts it injects run too."))
    broad = [s for s in script if s.startswith("*.") or "://*." in s]
    if broad:
        f.append(Finding("low", "CSP_SCRIPT_HOST_WILDCARD", f"{used} allows wildcard hosts: {', '.join(broad[:5])}" + label,
                         "Prefer exact hostnames so a takeover of one sub-domain cannot serve scripts."))

Step 5: Save a baseline and diff every new scan

The first scan is saved as JSON. Later scans are compared with it. This is the heart of the third-party script monitor: a changed hash on a vendor file, a new host referenced inside it, or a brand-new script domain are the signals Report URI said would have exposed the Optimizely attack.

for url in sorted(o.keys() & n.keys()):
    a, b = o[url], n[url]
    if a.get("sha256") and b.get("sha256") and a["sha256"] != b["sha256"]:
        sev = "medium" if b["third_party"] else "low"
        f.append(Finding(sev, "CONTENT_CHANGED", f"{b['kind'].capitalize()} content changed (same URL)",
                         f"sha256 {a['sha256'][:12]}… → {b['sha256'][:12]}…, size {a.get('size')} → {b.get('size')} bytes.", url))
        new_refs = sorted(set(b.get("referenced_hosts", [])) - set(a.get("referenced_hosts", [])))
        if new_refs:
            f.append(Finding("high", "NEW_REFERENCED_HOST", "Changed script now references new host(s)",
                             ", ".join(new_refs) + ". A loader added to a trusted file usually looks like this.", url))
        new_hints = sorted(set(b.get("hints", [])) - set(a.get("hints", [])))
        if new_hints:
            f.append(Finding("high" if b["third_party"] else "medium", "NEW_RISKY_PATTERN",
                             "Changed script gained risky patterns", ", ".join(new_hints), url))

Installation and Running the Project

git clone https://github.com/GetProjectsIdea/Third-Party-Script-Monitor-Python.git
cd Third-Party-Script-Monitor-Python
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt

# 1. Offline demo (no internet needed)
python -m script_monitor demo

# 2. Scan your own site; the first run creates the baseline
python -m script_monitor scan https://your-site.example/ --baseline baseline.json --html report.html

# 3. Review a CSP before you deploy it
python -m script_monitor csp "default-src 'self'; script-src 'self' 'unsafe-eval'"

# 4. Generate an SRI value for a library you are adding
python -m script_monitor sri https://cdn.example/[email protected]/lib.min.js

# 5. Optional web UI at http://127.0.0.1:5000
python app.py

Output and Screenshots

The demo uses a harmless fake shop with two versions. Version 2 imitates the outside view of a script supply-chain incident: a vendor snippet gains extra code that references a new host, a pinned library changes, an integrity attribute is removed, a new widget domain appears and the CSP gains 'unsafe-eval', 'strict-dynamic' and connect-src https:.

Third-party script monitor report showing changes since baseline: new host, changed hash, SRI removed and weaker CSP
Version 2 of the demo shop compared with its baseline: every supply-chain signal is flagged.
Third-party script monitor CLI output in the terminal with colour-coded severities
The same demo in the terminal: resource inventory, SRI status, hashes and changes.

The web UI lets you scan up to ten URLs, save a baseline, or run the offline demo with two clicks:

Home page of the third-party script monitor Flask web UI
The optional Flask web UI with the offline demo buttons.
Mobile view of the third-party script monitor report
The report on a 390 px mobile screen.

How to Monitor Your Own Website Every Day

SRI and CSP are set once, but a third-party script monitor has to run often. The repo ships examples/github-actions-monitor.yml, a workflow that scans your pages every six hours, compares them with a committed baseline and fails (so GitHub emails you) when a high or critical change appears. A simple cron job works too:

# crontab -e  (every 6 hours)
17 */6 * * * cd /opt/monitor && .venv/bin/python -m script_monitor scan \
    --urls-file urls.txt --baseline baseline.json --html report.html --fail-on high

When an alert fires, find who added the new tag, diff the changed file against your baseline copy, and ask the vendor before you accept it with --update-baseline.

Hardening Checklist: SRI, CSP and Third-Party Scripts

  1. Pin static, versioned third-party files with SRI and crossorigin="anonymous", or self-host them.
  2. Enforce a CSP with an explicit script-src host list and a tight connect-src.
  3. Avoid 'unsafe-eval', bare https: and *. Use nonces or hashes instead of 'unsafe-inline', and use 'strict-dynamic' only as a deliberate choice.
  4. Add object-src 'none', base-uri 'self' and report-to so the browser reports violations to you.
  5. Keep marketing and A/B testing tags off checkout pages, and take card details in the payment provider’s hosted iframe.
  6. Mark session cookies HttpOnly and Secure.
  7. Run the third-party script monitor on a schedule and review every change.

Testing the Project

The project ships with 27 pytest tests covering SRI maths, HTML parsing, third-party detection, every CSP rule, CSP comparison, scans of both demo versions, baseline create/compare/update, path-escape safety in the fixture fetcher, a real local HTTP server, the CLI, HTML escaping in reports and the Flask UI (including blocking private addresses).

$ python -m pytest -q
...........................                              [100%]
27 passed in 0.75s

Limitations and Responsible Use

The third-party script monitor reads HTML and files; it does not run a browser. Scripts injected at runtime by other scripts show up only through the “referenced hosts” and “risky patterns” signals of the parent file, so pair it with CSP violation reports. Some vendors serve different code per browser or region, so a hash change is a reason to review, not proof of an attack.

Scan only websites you own or are allowed to test. The tool is for detection and hardening, not for attacking anyone.

Future Scope and Viva Tips

  • Use Playwright to record scripts that load at runtime and network destinations.
  • Store every changed file so you can diff old and new code line by line.
  • Send alerts to email, Slack or Telegram.
  • Add a CSP violation-report endpoint to the Flask app.
  • Measure how often popular vendor scripts change, as a small research study.

Yesterday we built an AI coding agent security scanner in Python that checks repos before you open them; this project protects the website side of the supply chain. For a research angle, browse the security sections of our AI PhD thesis topics 2026 and MTech thesis ideas, or pick more projects from our 50 major project ideas for BTech and MCA. Stuck on an error? Read 13 reasons why your code is not working.

FAQs: Third-Party Script Monitor

Is this third-party script monitor a good final-year project?

Yes. It covers web security, HTTP, HTML parsing, hashing, CSP, JSON storage, a Flask web app and automated testing, and it is built around a real November 2026 incident that examiners will recognise.

Does the tool run any JavaScript from the sites it scans?

No. It downloads files as text, hashes and searches them. It never executes them.

Would it have caught the Optimizely attack?

It would have flagged the changed snippet hash, the new host referenced inside it and, with frequent scans, the change on the same day. Report URI says those kinds of signals would have exposed the attack. Blocking still needs a strict CSP.

Why not just add SRI to every script?

Because some vendor files, such as A/B testing snippets and tag managers, change every time someone edits a dashboard. SRI would break them. Monitor those files and restrict them with CSP.

Does the repo contain malware samples?

No. The demo uses harmless placeholder files on reserved .example domains.

Is the source code free?

Yes. The full code is on GitHub under the MIT License.

References


Download the Source Code

The complete third-party script monitor project, with the CLI, Flask web UI, offline demo, README, screenshots, GitHub Actions example and tests, is free on GitHub. Clone it, star it and open an issue if you get stuck.

Conclusion

The Optimizely incident showed that a website can serve malware without its own servers ever being touched. In this tutorial you built a third-party script monitor in Python that inventories third-party code, checks SRI and CSP, and tells you the moment a trusted script changes.

Pin what you can, restrict what you cannot, and watch everything. Built something on top of it? Tell us in the comments below. Happy (and safe) coding!

Advertisement

Team Get Projects

Contributor & Author
View All Projects →

Contributor at GetProjects.org, sharing open-source codebases, tutorials, and practical software architectures.

0 Discussion Comments

Markdown Supported

Join the Discussion & Code Review

Share architectural feedback, benchmark results, or troubleshooting notes.