fix(dashboard): serve tailwind/htmx/alpine locally instead of from CDNs (#2734)

## Description

The dashboard loaded all three of its front-end dependencies from
third-party CDNs at page load:

```html
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script src="https://unpkg.com/alpinejs@3.13.3/dist/cdn.min.js" defer></script>
```

Microsoft Edge's Tracking Prevention classifies `unpkg.com` as a tracker
and blocks it by default on Windows; locked-down corporate proxies block
both hosts. On those machines none of the three scripts executed — no
Tailwind CSS, no htmx polling, no Alpine bindings, plus an uncaught
`ReferenceError: tailwind is not defined` from the inline
`tailwind.config` assignment at `dashboard.html:21`. The dashboard
rendered blank. Reported from a Windows user's console:

```text
Tracking Prevention blocked access to storage for https://unpkg.com/htmx.org@1.9.10.
Tracking Prevention blocked access to storage for https://unpkg.com/alpinejs@3.13.3/dist/cdn.min.js.
```

This vendors the three files and serves them from the proxy, so the
dashboard has no external network dependency at all.

Note for anyone triaging the same report: the `cdn.tailwindcss.com
should not be used in production` line in that console output is **not**
related. It is an unconditional `console.warn` in the Tailwind Play CDN
build (no hostname guard), so it fires on every load, localhost
included, and it still fires now that the bundle is self-hosted.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Vendored
`headroom/dashboard/static/{tailwind.min.js,htmx.min.js,alpine.min.js}`
— Tailwind Play CDN 3.4.17, htmx 1.9.10, Alpine 3.13.3, byte-for-byte as
published.
- `headroom/dashboard/__init__.py`: added `STATIC_DIR`.
- `headroom/proxy/server.py`: mounted `/dashboard/static`, registered
**before** `register_provider_routes`' catch-all so the asset requests
are not tunneled to the wrapped upstream provider (same ordering
constraint as the `/favicon.ico` route, GH #1787). `check_dir=False` so
a missing assets directory 404s the dashboard JS rather than aborting
proxy startup.
- `headroom/dashboard/templates/{dashboard,settings}.html`: script `src`
→ `/dashboard/static/…`.
- `NOTICE`: MIT / 0BSD attribution for the three vendored bundles.
- `tests/test_dashboard_static_assets.py`: new.

No packaging change needed — `[tool.maturin]` includes everything under
`headroom/`, so the wheel picks the assets up. Wheel grows ~498 KB (407
KB of that is the Tailwind Play bundle).

## Testing

- [x] Unit tests pass (`pytest`) — targeted, see note under *Not tested*
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_dashboard_static_assets.py tests/test_proxy_settings_endpoints.py -q
tests/test_dashboard_static_assets.py ......                             [ 21%]
tests/test_proxy_settings_endpoints.py ......................            [100%]
============================== 28 passed in 4.47s ==============================

$ ruff check .
All checks passed!

$ ruff format --check headroom/proxy/server.py headroom/dashboard/__init__.py tests/test_dashboard_static_assets.py
3 files already formatted

$ mypy headroom
Success: no issues found in 509 source files
```

## Real Behavior Proof

- **Environment:** macOS 15 (Darwin 25.4.0), Python 3.12.6, headless
Chromium via Playwright, proxy served in-process with
`create_app(ProxyConfig(optimize=False, cache_enabled=False,
log_full_messages=True))` on `:8787`.
- **Exact command / steps:** loaded `/dashboard` and
`/dashboard/settings` with `wait_until="networkidle"`, then asserted the
globals exist, that Tailwind actually generated CSS (computed style of a
`px-3` element), and recorded every non-localhost request plus all
`pageerror`/`console.error` events.
- **Observed result:**

```text
/dashboard          | alpine: True | tailwind css: True | external: none | errors: none
/dashboard/settings | alpine: True | tailwind css: True | external: none | errors: none

/dashboard                        200 text/html; charset=utf-8  191549
/dashboard/static/tailwind.min.js 200 text/javascript; charset=utf-8  407279
/dashboard/static/htmx.min.js     200 text/javascript; charset=utf-8   47755
/dashboard/static/alpine.min.js   200 text/javascript; charset=utf-8   43441

feed-toggle visible: True
alpine loaded: True  htmx: True  tailwind: True
tailwind applied (px-3 padding): 12px
external hosts: none
console errors: none
```

Zero external requests on either page, so the Edge/firewall failure mode
is structurally gone rather than worked around.

- **Not tested:**
- No Windows machine available — the fix is verified as "makes zero
external requests", which is the property the Windows failure depended
on, but it has not been confirmed against Edge with Tracking Prevention
on. Worth a check by someone on Windows before release.
  - Full `pytest` suite not run (targeted runs only); CI covers it.
- `tests/test_dashboard/test_live_feed.py` still has 2 failures, both
pre-existing and unrelated: those tests need a manually started proxy on
`:8787` with `--log-messages`, and `test_live_feed_button_exists`
asserts `is_visible()` with no wait for the `/stats` poll that flips
`log_full_messages`. The other 2 in that file pass against this change,
which is itself end-to-end evidence that Alpine and htmx work from the
vendored bundles.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

- No issue number: reported directly rather than filed, so `Closes #` is
omitted. Closed #22 ("Dashboard is not working") and closed #533
(Windows cp949 `get_dashboard_html()`) are different failures.
- **Docs checklist item is N/A** — nothing user-facing changes; the
dashboard URL and behaviour are identical.
- Deliberately **not** switching to a real Tailwind CLI build. It would
cut 407 KB to ~20 KB and silence the production warning, but it puts
Node in the release path and silently leaves any class added to the
2,713-line template unstyled with no CI guard. The Play bundle behaves
exactly as it does today, just served locally. Worth revisiting if wheel
size becomes a problem (note the PyPI project-size ceiling).
- Upgrades are now manual: bumping these three means re-downloading the
files. Pinned versions are recorded in `NOTICE`.
This commit is contained in:
Tejas Chopra 2026-08-03 06:07:27 -07:00 committed by GitHub
parent a70e5ff78d
commit 7c9b046595
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 215 additions and 8 deletions

14
NOTICE
View file

@ -41,3 +41,17 @@ NumPy (optional dependency)
Copyright (c) 2005-2024, NumPy Developers
Licensed under the BSD 3-Clause License
https://github.com/numpy/numpy
Vendored dashboard assets (headroom/dashboard/static/)
------------------------------------------------------
Tailwind CSS 3.4.17 (Play CDN build) — MIT License
Copyright (c) Tailwind Labs, Inc.
https://github.com/tailwindlabs/tailwindcss
htmx 1.9.10 — Zero-Clause BSD License
Copyright (c) 2020, Big Sky Software
https://github.com/bigskysoftware/htmx
Alpine.js 3.13.3 — MIT License
Copyright (c) 2019-2025 Caleb Porzio and contributors
https://github.com/alpinejs/alpine

View file

@ -4,6 +4,10 @@ from pathlib import Path
DASHBOARD_DIR = Path(__file__).parent
TEMPLATES_DIR = DASHBOARD_DIR / "templates"
# Vendored tailwind/htmx/alpine. Served locally because Edge's Tracking
# Prevention and corporate proxies block unpkg.com/cdn.tailwindcss.com, which
# left the dashboard unstyled and dataless on some Windows machines.
STATIC_DIR = DASHBOARD_DIR / "static"
def get_dashboard_html() -> str:

File diff suppressed because one or more lines are too long

1
headroom/dashboard/static/htmx.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -4,9 +4,9 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Headroom Dashboard</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script src="https://unpkg.com/alpinejs@3.13.3/dist/cdn.min.js" defer></script>
<script src="/dashboard/static/tailwind.min.js"></script>
<script src="/dashboard/static/htmx.min.js"></script>
<script src="/dashboard/static/alpine.min.js" defer></script>
<script>
(function() {
const saved = localStorage.getItem('headroom-theme');

View file

@ -4,8 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Headroom Settings</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/alpinejs@3.13.3/dist/cdn.min.js" defer></script>
<script src="/dashboard/static/tailwind.min.js"></script>
<script src="/dashboard/static/alpine.min.js" defer></script>
<script>
(function () {
const saved = localStorage.getItem('headroom-theme');

View file

@ -3353,6 +3353,20 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
content={"applied": applied, "runtime_env": runtime_env.effective_runtime_env()},
)
# Vendored dashboard JS (tailwind/htmx/alpine). Mounted before
# register_provider_routes' catch-all so it is not tunneled upstream.
from starlette.staticfiles import StaticFiles
from headroom.dashboard import STATIC_DIR
# check_dir=False keeps a missing assets directory from aborting proxy
# startup: the dashboard JS 404s, but proxying itself still works.
app.mount(
"/dashboard/static",
StaticFiles(directory=STATIC_DIR, check_dir=False),
name="dashboard-static",
)
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard():
"""Serve the Headroom dashboard UI."""

View file

@ -17,7 +17,11 @@ from urllib.parse import urlsplit
import pytest
from headroom.dashboard import get_dashboard_html
from tests.test_dashboard_cache_ttl_playwright import _sample_history, _sample_stats
from tests.test_dashboard_cache_ttl_playwright import (
_fulfill_static_asset,
_sample_history,
_sample_stats,
)
playwright = pytest.importorskip("playwright.sync_api")
Page = playwright.Page
@ -52,6 +56,8 @@ def _install_dashboard_routes(page: Page, stats: dict) -> None:
if path in ("/dashboard", "/"):
route.fulfill(status=200, content_type="text/html", body=dashboard_html)
return
if _fulfill_static_asset(route, path):
return
if "/stats-history" in path:
route.fulfill(status=200, content_type="application/json", body=json.dumps(history))
return

View file

@ -18,7 +18,11 @@ from urllib.parse import urlsplit
import pytest
from headroom.dashboard import get_dashboard_html
from tests.test_dashboard_cache_ttl_playwright import _sample_history, _sample_stats
from tests.test_dashboard_cache_ttl_playwright import (
_fulfill_static_asset,
_sample_history,
_sample_stats,
)
playwright = pytest.importorskip("playwright.sync_api")
Page = playwright.Page
@ -56,6 +60,8 @@ def _install_dashboard_routes(page: Page, stats: dict) -> None:
if path in ("/dashboard", "/"):
route.fulfill(status=200, content_type="text/html", body=dashboard_html)
return
if _fulfill_static_asset(route, path):
return
if "/stats-history" in path:
route.fulfill(status=200, content_type="application/json", body=json.dumps(history))
return

View file

@ -9,7 +9,7 @@ from urllib.parse import urlsplit
import pytest
from headroom.dashboard import get_dashboard_html
from headroom.dashboard import STATIC_DIR, get_dashboard_html
playwright = pytest.importorskip("playwright.sync_api")
Page = playwright.Page
@ -153,6 +153,25 @@ def _sample_history() -> dict:
}
def _fulfill_static_asset(route, path: str) -> bool: # type: ignore[no-untyped-def]
"""Serve the vendored dashboard JS from disk; True when it handled the route.
The harnesses in this file and its siblings intercept every request, so the
dashboard's relative asset URLs would otherwise fall through to a real fetch
against a fake origin with nothing listening. Alpine has to load: every
section of <main> lives inside a `<template x-if>`, which renders nothing at
all without it, so an empty <main> is the symptom to look for here.
"""
if not path.startswith("/dashboard/static/"):
return False
route.fulfill(
status=200,
content_type="text/javascript",
body=(STATIC_DIR / Path(path).name).read_bytes(),
)
return True
def _install_dashboard_routes(page: Page) -> None:
stats = _sample_stats()
history = _sample_history()
@ -167,6 +186,8 @@ def _install_dashboard_routes(page: Page) -> None:
if path in ("/dashboard", "/"):
route.fulfill(status=200, content_type="text/html", body=dashboard_html)
return
if _fulfill_static_asset(route, path):
return
if "/stats-history" in path:
route.fulfill(
status=200,

View file

@ -0,0 +1,53 @@
"""The dashboard must not depend on third-party CDNs.
Edge's Tracking Prevention (and corporate proxies) block unpkg.com and
cdn.tailwindcss.com, which left the dashboard unstyled and dataless on some
Windows machines. Tailwind/htmx/alpine are vendored and served locally instead.
"""
from __future__ import annotations
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient # noqa: E402
from headroom.dashboard import get_dashboard_html, get_settings_html # noqa: E402
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
ASSETS = ["tailwind.min.js", "htmx.min.js", "alpine.min.js"]
@pytest.fixture
def client():
app = create_app(
ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
)
)
with TestClient(app) as c:
yield c
@pytest.mark.parametrize("html", [get_dashboard_html(), get_settings_html()])
def test_templates_reference_no_cdn(html: str):
assert "unpkg.com" not in html
assert "cdn.tailwindcss.com" not in html
@pytest.mark.parametrize("asset", ASSETS)
def test_asset_is_served(client, asset: str):
resp = client.get(f"/dashboard/static/{asset}")
assert resp.status_code == 200, resp.text
assert len(resp.content) > 10_000
def test_dashboard_only_references_served_assets(client):
html = client.get("/dashboard").text
for asset in ASSETS:
assert f"/dashboard/static/{asset}" in html