## What this does The frontend half of serving the UI apart from the server. The server half was #2362. It gives CoreScope three deployment modes. The server container is the same image in all three, and it still serves everything, the classic UI included. | Mode | The UI is served by | API | Server CORS setting | Logins | |---|---|---|---|---| | All-in-one container (today) | the server container | same origin | none | yes | | Split containers (new) | a web container that forwards the API | same origin | none | yes | | Static host or CDN (new) | Cloudflare Pages, a CDN or any web server | another origin | `CORS_ALLOWED_ORIGINS` | no, links to the classic UI | ### Commit 1: the UI as static files, for any host - **One place for API URLs:** `public/deployment.js` says where the API is, and `public/api-base.js` (`CSApi`) builds every API and WebSocket URL. A lint rule keeps raw `/api` fetches out of the other files. The embedded UI keeps `apiBase: ''`, so it behaves as before, except that its WebSocket now uses `/ws` instead of `/`. - **Build:** `make web` (`scripts/static/build.sh`) writes `dist/web`, which is `public/` byte for byte except for the cache buster in `index.html` and `deployment.js`. - It is `dist/web` rather than `dist/` because the Go binaries are built into `dist/` and `make clean` removes that folder. - `API_BASE=same-origin` is for a host that forwards `/api` and `/ws` itself, as the web container does. - **Anonymous build (`AUTH=false`):** for another origin. It has no account features: login, account, admin and other writes link to the same page on the classic UI. It sends no cookies, and its three JSON POSTs go as `text/plain`, so there is no preflight. - **Error notices:** a blocked API answer or an HTML answer each show a notice. - **Channel badge:** `beta`, `next` and `dev` builds show a badge that opens a pre-filled issue, plus an "Open in classic" link. - **Runbook:** `deploy/static/README.md` covers Cloudflare Pages, previews, server CORS and rollback. ### Commit 2: the web container and the three modes - **`Dockerfile.web`:** Caddy on `alpine:3.24`, like the main image. It packages the UI with `build.sh` when the image is built, serves it, and forwards `/api/*` and `/ws` to `BACKEND` (default `corescope:3000`). `SITE_ADDRESS` set to a domain name turns on automatic HTTPS. - **Cache rules:** `docker/web/Caddyfile` sends the same no-cache rules as `deploy/static/_headers`, and compresses responses with zstd or gzip. - **`docker-compose.split.yml`:** the stock server image (its own Caddy off) plus the web container: `CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge docker compose -f docker-compose.split.yml up -d --build`. - `CORESCOPE_IMAGE` is required and must match the checkout's version, so a release server is never paired with a newer UI by default. - The server's built-in broker, which accepts anonymous clients, is published on `127.0.0.1` unless `MQTT_BIND` says otherwise. - **Docs:** `docs/deployment.md` has a new "Deployment modes" section, and `DEPLOY.md` points to it. ### Keeping new code on `CSApi` - **Lint rule:** `.eslintrc.json` now rejects every direct network call in `public/*.js`. That covers `fetch`, `XMLHttpRequest`, `EventSource`, `sendBeacon` and `WebSocket` without `CSApi.wsUrl`, plus `/api` paths in `href`, `src` and `action` (assigned, set with `setAttribute` or written into markup), `window.open`, `location.assign`, `location.replace` and `location =`. `api-base.js` is the one file exempt. - **HTML pages:** `eslint public/*.js` never sees the inline scripts and markup of `public/*.html`, so `test-lint-network-calls.js` applies the same rule to them, at their page lines. `area-map.html`'s two fetches carry an `eslint-disable` with the reason: its Server field can name another server. - **Why it changed:** the earlier rule only caught a literal `/api…` passed straight to `fetch`. - **Check:** CI already fails on lint errors, and `tests/e2e/test-lint-network-calls.js` pins exactly what the rule reports: 25 bad statements reported, 15 good ones not, `api-base.js` exempt. - **AGENTS.md:** a new "API calls" section covers: - which helper to use for each need; - the lint rule; - how anonymous builds gate login-only features; - loading `api-base.js` in vm and jsdom tests (the region quick-picks suite missed that, and failed shard 1 on the first CI run). ### Review follow-ups - **Account tokens:** the channel badge's pre-filled issue drops the query on `#/account/…` routes, so mail-link tokens never reach a GitHub URL. "Open in classic" keeps the full route, since the classic UI needs the token. - **HTML answers:** on a packaged UI (static host, web container), `api()` rejects an HTML answer before status and retry handling. An HTML 404 or 503 (a wrong `API_BASE`, a proxy error page) shows "Server returned an unexpected response" after one request. It used to give a generic error, or six "warming up" retries for a 503. JSON errors and the server's JSON 503 warm-up behave as before. The embedded UI keeps its old handling (`CSApi.embedded`). - **Logins:** `docs/deployment.md`, `Dockerfile.web` and `docker-compose.split.yml` say `userManagement.publicBaseUrl` must be the web container's public origin. ### Audit fixes - **No broken logins build:** `build.sh` refuses `AUTH=true` with a cross-origin `API_BASE`. The server allows no credentialed CORS, so every API request of such a build was blocked; in Chromium all 12 were, and the pages stayed empty. - **No accidental deletes:** `build.sh` refuses an `OUT` that is neither empty nor a previous build. It used to wipe whatever folder or file `OUT` named. - **Lint:** the rule now also reports `/api/` paths in `href`, `src` and `action` attributes in single-quoted strings and template literals. `tests/e2e/test-lint-network-calls.js` pins exactly what it reports. - **Compose:** `CORESCOPE_IMAGE` has no default, and MQTT is published on localhost only. - **Runbook:** the deploy and rollback examples use `vX.Y.Z`, since v3.16.0 and v3.15.0 predate the static build. It also names the server version the static build needs: before #2362 the warm-up headers stay hidden and wildcard previews are refused. ### Audit notes, fixed - **Cache busting on every page:** the tool pages (`area-map.html`, `geofilter-builder.html`) load their scripts with `?v=__BUST__`. The server and `build.sh` replace it in every top-level page, and `_headers` and the Caddyfile make every page revalidate. Behind Caddy, a returning visitor could otherwise get a new tool page with an old `api-base.js`. - **HTTP/3:** the split compose publishes 443 over UDP too, for the HTTP/3 Caddy advertises once `SITE_ADDRESS` is a domain. Checked with Chromium forced onto QUIC: the page and `/api/healthz` loaded over `h3`. - **WebSocket on `/`:** a Go test pins that an upgrade on `/` still works, for UIs cached from before `/ws`. ### Second review - **Trusted proxies:** the docs said to trust the compose subnet, and also to publish port 3000 if wanted. Together they let a client spoof its address: the subnet holds the gateway, where a client reaching a published 3000 through Docker's proxy arrives from. The compose file now fixes the subnet (`SPLIT_NET`, default `172.30.83.0/24`) and the web container's address (`172.30.83.200`), and the docs say to trust that address alone. - **Classic UI unchanged:** the HTML-answer notice above applies to packaged UIs only. On the embedded UI a proxy's HTML 503 is retried as before, and an unknown `/api` path fails to parse as before, with no notice. - **Lint coverage:** the HTML pages and the extra sinks above. AGENTS.md says what the rule cannot see: a URL assembled elsewhere and passed in a variable. - **AGENTS.md:** `build.sh` is described as packaging (a copy, `deployment.js` and `__BUST__`, never a code transform), and rule 3 says `__BUST__` is filled in every top-level page. - **CI builds the web image:** the image-check job (no publish) builds `Dockerfile.web`, runs it, and checks the busted, no-cache `index.html`, the same-origin `deployment.js` and that `/api` reaches `BACKEND`. It also validates the split compose file. - **Cross-origin logins:** a hand-edited `deployment.js` with `auth: true` and another origin now logs a warning naming the setting, instead of failing with CORS errors alone. ## Upgrade notes - **WebSocket path:** the UI's live feed connects to `/ws` instead of `/`. The server has answered `/ws` since #1793 and still upgrades `/`, so browsers holding the previous UI keep working. - A reverse proxy that forwards WebSocket upgrades only for an exact `/` must forward `/ws` too. - The nginx example in `docs/deployment.md` (`location /`) already covers it. - **Static UI from another origin:** - The server needs `CORS_ALLOWED_ORIGINS`, and a version with #2362 for the warm-up banner and wildcard preview origins. - `build.sh` refuses `AUTH=true` there, since the server allows no credentialed CORS. - **Split containers:** - `CORESCOPE_IMAGE` is required. - With user accounts on, `userManagement.publicBaseUrl` must be the web container's public origin. - The built-in MQTT broker is published on `127.0.0.1` unless `MQTT_BIND` says otherwise. - The compose network is `172.30.83.0/24`, with the web container at `.200`. If Docker reports that the pool overlaps another network, set `SPLIT_NET`. ## Testing - `go test ./...`, `go vet` and `gofmt` are clean in `cmd/server`, with new tests for busting every page and the WebSocket upgrade on `/`. - `sh test-all.sh` passes. New unit suites: - `test-static-build.js`: the build and its input checks, `same-origin` included, cross-origin logins refused, and an unrelated `OUT` left intact. - `test-web-container.js`: the Dockerfile, Caddyfile and compose file agree on packaging, forwarded paths, cache rules and the server port; the server image has no default and MQTT stays on localhost. - The `api-base`, anonymous mode, badge and `dev-static` suites. - `eslint public/*.js` has 0 errors. `test-lint-network-calls.js` passes 47/47, the four pages included; it needs eslint, so CI runs it on E2E shard 1. - **Static host or CDN mode:** `test-split-anonymous-e2e.js` passes 11/11. That is the static build on one origin against an API-only server on another, which CI runs on E2E shard 1. - **Split containers mode:** - The image builds, and `caddy validate` passes (Caddy 2.11.4). The new CI step passes locally, and fails when the Caddyfile stops forwarding `/api`. - Trusted proxies, with the stack up: the web container gets `172.30.83.200`. With only that address trusted, a spoofed `X-Forwarded-For` sent straight to a published 3000 is ignored, and one sent through Caddy is replaced with the client's address. With the subnet trusted, as the docs used to say, the spoofed address was believed: a deny entry for it rejected the upgrade. - With `docker-compose.split.yml` on the E2E fixture, seeded the way CI seeds it, `test-e2e-playwright.js` passes 149 of 152 (3 skipped) both through the web container and against the server directly. - Headers, checked with curl: - `no-cache` on `/`, `/index.html` and `/deployment.js`; - zstd on static assets; - `/api/*` proxied (`Via: 1.1 Caddy`); - a `101` WebSocket upgrade on `/ws`. - In Chromium: - every API request and the WebSocket stay on the web container's origin; - there are no page errors and no horizontal overflow at 390 px; - no badge shows on the `static` channel. - Logins through the web container: with user management on and `userManagement.publicBaseUrl` set to the web container's origin, a Chromium run passed every step, all on the web container's origin with no page errors: - registration, and activation from the mail link (which uses `publicBaseUrl`); - the session surviving a reload; - a CSRF-protected `PATCH /api/account`; - logout, then login with the form. - The same login with the backend's origin as `Origin` is refused with 403. The server checks `Origin` against `publicBaseUrl`, not `Host`, which is why the docs ask for it. ## Performance There are no hot-path changes. API calls go through `CSApi.url()`, a string concatenation. In the web container, Caddy serves files from disk and compresses them; API responses pass through with one proxy hop, the same as the all-in-one image's built-in Caddy. ## Notes - **Per-IP limits:** behind the web container, as behind the all-in-one image's Caddy, requests reach the server from the proxy's address. The per-IP limits stay off until `trustedProxies` lists it: `172.30.83.200`, the web container's fixed address. The docs say so. - **`depends_on`:** the web container starts with the server, not after its healthcheck, like the all-in-one image's Caddy. Gating on health would make every `up` wait for the first check (30 s) and fail outright when a large database loads for longer than the healthcheck allows; until the server listens, Caddy answers `/api` with 502. - **Not in this PR:** - publishing a `corescope-web` image (CI builds and smokes it, without publishing); - Cross-origin login—including a static frontend and API on sibling custom domains—is outside this PR. In the deployments supported by this PR, account support requires the frontend and API to share one browser origin, either served together or through a reverse proxy. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
7.7 KiB
Frontend on a static host or CDN
The CoreScope UI is static files. This directory and scripts/static/build.sh
let it be served from Cloudflare Pages or any other static host, while the
existing container keeps serving the API and the classic, embedded UI. This is
the third of the deployment modes in
docs/deployment.md; the other two
run the UI in a container.
This is the anonymous build (AUTH=false): it reads everything a logged-out
visitor can read, live updates included, and links to the classic site for
logging in and admin work. On the server it needs one setting,
CORS_ALLOWED_ORIGINS (see Server), on a version that includes #2362:
edge now, and releases cut from master after it. Older servers accept the
origin too, but they hide the Retry-After and X-CoreScope-Load-Status
headers from it, so the warm-up banner never shows, and they refuse wildcard
preview origins.
How it works
public/deployment.jssays where the API is. The embedded UI ships it withapiBase: ''(same origin, as today).build.shrewrites it for the static build.public/api-base.js(window.CSApi) is the only place that builds API and WebSocket URLs. A lint rule keeps rawfetch('/api…')out of every other file.- The anonymous build sends no cookies, sends its three JSON
POSTs astext/plain(so the browser sends no preflight), and hides login, account and admin controls in favour of an "available on classic" link.
Building
make web API_BASE=https://analyzer.example.org AUTH=false
writes dist/web: public/ byte for byte, except that every top-level page
(index.html and the tool pages) gets the cache buster and deployment.js says
where the API is. Serve that folder at the root of a hostname; the UI uses
absolute paths such as /icons/…. _headers holds the cache rules: the pages
and deployment.js always revalidate, while everything they load carries
?v=<commit>. Cloudflare Pages and Netlify read it; other hosts need the same
rules in their own config. The variables are in step 6 below and at the top of
scripts/static/build.sh.
Deploying from a fork
This repository is the software, not any one CoreScope instance: it has no Pages project and deploys nothing. Each instance (a region, the flagship) deploys from its own fork. Pages needs that anyway: its GitHub App is installed on a repository you administer.
The fork carries no code changes. Every setting lives in the Pages project variables, and deploying means moving a branch to a commit that already exists upstream.
One-time setup
-
Fork this repository into an account or org your maintainers administer.
-
In the fork, turn GitHub Actions off (Settings → Actions). Otherwise syncing
masterruns this repository's CI and deploy workflows there, which fail without its secrets. Pages builds do not use Actions. -
Create the deploy branches
stageandprod, and protectprodso only maintainers can move it. -
Install the Cloudflare Pages GitHub App on the fork only.
-
Create one Pages project per deploy branch, on the Free plan:
Project Production branch Serves API e.g. corescope-web-stagestageyour staging frontend your staging server e.g. corescope-web-prodprodyour production frontend your production server For both:
- build command:
bash scripts/static/build.sh; - build output directory:
dist/web; root directory: blank (the repository root holds files over Pages' 25 MiB limit); - preview branches: None, or All to get a preview of every other branch pushed to the fork (see Previews below).
One project on
prodis enough if you have no staging server. - build command:
-
Environment variables (Production environment, and Preview too if previews are on) for each project:
Name Example Notes API_BASEhttps://analyzer.example.orgThe CoreScope server. https, lowercase, no path AUTHfalseRequired, no default. Must be false: the server allows no credentialed CORS, sobuild.shrefusestruewith a cross-originAPI_BASECHANNELbetabeta,nextordevshow a badge;staticshows noneCLASSIC_URLhttps://analyzer.example.orgOptional. Target of the "Open in classic" links SKIP_DEPENDENCY_INSTALL1build.shneeds no npm packagesCOMMITdefaults to the first 7 characters ofCF_PAGES_COMMIT_SHA. -
Add a custom domain to each project (for example
beta.example.org). The UI uses absolute paths such as/icons/…, so it must be served at the root of a hostname.
Deploying
Keep each frontend on the version its server runs: prod on the release tag
your production containers run, stage on upstream master if staging runs
the master image. Upgrade the server first, then move the branch. Move branches
by fast-forward, so they stay identical to upstream commits (upstream is this
repository, region is your fork, and vX.Y.Z is the release your production
server runs):
git fetch upstream --tags
git push region vX.Y.Z:refs/heads/prod
git push region upstream/master:refs/heads/stage
Releases up to v3.16.0 predate scripts/static/build.sh and have nothing to
build, so prod can only follow releases cut after it.
Only move stage to a master commit whose CI passed. A pull request into
prod also works if you want a review step, but its merge commits make the
branch drift from upstream. Each project builds only when its branch moves.
Previews
With preview branches on, every other branch pushed to the fork, and every pull
request between branches of the fork, gets its own deployment at
<hash>.<project>.pages.dev plus a branch alias such as
my-branch.<project>.pages.dev. Set CHANNEL=dev in the Preview environment
so previews show the Dev badge. Pull requests to this repository come from
forks and get no preview.
A preview is code from a branch, so keep previews anonymous (AUTH=false),
pointed at a staging server if you have one.
Server
Append the static origin to the embed CORS list and restart:
# Keep every origin already listed; add the static one exactly. Never "*".
CORS_ALLOWED_ORIGINS=https://existing-embed.example.org,https://beta.example.org
- The env var replaces
corsAllowedOriginsfromconfig.json, so it must list every origin, old and new. - An entry is an exact origin: lowercase, scheme included, no trailing slash.
- For previews, also list
https://<project>.pages.devandhttps://*.<project>.pages.dev(wildcard labels need a server with #2362; seeconfig.example.json). The wildcard matches one label only, and the server refuseshttps://*.pages.dev. - The same list admits the origin to
/ws. A*entry does not work for/ws.
Check it:
curl -sI -H "Origin: https://beta.example.org" https://analyzer.example.org/api/stats | grep -i access-control-allow-origin
It must print the origin, and no Access-Control-Allow-Credentials line.
Local and CI
make dev-split
The UI on http://localhost:8788 calls an API-only server on
http://localhost:3000 cross-origin, with no proxy. CI runs
tests/e2e/test-split-anonymous-e2e.js the same way on E2E shard 1. Pull requests
to this repository get no preview deployment; this is how to try one.
Roll back
- The UI: in the Pages dashboard, roll back to the previous deployment, or
move the deploy branch back to the previous release tag
(
git push --force-with-lease region vX.Y.Z:refs/heads/prod). - Access from the static origin: remove it from
CORS_ALLOWED_ORIGINSand restart. The static UI then shows "Can't reach the CoreScope API"; the classic UI and embeds are unaffected.