mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-22 02:57:25 +00:00
feat(frontend): serve the UI from a web container or a static host, three deployment modes (#2383)
## 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>
This commit is contained in:
1 parent
d80ce90976
commit
e7fd48a054
107 files changed
+2861
-116
No files matched your search
+57
-2
@@ -12,12 +12,14 @@
|
||||
"CACHE_INVALIDATE_MS": "readonly",
|
||||
"CLIENT_CONFIG": "readonly",
|
||||
"CLIENT_TTL": "readonly",
|
||||
"CSApi": "readonly",
|
||||
"CSAuth": "readonly",
|
||||
"ChannelColorPicker": "readonly",
|
||||
"ChannelColors": "readonly",
|
||||
"ChannelDecrypt": "readonly",
|
||||
"ChannelQR": "readonly",
|
||||
"Chart": "readonly",
|
||||
"CSBeta": "readonly",
|
||||
"DIST_THRESHOLDS": "readonly",
|
||||
"DragManager": "readonly",
|
||||
"EXTERNAL_URLS": "readonly",
|
||||
@@ -298,6 +300,59 @@
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_"
|
||||
}
|
||||
],
|
||||
"no-restricted-syntax": [
|
||||
"error",
|
||||
{
|
||||
"selector": "CallExpression[callee.name='fetch']",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "CallExpression[callee.property.name='fetch'][callee.object.name=/^(window|self|globalThis)$/]",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "NewExpression[callee.name=/^(XMLHttpRequest|EventSource)$/]",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "CallExpression[callee.property.name='sendBeacon']",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "NewExpression[callee.name='WebSocket']:not([arguments.0.callee.property.name='wsUrl'])",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "Literal[value=/(href|src|action)=[\"']\\/api(\\/|$)/]",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "TemplateElement[value.raw=/(href|src|action)=[\"']\\/api(\\/|$)/]",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "AssignmentExpression:matches([left.property.name=/^(href|src|action|location)$/], [left.name='location']):matches([right.value=/^\\/api(\\/|$)/], [right.left.value=/^\\/api(\\/|$)/], [right.left.left.value=/^\\/api(\\/|$)/], [right.quasis.0.value.raw=/^\\/api(\\/|$)/])",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "CallExpression:matches([callee.name='open'], [callee.property.name='open'], [callee.object.name='location'][callee.property.name=/^(assign|replace)$/], [callee.object.property.name='location'][callee.property.name=/^(assign|replace)$/]):matches([arguments.0.value=/^\\/api(\\/|$)/], [arguments.0.left.value=/^\\/api(\\/|$)/], [arguments.0.left.left.value=/^\\/api(\\/|$)/], [arguments.0.quasis.0.value.raw=/^\\/api(\\/|$)/])",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
},
|
||||
{
|
||||
"selector": "CallExpression[callee.property.name='setAttribute'][arguments.0.value=/^(href|src|action|formaction)$/]:matches([arguments.1.value=/^\\/api(\\/|$)/], [arguments.1.left.value=/^\\/api(\\/|$)/], [arguments.1.left.left.value=/^\\/api(\\/|$)/], [arguments.1.quasis.0.value.raw=/^\\/api(\\/|$)/])",
|
||||
"message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md."
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"public/api-base.js"
|
||||
],
|
||||
"rules": {
|
||||
"no-restricted-syntax": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -553,6 +553,25 @@ jobs:
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Start split frontend (static build + API-only server)
|
||||
# The anonymous static build on :8788 against a stock server on :13591
|
||||
# that lists that origin in CORS_ALLOWED_ORIGINS, the way a static
|
||||
# frontend (Cloudflare Pages) calls the containers. -public on a missing
|
||||
# directory is API-only mode, so nothing is served same-origin.
|
||||
if: matrix.shard == 1
|
||||
run: |
|
||||
CHANNEL=dev COMMIT=e2e API_BASE=http://localhost:13591 AUTH=false CLASSIC_URL=http://localhost:13591 bash scripts/static/build.sh
|
||||
fuser -k 13591/tcp 8788/tcp 2>/dev/null || true
|
||||
CORS_ALLOWED_ORIGINS=http://localhost:8788 ./corescope-server -port 13591 -db test-fixtures/e2e-fixture.db -public /nonexistent &
|
||||
echo $! > .server-split.pid
|
||||
node scripts/dev-static.mjs --root dist/web --port 8788 &
|
||||
echo $! > .static-split.pid
|
||||
for i in $(seq 1 30); do
|
||||
if curl -sf http://localhost:13591/api/healthz > /dev/null 2>&1 && curl -sf -o /dev/null http://localhost:8788/; then echo "split frontend ready after ${i}s"; break; fi
|
||||
if [ "$i" -eq 30 ]; then echo "split frontend failed to start within 30s"; exit 1; fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Run Playwright E2E tests (fail-fast)
|
||||
env:
|
||||
# On master pushes every suite records the frontend coverage of the
|
||||
@@ -587,6 +606,8 @@ jobs:
|
||||
# Allowlist: tests/a11y-allowlist.yaml (0 entries — hard pass policy).
|
||||
# Per-viewport summary printed at the end; any net>0 fails the build.
|
||||
suite 1 test-a11y-axe-1668.js BASE_URL=$B AXE_SCREENSHOT_DIR=/tmp/axe-1668
|
||||
# The static build on another origin than the API (scripts/static/build.sh).
|
||||
suite 1 test-split-anonymous-e2e.js SPLIT_URL=http://localhost:8788 API_URL=http://localhost:13591
|
||||
suite 2 test-filter-ux-e2e.js BASE_URL=$B
|
||||
suite 2 test-radio-setting-1869-e2e.js BASE_URL=$B
|
||||
suite 2 test-observer-neighbors-2270-e2e.js BASE_URL=$B
|
||||
@@ -719,6 +740,8 @@ jobs:
|
||||
suite 3 test-path-inspector-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B
|
||||
suite 3 test-pr-1490-live-map-gpu-animations-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B
|
||||
suite 1 test-region-quick-picks.js
|
||||
# The lint rule that keeps network calls on CSApi (needs eslint).
|
||||
suite 1 test-lint-network-calls.js
|
||||
suite 3 test-table-sort.js
|
||||
suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B
|
||||
suite 3 test-live-dedup.js BASE_URL=$B
|
||||
@@ -784,6 +807,9 @@ jobs:
|
||||
kill $(cat .server-um.pid) 2>/dev/null || true
|
||||
rm -f .server-um.pid
|
||||
fi
|
||||
for f in .server-split.pid .static-split.pid; do
|
||||
if [ -f "$f" ]; then kill $(cat "$f") 2>/dev/null || true; rm -f "$f"; fi
|
||||
done
|
||||
|
||||
- name: Upload shard results
|
||||
if: success()
|
||||
@@ -944,9 +970,34 @@ jobs:
|
||||
- name: Validate staging compose file
|
||||
run: docker compose -f "$STAGING_COMPOSE_FILE" -p corescope-staging config --quiet
|
||||
|
||||
# Split containers: operators build the web image from their checkout and
|
||||
# nothing publishes it, so without this a broken base image, package or
|
||||
# Caddyfile would reach an operator first.
|
||||
- name: Validate split compose file
|
||||
run: CORESCOPE_IMAGE=corescope:check docker compose -f docker-compose.split.yml config --quiet
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and smoke the web image (Dockerfile.web)
|
||||
env:
|
||||
GIT_COMMIT: ${{ steps.meta.outputs.git_commit }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker buildx build . -f Dockerfile.web --load -t corescope-web:check --build-arg GIT_COMMIT="$GIT_COMMIT"
|
||||
# BACKEND is a closed port: /api must reach it (502), not the file server (404).
|
||||
docker run -d --name web-check -p 8080:80 -e BACKEND=127.0.0.1:9 corescope-web:check
|
||||
trap 'docker logs web-check 2>&1 | tail -20; docker rm -f web-check >/dev/null' EXIT
|
||||
for i in $(seq 1 30); do curl -fs -o /dev/null http://localhost:8080/ && break; sleep 1; done
|
||||
page=$(curl -fsS -D headers.txt http://localhost:8080/)
|
||||
echo "$page" | grep -q "app.js?v=$GIT_COMMIT" || { echo "::error::index.html is not busted with the commit"; exit 1; }
|
||||
if echo "$page" | grep -q __BUST__; then echo "::error::index.html still has __BUST__"; exit 1; fi
|
||||
grep -qi '^cache-control: no-cache' headers.txt || { echo "::error::index.html may be cached"; exit 1; }
|
||||
curl -fsS http://localhost:8080/deployment.js | grep -q "apiBase: ''" || { echo "::error::deployment.js is not same-origin"; exit 1; }
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/api/healthz)
|
||||
[ "$code" = 502 ] || { echo "::error::/api/healthz answered $code, not 502 from the closed BACKEND"; exit 1; }
|
||||
echo "web image serves the packaged UI and forwards /api ✅"
|
||||
|
||||
- name: Set up QEMU (arm64 runtime stage + arm64 smoke)
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ Guide for AI agents working on this codebase. Read this before writing any code.
|
||||
|
||||
## Architecture
|
||||
|
||||
Go backend + static frontend. No build step. No framework. No bundler.
|
||||
Go backend + static frontend. No build step: `public/` is what the browser runs. No framework. No bundler.
|
||||
`scripts/static/build.sh` is packaging, not a build: it copies `public/` for a static host or the web container, writes `deployment.js` and fills in `__BUST__`, and never transforms code.
|
||||
|
||||
**⚠️ The Node.js server (server.js) is DEPRECATED and has been removed. All backend code is in Go.**
|
||||
**⚠️ DO NOT create or modify any Node.js server files. All backend changes go in `cmd/server/` or `cmd/ingestor/`.**
|
||||
@@ -18,7 +19,9 @@ cmd/server/ — Go API server (REST + WebSocket broadcast + static file s
|
||||
decoder.go — MeshCore packet decoder
|
||||
cmd/ingestor/ — Go MQTT ingestor (separate binary, writes to shared SQLite DB)
|
||||
public/ — Frontend (vanilla JS, one file per page) — ACTIVE, NOT DEPRECATED
|
||||
app.js — SPA router, shared globals, theme loading
|
||||
app.js — SPA router, shared globals, theme loading, api() (cached GETs)
|
||||
deployment.js — where the API is (rewritten by scripts/static/build.sh for a static host)
|
||||
api-base.js — CSApi: the ONLY code that builds API URLs or opens connections (see "API calls")
|
||||
roles.js — ROLE_COLORS, TYPE_COLORS, health thresholds, shared helpers
|
||||
nodes.js — Nodes list + side pane + full detail page
|
||||
map.js — Leaflet map with markers, legend, filters
|
||||
@@ -33,9 +36,10 @@ public/ — Frontend (vanilla JS, one file per page) — ACTIVE, NOT
|
||||
style.css — Main styles, CSS variables for theming
|
||||
live.css — Live page styles
|
||||
home.css — Home page styles
|
||||
index.html — SPA shell, script/style tags with __BUST__ placeholder (auto-replaced at server startup)
|
||||
index.html — SPA shell, script/style tags with __BUST__ placeholder (filled in automatically; see rule 3)
|
||||
test-fixtures/ — Real data SQLite fixture from staging (used for E2E tests)
|
||||
scripts/ — Tooling (coverage collector, fixture capture, frontend instrumentation)
|
||||
scripts/ — Tooling (coverage collector, fixture capture, frontend instrumentation;
|
||||
static/build.sh packages the UI for a static host or the web container)
|
||||
```
|
||||
|
||||
### Data Flow
|
||||
@@ -105,7 +109,7 @@ Every change must consider performance impact BEFORE implementation. This codeba
|
||||
No proof = no merge.
|
||||
|
||||
### 1. No commit without tests
|
||||
Every change that touches logic MUST have tests. For Go backend: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test ./...`, or `make test` for all 14 modules. For frontend: `node tests/unit/test-packet-filter.js && node tests/unit/test-aging.js && node tests/unit/test-frontend-helpers.js`. If you add new logic, add tests. No exceptions.
|
||||
Every change that touches logic MUST have tests. For Go backend: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test ./...`, or `make test` for all 14 modules. For frontend: `node tests/unit/test-packet-filter.js && node tests/unit/test-aging.js && node tests/unit/test-frontend-helpers.js`, and `npx eslint public/*.js` (CI fails on any error). If you add new logic, add tests. No exceptions.
|
||||
|
||||
The SQLite driver (`github.com/mattn/go-sqlite3`) is cgo. **`CGO_ENABLED=0` still *builds*** — that is the trap. It links a stub, and the binary dies on the first query with `go-sqlite3 requires cgo to work. This is a stub`, so a green build proves nothing. A plain `GOOS=linux go build` likewise cannot cross-compile it. Use `make build` / `make crossbuild` — the latter needs [`zig`](https://ziglang.org/download/) as the cross C compiler and produces static musl binaries. Never re-add `CGO_ENABLED=0`.
|
||||
|
||||
@@ -113,7 +117,7 @@ The SQLite driver (`github.com/mattn/go-sqlite3`) is cgo. **`CGO_ENABLED=0` stil
|
||||
After pushing, verify the change works in an actual browser. Use `browser profile=openclaw` against the running instance. Take a screenshot if the change is visual. If you can't validate it, say so — don't claim it works.
|
||||
|
||||
### 3. Cache busters are automatic — do NOT manually edit them
|
||||
Cache busters are injected automatically by the Go server at startup. The `__BUST__` placeholder in `index.html` is replaced with a Unix timestamp when the server reads the file. No manual bumping needed — every server restart picks up new asset versions. Do NOT replace `__BUST__` with hardcoded timestamps.
|
||||
Cache busters are injected automatically. The Go server replaces the `__BUST__` placeholder in every top-level page (`index.html`, `area-map.html`, `geofilter-*.html`) with a Unix timestamp at startup, so every server restart picks up new asset versions. `scripts/static/build.sh` replaces it with the commit when it packages the UI. No manual bumping needed. Do NOT replace `__BUST__` with hardcoded timestamps, and give every local script or stylesheet a new page loads `?v=__BUST__`.
|
||||
|
||||
### 4. Verify API response shape before building UI
|
||||
Before writing client code that consumes an API endpoint, check what the endpoint ACTUALLY returns. Use `curl` or check the server code. Don't assume fields exist — grouped packets (`groupByHash=true`) have different fields than raw packets. This has caused multiple breakages.
|
||||
@@ -196,6 +200,22 @@ If you need to know how something works — a flag, a field, a timing, a behavio
|
||||
|
||||
## Frontend Conventions
|
||||
|
||||
### API calls (api-base.js)
|
||||
The UI runs embedded in the server, in the web container, and from a static host or CDN on another origin (see "Deployment modes" in `docs/deployment.md`). `public/deployment.js` says where the API is, and `public/api-base.js` (`window.CSApi`) is the only code that turns a path into a URL or opens a connection. Everything else goes through it:
|
||||
|
||||
| Need | Use |
|
||||
|------|-----|
|
||||
| GET JSON, cached | `api('/nodes?…')` (app.js) |
|
||||
| Any other request | `CSApi.fetch('/api/…', opts)` |
|
||||
| JSON POST | `CSApi.postJSON('/api/…', body)`: sends `text/plain`, so a cross-origin POST has no preflight (the server decodes JSON whatever the Content-Type; `cmd/server/simple_post_test.go`) |
|
||||
| Logged-in request | `CSAuth.request(method, '/api/…', body)` |
|
||||
| Link, download, `src` | `CSApi.url('/api/…')` |
|
||||
| WebSocket | `new WebSocket(CSApi.wsUrl('/ws'))` |
|
||||
|
||||
- **Never** call `fetch`, `XMLHttpRequest`, `EventSource`, `navigator.sendBeacon` or `new WebSocket(url)` directly, or put a bare `/api/…` path in an `href`, `src` or `action` (assigned, set with `setAttribute` or written into markup) or in `window.open`, `location.assign`, `location.replace` or `location =`. It works embedded and breaks on a static host. The `no-restricted-syntax` rule in `.eslintrc.json` rejects all of these in `public/*.js` (only `api-base.js` is exempt) and CI fails on it: run `npx eslint public/*.js` before pushing. That command never sees the inline scripts and markup of `public/*.html`; `tests/e2e/test-lint-network-calls.js` applies the same rule to them, and pins what the rule reports: extend it when you extend the rule. The rule sees a path at the start of a string, a concatenation or a template; a URL assembled elsewhere and passed in a variable gets past it, so it does not replace review. Do not silence it with `eslint-disable`. The one exception is `area-map.html`, whose Server field can name another server.
|
||||
- **Logins and writes:** the anonymous static build (`CSApi.anonymous`) sends no cookies. A feature that needs a login or a write shows `CSBeta.classicOnlyHtml('…')` (or links with `CSApi.classicHref(hash)`) instead, as `account.js`, `admin.js` and `perf.js` do.
|
||||
- **Tests:** a test that runs a frontend file outside the browser must load `deployment.js` and `api-base.js` first, or `CSApi` is undefined and its fetches fail silently inside their `try` blocks. vm sandboxes: `tests/unit/api-base-sandbox.js`. jsdom: `w.eval` both files before the file under test (`tests/e2e/test-region-quick-picks.js`).
|
||||
|
||||
### Theming
|
||||
All colors MUST use CSS variables. Never hardcode `#hex` values outside of `:root` definitions. The customizer controls colors via `THEME_CSS_MAP` in customize.js. If you add a new color, add it as a CSS variable and map it in the customizer.
|
||||
|
||||
@@ -378,6 +398,7 @@ One logical change per commit. Each commit is deployable. Each commit has its te
|
||||
| Gave up testing locally | 2 | Basic tests work on ARM — only heavy coverage scripts crash |
|
||||
| Copy-pasted functions for "coverage" | 1 | Test the real code, not copies in a helper file |
|
||||
| Subagent timed out mid-work | 4 | Give clear scope, don't try to run slow pipelines locally |
|
||||
| Frontend file tested without api-base.js | 1 | Load `deployment.js` + `api-base.js` first (see "API calls") |
|
||||
|
||||
## File Naming
|
||||
- Tests: `test-{feature}.js` in `tests/unit/` (standalone, listed in `test-all.sh`) or `tests/e2e/` (browser, listed in `scripts/non-unit-tests.json`) — never in repo root
|
||||
@@ -397,5 +418,6 @@ Existing patterns: `#/nodes/{pubkey}?section=node-neighbors`, `#/analytics?tab=c
|
||||
- Don't add framework abstractions (React, Vue, etc.)
|
||||
- Don't hardcode colors — use CSS variables
|
||||
- Don't make per-packet server API calls from the frontend
|
||||
- Don't call `fetch` / `WebSocket` / XHR directly from the frontend — go through `CSApi` (see "API calls")
|
||||
- Don't push without running tests
|
||||
- Don't start implementing without plan approval
|
||||
@@ -24,6 +24,13 @@ curl -sL https://raw.githubusercontent.com/Kpa-clawbot/CoreScope/master/docker-c
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
### Other deployment modes
|
||||
|
||||
The UI can also run in a container of its own (`docker-compose.split.yml`, with
|
||||
`CORESCOPE_IMAGE` set to the server image of your checkout's version) or from a
|
||||
static host or CDN such as Cloudflare Pages. See
|
||||
[Deployment modes](docs/deployment.md#deployment-modes).
|
||||
|
||||
## Image Tags
|
||||
|
||||
| Tag | Description |
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# CoreScope web container: the static UI on its own, served by Caddy, which
|
||||
# forwards /api and /ws to a CoreScope server container. The UI and the API
|
||||
# then share one origin, so the server needs no CORS settings. Logins work as
|
||||
# on the classic UI once the server's userManagement.publicBaseUrl is this
|
||||
# container's public origin. docker-compose.split.yml runs the two together;
|
||||
# see "Deployment modes" in docs/deployment.md.
|
||||
#
|
||||
# Runtime environment:
|
||||
# BACKEND host:port of the CoreScope server. Default corescope:3000.
|
||||
# SITE_ADDRESS :80 (default) for plain HTTP, or a domain name for Caddy's
|
||||
# automatic HTTPS (publish 80 and 443, and keep /data).
|
||||
|
||||
FROM alpine:3.24 AS build
|
||||
RUN apk add --no-cache bash
|
||||
WORKDIR /src
|
||||
COPY public/ public/
|
||||
COPY scripts/static/ scripts/static/
|
||||
COPY deploy/static/ deploy/static/
|
||||
# GIT_COMMIT is the cache buster on every asset (?v=); without one, the build
|
||||
# time, as the server does at start. CHANNEL beta, next or dev shows a badge.
|
||||
ARG GIT_COMMIT=
|
||||
ARG CHANNEL=static
|
||||
RUN COMMIT="$(printf '%.12s' "${GIT_COMMIT:-$(date +%s)}")" \
|
||||
API_BASE=same-origin AUTH=true CHANNEL="$CHANNEL" OUT=/srv \
|
||||
bash scripts/static/build.sh && \
|
||||
rm /srv/_headers
|
||||
|
||||
FROM alpine:3.24
|
||||
RUN apk add --no-cache caddy
|
||||
COPY --from=build /srv /srv
|
||||
COPY docker/web/Caddyfile /etc/caddy/Caddyfile
|
||||
ENV BACKEND=corescope:3000 \
|
||||
SITE_ADDRESS=:80 \
|
||||
XDG_DATA_HOME=/data \
|
||||
XDG_CONFIG_HOME=/config
|
||||
EXPOSE 80 443
|
||||
VOLUME ["/data"]
|
||||
CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
|
||||
@@ -15,6 +15,8 @@
|
||||
# make crossbuild # linux/amd64 + linux/arm64, static, into dist/
|
||||
# make test / vet / fmt-check # across all modules
|
||||
# make docker-build # multi-arch image via buildx
|
||||
# make web API_BASE=… AUTH=… # the UI alone, for a static host, into dist/web
|
||||
# make dev-split # UI on :8788 calling the API on :3000 cross-origin
|
||||
|
||||
GO ?= $(shell command -v go)
|
||||
GIT_VERSION ?= $(shell git describe --tags --match "v*" 2>/dev/null || echo unknown)
|
||||
@@ -59,12 +61,12 @@ DOCKER_IMAGE ?= ghcr.io/kpa-clawbot/corescope
|
||||
DOCKER_TAG ?= $(GIT_VERSION)
|
||||
DOCKER_PLATFORMS ?= linux/amd64,linux/arm64
|
||||
|
||||
.PHONY: all build crossbuild test vet fmt-check tidy clean docker-build docker-push help
|
||||
.PHONY: all build crossbuild test vet fmt-check tidy clean web dev-split docker-build docker-push help
|
||||
|
||||
all: build
|
||||
|
||||
help:
|
||||
@echo "targets: build crossbuild test vet fmt-check tidy clean docker-build docker-push"
|
||||
@echo "targets: build crossbuild test vet fmt-check tidy clean web dev-split docker-build docker-push"
|
||||
@echo " build-{$(shell echo $(CMDS) | tr ' ' ',')}"
|
||||
|
||||
# -- host builds ---------------------------------------------------------------
|
||||
@@ -119,6 +121,35 @@ tidy:
|
||||
clean:
|
||||
rm -rf $(DIST)
|
||||
|
||||
# -- static frontend ------------------------------------------------------------
|
||||
#
|
||||
# web packages public/ into dist/web for a static host or a CDN. It reads
|
||||
# API_BASE, AUTH, CHANNEL, CLASSIC_URL and COMMIT; see scripts/static/build.sh.
|
||||
# The Go binaries share dist/, which is why the UI gets a folder of its own.
|
||||
web:
|
||||
bash scripts/static/build.sh
|
||||
|
||||
# dev-split runs the UI the way a static host serves it: the anonymous
|
||||
# build on :8788 calling an API-only server on :3000 cross-origin, with no
|
||||
# proxy. The server change is the one env var, exactly as in production.
|
||||
# DEV_SPLIT_DB=path/to.db picks the data (default: the E2E fixture); it runs on a
|
||||
# migrated copy in dist/, so the original is never touched.
|
||||
DEV_SPLIT_DB ?= test-fixtures/e2e-fixture.db
|
||||
DEV_SPLIT_API_PORT ?= 3000
|
||||
DEV_SPLIT_STATIC_PORT ?= 8788
|
||||
|
||||
dev-split: build-server build-migrate
|
||||
cp $(DEV_SPLIT_DB) $(DIST)/dev-split.db
|
||||
$(DIST)/corescope-migrate -db $(DIST)/dev-split.db
|
||||
CHANNEL=dev COMMIT=dev AUTH=false \
|
||||
API_BASE=http://localhost:$(DEV_SPLIT_API_PORT) CLASSIC_URL=http://localhost:$(DEV_SPLIT_API_PORT) \
|
||||
bash scripts/static/build.sh
|
||||
@echo "UI: http://localhost:$(DEV_SPLIT_STATIC_PORT) API: http://localhost:$(DEV_SPLIT_API_PORT) (Ctrl-C stops both)"
|
||||
@trap 'kill 0' INT TERM EXIT; \
|
||||
CORS_ALLOWED_ORIGINS=http://localhost:$(DEV_SPLIT_STATIC_PORT) \
|
||||
$(DIST)/corescope-server -port $(DEV_SPLIT_API_PORT) -db $(DIST)/dev-split.db -public /nonexistent & \
|
||||
node scripts/dev-static.mjs --root $(DIST)/web --port $(DEV_SPLIT_STATIC_PORT)
|
||||
|
||||
# -- docker --------------------------------------------------------------------
|
||||
|
||||
docker-build:
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -447,6 +448,37 @@ func TestSpaHandlerCacheBust(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// Every top-level page gets the same cache buster as index.html, so a tool
|
||||
// page (area-map.html, geofilter-builder.html) served fresh never runs a
|
||||
// script cached from before the server started.
|
||||
func TestSpaHandlerBustsEveryTopLevelPage(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.WriteFile(filepath.Join(dir, "index.html"), []byte(`<script src="app.js?v=__BUST__"></script>`), 0644)
|
||||
os.WriteFile(filepath.Join(dir, "tool.html"), []byte(`<script src="api-base.js?v=__BUST__"></script>`), 0644)
|
||||
handler := spaHandler(dir, http.FileServer(http.Dir(dir)))
|
||||
|
||||
get := func(p string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, httptest.NewRequest("GET", p, nil))
|
||||
return w
|
||||
}
|
||||
bust := regexp.MustCompile(`v=(\d+)`)
|
||||
index, tool := get("/"), get("/tool.html")
|
||||
if strings.Contains(tool.Body.String(), "__BUST__") {
|
||||
t.Fatalf("tool.html kept its placeholder: %s", tool.Body.String())
|
||||
}
|
||||
im, tm := bust.FindStringSubmatch(index.Body.String()), bust.FindStringSubmatch(tool.Body.String())
|
||||
if im == nil || tm == nil || im[1] != tm[1] {
|
||||
t.Errorf("tool.html buster %v, index.html buster %v: want the same timestamp", tm, im)
|
||||
}
|
||||
if got := tool.Header().Get("Cache-Control"); got != "no-cache, no-store, must-revalidate" {
|
||||
t.Errorf("tool.html Cache-Control = %q", got)
|
||||
}
|
||||
if got := tool.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") {
|
||||
t.Errorf("tool.html Content-Type = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteJSON(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
writeJSON(w, map[string]interface{}{"key": "value"})
|
||||
|
||||
+47
-17
@@ -606,16 +606,22 @@ func main() {
|
||||
// It reads index.html once at creation time and replaces the __BUST__ placeholder
|
||||
// with a Unix timestamp so browsers fetch fresh JS/CSS after each server restart.
|
||||
func spaHandler(root string, fs http.Handler) http.Handler {
|
||||
// Pre-process index.html: replace __BUST__ with a cache-bust timestamp
|
||||
indexPath := filepath.Join(root, "index.html")
|
||||
rawHTML, err := os.ReadFile(indexPath)
|
||||
if err != nil {
|
||||
log.Printf("[static] warning: could not read index.html for cache-bust: %v", err)
|
||||
rawHTML = []byte("<!DOCTYPE html><html><body><h1>CoreScope</h1><p>index.html not found</p></body></html>")
|
||||
}
|
||||
// Pre-process every top-level page, index.html and the tool pages
|
||||
// (area-map.html, geofilter-builder.html): replace __BUST__ with a
|
||||
// cache-bust timestamp, so each loads the scripts of this start.
|
||||
bustValue := fmt.Sprintf("%d", time.Now().Unix())
|
||||
indexHTML := []byte(strings.ReplaceAll(string(rawHTML), "__BUST__", bustValue))
|
||||
log.Printf("[static] cache-bust value: %s", bustValue)
|
||||
pages := bustPages(root, bustValue)
|
||||
indexHTML, ok := pages["/index.html"]
|
||||
if !ok {
|
||||
log.Printf("[static] warning: could not read index.html for cache-bust")
|
||||
indexHTML = []byte("<!DOCTYPE html><html><body><h1>CoreScope</h1><p>index.html not found</p></body></html>")
|
||||
}
|
||||
log.Printf("[static] cache-bust value: %s (%d pages)", bustValue, len(pages))
|
||||
servePage := func(w http.ResponseWriter, body []byte) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Write(body)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Defense-in-depth: explicitly reject path-traversal attempts before
|
||||
@@ -628,20 +634,21 @@ func spaHandler(root string, fs http.Handler) http.Handler {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Serve pre-processed index.html for root and /index.html
|
||||
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Write(indexHTML)
|
||||
// Serve the pre-processed index.html for the root, and each
|
||||
// pre-processed page (/index.html included) at its own path
|
||||
if r.URL.Path == "/" {
|
||||
servePage(w, indexHTML)
|
||||
return
|
||||
}
|
||||
if page, ok := pages[r.URL.Path]; ok {
|
||||
servePage(w, page)
|
||||
return
|
||||
}
|
||||
|
||||
path := filepath.Join(root, r.URL.Path)
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
// SPA fallback — serve pre-processed index.html
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Write(indexHTML)
|
||||
servePage(w, indexHTML)
|
||||
return
|
||||
}
|
||||
// Disable caching for JS/CSS/HTML
|
||||
@@ -652,6 +659,29 @@ func spaHandler(root string, fs http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// bustPages reads each .html file at the top of root, keyed by its URL path
|
||||
// ("/index.html"), with every __BUST__ replaced by bust.
|
||||
func bustPages(root, bust string) map[string][]byte {
|
||||
pages := map[string][]byte{}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
log.Printf("[static] warning: could not list %s for cache-bust: %v", root, err)
|
||||
return pages
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || !strings.EqualFold(filepath.Ext(e.Name()), ".html") {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(root, e.Name()))
|
||||
if err != nil {
|
||||
log.Printf("[static] warning: could not read %s for cache-bust: %v", e.Name(), err)
|
||||
continue
|
||||
}
|
||||
pages["/"+e.Name()] = []byte(strings.ReplaceAll(string(raw), "__BUST__", bust))
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
// isSafeStaticPath rejects request paths that contain traversal sequences
|
||||
// or backslashes — defense-in-depth for the SPA static handler so a future
|
||||
// router with SkipClean(true) cannot expose the filesystem. Empty input is
|
||||
|
||||
@@ -454,3 +454,31 @@ func TestHubDefaultPingInterval(t *testing.T) {
|
||||
t.Fatalf("pingInterval = %v, want 30s (public/app.js WS_STALE_MS depends on it)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// UIs cached from before the UI moved its WebSocket to /ws still connect on
|
||||
// "/": wsOrStatic upgrades any path the static handler serves. Keep that
|
||||
// until those clients are gone; this pins it.
|
||||
func TestWebSocketUpgradeOnRootStillWorks(t *testing.T) {
|
||||
hub := NewHub()
|
||||
static := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("static"))
|
||||
})
|
||||
srv := httptest.NewServer(wsOrStatic(hub, static))
|
||||
defer srv.Close()
|
||||
|
||||
conn, resp, err := websocket.DefaultDialer.Dial("ws"+srv.URL[4:]+"/", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("dial /: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if resp.StatusCode != http.StatusSwitchingProtocols {
|
||||
t.Fatalf("dial /: status %d, want 101", resp.StatusCode)
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for hub.ClientCount() != 1 && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if hub.ClientCount() != 1 {
|
||||
t.Errorf("expected the root connection to register with the hub, got %d clients", hub.ClientCount())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
# 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](../../docs/deployment.md#deployment-modes); 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](#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.js` says where the API is. The embedded UI ships it with
|
||||
`apiBase: ''` (same origin, as today). `build.sh` rewrites 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 raw `fetch('/api…')` out of every other file.
|
||||
- The anonymous build sends no cookies, sends its three JSON `POST`s as
|
||||
`text/plain` (so the browser sends no preflight), and hides login, account and
|
||||
admin controls in favour of an "available on classic" link.
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
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
|
||||
|
||||
1. Fork this repository into an account or org your maintainers administer.
|
||||
2. In the fork, turn GitHub Actions off (Settings → Actions). Otherwise syncing
|
||||
`master` runs this repository's CI and deploy workflows there, which fail
|
||||
without its secrets. Pages builds do not use Actions.
|
||||
3. Create the deploy branches `stage` and `prod`, and protect `prod` so only
|
||||
maintainers can move it.
|
||||
4. Install the Cloudflare Pages GitHub App on the fork only.
|
||||
5. Create one Pages project per deploy branch, on the Free plan:
|
||||
|
||||
| Project | Production branch | Serves | API |
|
||||
|---|---|---|---|
|
||||
| e.g. `corescope-web-stage` | `stage` | your staging frontend | your staging server |
|
||||
| e.g. `corescope-web-prod` | `prod` | your 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 `prod` is enough if you have no staging server.
|
||||
6. Environment variables (Production environment, and Preview too if previews
|
||||
are on) for each project:
|
||||
|
||||
| Name | Example | Notes |
|
||||
|---|---|---|
|
||||
| `API_BASE` | `https://analyzer.example.org` | The CoreScope server. https, lowercase, no path |
|
||||
| `AUTH` | `false` | Required, no default. Must be `false`: the server allows no credentialed CORS, so `build.sh` refuses `true` with a cross-origin `API_BASE` |
|
||||
| `CHANNEL` | `beta` | `beta`, `next` or `dev` show a badge; `static` shows none |
|
||||
| `CLASSIC_URL` | `https://analyzer.example.org` | Optional. Target of the "Open in classic" links |
|
||||
| `SKIP_DEPENDENCY_INSTALL` | `1` | `build.sh` needs no npm packages |
|
||||
|
||||
`COMMIT` defaults to the first 7 characters of `CF_PAGES_COMMIT_SHA`.
|
||||
7. 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):
|
||||
|
||||
```bash
|
||||
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:
|
||||
|
||||
```bash
|
||||
# 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 `corsAllowedOrigins` from `config.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.dev` and
|
||||
`https://*.<project>.pages.dev` (wildcard labels need a server with #2362; see
|
||||
`config.example.json`). The wildcard matches one label only, and the server
|
||||
refuses `https://*.pages.dev`.
|
||||
- The same list admits the origin to `/ws`. A `*` entry does not work for `/ws`.
|
||||
|
||||
Check it:
|
||||
|
||||
```bash
|
||||
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
|
||||
|
||||
```bash
|
||||
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_ORIGINS` and
|
||||
restart. The static UI then shows "Can't reach the CoreScope API"; the classic
|
||||
UI and embeds are unaffected.
|
||||
@@ -0,0 +1,19 @@
|
||||
# Copied into the static build by scripts/static/build.sh. Cloudflare Pages
|
||||
# and Netlify read it; other hosts ignore it and need the same rules in their
|
||||
# own config (the web container's are in docker/web/Caddyfile). The pages and
|
||||
# deployment.js change on every deploy without a ?v= buster, so a browser must
|
||||
# always revalidate them. Every local script and stylesheet a page loads
|
||||
# carries ?v=<commit> (vendor/ files carry their version in the path), so
|
||||
# those may use the host's default caching.
|
||||
/
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
/index.html
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
/area-map.html
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
/geofilter-builder.html
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
/geofilter-docs.html
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
/deployment.js
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
@@ -0,0 +1,99 @@
|
||||
# CoreScope — split containers: the UI in its own web container and the
|
||||
# server in the usual image.
|
||||
#
|
||||
# The web container (Dockerfile.web, Caddy) serves the static UI and forwards
|
||||
# /api and /ws to the server, so both share one origin: no CORS settings. With
|
||||
# user management on, set the server's userManagement.publicBaseUrl to the web
|
||||
# container's public origin (scheme and port included): logins and other
|
||||
# writes are checked against it. The server container is unchanged and still
|
||||
# serves everything, the classic UI included, on port 3000 inside the compose
|
||||
# network; publish it too if you want to reach that directly. For per-IP
|
||||
# limits, the server trusts the web container's fixed address: see networks.
|
||||
#
|
||||
# Usage: CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge \
|
||||
# docker compose -f docker-compose.split.yml up -d --build
|
||||
# Docs: docs/deployment.md, "Deployment modes"
|
||||
#
|
||||
# Variables (shell or .env):
|
||||
# CORESCOPE_IMAGE required: the server image of the same version as this
|
||||
# checkout, which the web image is built from. :edge on
|
||||
# master, :vX.Y.Z on a release tag. There is no default, so
|
||||
# a release server is never paired with a newer UI unasked.
|
||||
# DATA_DIR the server's data directory. Default ./data
|
||||
# HTTP_PORT default 80; HTTPS_PORT default 443 (TCP and UDP)
|
||||
# SITE_ADDRESS :80 (default), or a domain name for automatic HTTPS, which
|
||||
# needs the default ports: certificate issuance and the
|
||||
# HTTP/3 advertisement both assume 80 and 443
|
||||
# GIT_COMMIT the UI's cache buster; default the build time
|
||||
# CHANNEL static (default), or beta, next, dev for a badge
|
||||
# MQTT_BIND where the server's built-in broker is published. Default
|
||||
# 127.0.0.1: it accepts anonymous clients, so set 0.0.0.0
|
||||
# only to let gateways on a network you trust publish to it.
|
||||
# MQTT_PORT default 1883
|
||||
# SPLIT_NET the compose network's /24, as its first three octets.
|
||||
# Default 172.30.83, which puts the web container at
|
||||
# 172.30.83.200. Change it only if Docker reports that the
|
||||
# pool overlaps another network, and update the server's
|
||||
# trustedProxies to match.
|
||||
|
||||
services:
|
||||
corescope:
|
||||
image: ${CORESCOPE_IMAGE:?set CORESCOPE_IMAGE to the server image of this checkout's version, e.g. ghcr.io/kpa-clawbot/corescope:edge on master or :vX.Y.Z on a release tag}
|
||||
ports:
|
||||
- "${MQTT_BIND:-127.0.0.1}:${MQTT_PORT:-1883}:1883"
|
||||
volumes:
|
||||
- ${DATA_DIR:-./data}:/app/data
|
||||
environment:
|
||||
- DISABLE_CADDY=true
|
||||
- DISABLE_MOSQUITTO=${DISABLE_MOSQUITTO:-false}
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/healthz"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.web
|
||||
args:
|
||||
GIT_COMMIT: ${GIT_COMMIT:-}
|
||||
CHANNEL: ${CHANNEL:-static}
|
||||
image: corescope-web:latest
|
||||
ports:
|
||||
- "${HTTP_PORT:-80}:80"
|
||||
- "${HTTPS_PORT:-443}:443"
|
||||
# HTTP/3: Caddy advertises it on 443 when SITE_ADDRESS is a domain.
|
||||
- "${HTTPS_PORT:-443}:443/udp"
|
||||
volumes:
|
||||
- web-caddy-data:/data
|
||||
environment:
|
||||
- BACKEND=corescope:3000
|
||||
- SITE_ADDRESS=${SITE_ADDRESS:-:80}
|
||||
networks:
|
||||
default:
|
||||
# The one address the server's trustedProxies lists; see networks.
|
||||
ipv4_address: "${SPLIT_NET:-172.30.83}.200"
|
||||
depends_on:
|
||||
- corescope
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
# A fixed subnet gives the web container a fixed address, so the server's
|
||||
# webSocket.trustedProxies and userManagement.trustedProxies can list it
|
||||
# alone (172.30.83.200 by default) and still match after a recreate. Never
|
||||
# list the whole subnet: it holds the gateway address too, and a client
|
||||
# that reaches a published port 3000 through Docker's proxy arrives from
|
||||
# there, so its own X-Forwarded-For would be believed.
|
||||
default:
|
||||
ipam:
|
||||
config:
|
||||
- subnet: "${SPLIT_NET:-172.30.83}.0/24"
|
||||
# Automatic addresses come from the lower half, so no container
|
||||
# can take the web container's.
|
||||
ip_range: "${SPLIT_NET:-172.30.83}.0/25"
|
||||
|
||||
volumes:
|
||||
# Caddy's TLS certificates when SITE_ADDRESS is a domain name.
|
||||
web-caddy-data:
|
||||
@@ -0,0 +1,23 @@
|
||||
# The web container (Dockerfile.web): the static UI from /srv, with the API
|
||||
# and the WebSocket forwarded to the CoreScope server, so both share this
|
||||
# origin. BACKEND is the server's host:port; SITE_ADDRESS is ":80" for plain
|
||||
# HTTP, or a domain name for automatic HTTPS.
|
||||
#
|
||||
# Caddy adds X-Forwarded-For. To keep the server's per-IP limits behind this
|
||||
# proxy, list its address in webSocket.trustedProxies (and
|
||||
# userManagement.trustedProxies) in the server's config.json.
|
||||
|
||||
{$SITE_ADDRESS::80} {
|
||||
encode zstd gzip
|
||||
|
||||
@backend path /api/* /ws
|
||||
reverse_proxy @backend {$BACKEND}
|
||||
|
||||
# The same rules as deploy/static/_headers: these change on every deploy
|
||||
# without a ?v= buster, so a browser must always revalidate them.
|
||||
@nocache path / /index.html /area-map.html /geofilter-builder.html /geofilter-docs.html /deployment.js
|
||||
header @nocache Cache-Control "no-cache, no-store, must-revalidate"
|
||||
|
||||
root * /srv
|
||||
file_server
|
||||
}
|
||||
@@ -5,6 +5,7 @@ Comprehensive guide to deploying and operating CoreScope. For a quick start, see
|
||||
## Table of Contents
|
||||
|
||||
- [System Requirements](#system-requirements)
|
||||
- [Deployment modes](#deployment-modes)
|
||||
- [Docker Deployment](#docker-deployment)
|
||||
- [Configuration Reference](#configuration-reference)
|
||||
- [MQTT Setup](#mqtt-setup)
|
||||
@@ -33,6 +34,85 @@ CoreScope runs well on Raspberry Pi 4/5 (ARM64). The Go server uses ~300 MB RAM
|
||||
|
||||
---
|
||||
|
||||
## Deployment modes
|
||||
|
||||
The UI is static files (`public/`) that call the server's API. The three modes
|
||||
differ only in what serves those files. The server container is the same image
|
||||
in all three, and it still serves the classic UI itself.
|
||||
|
||||
| Mode | The UI is served by | API | Server CORS setting | Logins |
|
||||
|---|---|---|---|---|
|
||||
| [All-in-one container](#all-in-one-container) | the server container | same origin | none | yes |
|
||||
| [Split containers](#split-containers) | a web container (`Dockerfile.web`) that forwards the API | same origin | none | yes |
|
||||
| [Static host or CDN](#static-host-or-cdn) | Cloudflare Pages, a CDN or any web server | another origin | `CORS_ALLOWED_ORIGINS` | no, links to the classic UI |
|
||||
|
||||
### All-in-one container
|
||||
|
||||
The default, and what the rest of this guide describes: one image runs the
|
||||
server, the ingestor and, optionally, Mosquitto and Caddy. The server serves the
|
||||
UI from `/app/public` and the API on one origin. See
|
||||
[Docker Deployment](#docker-deployment).
|
||||
|
||||
### Split containers
|
||||
|
||||
`docker-compose.split.yml` runs the server image unchanged next to a web
|
||||
container built from `Dockerfile.web`. The web container is Caddy: it serves the
|
||||
UI, packaged by `scripts/static/build.sh` when the image is built, and forwards
|
||||
`/api/*` and `/ws` to the server. The browser sees one origin, so the server
|
||||
needs no CORS setting. Logins work as on the classic UI when account
|
||||
configuration uses the public web origin, as described below.
|
||||
|
||||
```bash
|
||||
CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge \
|
||||
docker compose -f docker-compose.split.yml up -d --build
|
||||
```
|
||||
|
||||
| Variable | Default | |
|
||||
|---|---|---|
|
||||
| `HTTP_PORT`, `HTTPS_PORT` | `80`, `443` | Published by the web container; 443 over TCP and UDP (HTTP/3) |
|
||||
| `SITE_ADDRESS` | `:80` | A domain name turns on Caddy's automatic HTTPS and HTTP/3. Keep the default ports then: certificate issuance and the HTTP/3 advertisement both assume 80 and 443 |
|
||||
| `CORESCOPE_IMAGE` | none, required | The server image of the same version as the checkout the web image is built from: `:edge` on `master`, `:vX.Y.Z` on a release tag |
|
||||
| `DATA_DIR` | `./data` | The server's data directory |
|
||||
| `GIT_COMMIT` | the build time | The UI's cache buster |
|
||||
| `CHANNEL` | `static` | `beta`, `next` or `dev` shows a badge |
|
||||
| `MQTT_BIND`, `MQTT_PORT` | `127.0.0.1`, `1883` | Where the server's built-in broker is published. It accepts anonymous clients, so set `MQTT_BIND=0.0.0.0` only to let gateways on a network you trust publish to it |
|
||||
| `SPLIT_NET` | `172.30.83` | The compose network's /24, as its first three octets; the web container is `.200` in it. Change it only if Docker reports that the pool overlaps another network, and update `trustedProxies` to match |
|
||||
|
||||
- When `userManagement.enabled` is true, set `userManagement.publicBaseUrl` in
|
||||
the server's config to the public web origin, including its scheme and port
|
||||
(for example, `http://localhost:8080` for a web container published on port
|
||||
8080). Login and other state-changing requests compare the browser's `Origin`
|
||||
or `Referer` with this configured origin; forwarding the public `Host` header
|
||||
alone is not enough. This value also determines mail links. See
|
||||
[account configuration](user-guide/accounts.md#2-configure).
|
||||
- The web container finds the server through `BACKEND` (`corescope:3000` in the
|
||||
compose file). Port 3000 stays inside the compose network, and the server
|
||||
still serves everything there, the classic UI included; publish it if you want
|
||||
to reach that directly.
|
||||
- The web image is built from your checkout, so keep the checkout and
|
||||
`CORESCOPE_IMAGE` on the same version: a newer UI may call endpoints an older
|
||||
server lacks. To update only the UI, rebuild the web container:
|
||||
`docker compose -f docker-compose.split.yml up -d --build web`.
|
||||
- Behind the web container, as behind the all-in-one image's Caddy, every
|
||||
request reaches the server from the proxy's address, so per-IP limits are off
|
||||
until `webSocket.trustedProxies` and `userManagement.trustedProxies` list it.
|
||||
The compose file fixes that address at `172.30.83.200`: list it alone. Never
|
||||
list the compose subnet. It also holds the gateway address, and a client that
|
||||
reaches a published port 3000 through Docker's proxy (from the host itself or
|
||||
over IPv6, for example) arrives from there, so its own `X-Forwarded-For`
|
||||
would be believed.
|
||||
|
||||
### Static host or CDN
|
||||
|
||||
`make web` (or `scripts/static/build.sh`) writes the anonymous build to
|
||||
`dist/web` for Cloudflare Pages or any static host. It calls the server
|
||||
cross-origin, so the server lists the UI's origin in `CORS_ALLOWED_ORIGINS`.
|
||||
It sends no cookies; logins and admin pages link to the classic UI on the
|
||||
server. Setup, previews, server settings and rollback:
|
||||
[deploy/static/README.md](../deploy/static/README.md).
|
||||
|
||||
---
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
### Quick Start (one command)
|
||||
|
||||
+2
-1
@@ -119,7 +119,7 @@
|
||||
(window.CSSettingsSync ? '<h3>Settings sync</h3><div id="syncSection"></div>' : '') +
|
||||
'<h3>My data</h3>' +
|
||||
'<p class="account-hint">One JSON file with everything this instance stores about your account: profile, devices, synced settings, proposals, notifications, and your account and mail history. Passwords and login tokens are not included.</p>' +
|
||||
'<div class="account-actions"><a class="account-btn account-btn-secondary" id="accountExport" href="/api/account/export" download>Download my data</a></div>' +
|
||||
'<div class="account-actions"><a class="account-btn account-btn-secondary" id="accountExport" href="' + escapeHtml(CSApi.url('/api/account/export')) + '" download>Download my data</a></div>' +
|
||||
'<h3>Delete account</h3><form id="delForm" class="account-form" novalidate>' +
|
||||
'<p class="account-hint">This removes your account permanently. Server backups can still hold a copy for a few days until they rotate out.</p>' +
|
||||
field('delPw', 'Current password', 'password', 'current-password') +
|
||||
@@ -460,6 +460,7 @@
|
||||
};
|
||||
|
||||
function init(app, routeParam) {
|
||||
if (CSApi.anonymous) { app.innerHTML = shell('Accounts', CSBeta.classicOnlyHtml('Logging in')); return; }
|
||||
if (!window.CSAuth) { app.innerHTML = shell('Accounts', '<p>Accounts are not available.</p>'); return; }
|
||||
app.innerHTML = shell('Accounts', '<p>Loading…</p>');
|
||||
// A page left before the session is known must not render over the next one (#2230).
|
||||
|
||||
@@ -68,6 +68,7 @@
|
||||
history.replaceState(null, '', legacy);
|
||||
routeParam = null;
|
||||
}
|
||||
if (CSApi.anonymous) { app.innerHTML = page('<h2>Admin</h2>' + CSBeta.classicOnlyHtml('Administration')); return Promise.resolve(); }
|
||||
app.innerHTML = page('<p>Loading…</p>');
|
||||
var ready = window.CSAuth ? CSAuth.ready() : Promise.resolve();
|
||||
return ready.then(function () {
|
||||
|
||||
+3
-3
@@ -506,10 +506,10 @@
|
||||
`;
|
||||
|
||||
// Affinity stats widget — fetch and append if debugAffinity enabled
|
||||
var showDebug = (window.CLIENT_CONFIG && window.CLIENT_CONFIG.debugAffinity) || localStorage.getItem('meshcore-affinity-debug') === 'true';
|
||||
var showDebug = !CSApi.anonymous && ((window.CLIENT_CONFIG && window.CLIENT_CONFIG.debugAffinity) || localStorage.getItem('meshcore-affinity-debug') === 'true');
|
||||
if (showDebug) {
|
||||
var apiKey = localStorage.getItem('meshcore-api-key') || '';
|
||||
fetch('/api/debug/affinity', { headers: { 'X-API-Key': apiKey } })
|
||||
CSApi.fetch('/api/debug/affinity', { headers: { 'X-API-Key': apiKey } })
|
||||
.then(function (r) { return r.ok ? r.json() : null; })
|
||||
.then(function (data) {
|
||||
if (!data || !data.stats) return;
|
||||
@@ -4904,7 +4904,7 @@ function destroy() { _stopRolesRefresh(); _stopScopesRefresh(); _stopDistanceRet
|
||||
el.innerHTML = '<div class="text-center text-muted" style="padding:40px">Loading clock health data…</div>';
|
||||
try {
|
||||
const aqs = AreaFilter.areaQueryString();
|
||||
var data = await (await fetch('/api/nodes/clock-skew' + (aqs ? '?' + aqs.slice(1) : ''))).json();
|
||||
var data = await (await CSApi.fetch('/api/nodes/clock-skew' + (aqs ? '?' + aqs.slice(1) : ''))).json();
|
||||
if (!Array.isArray(data) || !data.length) {
|
||||
el.innerHTML = '<div class="text-center text-muted" style="padding:40px">No clock skew data available. Nodes need recent adverts for clock analysis.</div>';
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/* The one place that knows where the API lives. Every /api request and the
|
||||
* WebSocket go through window.CSApi, so the same files work embedded in the
|
||||
* Go server (apiBase '') and from a static host that calls the API on another
|
||||
* origin (apiBase 'https://api.example'). Reads window.CS_DEPLOYMENT, set by
|
||||
* deployment.js, which must load first. .eslintrc.json keeps raw '/api'
|
||||
* fetches out of every other file. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var dep = window.CS_DEPLOYMENT || {};
|
||||
var base = String(dep.apiBase || '').replace(/\/+$/, '');
|
||||
var auth = dep.auth !== false;
|
||||
var classicBase = String(dep.classicUrl || '').replace(/\/+$/, '');
|
||||
|
||||
// Logins on another origin send the session cookie, which no server accepts
|
||||
// across origins yet, so CORS blocks every request. build.sh refuses the
|
||||
// pair; a hand-edited deployment.js gets told why instead.
|
||||
if (base && auth && window.console) {
|
||||
window.console.warn('CoreScope: deployment.js pairs an apiBase on another origin with auth: true. ' +
|
||||
'The server does not accept the session cookie across origins, so every API request will be blocked. ' +
|
||||
'Set auth: false, or serve this UI from the API origin.');
|
||||
}
|
||||
|
||||
// url('/api/nodes?limit=50') is the full URL of an API path.
|
||||
function url(path) {
|
||||
if (typeof path !== 'string' || path.charAt(0) !== '/') throw new Error('api path must start with /: ' + path);
|
||||
return base + path;
|
||||
}
|
||||
|
||||
// wsUrl('/ws') is the WebSocket URL on the API host.
|
||||
function wsUrl(path) {
|
||||
if (base) return base.replace(/^http/, 'ws') + path;
|
||||
return (location.protocol === 'https:' ? 'wss:' : 'ws:') + '//' + location.host + path;
|
||||
}
|
||||
|
||||
// credentials picks what a request may carry. Same origin keeps the
|
||||
// browser default. Cross-origin with logins sends the session cookie, which
|
||||
// no server accepts yet: build.sh refuses that combination. Cross-origin
|
||||
// without logins sends nothing: the server's embed CORS tier never allows
|
||||
// credentials, so an 'include' request would be blocked.
|
||||
function credentials() {
|
||||
if (!base) return 'same-origin';
|
||||
return auth ? 'include' : 'omit';
|
||||
}
|
||||
|
||||
function apiFetch(path, opts) {
|
||||
var o = {};
|
||||
if (opts) for (var k in opts) if (Object.prototype.hasOwnProperty.call(opts, k)) o[k] = opts[k];
|
||||
if (!o.credentials) o.credentials = credentials();
|
||||
return fetch(url(path), o);
|
||||
}
|
||||
|
||||
// postJSON sends a JSON body as text/plain, so a cross-origin POST stays a
|
||||
// CORS simple request with no preflight. The server decodes the body as JSON
|
||||
// whatever its Content-Type; cmd/server/simple_post_test.go pins that.
|
||||
function postJSON(path, body) {
|
||||
return apiFetch(path, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'text/plain;charset=UTF-8' } });
|
||||
}
|
||||
|
||||
// classicHref('#/account') opens the same route on the embedded UI, or
|
||||
// returns null when this build has no classic UI to send people to.
|
||||
function classicHref(hash) {
|
||||
if (!classicBase) return null;
|
||||
var h = typeof hash === 'string' ? hash : (location.hash || '');
|
||||
return classicBase + '/' + (h && h.charAt(0) !== '#' ? '#' + h : h);
|
||||
}
|
||||
|
||||
window.CSApi = {
|
||||
base: base,
|
||||
auth: auth,
|
||||
crossOrigin: !!base,
|
||||
// anonymous: a static build that must not offer logins or admin actions.
|
||||
anonymous: !!base && !auth,
|
||||
// embedded: the server serves this UI (the classic descriptor on its own
|
||||
// origin). A packaged build in the web container is same-origin but not
|
||||
// embedded.
|
||||
embedded: !base && (dep.channel || 'classic') === 'classic',
|
||||
channel: dep.channel || 'classic',
|
||||
commit: dep.commit || null,
|
||||
url: url,
|
||||
wsUrl: wsUrl,
|
||||
fetch: apiFetch,
|
||||
postJSON: postJSON,
|
||||
classicHref: classicHref
|
||||
};
|
||||
})();
|
||||
+51
-8
@@ -130,11 +130,49 @@ const CLIENT_TTL = {
|
||||
nodeAnalytics: 60000, nodeSearch: 10000
|
||||
};
|
||||
// Fetch server cache config and use as client TTLs (server values are in seconds)
|
||||
fetch('/api/config/cache').then(r => r.json()).then(cfg => {
|
||||
CSApi.fetch('/api/config/cache').then(r => r.json()).then(cfg => {
|
||||
for (const [k, v] of Object.entries(cfg)) {
|
||||
if (k in CLIENT_TTL && typeof v === 'number') CLIENT_TTL[k] = v * 1000;
|
||||
}
|
||||
}).catch(() => {});
|
||||
// A packaged UI (a static host, the web container) can fail in two ways the
|
||||
// embedded UI never sees, and both would otherwise leave pages silently
|
||||
// empty. A blocked CORS request (the server does not list this origin)
|
||||
// rejects with a TypeError and no status: that becomes code
|
||||
// 'network_or_cors'. A wrong API base answers with a static host's HTML:
|
||||
// that becomes code 'not_json'. Each shows one toast a minute at most.
|
||||
const _apiProblemShownAt = {};
|
||||
function apiProblem(code, message, cause) {
|
||||
const err = new Error(message);
|
||||
err.code = code;
|
||||
if (cause) err.cause = cause;
|
||||
const now = Date.now();
|
||||
if (!_apiProblemShownAt[code] || now - _apiProblemShownAt[code] > 60000) {
|
||||
_apiProblemShownAt[code] = now;
|
||||
if (window.CSAuth && typeof window.CSAuth.notify === 'function') window.CSAuth.notify(message);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
async function apiFetchOrExplain(path) {
|
||||
try {
|
||||
return await CSApi.fetch('/api' + path);
|
||||
} catch (e) {
|
||||
if (CSApi.crossOrigin && e instanceof TypeError) throw apiProblem('network_or_cors', "Can't reach the CoreScope API", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
function rejectHtmlResponse(res, path) {
|
||||
const ct = res.headers && typeof res.headers.get === 'function' ? res.headers.get('Content-Type') : null;
|
||||
// Only HTML is refused: an /api answer is never a page, while some JSON
|
||||
// handlers leave Content-Type to Go's sniffing (text/plain).
|
||||
if (ct && /^text\/html/i.test(ct)) {
|
||||
const err = apiProblem('not_json', 'Server returned an unexpected response');
|
||||
err.status = res.status;
|
||||
err.path = path;
|
||||
err.retryAfter = res.headers.get('Retry-After');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
async function api(path, { ttl = 0, bust = false } = {}) {
|
||||
const t0 = performance.now();
|
||||
if (!bust && ttl > 0) {
|
||||
@@ -169,7 +207,13 @@ async function api(path, { ttl = 0, bust = false } = {}) {
|
||||
let notified = false;
|
||||
try {
|
||||
while (true) {
|
||||
const res = await fetch('/api' + path);
|
||||
const res = await apiFetchOrExplain(path);
|
||||
// On a packaged UI, a static host or proxy error page is not a server
|
||||
// warm-up response, even when its status is 503: explain it before
|
||||
// status/retry handling. The embedded UI keeps its old handling: a
|
||||
// proxy's HTML 503 is retried below, and the server's SPA fallback for
|
||||
// an unknown /api path fails to parse.
|
||||
if (!CSApi.embedded) rejectHtmlResponse(res, path);
|
||||
if (res.status === 503 && attempt < maxAttempts) {
|
||||
const ra = parseInt(res.headers.get('Retry-After'), 10);
|
||||
const wait = isFinite(ra) && ra > 0 ? ra * 1000 : delay;
|
||||
@@ -882,8 +926,7 @@ function connectWS() {
|
||||
clearTimeout(wsReconnectTimer);
|
||||
wsReconnectTimer = null;
|
||||
dropWS();
|
||||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const sock = new WebSocket(`${proto}//${location.host}`);
|
||||
const sock = new WebSocket(CSApi.wsUrl('/ws'));
|
||||
ws = sock;
|
||||
// Measured from creation, so a handshake that never completes is caught too.
|
||||
wsLastMessageAt = Date.now();
|
||||
@@ -1855,9 +1898,9 @@ window.addEventListener('DOMContentLoaded', () => {
|
||||
searchTimeout = setTimeout(async () => {
|
||||
try {
|
||||
const [packets, nodes, channels, reported] = await Promise.all([
|
||||
fetch('/api/packets?limit=5&hash=' + encodeURIComponent(q)).then(r => r.json()).catch(() => ({ packets: [] })),
|
||||
fetch('/api/nodes?search=' + encodeURIComponent(q)).then(r => r.json()).catch(() => []),
|
||||
fetch('/api/channels').then(r => r.json()).catch(() => []),
|
||||
CSApi.fetch('/api/packets?limit=5&hash=' + encodeURIComponent(q)).then(r => r.json()).catch(() => ({ packets: [] })),
|
||||
CSApi.fetch('/api/nodes?search=' + encodeURIComponent(q)).then(r => r.json()).catch(() => []),
|
||||
CSApi.fetch('/api/channels').then(r => r.json()).catch(() => []),
|
||||
// Repeaters known only from their reported name are not in /api/nodes.
|
||||
window.ReportedNodes ? window.ReportedNodes.load() : Promise.resolve({ nodes: [] })
|
||||
]);
|
||||
@@ -1952,7 +1995,7 @@ window.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
// --- Theme Customization ---
|
||||
// Fetch theme config and apply via customizer v2 pipeline
|
||||
fetch('/api/config/theme', { cache: 'no-store' }).then(r => r.json()).then(cfg => {
|
||||
CSApi.fetch('/api/config/theme', { cache: 'no-store' }).then(r => r.json()).then(cfg => {
|
||||
// Normalize timestamp defaults
|
||||
cfg = cfg || {};
|
||||
if (!cfg.timestamps) cfg.timestamps = {};
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
async function fetchAreas() {
|
||||
if (_loaded) return _areas;
|
||||
try {
|
||||
var data = await fetch('/api/config/areas').then(function (r) { return r.json(); });
|
||||
var data = await CSApi.fetch('/api/config/areas').then(function (r) { return r.json(); });
|
||||
_areas = Array.isArray(data) ? data : [];
|
||||
_loaded = true;
|
||||
if (_selected && !_areas.some(function (a) { return a.key === _selected; })) {
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Area Map</title>
|
||||
<link rel="stylesheet" href="vendor/leaflet-1.9.4/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="/>
|
||||
<script src="deployment.js?v=__BUST__"></script>
|
||||
<script src="api-base.js?v=__BUST__"></script>
|
||||
<script src="vendor/leaflet-1.9.4/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="></script>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -142,7 +144,7 @@ function setStatus(msg, isErr) {
|
||||
|
||||
// ---- load from server ----
|
||||
async function load() {
|
||||
baseUrl = document.getElementById('base-url').value.replace(/\/$/, '');
|
||||
baseUrl = (document.getElementById('base-url').value || window.CSApi.base).replace(/\/$/, '');
|
||||
setStatus('Loading…');
|
||||
|
||||
Object.values(areaLayers).forEach(g => { map.removeLayer(g.poly); map.removeLayer(g.nodes); });
|
||||
@@ -154,6 +156,7 @@ async function load() {
|
||||
document.getElementById('show-nodes').checked = false;
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line no-restricted-syntax -- baseUrl is whichever server the page's Server field names, not necessarily CSApi's.
|
||||
const areasResp = await fetch(`${baseUrl}/api/config/areas/polygons`);
|
||||
if (!areasResp.ok) throw new Error(`areas/polygons: ${areasResp.status}`);
|
||||
|
||||
@@ -234,6 +237,7 @@ function escapeHtml(s) {
|
||||
async function fetchAllNodesPaged(extra) {
|
||||
const PAGE = 500, CAP = 10000, out = [];
|
||||
for (let off = 0; off < CAP; off += PAGE) {
|
||||
// eslint-disable-next-line no-restricted-syntax -- baseUrl is whichever server the page's Server field names, not necessarily CSApi's.
|
||||
const r = await fetch(`${baseUrl}/api/nodes?limit=${PAGE}&offset=${off}${extra}`);
|
||||
if (!r.ok) throw new Error(`/api/nodes ${r.status} at offset ${off}`);
|
||||
const d = await r.json();
|
||||
|
||||
+23
-2
@@ -7,7 +7,7 @@
|
||||
var state = { enabled: false, user: null, ready: null };
|
||||
|
||||
function request(method, path, body) {
|
||||
var opts = { method: method, credentials: 'same-origin', headers: { 'Accept': 'application/json' } };
|
||||
var opts = { method: method, headers: { 'Accept': 'application/json' } };
|
||||
if (body !== undefined) {
|
||||
opts.headers['Content-Type'] = 'application/json';
|
||||
opts.body = JSON.stringify(body);
|
||||
@@ -15,7 +15,7 @@
|
||||
if (method !== 'GET' && state.user && state.user.csrfToken) {
|
||||
opts.headers['X-CS-CSRF'] = state.user.csrfToken;
|
||||
}
|
||||
return fetch(path, opts).then(function (res) {
|
||||
return CSApi.fetch(path, opts).then(function (res) {
|
||||
return res.json().catch(function () { return {}; }).then(function (data) {
|
||||
if (res.status === 401 && state.user && path !== '/api/auth/login' && path !== '/api/auth/activate') {
|
||||
setUser(null);
|
||||
@@ -171,7 +171,28 @@
|
||||
});
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeMenu(); });
|
||||
|
||||
// Anonymous static build on a server with accounts: the nav offers the
|
||||
// classic site's login, on the same page, instead of a login of its own.
|
||||
function renderClassicLogin() {
|
||||
var href = CSApi.classicHref('#/account/login');
|
||||
var right = document.querySelector('.top-nav .nav-right');
|
||||
if (!href || !right || document.getElementById('accountWrap')) return;
|
||||
var wrap = document.createElement('div');
|
||||
wrap.id = 'accountWrap';
|
||||
wrap.className = 'nav-account-wrap';
|
||||
var a = document.createElement('a');
|
||||
a.className = 'nav-account-btn';
|
||||
a.id = 'accountToggle';
|
||||
a.href = href;
|
||||
a.title = 'Accounts live on the classic site';
|
||||
a.innerHTML = icon('ph-user-circle') + '<span class="nav-account-label">Log in on classic</span>';
|
||||
wrap.appendChild(a);
|
||||
right.insertBefore(wrap, document.getElementById('hamburger'));
|
||||
window.dispatchEvent(new CustomEvent('cs-auth-control-added'));
|
||||
}
|
||||
|
||||
state.ready = Promise.resolve(window.MeshConfigReady).then(function () {
|
||||
if (window.MC_ACCOUNTS_ON_CLASSIC) { renderClassicLogin(); return null; }
|
||||
if (!window.MC_USER_MGMT || !window.MC_USER_MGMT.enabled) return null;
|
||||
state.enabled = true;
|
||||
renderControl();
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/* What a static build of the UI shows that the embedded one does not: a
|
||||
* channel badge in the nav that opens a pre-filled beta issue, an "Open in
|
||||
* classic" link, and the note that replaces a control an anonymous build
|
||||
* cannot offer. Reads window.CSApi (api-base.js). Inert on the embedded UI,
|
||||
* whose channel is classic. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var REPO = 'https://github.com/Kpa-clawbot/CoreScope';
|
||||
// The static channel is an operator's own frontend, not a beta: no badge.
|
||||
var BADGES = { beta: 'Beta', next: 'Next', dev: 'Dev' };
|
||||
|
||||
function esc(s) {
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function badgeLabel(channel) {
|
||||
return Object.prototype.hasOwnProperty.call(BADGES, channel) ? BADGES[channel] : null;
|
||||
}
|
||||
|
||||
// issueUrl opens a new issue pre-filled with what a report needs and nobody
|
||||
// remembers to type: page, channel, commit, browser. GitHub's title and body
|
||||
// parameters do this without an issue template in the repository.
|
||||
function issueUrl(channel, commit, page, browser) {
|
||||
// Account queries can contain mail-link tokens. Redact before creating
|
||||
// the badge: account.js removes tokens with replaceState, which does not
|
||||
// emit hashchange to refresh an already-created issue link.
|
||||
page = String(page || '');
|
||||
if (/^#\/account(?:\/|\?|$)/.test(page)) page = page.split('?')[0];
|
||||
var body = '**Page:** ' + (page || '') + '\n\n' +
|
||||
'**What I expected (what the classic site does):**\n\n\n' +
|
||||
'**What happened on the ' + (channel || 'beta') + ' frontend:**\n\n\n' +
|
||||
'---\n' +
|
||||
'Channel: ' + (channel || '') + ' · Commit: ' + (commit || 'unknown') + ' · Browser: ' + (browser || '') + '\n';
|
||||
return REPO + '/issues/new?title=' + encodeURIComponent('[' + (channel || 'beta') + '] ') +
|
||||
'&body=' + encodeURIComponent(body);
|
||||
}
|
||||
|
||||
// classicOnlyHtml stands in for a control this build cannot offer, e.g.
|
||||
// classicOnlyHtml('Resetting server stats').
|
||||
function classicOnlyHtml(what) {
|
||||
var href = window.CSApi.classicHref();
|
||||
return '<p class="cs-classic-only">' + esc(what) + ' is available on the classic site.' +
|
||||
(href ? ' <a class="cs-classic-link" href="' + esc(href) + '">Open in classic</a>' : '') + '</p>';
|
||||
}
|
||||
|
||||
function refreshLinks(doc) {
|
||||
var api = window.CSApi;
|
||||
var badge = doc.getElementById('csChannelBadge');
|
||||
if (badge) badge.href = issueUrl(api.channel, api.commit, location.hash || '#/', navigator.userAgent);
|
||||
var classic = doc.getElementById('csClassicLink');
|
||||
if (classic) classic.href = api.classicHref() || '#';
|
||||
}
|
||||
|
||||
// renderNav adds the badge (and, with classicUrl set, the classic link)
|
||||
// after the brand. Both follow the hash, so they open the current page.
|
||||
function renderNav(doc) {
|
||||
var api = window.CSApi;
|
||||
var label = badgeLabel(api.channel);
|
||||
if (!label || doc.getElementById('csChannelBadge')) return false;
|
||||
var brand = doc.querySelector('.top-nav .nav-brand');
|
||||
if (!brand) return false;
|
||||
var wrap = doc.createElement('span');
|
||||
wrap.className = 'cs-channel-wrap';
|
||||
var badge = doc.createElement('a');
|
||||
badge.id = 'csChannelBadge';
|
||||
badge.className = 'cs-channel-badge';
|
||||
badge.target = '_blank';
|
||||
badge.rel = 'noopener';
|
||||
badge.title = label + (api.commit ? ' ' + api.commit : '') + ': report an issue with this page';
|
||||
badge.textContent = label;
|
||||
wrap.appendChild(badge);
|
||||
if (api.classicHref()) {
|
||||
var classic = doc.createElement('a');
|
||||
classic.id = 'csClassicLink';
|
||||
classic.className = 'cs-classic-nav-link';
|
||||
classic.title = 'Open this page on the classic site';
|
||||
classic.textContent = 'Classic';
|
||||
wrap.appendChild(classic);
|
||||
}
|
||||
brand.parentNode.insertBefore(wrap, brand.nextSibling);
|
||||
refreshLinks(doc);
|
||||
window.addEventListener('hashchange', function () { refreshLinks(doc); });
|
||||
return true;
|
||||
}
|
||||
|
||||
window.CSBeta = { badgeLabel: badgeLabel, issueUrl: issueUrl, classicOnlyHtml: classicOnlyHtml, renderNav: renderNav };
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', function () { renderNav(document); });
|
||||
} else {
|
||||
renderNav(document);
|
||||
}
|
||||
})();
|
||||
+1
-1
@@ -1959,7 +1959,7 @@
|
||||
// and the user may want to browse other regions even if they're
|
||||
// viewing one. Future work: per-section region selector.
|
||||
var url = '/api/known-channels';
|
||||
fetch(url).then(function (r) { return r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)); })
|
||||
CSApi.fetch(url).then(function (r) { return r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)); })
|
||||
.then(function (snap) {
|
||||
__knownChannels = (snap && Array.isArray(snap.entries)) ? snap.entries : [];
|
||||
__knownChannelsError = null;
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
statusGreen: '--status-green', statusYellow: '--status-yellow', statusRed: '--status-red',
|
||||
statusYellowText: '--status-yellow-text', statusRedText: '--status-red-text',
|
||||
statusGreenTintText: '--status-green-tint-text',
|
||||
betaBadgeBg: '--beta-badge-bg', betaBadgeText: '--beta-badge-text',
|
||||
surface1: '--surface-1', surface2: '--surface-2', surface3: '--surface-3',
|
||||
sectionBg: '--section-bg',
|
||||
cardBg: '--card-bg', contentBg: '--content-bg', detailBg: '--detail-bg',
|
||||
@@ -1749,6 +1750,7 @@
|
||||
'<div style="position:absolute;top:7px;right:7px;background:rgba(255,255,255,0.88);border-radius:4px;padding:3px 8px;font-size:11px;color:#444;pointer-events:none;box-shadow:0 1px 3px rgba(0,0,0,0.15)"><svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor-sprite.svg#ph-magnifying-glass"/></svg> click to expand</div>' +
|
||||
'</div>' +
|
||||
'<div id="cv2-gf-status" style="font-size:12px;color:var(--text-muted);margin-bottom:10px">Loading current filter…</div>' +
|
||||
(window.CSApi && CSApi.anonymous ? CSBeta.classicOnlyHtml('Editing the geographic filter') : '') +
|
||||
// Edit controls — hidden until server confirms write access (writeEnabled=true)
|
||||
'<div id="cv2-gf-edit" style="display:none">' +
|
||||
'<div style="display:flex;gap:8px;margin-bottom:10px;align-items:center">' +
|
||||
@@ -1963,7 +1965,10 @@
|
||||
|
||||
// The editor is usable with a write-capable API key (gf.writeEnabled) or an
|
||||
// admin session (server: requireAdmin accepts both).
|
||||
// An anonymous static build cannot send the API key or the session in a
|
||||
// way the server accepts cross-origin, so it never offers the editor.
|
||||
function _gfCanEdit(gf, csAuth) {
|
||||
if (window.CSApi && CSApi.anonymous) return false;
|
||||
return !!((gf && gf.writeEnabled) || (csAuth && csAuth.isAdmin()));
|
||||
}
|
||||
|
||||
@@ -2004,7 +2009,7 @@
|
||||
var headers = _gfAuthHeaders(container, { 'Content-Type': 'application/json' }, window.CSAuth);
|
||||
if (!headers) { _gfMsg(container, 'API key required to save.', false); return; }
|
||||
var bufferKm = parseFloat((container.querySelector('#cv2-gf-buffer') || {}).value) || 0;
|
||||
fetch('/api/config/geo-filter', {
|
||||
CSApi.fetch('/api/config/geo-filter', {
|
||||
method: 'PUT',
|
||||
headers: headers,
|
||||
body: JSON.stringify({ polygon: _gfPoints, bufferKm: bufferKm })
|
||||
@@ -2020,7 +2025,7 @@
|
||||
var headers = _gfAuthHeaders(container, { 'Content-Type': 'application/json' }, window.CSAuth);
|
||||
if (!headers) { _gfMsg(container, 'API key required.', false); return; }
|
||||
if (!confirm('Remove geo filter? All nodes will be allowed through.')) return;
|
||||
fetch('/api/config/geo-filter', {
|
||||
CSApi.fetch('/api/config/geo-filter', {
|
||||
method: 'PUT',
|
||||
headers: headers,
|
||||
body: JSON.stringify({ polygon: null })
|
||||
@@ -2049,7 +2054,7 @@
|
||||
if (!headers) { _gfPruneMsg(container, 'API key required.', false); return; }
|
||||
var btn = container.querySelector('#cv2-gf-prune-preview');
|
||||
if (btn) btn.textContent = 'Loading…';
|
||||
fetch('/api/admin/prune-geo-filter', {
|
||||
CSApi.fetch('/api/admin/prune-geo-filter', {
|
||||
method: 'POST',
|
||||
headers: headers
|
||||
}).then(function (r) {
|
||||
@@ -2088,7 +2093,7 @@
|
||||
var count = _gfPruneNodes.length;
|
||||
if (!confirm('Delete ' + count + ' node' + (count !== 1 ? 's' : '') + ' from the database? This cannot be undone.')) return;
|
||||
var pubkeys = _gfPruneNodes.map(function (n) { return n.pubkey; });
|
||||
fetch('/api/admin/prune-geo-filter?confirm=true', {
|
||||
CSApi.fetch('/api/admin/prune-geo-filter?confirm=true', {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: JSON.stringify({ pubkeys: pubkeys })
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/* Deployment descriptor. The embedded (classic) UI ships this file as is.
|
||||
* scripts/static/build.sh replaces it when it packages public/ for a static
|
||||
* host, with the API base, channel and commit of that build.
|
||||
*
|
||||
* channel classic | beta | next | dev | static
|
||||
* apiBase '' = same origin (classic, or a host that forwards /api and
|
||||
* /ws to the server); an https origin on a static host
|
||||
* auth false = anonymous build: no cookies, no login or admin UI
|
||||
* classicUrl the embedded UI to link to for what the build cannot do */
|
||||
window.CS_DEPLOYMENT = { channel: 'classic', commit: null, version: null, apiBase: '', auth: true, classicUrl: null };
|
||||
@@ -84,8 +84,10 @@
|
||||
· <a href="/geofilter-docs.html">Documentation</a>
|
||||
</div>
|
||||
|
||||
<script src="geofilter-draft.js"></script>
|
||||
<script src="map-tile-providers.js"></script>
|
||||
<script src="deployment.js?v=__BUST__"></script>
|
||||
<script src="api-base.js?v=__BUST__"></script>
|
||||
<script src="geofilter-draft.js?v=__BUST__"></script>
|
||||
<script src="map-tile-providers.js?v=__BUST__"></script>
|
||||
<script>
|
||||
const map = L.map('map').setView([50.5, 4.4], 8);
|
||||
|
||||
@@ -98,7 +100,7 @@ const tiles = L.tileLayer(DEFAULT_DARK_TILES, {
|
||||
// This page is standalone (not the SPA), so it loads the server's map config
|
||||
// itself and re-resolves the tile URL through the shared registry. Without
|
||||
// this, CARTO serves every tile stamped 'API KEY REQUIRED' — with a 200.
|
||||
fetch('/api/config/client')
|
||||
CSApi.fetch('/api/config/client')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (cfg) {
|
||||
window.MC_MAP_CFG = (cfg && cfg.map) || { tiles: { providers: {} } };
|
||||
|
||||
@@ -192,6 +192,9 @@
|
||||
<main id="app" role="main"></main>
|
||||
|
||||
<script src="vendor/qrcode.js"></script>
|
||||
<script src="deployment.js?v=__BUST__"></script>
|
||||
<script src="api-base.js?v=__BUST__"></script>
|
||||
<script src="beta-ui.js?v=__BUST__"></script>
|
||||
<script src="payload-labels.js?v=__BUST__"></script>
|
||||
<script src="roles.js?v=__BUST__"></script>
|
||||
<script src="map-tile-providers.js?v=__BUST__"></script>
|
||||
|
||||
+9
-9
@@ -466,7 +466,7 @@
|
||||
loadNodes(targetTs);
|
||||
|
||||
// Fetch packets from scrub point forward (ASC order, no limit clipping from the wrong end)
|
||||
fetch(`/api/packets?limit=10000&grouped=false&expand=observations&since=${encodeURIComponent(fetchFrom)}&order=asc`)
|
||||
CSApi.fetch(`/api/packets?limit=10000&grouped=false&expand=observations&since=${encodeURIComponent(fetchFrom)}&order=asc`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const pkts = data.packets || [];
|
||||
@@ -527,7 +527,7 @@
|
||||
// Fetch packets from DB for the time window
|
||||
const now = Date.now();
|
||||
const from = new Date(now - ms).toISOString();
|
||||
fetch(`/api/packets?limit=${window.LIVE_MAP_MAX_NODES}&grouped=false&expand=observations&since=${encodeURIComponent(from)}`)
|
||||
CSApi.fetch(`/api/packets?limit=${window.LIVE_MAP_MAX_NODES}&grouped=false&expand=observations&since=${encodeURIComponent(from)}`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const pkts = (data.packets || []).reverse(); // oldest first
|
||||
@@ -601,7 +601,7 @@
|
||||
if (!last) return Promise.resolve(false);
|
||||
var gen = VCR.replayGen;
|
||||
const since = new Date(last.ts + 1).toISOString(); // +1ms to avoid dupe
|
||||
return fetch(`/api/packets?limit=10000&grouped=false&expand=observations&since=${encodeURIComponent(since)}&order=asc`)
|
||||
return CSApi.fetch(`/api/packets?limit=10000&grouped=false&expand=observations&since=${encodeURIComponent(since)}&order=asc`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const pkts = data.packets || [];
|
||||
@@ -992,7 +992,7 @@
|
||||
if (scopeMs === VCR.timelineFetchedScope) return;
|
||||
const since = new Date(Date.now() - scopeMs).toISOString();
|
||||
try {
|
||||
const resp = await fetch(`/api/packets/timestamps?since=${encodeURIComponent(since)}`);
|
||||
const resp = await CSApi.fetch(`/api/packets/timestamps?since=${encodeURIComponent(since)}`);
|
||||
if (resp.ok) {
|
||||
const timestamps = await resp.json(); // array of ISO strings
|
||||
VCR.timelineTimestamps = timestamps.map(t => new Date(t).getTime());
|
||||
@@ -1396,7 +1396,7 @@
|
||||
let mapCenter = [37.45, -122.0];
|
||||
let mapZoom = 9;
|
||||
try {
|
||||
const mapCfg = await (await fetch('/api/config/map')).json();
|
||||
const mapCfg = await (await CSApi.fetch('/api/config/map')).json();
|
||||
if (Array.isArray(mapCfg.center) && mapCfg.center.length === 2) mapCenter = mapCfg.center;
|
||||
if (typeof mapCfg.zoom === 'number') mapZoom = mapCfg.zoom;
|
||||
} catch { }
|
||||
@@ -1712,7 +1712,7 @@
|
||||
// (cmd/server/types.go ObserverListResponse) — NOT a top-level array.
|
||||
// Bug #1136: previously parsed as array → map empty → region filter
|
||||
// dropped every packet.
|
||||
fetch('/api/observers').then(function(r) { return r.json(); }).then(function(data) {
|
||||
CSApi.fetch('/api/observers').then(function(r) { return r.json(); }).then(function(data) {
|
||||
setObserverIataMap(buildObserverIataMap(data));
|
||||
}).catch(function() { /* leave map empty; filter will hide all when active */ });
|
||||
RegionFilter.init(rfEl, { dropdown: true });
|
||||
@@ -1807,7 +1807,7 @@
|
||||
if (!nodeFilterDropdown) return;
|
||||
if (!q || q.length < 1) { hideDropdown(); return; }
|
||||
try {
|
||||
const resp = await fetch('/api/nodes/search?q=' + encodeURIComponent(q));
|
||||
const resp = await CSApi.fetch('/api/nodes/search?q=' + encodeURIComponent(q));
|
||||
if (!resp.ok) { hideDropdown(); return; }
|
||||
const data = await resp.json();
|
||||
const nodes = (data && data.nodes) || [];
|
||||
@@ -2801,7 +2801,7 @@
|
||||
|
||||
async function fetchAffinityData() {
|
||||
try {
|
||||
const resp = await fetch('/api/analytics/neighbor-graph');
|
||||
const resp = await CSApi.fetch('/api/analytics/neighbor-graph');
|
||||
const graph = await resp.json();
|
||||
if (window.HopResolver && HopResolver.setAffinity) {
|
||||
HopResolver.setAffinity(graph);
|
||||
@@ -3265,7 +3265,7 @@
|
||||
async function replayRecent() {
|
||||
try {
|
||||
// Single bulk fetch with expand=observations — no N+1 calls
|
||||
const resp = await fetch('/api/packets?limit=8&expand=observations');
|
||||
const resp = await CSApi.fetch('/api/packets?limit=8&expand=observations');
|
||||
const data = await resp.json();
|
||||
const groups = (data.packets || []).reverse();
|
||||
|
||||
|
||||
+10
-13
@@ -628,7 +628,7 @@
|
||||
let defaultCenter = [37.6, -122.1];
|
||||
let defaultZoom = 9;
|
||||
try {
|
||||
const mapCfg = await (await fetch('/api/config/map')).json();
|
||||
const mapCfg = await (await CSApi.fetch('/api/config/map')).json();
|
||||
if (Array.isArray(mapCfg.center) && mapCfg.center.length === 2) defaultCenter = mapCfg.center;
|
||||
if (typeof mapCfg.zoom === 'number') defaultZoom = mapCfg.zoom;
|
||||
} catch {}
|
||||
@@ -877,7 +877,8 @@
|
||||
// Affinity Debug overlay toggle — shown only when debugAffinity config is on or localStorage override
|
||||
(function initAffinityDebug() {
|
||||
var label = document.getElementById('mcAffinityDebugLabel');
|
||||
var show = (window.CLIENT_CONFIG && window.CLIENT_CONFIG.debugAffinity) || localStorage.getItem('meshcore-affinity-debug') === 'true';
|
||||
// Needs the admin API key, which an anonymous static build cannot send.
|
||||
var show = !CSApi.anonymous && ((window.CLIENT_CONFIG && window.CLIENT_CONFIG.debugAffinity) || localStorage.getItem('meshcore-affinity-debug') === 'true');
|
||||
if (show && label) label.style.display = '';
|
||||
var cb = document.getElementById('mcAffinityDebug');
|
||||
if (!cb) return;
|
||||
@@ -1137,7 +1138,7 @@
|
||||
try {
|
||||
const hopList = (hopKeys || []).join(',');
|
||||
const apiUrl = '/api/resolve-hops?hops=' + encodeURIComponent(hopList);
|
||||
const resp = await fetch(apiUrl, { cache: 'no-cache' });
|
||||
const resp = await CSApi.fetch(apiUrl, { cache: 'no-cache' });
|
||||
if (resp.ok) {
|
||||
const json = await resp.json();
|
||||
serverResolved = json && json.resolved ? json.resolved : null;
|
||||
@@ -1406,7 +1407,7 @@
|
||||
if (!inferred) {
|
||||
try {
|
||||
const apiUrl = '/api/resolve-hops?hops=' + encodeURIComponent(canonicalPath.join(','));
|
||||
const resp = await fetch(apiUrl, { cache: 'no-cache' });
|
||||
const resp = await CSApi.fetch(apiUrl, { cache: 'no-cache' });
|
||||
if (resp.ok) {
|
||||
const json = await resp.json();
|
||||
serverResolved = json && json.resolved ? json.resolved : null;
|
||||
@@ -1532,7 +1533,7 @@
|
||||
if (!nodes || !nodes.length) {
|
||||
await new Promise(r => setTimeout(r, 600));
|
||||
}
|
||||
const resp = await fetch('/api/packets/' + encodeURIComponent(packetHash));
|
||||
const resp = await CSApi.fetch('/api/packets/' + encodeURIComponent(packetHash));
|
||||
if (!resp.ok) {
|
||||
console.warn('[deep-link] /api/packets/' + packetHash + ' returned ' + resp.status);
|
||||
return;
|
||||
@@ -1668,7 +1669,7 @@
|
||||
// GRP_TXT: try to resolve the channel name from /api/channels.
|
||||
if (inferredType === 'GRP_TXT' && inferredChannelHash) {
|
||||
try {
|
||||
const chResp = await fetch('/api/channels?includeEncrypted=true');
|
||||
const chResp = await CSApi.fetch('/api/channels?includeEncrypted=true');
|
||||
if (chResp.ok) {
|
||||
const chData = await chResp.json();
|
||||
const chList = chData.channels || [];
|
||||
@@ -1718,7 +1719,7 @@
|
||||
if (!pktCtx.channelEncrypted) {
|
||||
try {
|
||||
const cleanName = (pktCtx.channelName || '').replace(/^#/, '');
|
||||
const msgResp = await fetch('/api/channels/' + encodeURIComponent(cleanName) + '/messages?limit=10');
|
||||
const msgResp = await CSApi.fetch('/api/channels/' + encodeURIComponent(cleanName) + '/messages?limit=10');
|
||||
if (msgResp.ok) {
|
||||
const msgs = await msgResp.json();
|
||||
const m = (msgs.messages || []).find(mm => mm.packet_hash === packetHash || mm.hash === packetHash);
|
||||
@@ -2456,11 +2457,7 @@
|
||||
if (err) { errDiv.textContent = err; return; }
|
||||
|
||||
resultsDiv.innerHTML = '<p style="font-size:12px;">Loading...</p>';
|
||||
fetch('/api/paths/inspect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prefixes: prefixes })
|
||||
})
|
||||
CSApi.postJSON('/api/paths/inspect', { prefixes: prefixes })
|
||||
.then(function (r) {
|
||||
if (r.status === 503) return r.json().then(function () { throw new Error('Service warming up, retry shortly.'); });
|
||||
if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || 'Request failed'); });
|
||||
@@ -2589,7 +2586,7 @@
|
||||
clearAffinityOverlay();
|
||||
// Fetch debug data — requires API key stored in localStorage
|
||||
var apiKey = localStorage.getItem('meshcore-api-key') || '';
|
||||
fetch('/api/debug/affinity', { headers: { 'X-API-Key': apiKey } })
|
||||
CSApi.fetch('/api/debug/affinity', { headers: { 'X-API-Key': apiKey } })
|
||||
.then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
|
||||
.then(function (data) {
|
||||
affinityData = data;
|
||||
|
||||
@@ -223,7 +223,7 @@
|
||||
// The optional `opts.fetchImpl` lets tests inject a fake fetch.
|
||||
function mount(container, opts) {
|
||||
opts = opts || {};
|
||||
var fetchImpl = opts.fetchImpl || (typeof window !== 'undefined' && window.fetch ? window.fetch.bind(window) : null);
|
||||
var fetchImpl = opts.fetchImpl || (typeof window !== 'undefined' && window.CSApi ? window.CSApi.fetch : null);
|
||||
if (!fetchImpl) return function noop() {};
|
||||
var stopped = false;
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
var versionPromise = null;
|
||||
function fetchVersion() {
|
||||
if (versionPromise) return versionPromise;
|
||||
versionPromise = fetch('/api/health', { headers: { Accept: 'application/json' } })
|
||||
versionPromise = CSApi.fetch('/api/health', { headers: { Accept: 'application/json' } })
|
||||
.then(function (r) { return r.ok ? r.json() : null; })
|
||||
.catch(function () { return null; });
|
||||
return versionPromise;
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
var b = map.getBounds();
|
||||
var bbox = [b.getSouth(), b.getWest(), b.getNorth(), b.getEast()].join(',');
|
||||
var url = '/api/nodes/' + encodeURIComponent(pubkey) + '/rx-coverage?bbox=' + bbox + '&z=' + map.getZoom();
|
||||
fetch(url).then(function (r) { return r.json(); }).then(function (fc) {
|
||||
CSApi.fetch(url).then(function (r) { return r.json(); }).then(function (fc) {
|
||||
group.clearLayers();
|
||||
(fc.features || []).forEach(function (f) {
|
||||
var ring = (f.geometry.coordinates[0] || []).map(function (c) { return [c[1], c[0]]; }); // [lon,lat]→[lat,lon]
|
||||
|
||||
+3
-1
@@ -1173,8 +1173,10 @@
|
||||
var panel = document.getElementById('node-affinity-debug');
|
||||
if (!show || !panel) return;
|
||||
panel.style.display = '';
|
||||
var debugEl = document.getElementById('affinityDebugContent');
|
||||
if (CSApi.anonymous) { if (debugEl) debugEl.innerHTML = CSBeta.classicOnlyHtml('Affinity debug'); return; }
|
||||
var apiKey = localStorage.getItem('meshcore-api-key') || '';
|
||||
fetch('/api/debug/affinity?node=' + encodeURIComponent(n.public_key), { headers: { 'X-API-Key': apiKey } })
|
||||
CSApi.fetch('/api/debug/affinity?node=' + encodeURIComponent(n.public_key), { headers: { 'X-API-Key': apiKey } })
|
||||
.then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
|
||||
.then(function (data) {
|
||||
var el = document.getElementById('affinityDebugContent');
|
||||
|
||||
+3
-10
@@ -2272,11 +2272,7 @@
|
||||
if (toFetch.length > 0) {
|
||||
const hashes = toFetch.map(p => p.hash);
|
||||
try {
|
||||
const resp = await fetch('/api/packets/observations', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({hashes})
|
||||
});
|
||||
const resp = await CSApi.postJSON('/api/packets/observations', {hashes});
|
||||
if (resp.ok) {
|
||||
const data = await resp.json();
|
||||
const results = data.results || {};
|
||||
@@ -2404,7 +2400,7 @@
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const resp = await fetch('/api/nodes/search?q=' + encodeURIComponent(q));
|
||||
const resp = await CSApi.fetch('/api/nodes/search?q=' + encodeURIComponent(q));
|
||||
const data = await resp.json();
|
||||
if (seq !== nodeSearchSeq) return;
|
||||
const nodes = data.nodes || [];
|
||||
@@ -4293,10 +4289,7 @@
|
||||
if (!/^[0-9a-fA-F]+$/.test(hex)) { result.innerHTML = '<p class="byop-err" role="alert">Invalid hex — only 0-9 and A-F allowed</p>'; return; }
|
||||
result.innerHTML = '<p class="text-muted">Decoding...</p>';
|
||||
try {
|
||||
const res = await fetch('/api/decode', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ hex })
|
||||
});
|
||||
const res = await CSApi.postJSON('/api/decode', { hex });
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
result.innerHTML = renderDecodedPacket(data.decoded, hex);
|
||||
|
||||
@@ -82,11 +82,7 @@
|
||||
}
|
||||
|
||||
resultsDiv.innerHTML = '<p>Loading...</p>';
|
||||
fetch('/api/paths/inspect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prefixes: prefixes })
|
||||
})
|
||||
CSApi.postJSON('/api/paths/inspect', { prefixes: prefixes })
|
||||
.then(function (r) {
|
||||
if (r.status === 503) return r.json().then(function (d) { throw new Error('Service warming up, retry in a few seconds.'); });
|
||||
if (!r.ok) return r.json().then(function (d) { throw new Error(d.error || 'Request failed'); });
|
||||
|
||||
+10
-7
@@ -118,12 +118,12 @@ function renderVersionCard(health) {
|
||||
// #1258: /api/health was awaited AFTER Promise.all, adding a full RTT
|
||||
// (~50-200ms) on every 5s refresh. Issue it in parallel with the rest.
|
||||
const [server, client, ioStats, sqliteStats, writeSources, health] = await Promise.all([
|
||||
fetch('/api/perf').then(r => r.json()),
|
||||
CSApi.fetch('/api/perf').then(r => r.json()),
|
||||
Promise.resolve(window.apiPerf ? window.apiPerf() : null),
|
||||
fetch('/api/perf/io').then(r => r.json()).catch(() => null),
|
||||
fetch('/api/perf/sqlite').then(r => r.json()).catch(() => null),
|
||||
fetch('/api/perf/write-sources').then(r => r.json()).catch(() => null),
|
||||
fetch('/api/health').then(r => r.json()).catch(() => null)
|
||||
CSApi.fetch('/api/perf/io').then(r => r.json()).catch(() => null),
|
||||
CSApi.fetch('/api/perf/sqlite').then(r => r.json()).catch(() => null),
|
||||
CSApi.fetch('/api/perf/write-sources').then(r => r.json()).catch(() => null),
|
||||
CSApi.fetch('/api/health').then(r => r.json()).catch(() => null)
|
||||
]);
|
||||
|
||||
let html = '';
|
||||
@@ -359,11 +359,14 @@ function renderVersionCard(health) {
|
||||
html += '</tbody></table></div>';
|
||||
}
|
||||
|
||||
html += `<div style="margin-top:16px"><button id="perfReset" style="padding:8px 16px;cursor:pointer">Reset Stats</button> <button id="perfRefresh" style="padding:8px 16px;cursor:pointer">Refresh</button></div>`;
|
||||
// Reset needs an admin; an anonymous static build cannot be one.
|
||||
const resetHtml = CSApi.anonymous ? '' : '<button id="perfReset" style="padding:8px 16px;cursor:pointer">Reset Stats</button> ';
|
||||
html += `<div style="margin-top:16px">${resetHtml}<button id="perfRefresh" style="padding:8px 16px;cursor:pointer">Refresh</button></div>`;
|
||||
if (CSApi.anonymous) html += CSBeta.classicOnlyHtml('Resetting server stats');
|
||||
el.innerHTML = html;
|
||||
|
||||
document.getElementById('perfReset')?.addEventListener('click', async () => {
|
||||
if (!(await resetPerfStats(window, fetch, alert))) return;
|
||||
if (!(await resetPerfStats(window, CSApi.fetch, alert))) return;
|
||||
if (window._apiPerf) { window._apiPerf = { calls: 0, totalMs: 0, log: [] }; }
|
||||
refresh();
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
/** Fetch the configured quick picks. A failure only means no quick picks. */
|
||||
async function fetchQuickPicks() {
|
||||
try {
|
||||
var data = await fetch('/api/config/region-quick-picks').then(function (r) { return r.json(); });
|
||||
var data = await CSApi.fetch('/api/config/region-quick-picks').then(function (r) { return r.json(); });
|
||||
_picks = (data && Array.isArray(data.quickPicks)) ? data.quickPicks : [];
|
||||
} catch (e) {
|
||||
// Offline or an older server without the endpoint: the region filter
|
||||
@@ -48,7 +48,7 @@
|
||||
if (_loaded) return _regions;
|
||||
var picksLoaded = fetchQuickPicks();
|
||||
try {
|
||||
var data = await fetch('/api/config/regions').then(function (r) { return r.json(); });
|
||||
var data = await CSApi.fetch('/api/config/regions').then(function (r) { return r.json(); });
|
||||
_regions = data || {};
|
||||
_loaded = true;
|
||||
// If stored selection has codes no longer valid, clean up
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
// failed request, yields an empty list so callers never break on it.
|
||||
function load() {
|
||||
if (cache && Date.now() - cache.at < TTL_MS) return cache.promise;
|
||||
var p = fetch('/api/nodes/reported')
|
||||
var p = CSApi.fetch('/api/nodes/reported')
|
||||
.then(function (r) { return r.ok ? r.json() : { nodes: [] }; })
|
||||
.then(function (j) { return { nodes: (j && j.nodes) || [], method: (j && j.method) || null }; })
|
||||
.catch(function () { return { nodes: [], method: null }; });
|
||||
|
||||
+7
-2
@@ -622,7 +622,7 @@
|
||||
};
|
||||
|
||||
// ─── Fetch server overrides ───
|
||||
window.MeshConfigReady = fetch('/api/config/client').then(function (r) { return r.json(); }).then(function (cfg) {
|
||||
window.MeshConfigReady = CSApi.fetch('/api/config/client').then(function (r) { return r.json(); }).then(function (cfg) {
|
||||
window.MC_CLIENT_RX_COVERAGE = cfg.clientRxCoverage === true;
|
||||
window.MC_CLIENT_RF_SAMPLES = cfg.clientRfSamples === true;
|
||||
window.MC_CLIENT_RX_APP_URL = typeof cfg.clientRxAppUrl === 'string' ? cfg.clientRxAppUrl : '';
|
||||
@@ -705,7 +705,12 @@
|
||||
? { disabledTabs: Array.isArray(cfg.customizer.disabledTabs) ? cfg.customizer.disabledTabs : [] }
|
||||
: { disabledTabs: [] };
|
||||
// Optional user management: present only when the server enables it.
|
||||
window.MC_USER_MGMT = (cfg.userManagement && cfg.userManagement.enabled) ? { enabled: true, channelProposals: !!cfg.userManagement.channelProposals, notifications: !!cfg.userManagement.notifications, observerLogins: !!cfg.userManagement.observerLogins } : null;
|
||||
// An anonymous static build (CSApi.anonymous) sends no cookies, so it
|
||||
// cannot log anyone in: every account feature stays off there, and
|
||||
// MC_ACCOUNTS_ON_CLASSIC tells the nav to link to classic instead.
|
||||
var userMgmt = (cfg.userManagement && cfg.userManagement.enabled) ? { enabled: true, channelProposals: !!cfg.userManagement.channelProposals, notifications: !!cfg.userManagement.notifications, observerLogins: !!cfg.userManagement.observerLogins } : null;
|
||||
window.MC_USER_MGMT = CSApi.anonymous ? null : userMgmt;
|
||||
window.MC_ACCOUNTS_ON_CLASSIC = !!(CSApi.anonymous && userMgmt);
|
||||
// #1574 — operator-configurable cap on /live map node count.
|
||||
if (cfg.liveMapMaxNodes != null) window.LIVE_MAP_MAX_NODES = cfg.liveMapMaxNodes;
|
||||
// #1784 — path trust threshold: minimum hash bytes for mapping evidence.
|
||||
|
||||
@@ -99,9 +99,9 @@
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
return Promise.all([
|
||||
fetch('/api/nodes/' + pk).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }),
|
||||
fetch('/api/nodes/' + pk + '/analytics?window=24h').then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }),
|
||||
fetch('/api/nodes/' + pk + '/paths?limit=20').then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }),
|
||||
CSApi.fetch('/api/nodes/' + pk).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }),
|
||||
CSApi.fetch('/api/nodes/' + pk + '/analytics?window=24h').then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }),
|
||||
CSApi.fetch('/api/nodes/' + pk + '/paths?limit=20').then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }),
|
||||
]).then(function (out) {
|
||||
var result = { detail: out[0], analytics: out[1], paths: out[2] };
|
||||
// Evict oldest entry (Map preserves insertion order) before adding.
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
// mine=1 was refused (the toggle is then cleared and the map redrawn).
|
||||
function fetchLayer(path, bbox, extra, seq) {
|
||||
var sentMine = mineSent();
|
||||
return fetch(coverageUrl(path, bbox, map.getZoom(), days, selectedRx, sentMine) + extra).then(function (r) {
|
||||
return CSApi.fetch(coverageUrl(path, bbox, map.getZoom(), days, selectedRx, sentMine) + extra).then(function (r) {
|
||||
var verdict = coverageReply(seq, drawSeq, r.status, sentMine);
|
||||
if (verdict === 'ignore') return null;
|
||||
if (verdict === 'mine-refused') {
|
||||
@@ -466,7 +466,7 @@
|
||||
function fitToObserver() {
|
||||
if (!map || !selectedRx) { drawCoverage(); return; }
|
||||
var url = '/api/rx-coverage?bbox=-90,-180,90,180&z=' + Math.max(8, map.getZoom()) + '&days=' + days + '&rx=' + encodeURIComponent(selectedRx);
|
||||
fetch(url).then(function (r) { return r.json(); }).then(function (fc) {
|
||||
CSApi.fetch(url).then(function (r) { return r.json(); }).then(function (fc) {
|
||||
if (destroyed || !map) return;
|
||||
var minLat = 90, minLon = 180, maxLat = -90, maxLon = -180, any = false;
|
||||
(fc.features || []).forEach(function (f) {
|
||||
@@ -483,7 +483,7 @@
|
||||
}
|
||||
|
||||
function loadBoard() {
|
||||
fetch('/api/rx-leaderboard?days=' + days + '&limit=25').then(function (r) { return r.json(); })
|
||||
CSApi.fetch('/api/rx-leaderboard?days=' + days + '&limit=25').then(function (r) { return r.json(); })
|
||||
.then(function (d) { if (destroyed) return; boardCache = d.observers || []; renderBoard(); })
|
||||
.catch(function (e) {
|
||||
console.warn('rx-coverage: leaderboard fetch failed', e);
|
||||
@@ -582,7 +582,7 @@
|
||||
if (!viewport) {
|
||||
viewport = { lat: 37.6, lon: -122.1, zoom: 9 };
|
||||
try {
|
||||
var response = await fetch('/api/config/map');
|
||||
var response = await CSApi.fetch('/api/config/map');
|
||||
var cfg = await response.json();
|
||||
if (cfg && Array.isArray(cfg.center) && cfg.center.length === 2) {
|
||||
viewport = parseViewportHash(new URLSearchParams({ lat: cfg.center[0], lon: cfg.center[1], zoom: cfg.zoom == null ? 9 : cfg.zoom }).toString()) || viewport;
|
||||
|
||||
@@ -265,6 +265,9 @@
|
||||
/* Green status words in the admin/user tables: green-700 is 4.48:1 on the
|
||||
row-hover tint #eef2ff, green-800 is 6.4:1 there. Dark keeps the bright hue. */
|
||||
--status-green-tint-text: var(--palette-green-800, #166534);
|
||||
/* Channel badge of a static build (beta-ui.js): amber, 6.85:1 white on yellow-800. */
|
||||
--beta-badge-bg: var(--palette-yellow-800, #854d0e);
|
||||
--beta-badge-text: #ffffff;
|
||||
/* Text-only yellow/red for surfaces that print status words on light cards
|
||||
(user-management chips): yellow-800 #854d0e is 6.85:1 on #fff and 6.13:1 on the row-hover tint #eef2ff (yellow-700 #a16207 was 4.4:1 there); red-700 #b91c1c
|
||||
is 6.47:1 on #fff. Dark theme keeps the bright hues, like green-text. */
|
||||
@@ -403,6 +406,8 @@
|
||||
/* #1996: dark already passes at 6.48:1 — keep the bright hue. */
|
||||
--sa-chip-observed-fg: #22c55e;
|
||||
--status-green-tint-text: #22c55e;
|
||||
--beta-badge-bg: #eab308;
|
||||
--beta-badge-text: #1c1917;
|
||||
/* #1719 — keep --skew-badge-no-clock-bg dark enough for #fff text. */
|
||||
--skew-badge-no-clock-bg: var(--palette-gray-600, #4b5563);
|
||||
--status-yellow-text: #eab308;
|
||||
@@ -473,6 +478,8 @@
|
||||
/* #1996: dark already passes at 6.48:1 — keep the bright hue. */
|
||||
--sa-chip-observed-fg: #22c55e;
|
||||
--status-green-tint-text: #22c55e;
|
||||
--beta-badge-bg: #eab308;
|
||||
--beta-badge-text: #1c1917;
|
||||
--skew-badge-no-clock-bg: var(--palette-gray-600, #4b5563);
|
||||
--status-yellow-text: #eab308;
|
||||
--status-red-text: var(--palette-red-400, #f87171);
|
||||
@@ -781,6 +788,12 @@ input[type="radio"] {
|
||||
/* #1403: removed overflow:hidden — was clipping flex children offscreen (vertical) AND clipping the More dropdown contents. The original purpose was to prevent horizontal overflow during Priority+ measurement (#1066) — that purpose is served by .top-nav itself which still has overflow:hidden. */
|
||||
.nav-left { display: flex; align-items: center; gap: var(--space-lg); min-width: 0; flex-shrink: 1; }
|
||||
.nav-brand { display: flex; align-items: center; gap: var(--space-sm); text-decoration: none; color: var(--nav-text); font-weight: 700; font-size: var(--fs-md); }
|
||||
/* Static builds only (beta-ui.js): channel badge and classic link after the brand. */
|
||||
.cs-channel-wrap { display: inline-flex; align-items: center; gap: 6px; margin-right: var(--space-sm); flex-shrink: 0; }
|
||||
.cs-channel-badge { background: var(--beta-badge-bg); color: var(--beta-badge-text); border-radius: 999px; padding: 2px 8px; font-size: 11px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; text-decoration: none; }
|
||||
.cs-channel-badge:hover, .cs-channel-badge:focus-visible { filter: brightness(1.1); }
|
||||
.cs-classic-nav-link { color: var(--nav-text-muted); font-size: 12px; text-decoration: underline; }
|
||||
.cs-classic-only { color: var(--text-muted); font-size: 13px; }
|
||||
.brand-icon { font-size: 20px; }
|
||||
/* #1450 — split .brand-logo by element type:
|
||||
- Inline default wordmark (<svg>) keeps the 125x36 pin tuned to its
|
||||
|
||||
@@ -156,7 +156,7 @@
|
||||
function pollOnce() {
|
||||
if (state.inflight || typeof fetch !== 'function') return;
|
||||
state.inflight = true;
|
||||
fetch('/api/healthz', { credentials: 'same-origin', cache: 'no-store' })
|
||||
window.CSApi.fetch('/api/healthz', { cache: 'no-store' })
|
||||
.then(function (resp) {
|
||||
if (resp && resp.headers && resp.headers.get) {
|
||||
noteLoadStatus(resp.headers.get('X-Corescope-Load-Status'));
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env node
|
||||
// Zero-dependency static file server for running the UI from one origin
|
||||
// against a CoreScope server on another, the way a static host does. There is
|
||||
// no proxy on purpose: the page on this port really calls the API cross-origin.
|
||||
//
|
||||
// node scripts/dev-static.mjs --root dist/web --port 8788
|
||||
//
|
||||
// Development and CI only. It serves files and nothing else.
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.ttf': 'font/ttf',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.webmanifest': 'application/manifest+json',
|
||||
'.wav': 'audio/wav',
|
||||
'.mp3': 'audio/mpeg',
|
||||
};
|
||||
|
||||
export function parseArgs(argv) {
|
||||
const opts = { root: 'dist/web', port: 8788, host: '127.0.0.1' };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === '--root') opts.root = argv[++i];
|
||||
else if (a === '--port') opts.port = Number(argv[++i]);
|
||||
else if (a === '--host') opts.host = argv[++i];
|
||||
else throw new Error('unknown argument: ' + a);
|
||||
}
|
||||
if (!Number.isInteger(opts.port) || opts.port < 0 || opts.port > 65535) throw new Error('bad --port');
|
||||
return opts;
|
||||
}
|
||||
|
||||
// resolveFile maps a URL path to a file under root, or null. It never leaves
|
||||
// root: the decoded path is normalised and must stay inside it.
|
||||
export function resolveFile(root, urlPath) {
|
||||
let p;
|
||||
try { p = decodeURIComponent(urlPath.split('?')[0].split('#')[0]); } catch { return null; }
|
||||
if (p.includes('\0')) return null;
|
||||
const abs = path.resolve(root, '.' + path.posix.normalize('/' + p));
|
||||
const rootAbs = path.resolve(root);
|
||||
if (abs !== rootAbs && !abs.startsWith(rootAbs + path.sep)) return null;
|
||||
let file = abs;
|
||||
try {
|
||||
if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html');
|
||||
if (!fs.statSync(file).isFile()) return null;
|
||||
} catch { return null; }
|
||||
return file;
|
||||
}
|
||||
|
||||
export function createServer(root) {
|
||||
return http.createServer((req, res) => {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
res.writeHead(405, { Allow: 'GET, HEAD', 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
res.end('method not allowed\n');
|
||||
return;
|
||||
}
|
||||
const file = resolveFile(root, req.url || '/');
|
||||
if (!file) {
|
||||
// An HTML page, like a static host's 404: api() must report it as not
|
||||
// JSON instead of failing to parse it.
|
||||
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end('<!doctype html><title>404</title><p>Not found</p>\n');
|
||||
return;
|
||||
}
|
||||
const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
|
||||
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-cache' });
|
||||
if (req.method === 'HEAD') { res.end(); return; }
|
||||
fs.createReadStream(file).pipe(res);
|
||||
});
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('dev-static.mjs')) {
|
||||
const opts = parseArgs(process.argv.slice(2));
|
||||
if (!fs.existsSync(opts.root)) {
|
||||
console.error(`dev-static: ${opts.root} not found (run scripts/static/build.sh first)`);
|
||||
process.exit(1);
|
||||
}
|
||||
createServer(opts.root).listen(opts.port, opts.host, () => {
|
||||
console.log(`dev-static: serving ${opts.root} on http://localhost:${opts.port}`);
|
||||
});
|
||||
}
|
||||
@@ -126,6 +126,7 @@
|
||||
"tests/e2e/test-show-neighbors.js",
|
||||
"tests/e2e/test-slideover-1056-e2e.js",
|
||||
"tests/e2e/test-slideover-1168-munger-e2e.js",
|
||||
"tests/e2e/test-split-anonymous-e2e.js",
|
||||
"tests/e2e/test-table-fluid-e2e.js",
|
||||
"tests/e2e/test-theme-url-param-2236-e2e.js",
|
||||
"tests/e2e/test-touch-gestures-coverage-e2e.js",
|
||||
@@ -134,9 +135,10 @@
|
||||
]
|
||||
},
|
||||
"domIntegration": {
|
||||
"reason": "Requires jsdom. The JS unit gate runs with no node_modules at all (its job has no npm install), so a suite needing a third-party module cannot live in test-all.sh. It runs in the E2E job, which does npm ci, and is invoked by its own deploy.yml line.",
|
||||
"reason": "Requires a third-party module (jsdom, or eslint for the lint rule suite). The JS unit gate runs with no node_modules at all (its job has no npm install), so a suite needing a third-party module cannot live in test-all.sh. It runs in the E2E job, which does npm ci, and is invoked by its own deploy.yml line.",
|
||||
"files": [
|
||||
"tests/e2e/test-region-quick-picks.js",
|
||||
"tests/e2e/test-lint-network-calls.js",
|
||||
"tests/e2e/test-radio-setting-1869-e2e.js",
|
||||
"tests/e2e/test-observer-neighbors-2270-e2e.js",
|
||||
"tests/e2e/test-table-sort.js"
|
||||
|
||||
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env bash
|
||||
# Packages public/ for a static host (Cloudflare Pages, a CDN, the web
|
||||
# container) instead of the CoreScope server. This is a packaging step, not a
|
||||
# build step: the output is public/ byte for byte, except that index.html gets
|
||||
# a cache buster and deployment.js says where the API is.
|
||||
#
|
||||
# A static host runs it as the build command (output dir dist/web); the web
|
||||
# container (Dockerfile.web) runs it when the image is built. Locally:
|
||||
# make web, or make dev-split to try it against a local server.
|
||||
#
|
||||
# Environment:
|
||||
# API_BASE required. https://host[:port] of the CoreScope server
|
||||
# (http only for localhost / 127.0.0.1), or same-origin for a
|
||||
# host that forwards /api and /ws to the server itself.
|
||||
# AUTH required, true or false; there is no default, so nobody turns
|
||||
# logins on by accident. false builds the anonymous UI: no
|
||||
# cookies, no login or admin controls. It is the only kind that
|
||||
# works on another origin, because the server allows no
|
||||
# credentialed CORS. true needs API_BASE=same-origin: the UI
|
||||
# then uses the server's logins exactly as embedded.
|
||||
# CHANNEL beta | next | dev | static. Default static.
|
||||
# COMMIT shown in the UI and used as the cache buster. Default: the
|
||||
# first 7 characters of CF_PAGES_COMMIT_SHA (set by Pages), else
|
||||
# git rev-parse --short HEAD.
|
||||
# CLASSIC_URL optional. The embedded UI, for "Open in classic" links.
|
||||
# OUT output directory. Default dist/web.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
|
||||
fail() { echo "build: $*" >&2; exit 1; }
|
||||
|
||||
OUT="${OUT:-dist/web}"
|
||||
CHANNEL="${CHANNEL:-static}"
|
||||
API_BASE="${API_BASE:-}"
|
||||
AUTH="${AUTH:-}"
|
||||
CLASSIC_URL="${CLASSIC_URL:-}"
|
||||
COMMIT="${COMMIT:-}"
|
||||
if [ -z "$COMMIT" ] && [ -n "${CF_PAGES_COMMIT_SHA:-}" ]; then COMMIT="${CF_PAGES_COMMIT_SHA:0:7}"; fi
|
||||
if [ -z "$COMMIT" ]; then COMMIT="$(git rev-parse --short HEAD 2>/dev/null || true)"; fi
|
||||
|
||||
# Every value lands inside a JS string literal, so each one is held to a
|
||||
# shape that cannot break out of it.
|
||||
origin_ok() {
|
||||
[[ "$1" =~ ^https://[a-z0-9.-]+(:[0-9]{1,5})?$ ]] && return 0
|
||||
[[ "$1" =~ ^http://(localhost|127\.0\.0\.1)(:[0-9]{1,5})?$ ]]
|
||||
}
|
||||
[ -n "$API_BASE" ] || fail "API_BASE is required (the CoreScope server, e.g. https://analyzer.example.org, or same-origin)"
|
||||
case "$AUTH" in
|
||||
true|false) ;;
|
||||
*) fail "AUTH must be true or false (false for the anonymous build)" ;;
|
||||
esac
|
||||
API_BASE="${API_BASE%/}"
|
||||
if [ "$API_BASE" = same-origin ]; then
|
||||
[ "$AUTH" = true ] || fail "same-origin needs AUTH=true: a UI on the server's own origin uses its logins"
|
||||
API_BASE=''
|
||||
else
|
||||
origin_ok "$API_BASE" || fail "API_BASE must be https://host[:port] in lowercase, with no path (http only for localhost), or same-origin: $API_BASE"
|
||||
# A build with logins sends the session cookie with every request, and the
|
||||
# server never answers a credentialed cross-origin request, so the browser
|
||||
# would block all of them.
|
||||
[ "$AUTH" = false ] || fail "AUTH=true needs API_BASE=same-origin: the server allows no credentialed CORS, so every API request of a cross-origin build with logins would be blocked (use AUTH=false)"
|
||||
fi
|
||||
if [ -n "$CLASSIC_URL" ]; then
|
||||
CLASSIC_URL="${CLASSIC_URL%/}"
|
||||
origin_ok "$CLASSIC_URL" || fail "CLASSIC_URL must be https://host[:port], with no path: $CLASSIC_URL"
|
||||
fi
|
||||
case "$CHANNEL" in
|
||||
beta|next|dev|static) ;;
|
||||
*) fail "CHANNEL must be beta, next, dev or static: $CHANNEL" ;;
|
||||
esac
|
||||
[[ "$COMMIT" =~ ^[A-Za-z0-9._-]{1,40}$ ]] || fail "COMMIT must be 1-40 characters of [A-Za-z0-9._-]: '$COMMIT'"
|
||||
|
||||
# OUT is replaced wholesale, so it must be new, empty or a previous build:
|
||||
# a typo in OUT must not wipe an unrelated folder.
|
||||
MARKER='/* Written by scripts/static/build.sh. */'
|
||||
if [ -e "$OUT" ]; then
|
||||
[ -d "$OUT" ] || fail "OUT is not a directory: $OUT"
|
||||
if [ -n "$(ls -A "$OUT")" ] && [ "$(head -n 1 "$OUT/deployment.js" 2>/dev/null)" != "$MARKER" ]; then
|
||||
fail "refusing to replace $OUT: it is neither empty nor a previous build (no deployment.js written by this script)"
|
||||
fi
|
||||
fi
|
||||
|
||||
rm -rf "$OUT"
|
||||
mkdir -p "$OUT"
|
||||
cp -R public/. "$OUT/"
|
||||
|
||||
# The same substitution spaHandler makes at server start in every top-level
|
||||
# page, with the commit in place of a timestamp so a rebuild of one commit is
|
||||
# byte-identical.
|
||||
for page in "$OUT"/*.html; do
|
||||
sed -i.bak "s/__BUST__/$COMMIT/g" "$page" && rm -f "$page.bak"
|
||||
done
|
||||
|
||||
classic_js=null
|
||||
[ -n "$CLASSIC_URL" ] && classic_js="'$CLASSIC_URL'"
|
||||
cat > "$OUT/deployment.js" <<EOF
|
||||
$MARKER
|
||||
window.CS_DEPLOYMENT = { channel: '$CHANNEL', commit: '$COMMIT', version: null, apiBase: '$API_BASE', auth: $AUTH, classicUrl: $classic_js };
|
||||
EOF
|
||||
|
||||
cp deploy/static/_headers "$OUT/_headers"
|
||||
|
||||
# -- checks ---------------------------------------------------------------------
|
||||
if grep -rl "__BUST__" "$OUT" >/dev/null; then fail "a __BUST__ placeholder is left in $(grep -rl "__BUST__" "$OUT" | head -1)"; fi
|
||||
[ ! -e "$OUT/functions" ] && [ ! -e "$OUT/_worker.js" ] || fail "functions/ and _worker.js are not allowed: the frontend is static only"
|
||||
count=$(find "$OUT" -type f | wc -l)
|
||||
[ "$count" -lt 20000 ] || fail "$count files; Cloudflare Pages allows fewer than 20000"
|
||||
# 25 MiB in bytes: busybox find (the web image) has no M suffix.
|
||||
big=$(find "$OUT" -type f -size +26214400c | head -1)
|
||||
[ -z "$big" ] || fail "$big is over 25 MiB, the Cloudflare Pages per-file limit"
|
||||
# Byte for byte public/, plus _headers. deployment.js is new, and the
|
||||
# top-level pages differ only by the cache buster.
|
||||
expected=$( (cd public && find . -type f; echo ./_headers) | sort)
|
||||
actual=$(cd "$OUT" && find . -type f | sort)
|
||||
[ "$expected" = "$actual" ] || fail "the output is not exactly public/ plus _headers:
|
||||
$(diff <(echo "$expected") <(echo "$actual") || true)"
|
||||
while IFS= read -r f; do
|
||||
case "$f" in
|
||||
./deployment.js|./_headers) ;;
|
||||
./*/*) cmp -s "public/$f" "$OUT/$f" || fail "$f differs from public/$f" ;;
|
||||
./*.html) sed "s/__BUST__/$COMMIT/g" "public/$f" | cmp -s - "$OUT/$f" || fail "$f is not public/$f with the cache buster" ;;
|
||||
*) cmp -s "public/$f" "$OUT/$f" || fail "$f differs from public/$f" ;;
|
||||
esac
|
||||
done <<< "$actual"
|
||||
|
||||
echo "build: $OUT ($count files) channel=$CHANNEL commit=$COMMIT apiBase=${API_BASE:-same-origin} auth=$AUTH"
|
||||
@@ -20,7 +20,10 @@ node tests/unit/test-admin-dashboard-ui.js
|
||||
node tests/unit/test-aging.js
|
||||
node tests/unit/test-analytics-channels-integration.js
|
||||
node tests/unit/test-anl1-tooltip-render.js
|
||||
node tests/unit/test-anonymous-mode.js
|
||||
node tests/unit/test-api-base.js
|
||||
node tests/unit/test-area-filter.js
|
||||
node tests/unit/test-beta-ui.js
|
||||
node tests/unit/test-channel-color-picker.js
|
||||
node tests/unit/test-channel-colors.js
|
||||
node tests/unit/test-channel-decrypt-ecb.js
|
||||
@@ -48,11 +51,14 @@ node tests/unit/test-compare-overlap.js
|
||||
node tests/unit/test-confidence-indicator.js
|
||||
node tests/unit/test-coverage-gate.js
|
||||
node tests/unit/test-customizer-v2.js
|
||||
node tests/unit/test-dev-static.js
|
||||
node tests/unit/test-dockerfile-buildplatform.js
|
||||
node tests/unit/test-drag-manager.js
|
||||
node tests/unit/test-e2e-coverage.js
|
||||
node tests/unit/test-direct-rf-heard-by.js
|
||||
node tests/unit/test-embed-mode-1369.js
|
||||
node tests/unit/test-static-build.js
|
||||
node tests/unit/test-web-container.js
|
||||
node tests/unit/test-theme-url-param-2236.js
|
||||
node tests/unit/test-fetch-all-nodes-pagination.js
|
||||
node tests/unit/test-fluid-scaffolding.js
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env node
|
||||
/* The no-restricted-syntax rule in .eslintrc.json keeps every request to the
|
||||
* CoreScope server on CSApi (public/api-base.js), so the UI also works from a
|
||||
* static host or CDN. This lints snippets as a file in public/ with the
|
||||
* repository's own config and checks exactly which lines the rule reports:
|
||||
* the ways around CSApi must be reported, and CSApi itself, api(),
|
||||
* CSAuth.request and plain app links must not. public/api-base.js is the one
|
||||
* file exempt. It also applies the rule to the inline scripts and markup of
|
||||
* public/*.html, which `eslint public/*.js` never sees.
|
||||
*
|
||||
* Needs eslint (a devDependency), so it runs in the E2E job, which does
|
||||
* npm ci, rather than in test-all.sh.
|
||||
*/
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { ESLint } = require('eslint');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const RULE = 'no-restricted-syntax';
|
||||
|
||||
// [statement, reported]: one statement per line of the linted text.
|
||||
const CASES = [
|
||||
['fetch(u);', true],
|
||||
['window.fetch(u);', true],
|
||||
['globalThis.fetch(u);', true],
|
||||
['var x = new XMLHttpRequest();', true],
|
||||
["navigator.sendBeacon('/api/perf', 'x');", true],
|
||||
["var es = new EventSource('/api/stream');", true],
|
||||
["var ws = new WebSocket('ws://' + location.host + '/ws');", true],
|
||||
["var h1 = '<a href=\"/api/export\">';", true],
|
||||
["var h2 = '<a href=\\'/api/export\\'>';", true],
|
||||
['var h3 = `<a href="/api/export/${u}">`;', true],
|
||||
["var h4 = '<img src=\"/api/nodes/' + u + '/avatar\">';", true],
|
||||
["var h5 = '<form action=\"/api/decode\">';", true],
|
||||
["location.href = '/api/export?x=1';", true],
|
||||
["a.href = '/api/export/' + u;", true],
|
||||
['a.src = `/api/export/${u}`;', true],
|
||||
["window.open('/api/export');", true],
|
||||
["a.href = '/api/nodes/' + u + '/avatar';", true],
|
||||
["a.href = '/api' + u;", true],
|
||||
["var h9 = '<a href=\"/api' + u + '\">';", true],
|
||||
["a.setAttribute('href', '/api/export');", true],
|
||||
["a.setAttribute('src', '/api/nodes/' + u + '/avatar');", true],
|
||||
["a.setAttribute('action', `/api/decode?x=${u}`);", true],
|
||||
["location.assign('/api/export');", true],
|
||||
["window.location.replace('/api/export/' + u);", true],
|
||||
["window.location = '/api/export';", true],
|
||||
["CSApi.fetch('/api/nodes');", false],
|
||||
["CSApi.postJSON('/api/decode', {});", false],
|
||||
["api('/nodes?limit=5');", false],
|
||||
["CSAuth.request('GET', '/api/account');", false],
|
||||
["var ws2 = new WebSocket(CSApi.wsUrl('/ws'));", false],
|
||||
["a.href = CSApi.url('/api/export');", false],
|
||||
['var h6 = `<a href="${CSApi.url(\'/api/export\')}">`;', false],
|
||||
["var h7 = '<a href=\"#/nodes\">';", false],
|
||||
["var h8 = '<img src=\"/icons/x.svg\">';", false],
|
||||
["location.href = '#/nodes';", false],
|
||||
["a.setAttribute('href', CSApi.url('/api/export'));", false],
|
||||
["a.setAttribute('title', '/api/export');", false],
|
||||
["location.assign('#/nodes');", false],
|
||||
["var p = u.replace('/api/', '');", false],
|
||||
["a.href = '/apiary';", false],
|
||||
];
|
||||
const HEADER = ['/* global api */', "var u = '/api/nodes', a = document.createElement('a');"];
|
||||
|
||||
let passed = 0, failed = 0;
|
||||
function test(name, fn) {
|
||||
try { fn(); passed++; console.log(' ✅ ' + name); }
|
||||
catch (e) { failed++; console.log(' ❌ ' + name + ': ' + e.message); }
|
||||
}
|
||||
|
||||
// A bare /api path in a URL attribute of a page's markup.
|
||||
const API_ATTR = /\b(href|src|action|formaction)\s*=\s*["']?\/api(\/|["'\s>])/i;
|
||||
|
||||
(async () => {
|
||||
// Unused disable directives are reported too, so an exception cannot outlive
|
||||
// the call it excused.
|
||||
const eslint = new ESLint({ cwd: ROOT, reportUnusedDisableDirectives: 'error' });
|
||||
async function lint(text, file) {
|
||||
const [result] = await eslint.lintText(text, { filePath: path.join(ROOT, 'public', file) });
|
||||
const fatal = result.messages.find((m) => m.fatal);
|
||||
if (fatal) throw new Error(file + ': ' + fatal.message);
|
||||
return result.messages.filter((m) => m.ruleId === RULE || (m.ruleId === null && /eslint-disable/.test(m.message)));
|
||||
}
|
||||
|
||||
console.log('Lint rule: network calls go through CSApi');
|
||||
const reported = new Set((await lint(HEADER.concat(CASES.map((c) => c[0])).join('\n') + '\n', 'zz-lint-probe.js'))
|
||||
.map((m) => m.line));
|
||||
CASES.forEach(([statement, bad], i) => {
|
||||
test((bad ? 'reports ' : 'allows ') + statement, () => {
|
||||
assert.strictEqual(reported.has(HEADER.length + 1 + i), bad);
|
||||
});
|
||||
});
|
||||
|
||||
const exempt = await lint("fetch(u);\nvar ws = new WebSocket('ws://x/ws');\n", 'api-base.js');
|
||||
test('public/api-base.js is exempt', () => assert.deepStrictEqual(exempt.map((m) => m.line), []));
|
||||
|
||||
// `eslint public/*.js` never sees the pages' inline scripts or markup. Lint
|
||||
// each inline script with the same rule, its lines kept, and check the
|
||||
// markup's own URL attributes.
|
||||
console.log('\nInline scripts and markup of public/*.html');
|
||||
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
||||
const pages = fs.readdirSync(path.join(ROOT, 'public')).filter((f) => f.endsWith('.html')).sort();
|
||||
for (const page of pages) {
|
||||
const src = fs.readFileSync(path.join(ROOT, 'public', page), 'utf8');
|
||||
const problems = [];
|
||||
let m, n = 0;
|
||||
while ((m = SCRIPT.exec(src))) {
|
||||
if (/\bsrc\s*=/i.test(m[1])) continue;
|
||||
const before = src.slice(0, m.index + m[0].indexOf('>') + 1).split('\n').length - 1;
|
||||
const found = await lint('\n'.repeat(before) + m[2], page.replace(/\.html$/, '') + '-inline-' + (n++) + '.js');
|
||||
found.forEach((f) => problems.push(page + ':' + f.line + ' ' + f.message.split(':')[0]));
|
||||
}
|
||||
const markup = src.replace(SCRIPT, '');
|
||||
(markup.match(new RegExp(API_ATTR.source, 'gi')) || []).forEach((x) => problems.push(page + ' markup: ' + x));
|
||||
test(page + ': inline scripts and markup reach the server only through CSApi', () =>
|
||||
assert.deepStrictEqual(problems, []));
|
||||
}
|
||||
const probe = await lint('\n'.repeat(4) + "fetch('/api/x');\n// eslint-disable-next-line no-restricted-syntax\nvar ok = 1;\n", 'zz-page-probe.js');
|
||||
test('the page check reports at the page line, and a stale eslint-disable too', () =>
|
||||
assert.deepStrictEqual(probe.map((f) => f.line), [5, 6]));
|
||||
test('the markup check sees /api in href, src and action, and not elsewhere', () => {
|
||||
['<a href="/api/export">', "<img src='/api/x'>", '<form action=/api/decode>', '<a href="/api">']
|
||||
.forEach((s) => assert.ok(API_ATTR.test(s), s));
|
||||
['<a href="#/api/x">', '<code>/api/nodes</code>', '<a href="/apiary">'].forEach((s) => assert.ok(!API_ATTR.test(s), s));
|
||||
});
|
||||
|
||||
console.log(`\nlint network calls: ${passed} passed, ${failed} failed`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
})().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -13,6 +13,9 @@ const { JSDOM } = require('jsdom');
|
||||
const byCode = (a, b) => a.localeCompare(b);
|
||||
|
||||
const SRC = fs.readFileSync(REPO_ROOT + '/public/region-filter.js', 'utf8');
|
||||
// region-filter.js fetches through window.CSApi, as in the browser, where
|
||||
// deployment.js and api-base.js load first.
|
||||
const API_SRC = ['deployment.js', 'api-base.js'].map((f) => fs.readFileSync(REPO_ROOT + '/public/' + f, 'utf8'));
|
||||
let passed = 0, failed = 0;
|
||||
async function test(name, fn) {
|
||||
try { await fn(); passed++; console.log(' ✓ ' + name); }
|
||||
@@ -38,6 +41,7 @@ async function setup(regions, picks, opts) {
|
||||
}
|
||||
return { json: async () => regions };
|
||||
};
|
||||
API_SRC.forEach((src) => w.eval(src));
|
||||
w.eval(SRC);
|
||||
const rf = w.RegionFilter;
|
||||
const calls = [];
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* E2E: the anonymous static build, served from one origin, against a stock
|
||||
* CoreScope server on another that lists it in CORS_ALLOWED_ORIGINS. No
|
||||
* server code is involved beyond that env var.
|
||||
*
|
||||
* Checks, in a real browser with real CORS:
|
||||
* - every top-level page renders, with no page error and no /api request
|
||||
* left on the static origin;
|
||||
* - no API request carries the API host's cookies (the embed tier never
|
||||
* allows credentials);
|
||||
* - the WebSocket connects to the API host's /ws;
|
||||
* - the three JSON POSTs go as text/plain, with no preflight;
|
||||
* - the badge is shown, and account and admin point to classic;
|
||||
* - a blocked request and an HTML answer each show their notice.
|
||||
*
|
||||
* Setup (what CI does):
|
||||
* CHANNEL=dev COMMIT=e2e API_BASE=http://localhost:13591 AUTH=false \
|
||||
* CLASSIC_URL=http://localhost:13591 bash scripts/static/build.sh
|
||||
* CORS_ALLOWED_ORIGINS=http://localhost:8788 ./corescope-server -port 13591 \
|
||||
* -db test-fixtures/e2e-fixture.db -public /nonexistent &
|
||||
* node scripts/dev-static.mjs --root dist/web --port 8788 &
|
||||
*
|
||||
* Usage: SPLIT_URL=http://localhost:8788 API_URL=http://localhost:13591 node test-split-anonymous-e2e.js
|
||||
*/
|
||||
const { chromium } = require('playwright');
|
||||
|
||||
const SPLIT = process.env.SPLIT_URL || 'http://localhost:8788';
|
||||
const API = process.env.API_URL || 'http://localhost:13591';
|
||||
const PAGES = ['#/home', '#/packets', '#/live', '#/map', '#/channels', '#/nodes', '#/analytics', '#/observers', '#/tools', '#/perf', '#/compare'];
|
||||
|
||||
async function test(name, fn) {
|
||||
try {
|
||||
await fn();
|
||||
console.log(` ✅ ${name}`);
|
||||
} catch (err) {
|
||||
console.log(` ❌ ${name}: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function assert(cond, msg) {
|
||||
if (!cond) throw new Error(msg || 'Assertion failed');
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.CHROMIUM_PATH || undefined,
|
||||
args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'],
|
||||
});
|
||||
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
|
||||
// A session cookie for the API host, as a visitor logged in on classic has.
|
||||
// The anonymous build must never send it.
|
||||
await context.addCookies([{ name: 'cs_session', value: 'e2e-classic-session', url: API }]);
|
||||
const page = await context.newPage();
|
||||
|
||||
const errors = [];
|
||||
const apiRequests = [];
|
||||
const sockets = [];
|
||||
page.on('pageerror', (e) => errors.push(e.message));
|
||||
page.on('request', (r) => { if (r.url().includes('/api/')) apiRequests.push(r); });
|
||||
page.on('websocket', (ws) => sockets.push(ws.url()));
|
||||
|
||||
console.log(`Split anonymous E2E: static ${SPLIT}, API ${API}`);
|
||||
|
||||
await test('every top-level page renders from the static origin', async () => {
|
||||
for (const hash of PAGES) {
|
||||
await page.goto(SPLIT + '/' + hash, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => {
|
||||
const app = document.getElementById('app');
|
||||
return app && app.innerText.trim().length > 20;
|
||||
}, null, { timeout: 15000 });
|
||||
await page.waitForTimeout(800);
|
||||
}
|
||||
assert(errors.length === 0, 'page errors: ' + errors.join(' | '));
|
||||
});
|
||||
|
||||
await test('every API request goes to the API origin', async () => {
|
||||
const stray = apiRequests.filter((r) => r.url().startsWith(SPLIT + '/api/'));
|
||||
assert(stray.length === 0, 'requests left on the static origin: ' + stray.map((r) => r.url()).join(', '));
|
||||
const toApi = apiRequests.filter((r) => r.url().startsWith(API + '/api/'));
|
||||
assert(toApi.length >= 10, 'expected the pages to call the API, saw ' + toApi.length);
|
||||
});
|
||||
|
||||
await test('no API request carries the API host\'s cookies', async () => {
|
||||
const withCookie = [];
|
||||
for (const r of apiRequests) {
|
||||
const h = await r.allHeaders();
|
||||
if (h.cookie) withCookie.push(r.url());
|
||||
}
|
||||
assert(withCookie.length === 0, 'cookies sent to: ' + withCookie.slice(0, 5).join(', '));
|
||||
});
|
||||
|
||||
await test('the WebSocket connects to the API host\'s /ws', async () => {
|
||||
const wsBase = API.replace(/^http/, 'ws');
|
||||
assert(sockets.length > 0, 'no WebSocket opened');
|
||||
assert(sockets.every((u) => u === wsBase + '/ws'), 'unexpected WebSocket URLs: ' + sockets.join(', '));
|
||||
await page.goto(SPLIT + '/#/live', { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => typeof ws !== 'undefined' && ws && ws.readyState === 1, null, { timeout: 10000 });
|
||||
});
|
||||
|
||||
await test('the three JSON POSTs go as text/plain with no preflight, and succeed', async () => {
|
||||
const seen = [];
|
||||
const onReq = (r) => { if (r.url().startsWith(API + '/api/')) seen.push({ method: r.method(), url: r.url(), type: r.headers()['content-type'] }); };
|
||||
page.on('request', onReq);
|
||||
const result = await page.evaluate(async () => {
|
||||
const pk = await (await CSApi.fetch('/api/packets?limit=2')).json();
|
||||
const hashes = (pk.packets || []).map((p) => p.hash).filter(Boolean);
|
||||
const a = await CSApi.postJSON('/api/packets/observations', { hashes });
|
||||
const b = await CSApi.postJSON('/api/decode', { hex: '1100' });
|
||||
const c = await CSApi.postJSON('/api/paths/inspect', { prefixes: ['aa', 'bb'] });
|
||||
return { obs: [a.status, Object.keys(await a.json())], decode: [b.status, Object.keys(await b.json())], inspect: [c.status] };
|
||||
});
|
||||
page.off('request', onReq);
|
||||
assert(result.obs[0] === 200 && result.obs[1].includes('results'), 'observations: ' + JSON.stringify(result.obs));
|
||||
assert(result.decode[0] === 200 && result.decode[1].includes('decoded'), 'decode: ' + JSON.stringify(result.decode));
|
||||
assert(result.inspect[0] === 200 || result.inspect[0] === 503, 'inspect: ' + JSON.stringify(result.inspect));
|
||||
const posts = seen.filter((s) => s.method === 'POST');
|
||||
assert(posts.length === 3, 'expected 3 POSTs, saw ' + JSON.stringify(seen));
|
||||
assert(posts.every((p) => /^text\/plain/.test(p.type)), 'POST content types: ' + posts.map((p) => p.type).join(', '));
|
||||
assert(!seen.some((s) => s.method === 'OPTIONS'), 'a preflight was sent');
|
||||
});
|
||||
|
||||
await test('the channel badge is shown and opens a pre-filled issue', async () => {
|
||||
await page.goto(SPLIT + '/#/nodes', { waitUntil: 'domcontentloaded' });
|
||||
const badge = page.locator('#csChannelBadge');
|
||||
await badge.waitFor({ timeout: 5000 });
|
||||
const href = await badge.getAttribute('href');
|
||||
const body = new URL(href).searchParams.get('body') || '';
|
||||
assert(/\/issues\/new\?title=/.test(href) && body.includes('**Page:** #/nodes') && body.includes('Channel: dev'), 'badge href: ' + href);
|
||||
const classic = await page.locator('#csClassicLink').getAttribute('href');
|
||||
assert(classic === API + '/#/nodes', 'classic link: ' + classic);
|
||||
});
|
||||
|
||||
await test('account and admin point to classic and offer no login', async () => {
|
||||
for (const [hash, text] of [['#/account/login', 'Logging in is available on the classic site.'], ['#/admin', 'Administration is available on the classic site.']]) {
|
||||
await page.goto(SPLIT + '/' + hash, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction((t) => document.getElementById('app').innerText.includes(t), text, { timeout: 5000 });
|
||||
assert(await page.locator('#app input[type=password]').count() === 0, hash + ' shows a password field');
|
||||
}
|
||||
});
|
||||
|
||||
await test('account tokens stay out of issue reports and remain in classic transfer links', async () => {
|
||||
for (const view of ['activate', 'reset', 'confirm-email', 'unsubscribe']) {
|
||||
const route = '#/account/' + view;
|
||||
const hash = route + '?token=e2e-private-link-token';
|
||||
await page.goto(SPLIT + '/' + hash, { waitUntil: 'domcontentloaded' });
|
||||
const classic = page.locator('#app .cs-classic-link');
|
||||
await classic.waitFor({ timeout: 5000 });
|
||||
const report = new URL(await page.locator('#csChannelBadge').getAttribute('href')).searchParams.get('body');
|
||||
assert(report.startsWith('**Page:** ' + route + '\n'), 'report should retain only the account route: ' + report);
|
||||
assert(!report.includes('e2e-private-link-token'), 'account token leaked into issue report');
|
||||
assert(await page.locator('#csClassicLink').getAttribute('href') === API + '/' + hash, 'nav transfer lost token');
|
||||
assert(await classic.getAttribute('href') === API + '/' + hash, 'account transfer lost token');
|
||||
}
|
||||
});
|
||||
|
||||
await test('a blocked API request shows "Can\'t reach the CoreScope API"', async () => {
|
||||
const p = await context.newPage();
|
||||
await p.route(API + '/api/stats', (route) => route.abort('failed'));
|
||||
await p.goto(SPLIT + '/#/home', { waitUntil: 'domcontentloaded' });
|
||||
await p.waitForFunction(() => {
|
||||
const t = document.getElementById('csAuthToast');
|
||||
return t && t.textContent === "Can't reach the CoreScope API";
|
||||
}, null, { timeout: 20000 });
|
||||
await p.close();
|
||||
});
|
||||
|
||||
for (const status of [200, 404]) await test('an HTML ' + status + ' answer shows "Server returned an unexpected response"', async () => {
|
||||
const p = await context.newPage();
|
||||
await p.route(API + '/api/stats', (route) => route.fulfill({ status, contentType: 'text/html', body: '<!doctype html><p>static host page</p>',
|
||||
headers: { 'Access-Control-Allow-Origin': SPLIT } }));
|
||||
await p.goto(SPLIT + '/#/home', { waitUntil: 'domcontentloaded' });
|
||||
await p.waitForFunction(() => {
|
||||
const t = document.getElementById('csAuthToast');
|
||||
return t && t.textContent === 'Server returned an unexpected response';
|
||||
}, null, { timeout: 20000 });
|
||||
await p.close();
|
||||
});
|
||||
|
||||
if (process.env.SPLIT_SCREENSHOT) {
|
||||
await page.goto(SPLIT + '/#/nodes', { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(1500);
|
||||
await page.screenshot({ path: process.env.SPLIT_SCREENSHOT });
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
console.log('Split anonymous E2E: all passed');
|
||||
}
|
||||
|
||||
run().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,30 @@
|
||||
/* Shared by the unit suites that run frontend files in a vm sandbox: loads
|
||||
* the real public/deployment.js and public/api-base.js into it, so code that
|
||||
* calls CSApi sees the same seam as in the browser. `deployment` overrides
|
||||
* fields of the classic descriptor (e.g. { apiBase: 'https://api.test',
|
||||
* auth: false } for the anonymous static build). Not a suite itself. */
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
const PUBLIC = path.join(__dirname, '..', '..', 'public');
|
||||
const DEPLOYMENT_SRC = fs.readFileSync(path.join(PUBLIC, 'deployment.js'), 'utf8');
|
||||
const API_BASE_SRC = fs.readFileSync(path.join(PUBLIC, 'api-base.js'), 'utf8');
|
||||
|
||||
// Some suites give the sandbox its own `window` object, others make the
|
||||
// sandbox the window. Both files write to `window`, and the code under test
|
||||
// reads CSApi bare (the sandbox global) and as window.CSApi.
|
||||
const WITH_WINDOW = src => '(function (window) {\n' + src + '\n})(this.window && typeof this.window === "object" ? this.window : this);';
|
||||
|
||||
function loadApiBase(ctx, deployment) {
|
||||
if (!vm.isContext(ctx)) vm.createContext(ctx);
|
||||
vm.runInContext(WITH_WINDOW(DEPLOYMENT_SRC), ctx);
|
||||
const win = ctx.window && typeof ctx.window === 'object' ? ctx.window : ctx;
|
||||
if (deployment) win.CS_DEPLOYMENT = Object.assign({}, win.CS_DEPLOYMENT, deployment);
|
||||
vm.runInContext(WITH_WINDOW(API_BASE_SRC), ctx);
|
||||
ctx.CSApi = win.CSApi;
|
||||
return ctx.CSApi;
|
||||
}
|
||||
|
||||
module.exports = { loadApiBase };
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -47,6 +48,7 @@ function makeCtx(fetchImpl) {
|
||||
Map, Set,
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
// Provide the no-op fetch('/api/config/cache') hit that app.js makes
|
||||
// on module load by returning a thenable that ignores.
|
||||
const src = fs.readFileSync('public/app.js', 'utf8');
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* test-user-management-ui.js). */
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const assert = require('assert');
|
||||
@@ -71,6 +72,7 @@ function loadTab(files, hash, routes, extra) {
|
||||
}, extra || {});
|
||||
ctx.window = ctx;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
[].concat(files).forEach((f) => vm.runInContext(src(f), ctx));
|
||||
return { ctx, dom, els: dom.els, loc, replaced, calls, bodies, timers };
|
||||
}
|
||||
@@ -433,6 +435,7 @@ function loadShell(hash, opts) {
|
||||
registerPage(n, m) { pages[n] = m; }, addEventListener(t, fn) { listeners[t] = fn; } }, mods);
|
||||
ctx.window = ctx;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(src('public/admin.js'), ctx);
|
||||
return { t: ctx.CSAdmin._test, page: pages.admin, app: { innerHTML: '' }, loc, replaced, mods, els: dom.els,
|
||||
fire(detail) { me.current = detail; if (listeners['cs-auth-changed']) listeners['cs-auth-changed']({ detail }); } };
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
/* Unit tests for node aging system */
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
// Load roles.js in a sandboxed context
|
||||
const ctx = { window: {}, console, Date, Infinity, document: { readyState: 'complete', createElement: () => ({ id: '' }), head: { appendChild: () => {} }, getElementById: () => null, addEventListener: () => {} }, fetch: () => Promise.resolve({ json: () => Promise.resolve({}) }) };
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync('public/roles.js', 'utf8'), ctx);
|
||||
|
||||
// The IIFE assigns to window.*, but the functions reference HEALTH_THRESHOLDS as a bare global
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
/* The anonymous static build (deployment.js auth:false on another origin)
|
||||
* sends no cookies, so nothing in it may offer a login or an admin action.
|
||||
* roles.js turns every account feature off there; auth.js links to the
|
||||
* classic site's login instead; the account and admin pages say where to go. */
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const src = (f) => fs.readFileSync(path.join(ROOT, f), 'utf8');
|
||||
const ANON = { channel: 'beta', apiBase: 'https://analyzer.example', auth: false, classicUrl: 'https://analyzer.example' };
|
||||
|
||||
let passed = 0, failed = 0;
|
||||
let chain = Promise.resolve();
|
||||
function test(name, fn) {
|
||||
chain = chain.then(fn).then(
|
||||
() => { passed++; console.log(' ✅ ' + name); },
|
||||
(e) => { failed++; console.log(' ❌ ' + name + ': ' + (e && e.stack || e)); });
|
||||
}
|
||||
function section(title) { chain = chain.then(() => console.log(title)); }
|
||||
|
||||
// beta-ui.js in the same sandbox, for CSBeta.classicOnlyHtml.
|
||||
function loadBetaUi(ctx) { vm.runInContext(src('public/beta-ui.js'), ctx); }
|
||||
|
||||
section('roles.js');
|
||||
|
||||
async function rolesWith(deployment, cfg) {
|
||||
const ctx = {
|
||||
console, Date, Infinity,
|
||||
document: { readyState: 'complete', createElement: () => ({ id: '', style: {} }), head: { appendChild() {} },
|
||||
getElementById: () => null, querySelector: () => null, querySelectorAll: () => [], addEventListener() {},
|
||||
documentElement: { style: { setProperty() {} } } },
|
||||
location: { protocol: 'https:', host: 'beta.example', hash: '' },
|
||||
fetch: () => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(cfg) }),
|
||||
};
|
||||
ctx.window = {};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx, deployment);
|
||||
vm.runInContext(src('public/roles.js'), ctx);
|
||||
await ctx.window.MeshConfigReady;
|
||||
return ctx.window;
|
||||
}
|
||||
const UM_ON = { userManagement: { enabled: true, channelProposals: true, notifications: true, observerLogins: true } };
|
||||
|
||||
test('the embedded UI keeps user management as the server reports it', async () => {
|
||||
const win = await rolesWith(undefined, UM_ON);
|
||||
assert.strictEqual(win.MC_USER_MGMT.enabled, true);
|
||||
assert.strictEqual(win.MC_USER_MGMT.channelProposals, true);
|
||||
assert.strictEqual(win.MC_ACCOUNTS_ON_CLASSIC, false);
|
||||
});
|
||||
|
||||
test('an anonymous build turns every account feature off, and remembers classic has them', async () => {
|
||||
const win = await rolesWith(ANON, UM_ON);
|
||||
assert.strictEqual(win.MC_USER_MGMT, null);
|
||||
assert.strictEqual(win.MC_ACCOUNTS_ON_CLASSIC, true);
|
||||
});
|
||||
|
||||
test('an anonymous build on a server without accounts has nothing to link to', async () => {
|
||||
const win = await rolesWith(ANON, {});
|
||||
assert.strictEqual(win.MC_USER_MGMT, null);
|
||||
assert.strictEqual(win.MC_ACCOUNTS_ON_CLASSIC, false);
|
||||
});
|
||||
|
||||
test('a static build with logins (auth: true) keeps user management', async () => {
|
||||
const win = await rolesWith(Object.assign({}, ANON, { auth: true }), UM_ON);
|
||||
assert.strictEqual(win.MC_USER_MGMT.enabled, true);
|
||||
assert.strictEqual(win.MC_ACCOUNTS_ON_CLASSIC, false);
|
||||
});
|
||||
|
||||
section('auth.js');
|
||||
|
||||
function authWith(deployment, accountsOnClassic) {
|
||||
const inserted = [];
|
||||
const events = [];
|
||||
const fetches = [];
|
||||
const mkEl = () => {
|
||||
const el = { id: '', className: '', innerHTML: '', title: '', href: '', children: [] };
|
||||
el.appendChild = (c) => { el.children.push(c); return c; };
|
||||
return el;
|
||||
};
|
||||
const doc = {
|
||||
getElementById: (id) => inserted.find((e) => e.id === id) || null,
|
||||
querySelector: (sel) => (sel === '.top-nav .nav-right' ? { insertBefore(el) { inserted.push(el); } } : null),
|
||||
createElement: mkEl,
|
||||
addEventListener() {},
|
||||
};
|
||||
const win = { MC_USER_MGMT: null, MC_ACCOUNTS_ON_CLASSIC: accountsOnClassic, MeshConfigReady: Promise.resolve(),
|
||||
addEventListener() {}, dispatchEvent: (e) => events.push(e.type) };
|
||||
const ctx = { window: win, document: doc, console, Promise, JSON, String, Object, setTimeout, clearTimeout,
|
||||
location: { protocol: 'https:', host: 'beta.example', hash: '#/nodes' },
|
||||
CustomEvent: function (type) { this.type = type; },
|
||||
fetch: (u) => { fetches.push(u); return Promise.reject(new Error('no fetch expected')); } };
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx, deployment);
|
||||
vm.runInContext(src('public/auth.js'), ctx);
|
||||
return { win, inserted, events, fetches };
|
||||
}
|
||||
|
||||
test('anonymous build on a server with accounts: "Log in on classic", and no session request', async () => {
|
||||
const env = authWith(ANON, true);
|
||||
await env.win.CSAuth.ready();
|
||||
assert.strictEqual(env.win.CSAuth.isEnabled(), false);
|
||||
assert.deepStrictEqual(env.fetches, []);
|
||||
const wrap = env.inserted.find((e) => e.id === 'accountWrap');
|
||||
assert.ok(wrap, 'nav control rendered');
|
||||
const link = wrap.children[0];
|
||||
assert.strictEqual(link.href, 'https://analyzer.example/#/account/login');
|
||||
assert.ok(link.innerHTML.includes('Log in on classic'), link.innerHTML);
|
||||
assert.deepStrictEqual(env.events, ['cs-auth-control-added']);
|
||||
});
|
||||
|
||||
test('anonymous build without a classic URL shows no login control at all', async () => {
|
||||
const env = authWith(Object.assign({}, ANON, { classicUrl: null }), true);
|
||||
await env.win.CSAuth.ready();
|
||||
assert.strictEqual(env.inserted.length, 0);
|
||||
assert.deepStrictEqual(env.fetches, []);
|
||||
});
|
||||
|
||||
test('nothing renders when classic has no accounts either', async () => {
|
||||
const env = authWith(ANON, false);
|
||||
await env.win.CSAuth.ready();
|
||||
assert.strictEqual(env.inserted.length, 0);
|
||||
});
|
||||
|
||||
section('account.js and admin.js');
|
||||
|
||||
function pageWith(file, name, deployment) {
|
||||
const pages = {};
|
||||
const ctx = { console, Promise, String, Object, URLSearchParams,
|
||||
location: { protocol: 'https:', host: 'beta.example', hash: '#/' + name },
|
||||
document: { readyState: 'complete', getElementById: () => null, querySelector: () => null, addEventListener() {} },
|
||||
history: { replaceState() {} }, escapeHtml: (s) => String(s), viewGeneration: () => 0,
|
||||
registerPage: (n, m) => { pages[n] = m; },
|
||||
CSAuth: { ready: () => { throw new Error('anonymous pages must not wait for a session'); } },
|
||||
addEventListener() {} };
|
||||
ctx.window = ctx;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx, deployment);
|
||||
loadBetaUi(ctx);
|
||||
vm.runInContext(src(file), ctx);
|
||||
return pages[name];
|
||||
}
|
||||
|
||||
test('#/account on an anonymous build points to the classic login', () => {
|
||||
const app = { innerHTML: '' };
|
||||
pageWith('public/account.js', 'account', ANON).init(app, 'login');
|
||||
assert.ok(app.innerHTML.includes('Logging in is available on the classic site.'), app.innerHTML);
|
||||
assert.ok(app.innerHTML.includes('href="https://analyzer.example/#/account"'), app.innerHTML);
|
||||
});
|
||||
|
||||
test('#/admin on an anonymous build points to classic', async () => {
|
||||
const app = { innerHTML: '' };
|
||||
await pageWith('public/admin.js', 'admin', ANON).init(app);
|
||||
assert.ok(app.innerHTML.includes('Administration is available on the classic site.'), app.innerHTML);
|
||||
});
|
||||
|
||||
chain.then(() => {
|
||||
console.log(`\nanonymous mode: ${passed} passed, ${failed} failed`);
|
||||
if (failed) process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
/* public/api-base.js and public/deployment.js: where every /api request and
|
||||
* the WebSocket go, and what each request may carry, for the embedded UI and
|
||||
* for a static build on another origin. Also api()'s two errors for a
|
||||
* packaged UI in public/app.js: a blocked request (network_or_cors) and an
|
||||
* HTML answer from a wrong API base (not_json). */
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
let passed = 0, failed = 0;
|
||||
let chain = Promise.resolve();
|
||||
function test(name, fn) {
|
||||
chain = chain.then(fn).then(
|
||||
() => { passed++; console.log(' ✅ ' + name); },
|
||||
(e) => { failed++; console.log(' ❌ ' + name + ': ' + (e && e.stack || e)); });
|
||||
}
|
||||
function section(title) { chain = chain.then(() => console.log(title)); }
|
||||
|
||||
function sandbox(deployment, loc) {
|
||||
const calls = [];
|
||||
const ctx = {
|
||||
location: loc || { protocol: 'http:', host: 'analyzer.test', hash: '#/packets' },
|
||||
fetch(url, opts) { calls.push({ url, opts }); return Promise.resolve({ ok: true, status: 200 }); },
|
||||
};
|
||||
ctx.window = ctx;
|
||||
const api = loadApiBase(ctx, deployment);
|
||||
return { api, calls };
|
||||
}
|
||||
|
||||
section('deployment.js');
|
||||
|
||||
test('the embedded UI ships the classic descriptor: same origin, logins on', () => {
|
||||
const ctx = {};
|
||||
ctx.window = ctx;
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(fs.readFileSync(path.join(ROOT, 'public/deployment.js'), 'utf8'), ctx);
|
||||
assert.deepStrictEqual(JSON.parse(JSON.stringify(ctx.CS_DEPLOYMENT)),
|
||||
{ channel: 'classic', commit: null, version: null, apiBase: '', auth: true, classicUrl: null });
|
||||
});
|
||||
|
||||
section('api-base.js: classic (same origin)');
|
||||
|
||||
test('URLs stay relative and the WebSocket is on this host', () => {
|
||||
const { api } = sandbox();
|
||||
assert.strictEqual(api.url('/api/nodes?limit=50'), '/api/nodes?limit=50');
|
||||
assert.strictEqual(api.wsUrl('/ws'), 'ws://analyzer.test/ws');
|
||||
assert.strictEqual(api.crossOrigin, false);
|
||||
assert.strictEqual(api.anonymous, false);
|
||||
assert.strictEqual(api.channel, 'classic');
|
||||
});
|
||||
|
||||
test('embedded is the classic descriptor on its own origin, and nothing else', () => {
|
||||
assert.strictEqual(sandbox().api.embedded, true);
|
||||
// The web container's build: the same origin, but packaged apart from the server.
|
||||
assert.strictEqual(sandbox({ channel: 'static' }).api.embedded, false);
|
||||
// A hand-edited descriptor that only moves the API base.
|
||||
assert.strictEqual(sandbox({ apiBase: 'https://analyzer.example', auth: false }).api.embedded, false);
|
||||
});
|
||||
|
||||
test('the WebSocket follows the page to wss on https', () => {
|
||||
const { api } = sandbox({}, { protocol: 'https:', host: 'analyzer.test:8443', hash: '' });
|
||||
assert.strictEqual(api.wsUrl('/ws'), 'wss://analyzer.test:8443/ws');
|
||||
});
|
||||
|
||||
test('fetch keeps the caller options, adds same-origin credentials and does not mutate the options', async () => {
|
||||
const { api, calls } = sandbox();
|
||||
const opts = { method: 'PUT', headers: { 'X-CS-CSRF': 't' } };
|
||||
await api.fetch('/api/account', opts);
|
||||
assert.strictEqual(calls[0].url, '/api/account');
|
||||
assert.strictEqual(calls[0].opts.method, 'PUT');
|
||||
assert.strictEqual(calls[0].opts.headers['X-CS-CSRF'], 't');
|
||||
assert.strictEqual(calls[0].opts.credentials, 'same-origin');
|
||||
assert.strictEqual(opts.credentials, undefined);
|
||||
});
|
||||
|
||||
test('a path that is not absolute is a programming error', () => {
|
||||
const { api } = sandbox();
|
||||
assert.throws(() => api.url('api/nodes'), /must start with \//);
|
||||
assert.throws(() => api.url('https://elsewhere.test/api'), /must start with \//);
|
||||
});
|
||||
|
||||
test('classicHref is null without a classic URL', () => {
|
||||
const { api } = sandbox();
|
||||
assert.strictEqual(api.classicHref(), null);
|
||||
});
|
||||
|
||||
section('api-base.js: static build with logins (auth: true)');
|
||||
|
||||
test('URLs and the WebSocket go to the API origin, and cookies ride along', async () => {
|
||||
const { api, calls } = sandbox({ channel: 'beta', apiBase: 'https://analyzer.example/', auth: true });
|
||||
assert.strictEqual(api.base, 'https://analyzer.example');
|
||||
assert.strictEqual(api.url('/api/stats'), 'https://analyzer.example/api/stats');
|
||||
assert.strictEqual(api.wsUrl('/ws'), 'wss://analyzer.example/ws');
|
||||
assert.strictEqual(api.crossOrigin, true);
|
||||
assert.strictEqual(api.anonymous, false);
|
||||
await api.fetch('/api/stats');
|
||||
assert.strictEqual(calls[0].opts.credentials, 'include');
|
||||
});
|
||||
|
||||
test('a hand-edited descriptor with logins on another origin warns once at load', () => {
|
||||
// build.sh refuses this pair: no server accepts the cookie across origins,
|
||||
// so CORS blocks every request. Say why instead of failing silently.
|
||||
function warnings(deployment) {
|
||||
const out = [];
|
||||
const ctx = { console: { warn: (m) => out.push(m) }, location: { protocol: 'https:', host: 'beta.example', hash: '' } };
|
||||
ctx.window = ctx;
|
||||
loadApiBase(ctx, deployment);
|
||||
return out;
|
||||
}
|
||||
const w = warnings({ channel: 'beta', apiBase: 'https://analyzer.example', auth: true });
|
||||
assert.strictEqual(w.length, 1);
|
||||
assert.match(w[0], /auth: false/);
|
||||
assert.deepStrictEqual(warnings({ channel: 'beta', apiBase: 'https://analyzer.example', auth: false }), []);
|
||||
assert.deepStrictEqual(warnings(undefined), []);
|
||||
assert.deepStrictEqual(warnings({ channel: 'static' }), []);
|
||||
});
|
||||
|
||||
section('api-base.js: anonymous static build (auth: false)');
|
||||
|
||||
test('no request carries cookies: the embed CORS tier would block an include request', async () => {
|
||||
const { api, calls } = sandbox({ channel: 'beta', apiBase: 'https://analyzer.example', auth: false });
|
||||
assert.strictEqual(api.anonymous, true);
|
||||
await api.fetch('/api/stats');
|
||||
assert.strictEqual(calls[0].url, 'https://analyzer.example/api/stats');
|
||||
assert.strictEqual(calls[0].opts.credentials, 'omit');
|
||||
});
|
||||
|
||||
test('an explicit credentials option still wins', async () => {
|
||||
const { api, calls } = sandbox({ apiBase: 'https://analyzer.example', auth: false });
|
||||
await api.fetch('/api/stats', { credentials: 'same-origin' });
|
||||
assert.strictEqual(calls[0].opts.credentials, 'same-origin');
|
||||
});
|
||||
|
||||
test('postJSON sends a JSON body as text/plain, so the POST needs no preflight', async () => {
|
||||
const { api, calls } = sandbox({ apiBase: 'https://analyzer.example', auth: false });
|
||||
await api.postJSON('/api/decode', { hex: 'ab' });
|
||||
const c = calls[0];
|
||||
assert.strictEqual(c.url, 'https://analyzer.example/api/decode');
|
||||
assert.strictEqual(c.opts.method, 'POST');
|
||||
assert.strictEqual(c.opts.headers['Content-Type'], 'text/plain;charset=UTF-8');
|
||||
assert.deepStrictEqual(JSON.parse(c.opts.body), { hex: 'ab' });
|
||||
assert.strictEqual(c.opts.credentials, 'omit');
|
||||
});
|
||||
|
||||
test('postJSON is the same request on the embedded UI', async () => {
|
||||
const { api, calls } = sandbox();
|
||||
await api.postJSON('/api/paths/inspect', { prefixes: ['aa'] });
|
||||
assert.strictEqual(calls[0].url, '/api/paths/inspect');
|
||||
assert.strictEqual(calls[0].opts.headers['Content-Type'], 'text/plain;charset=UTF-8');
|
||||
assert.strictEqual(calls[0].opts.credentials, 'same-origin');
|
||||
});
|
||||
|
||||
test('classicHref opens the current or a given route on the classic site', () => {
|
||||
const { api } = sandbox({ apiBase: 'https://analyzer.example', auth: false, classicUrl: 'https://analyzer.example/' },
|
||||
{ protocol: 'https:', host: 'beta.example', hash: '#/nodes/abc?section=x' });
|
||||
assert.strictEqual(api.classicHref(), 'https://analyzer.example/#/nodes/abc?section=x');
|
||||
assert.strictEqual(api.classicHref('#/account/login'), 'https://analyzer.example/#/account/login');
|
||||
assert.strictEqual(api.classicHref('/packets'), 'https://analyzer.example/#/packets');
|
||||
});
|
||||
|
||||
section('app.js api(): cross-origin failures');
|
||||
|
||||
function appCtx(deployment, fetchImpl) {
|
||||
const notices = [];
|
||||
const ctx = {
|
||||
console, Date, Math, Promise, Error, TypeError, isFinite, parseInt, JSON, Map, Set,
|
||||
performance: { now: () => 0 },
|
||||
document: { readyState: 'complete', body: { appendChild() {} }, createElement: () => ({ style: {} }) },
|
||||
location: { protocol: 'https:', host: 'beta.example', hash: '' },
|
||||
fetch: fetchImpl,
|
||||
setTimeout: (fn) => { fn(); return 0; },
|
||||
clearTimeout() {}, setInterval: () => 0, clearInterval() {},
|
||||
};
|
||||
ctx.window = ctx;
|
||||
ctx.CSAuth = { notify: (m) => notices.push(m) };
|
||||
loadApiBase(ctx, deployment);
|
||||
try { vm.runInContext(fs.readFileSync(path.join(ROOT, 'public/app.js'), 'utf8'), ctx); } catch (_) { /* only api() is needed */ }
|
||||
return { ctx, notices };
|
||||
}
|
||||
const json = (body, ct, status = 200, retryAfter = null) => ({
|
||||
ok: status >= 200 && status < 300, status,
|
||||
headers: { get: (k) => ({ 'content-type': ct, 'retry-after': retryAfter })[k.toLowerCase()] || null },
|
||||
json: async () => body,
|
||||
});
|
||||
|
||||
test('a blocked request on another origin becomes network_or_cors, with one notice', async () => {
|
||||
const { ctx, notices } = appCtx({ apiBase: 'https://analyzer.example', auth: false }, (url) =>
|
||||
/config\/cache/.test(url) ? Promise.resolve(json({})) : Promise.reject(new TypeError('Failed to fetch')));
|
||||
let err = null;
|
||||
try { await ctx.api('/stats'); } catch (e) { err = e; }
|
||||
assert.ok(err, 'api() must reject');
|
||||
assert.strictEqual(err.code, 'network_or_cors');
|
||||
try { await ctx.api('/nodes'); } catch (_) { /* second failure */ }
|
||||
assert.deepStrictEqual(notices, ["Can't reach the CoreScope API"]);
|
||||
});
|
||||
|
||||
test('the same failure on the embedded UI keeps its original error', async () => {
|
||||
const { ctx, notices } = appCtx({}, (url) =>
|
||||
/config\/cache/.test(url) ? Promise.resolve(json({})) : Promise.reject(new TypeError('Failed to fetch')));
|
||||
let err = null;
|
||||
try { await ctx.api('/stats'); } catch (e) { err = e; }
|
||||
assert.ok(err instanceof ctx.TypeError || err.name === 'TypeError');
|
||||
assert.strictEqual(err.code, undefined);
|
||||
assert.deepStrictEqual(notices, []);
|
||||
});
|
||||
|
||||
test('an HTML answer (a static host page) becomes not_json, not a parse error', async () => {
|
||||
const { ctx, notices } = appCtx({ apiBase: 'https://wrong.example', auth: false }, async () =>
|
||||
json(null, 'text/html; charset=utf-8'));
|
||||
let err = null;
|
||||
try { await ctx.api('/stats'); } catch (e) { err = e; }
|
||||
assert.ok(err, 'api() must reject');
|
||||
assert.strictEqual(err.code, 'not_json');
|
||||
assert.strictEqual(err.status, 200);
|
||||
assert.deepStrictEqual(notices, ['Server returned an unexpected response']);
|
||||
});
|
||||
|
||||
for (const status of [404, 503]) {
|
||||
test('HTML ' + status + ' reports not_json before status handling and does not retry', async () => {
|
||||
let calls = 0;
|
||||
const { ctx, notices } = appCtx({ apiBase: 'https://wrong.example', auth: false }, async (url) => {
|
||||
if (/config\/cache/.test(url)) return json({});
|
||||
calls++;
|
||||
return json(null, 'text/html; charset=utf-8', status, '3');
|
||||
});
|
||||
const warmups = [];
|
||||
ctx.onWarmup_1659 = (active) => warmups.push(active);
|
||||
await assert.rejects(ctx.api('/stats'), (err) => {
|
||||
assert.strictEqual(err.code, 'not_json');
|
||||
assert.strictEqual(err.status, status);
|
||||
assert.strictEqual(err.path, '/stats');
|
||||
assert.strictEqual(err.retryAfter, '3');
|
||||
return true;
|
||||
});
|
||||
assert.strictEqual(calls, 1, 'HTML errors must not retry');
|
||||
assert.deepStrictEqual(warmups, [], 'HTML is not an analytics warm-up');
|
||||
assert.deepStrictEqual(notices, ['Server returned an unexpected response']);
|
||||
});
|
||||
}
|
||||
|
||||
// A real HTML Response: res.json() throws on it.
|
||||
const html = (status) => ({
|
||||
ok: status >= 200 && status < 300, status,
|
||||
headers: { get: (k) => (k.toLowerCase() === 'content-type' ? 'text/html; charset=utf-8' : null) },
|
||||
json: async () => { throw new SyntaxError("Unexpected token '<', \"<!doctype \"... is not valid JSON"); },
|
||||
});
|
||||
|
||||
test('the web container (same origin, packaged) reports an HTML answer as not_json too', async () => {
|
||||
const { ctx, notices } = appCtx({ channel: 'static' }, async (url) =>
|
||||
(/config\/cache/.test(url) ? json({}) : html(200)));
|
||||
await assert.rejects(ctx.api('/stats'), (err) => err.code === 'not_json');
|
||||
assert.deepStrictEqual(notices, ['Server returned an unexpected response']);
|
||||
});
|
||||
|
||||
test("the embedded UI keeps its old handling of an HTML answer: no notice, 503 retried", async () => {
|
||||
// The server's SPA fallback answers an unknown /api path with index.html.
|
||||
const a = appCtx({}, async (url) => (/config\/cache/.test(url) ? json({}) : html(200)));
|
||||
await assert.rejects(a.ctx.api('/nope'), (err) => {
|
||||
assert.strictEqual(err.name, 'SyntaxError');
|
||||
assert.strictEqual(err.code, undefined);
|
||||
return true;
|
||||
});
|
||||
// A proxy's HTML 503 is retried like the server's warm-up.
|
||||
let calls = 0;
|
||||
const b = appCtx({}, async (url) => {
|
||||
if (/config\/cache/.test(url)) return json({});
|
||||
calls++;
|
||||
return html(503);
|
||||
});
|
||||
await assert.rejects(b.ctx.api('/stats'), (err) => {
|
||||
assert.strictEqual(err.status, 503);
|
||||
assert.strictEqual(err.code, undefined);
|
||||
return true;
|
||||
});
|
||||
assert.strictEqual(calls, 7, 'one initial request plus six retries');
|
||||
assert.deepStrictEqual(a.notices.concat(b.notices), []);
|
||||
});
|
||||
|
||||
test('JSON 4xx errors retain their status and retry metadata without an unexpected-response notice', async () => {
|
||||
for (const status of [404, 429]) {
|
||||
let calls = 0;
|
||||
const { ctx, notices } = appCtx({ apiBase: 'https://api.example', auth: false }, async (url) => {
|
||||
if (/config\/cache/.test(url)) return json({});
|
||||
calls++;
|
||||
return json({ error: 'unavailable' }, 'application/json', status, '5');
|
||||
});
|
||||
await assert.rejects(ctx.api('/stats'), (err) => {
|
||||
assert.strictEqual(err.message, 'API ' + status + ': /stats');
|
||||
assert.strictEqual(err.status, status);
|
||||
assert.strictEqual(err.retryAfter, '5');
|
||||
assert.strictEqual(err.code, undefined);
|
||||
return true;
|
||||
});
|
||||
assert.strictEqual(calls, 1);
|
||||
assert.deepStrictEqual(notices, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('JSON 503 warm-up still retries and balances its notice on success or exhaustion', async () => {
|
||||
for (const recover of [true, false]) {
|
||||
let calls = 0;
|
||||
const { ctx, notices } = appCtx({ apiBase: 'https://api.example', auth: false }, async (url) => {
|
||||
if (/config\/cache/.test(url)) return json({});
|
||||
calls++;
|
||||
return calls > 1 && recover ? json({ ready: true }, 'application/json') :
|
||||
json({ error: 'warming up' }, 'application/json', 503, '2');
|
||||
});
|
||||
const warmups = [];
|
||||
ctx.onWarmup_1659 = (active) => warmups.push(active);
|
||||
if (recover) {
|
||||
assert.strictEqual((await ctx.api('/stats')).ready, true);
|
||||
assert.strictEqual(calls, 2);
|
||||
} else {
|
||||
await assert.rejects(ctx.api('/stats'), (err) => {
|
||||
assert.strictEqual(err.status, 503);
|
||||
assert.strictEqual(err.retryAfter, '2');
|
||||
assert.strictEqual(err.code, undefined);
|
||||
return true;
|
||||
});
|
||||
assert.strictEqual(calls, 7, 'one initial request plus six retries');
|
||||
}
|
||||
assert.deepStrictEqual(warmups, [true, false]);
|
||||
assert.deepStrictEqual(notices, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('JSON answers parse, including handlers that leave Content-Type to sniffing', async () => {
|
||||
for (const ct of ['application/json', 'application/json; charset=utf-8', 'text/plain; charset=utf-8', null]) {
|
||||
const { ctx } = appCtx({}, async () => json({ ok: ct }, ct));
|
||||
const data = await ctx.api('/stats');
|
||||
assert.strictEqual(data.ok, ct, 'Content-Type ' + ct);
|
||||
}
|
||||
});
|
||||
|
||||
chain.then(() => {
|
||||
console.log(`\napi-base: ${passed} passed, ${failed} failed`);
|
||||
if (failed) process.exit(1);
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -53,6 +54,7 @@ function buildCtx({ storageValue = null, fetchResponse = [] } = {}) {
|
||||
String,
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync('public/area-filter.js', 'utf8'), ctx);
|
||||
return { AF: ctx.window.AreaFilter, ctx, storage, listeners };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
/* public/beta-ui.js: the channel badge and classic link a static build adds
|
||||
* to the nav, the pre-filled beta issue URL, and the note that stands in for
|
||||
* a control an anonymous build cannot offer. */
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const SRC = fs.readFileSync(path.join(__dirname, '..', '..', 'public', 'beta-ui.js'), 'utf8');
|
||||
let passed = 0, failed = 0;
|
||||
function test(name, fn) {
|
||||
try { fn(); passed++; console.log(' ✅ ' + name); } catch (e) { failed++; console.log(' ❌ ' + name + ': ' + e.message); }
|
||||
}
|
||||
|
||||
// Just enough DOM for renderNav: elements, ids, insertBefore after the brand.
|
||||
function fakeDoc() {
|
||||
const byId = {};
|
||||
const make = (tag) => {
|
||||
const el = { tagName: tag.toUpperCase(), children: [], className: '', textContent: '', href: '', title: '' };
|
||||
el.appendChild = (c) => { el.children.push(c); if (c.id) byId[c.id] = c; return c; };
|
||||
return el;
|
||||
};
|
||||
const nav = make('div');
|
||||
const brand = make('a');
|
||||
nav.children.push(brand);
|
||||
nav.insertBefore = (el, ref) => {
|
||||
const i = ref ? nav.children.indexOf(ref) : nav.children.length;
|
||||
nav.children.splice(i < 0 ? nav.children.length : i, 0, el);
|
||||
(function index(e) { if (e.id) byId[e.id] = e; e.children.forEach(index); })(el);
|
||||
};
|
||||
brand.parentNode = nav;
|
||||
brand.nextSibling = null;
|
||||
return {
|
||||
nav, readyState: 'complete',
|
||||
createElement: make,
|
||||
getElementById: (id) => byId[id] || null,
|
||||
querySelector: (sel) => (sel === '.top-nav .nav-brand' ? brand : null),
|
||||
addEventListener() {},
|
||||
};
|
||||
}
|
||||
|
||||
function load(deployment, hash) {
|
||||
const listeners = {};
|
||||
const doc = fakeDoc();
|
||||
const ctx = {
|
||||
document: doc,
|
||||
location: { protocol: 'https:', host: 'beta.example', hash: hash || '#/packets' },
|
||||
navigator: { userAgent: 'TestBrowser/1.0' },
|
||||
addEventListener: (type, fn) => { (listeners[type] = listeners[type] || []).push(fn); },
|
||||
fetch() { throw new Error('beta-ui must not fetch'); },
|
||||
};
|
||||
ctx.window = ctx;
|
||||
loadApiBase(ctx, deployment);
|
||||
vm.runInContext(SRC, ctx);
|
||||
return { ctx, doc, listeners };
|
||||
}
|
||||
|
||||
console.log('beta-ui.js');
|
||||
|
||||
test('the embedded UI and an operator static build show no badge', () => {
|
||||
for (const channel of ['classic', 'static']) {
|
||||
const { doc } = load({ channel, apiBase: channel === 'static' ? 'https://api.example' : '', auth: false });
|
||||
assert.strictEqual(doc.getElementById('csChannelBadge'), null, channel);
|
||||
assert.strictEqual(doc.nav.children.length, 1, channel);
|
||||
}
|
||||
});
|
||||
|
||||
test('beta, next and dev get a labelled badge right after the brand', () => {
|
||||
for (const [channel, label] of [['beta', 'Beta'], ['next', 'Next'], ['dev', 'Dev']]) {
|
||||
const { doc } = load({ channel, commit: 'abc1234', apiBase: 'https://api.example', auth: false });
|
||||
const badge = doc.getElementById('csChannelBadge');
|
||||
assert.ok(badge, channel);
|
||||
assert.strictEqual(badge.textContent, label);
|
||||
assert.strictEqual(badge.title, label + ' abc1234: report an issue with this page');
|
||||
assert.strictEqual(badge.target, '_blank');
|
||||
assert.strictEqual(badge.rel, 'noopener');
|
||||
assert.strictEqual(doc.nav.children[1].className, 'cs-channel-wrap');
|
||||
}
|
||||
});
|
||||
|
||||
test('the badge opens a new issue with page, channel, commit and browser filled in, no template needed', () => {
|
||||
const { doc } = load({ channel: 'beta', commit: 'abc1234', apiBase: 'https://api.example', auth: false }, '#/nodes/ab?x=1');
|
||||
const url = new URL(doc.getElementById('csChannelBadge').href);
|
||||
assert.strictEqual(url.origin + url.pathname, 'https://github.com/Kpa-clawbot/CoreScope/issues/new');
|
||||
assert.strictEqual(url.searchParams.get('template'), null);
|
||||
assert.strictEqual(url.searchParams.get('title'), '[beta] ');
|
||||
const body = url.searchParams.get('body');
|
||||
assert.ok(body.startsWith('**Page:** #/nodes/ab?x=1\n'), body);
|
||||
assert.ok(body.includes('What happened on the beta frontend'), body);
|
||||
assert.ok(body.endsWith('Channel: beta · Commit: abc1234 · Browser: TestBrowser/1.0\n'), body);
|
||||
});
|
||||
|
||||
test('account reports omit private query values even before a token is removed from the address bar', () => {
|
||||
for (const auth of [false, true]) {
|
||||
for (const route of ['#/account', '#/account/activate', '#/account/reset', '#/account/confirm-email', '#/account/unsubscribe']) {
|
||||
const hash = route + '?token=private-link-token§ion=notifications';
|
||||
const { ctx, doc } = load({ channel: 'beta', apiBase: auth ? '' : 'https://api.example', auth,
|
||||
classicUrl: 'https://analyzer.example' }, hash);
|
||||
const badge = doc.getElementById('csChannelBadge');
|
||||
const body = new URL(badge.href).searchParams.get('body');
|
||||
assert.ok(body.startsWith('**Page:** ' + route + '\n'), body);
|
||||
assert.ok(!body.includes('private-link-token') && !body.includes('section='), body);
|
||||
assert.strictEqual(doc.getElementById('csClassicLink').href, 'https://analyzer.example/' + hash);
|
||||
assert.ok(ctx.CSBeta.classicOnlyHtml('Logging in').includes('token=private-link-token&section=notifications'));
|
||||
|
||||
// account.js uses replaceState, which does not emit hashchange. The
|
||||
// already-created badge must be safe without waiting for a refresh.
|
||||
ctx.location.hash = route;
|
||||
assert.ok(!new URL(badge.href).searchParams.get('body').includes('private-link-token'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('navigating to an account token link keeps the report private and the classic transfer intact', () => {
|
||||
const { ctx, doc, listeners } = load({ channel: 'beta', auth: false, classicUrl: 'https://analyzer.example' });
|
||||
ctx.location.hash = '#/account/reset?token=another-private-token';
|
||||
listeners.hashchange.forEach((fn) => fn());
|
||||
assert.ok(new URL(doc.getElementById('csChannelBadge').href).searchParams.get('body').startsWith('**Page:** #/account/reset\n'));
|
||||
assert.strictEqual(doc.getElementById('csClassicLink').href, 'https://analyzer.example/#/account/reset?token=another-private-token');
|
||||
});
|
||||
|
||||
test('the classic link appears only with a classic URL, and both links follow the hash', () => {
|
||||
const none = load({ channel: 'beta', apiBase: 'https://api.example', auth: false });
|
||||
assert.strictEqual(none.doc.getElementById('csClassicLink'), null);
|
||||
|
||||
const { ctx, doc, listeners } = load({ channel: 'beta', apiBase: 'https://api.example', auth: false, classicUrl: 'https://analyzer.example' });
|
||||
assert.strictEqual(doc.getElementById('csClassicLink').href, 'https://analyzer.example/#/packets');
|
||||
ctx.location.hash = '#/map';
|
||||
listeners.hashchange.forEach((fn) => fn());
|
||||
assert.strictEqual(doc.getElementById('csClassicLink').href, 'https://analyzer.example/#/map');
|
||||
assert.ok(new URL(doc.getElementById('csChannelBadge').href).searchParams.get('body').startsWith('**Page:** #/map\n'));
|
||||
});
|
||||
|
||||
test('renderNav runs once', () => {
|
||||
const { ctx, doc } = load({ channel: 'beta', apiBase: 'https://api.example', auth: false });
|
||||
assert.strictEqual(ctx.CSBeta.renderNav(doc), false);
|
||||
assert.strictEqual(doc.nav.children.length, 2);
|
||||
});
|
||||
|
||||
test('classicOnlyHtml names the feature, escapes it, and links to the same page on classic', () => {
|
||||
const { ctx } = load({ channel: 'beta', apiBase: 'https://api.example', auth: false, classicUrl: 'https://analyzer.example' }, '#/perf');
|
||||
assert.strictEqual(ctx.CSBeta.classicOnlyHtml('Resetting <stats>'),
|
||||
'<p class="cs-classic-only">Resetting <stats> is available on the classic site. <a class="cs-classic-link" href="https://analyzer.example/#/perf">Open in classic</a></p>');
|
||||
});
|
||||
|
||||
test('classicOnlyHtml escapes the link too, and drops it without a classic URL', () => {
|
||||
const { ctx } = load({ channel: 'beta', apiBase: 'https://api.example', auth: false, classicUrl: 'https://analyzer.example' }, '#/x"><b>');
|
||||
assert.ok(ctx.CSBeta.classicOnlyHtml('Admin').includes('href="https://analyzer.example/#/x"><b>"'));
|
||||
const bare = load({ channel: 'beta', apiBase: 'https://api.example', auth: false });
|
||||
assert.strictEqual(bare.ctx.CSBeta.classicOnlyHtml('Admin'), '<p class="cs-classic-only">Admin is available on the classic site.</p>');
|
||||
});
|
||||
|
||||
console.log(`\nbeta-ui: ${passed} passed, ${failed} failed`);
|
||||
if (failed) process.exit(1);
|
||||
@@ -0,0 +1,89 @@
|
||||
/* scripts/dev-static.mjs: the zero-dependency static server used to run the
|
||||
* UI on one origin against the API on another (make dev-split, CI). It must
|
||||
* never serve outside its root, and its 404 must be HTML, as a real static
|
||||
* host's is, so api() reports a wrong API base as not_json. */
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
|
||||
let passed = 0, failed = 0;
|
||||
let chain = Promise.resolve();
|
||||
function test(name, fn) {
|
||||
chain = chain.then(fn).then(
|
||||
() => { passed++; console.log(' ✅ ' + name); },
|
||||
(e) => { failed++; console.log(' ❌ ' + name + ': ' + (e && e.stack || e)); });
|
||||
}
|
||||
|
||||
function get(port, p, method) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: '127.0.0.1', port, path: p, method: method || 'GET' }, (res) => {
|
||||
let body = '';
|
||||
res.on('data', (c) => { body += c; });
|
||||
res.on('end', () => resolve({ status: res.statusCode, type: res.headers['content-type'], cache: res.headers['cache-control'], body }));
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const mod = await import(path.join(__dirname, '..', '..', 'scripts', 'dev-static.mjs'));
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cs-static-'));
|
||||
fs.writeFileSync(path.join(root, 'index.html'), '<!doctype html><p>ui</p>');
|
||||
fs.mkdirSync(path.join(root, 'icons'));
|
||||
fs.writeFileSync(path.join(root, 'icons', 'a.svg'), '<svg/>');
|
||||
fs.writeFileSync(path.join(path.dirname(root), 'cs-static-secret.txt'), 'secret');
|
||||
const server = mod.createServer(root);
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
const port = server.address().port;
|
||||
|
||||
console.log('dev-static.mjs');
|
||||
|
||||
test('serves index.html at / and files with their type', async () => {
|
||||
const a = await get(port, '/');
|
||||
assert.strictEqual(a.status, 200);
|
||||
assert.strictEqual(a.type, 'text/html; charset=utf-8');
|
||||
assert.strictEqual(a.cache, 'no-cache');
|
||||
const b = await get(port, '/icons/a.svg?v=abc');
|
||||
assert.strictEqual(b.status, 200);
|
||||
assert.strictEqual(b.type, 'image/svg+xml');
|
||||
});
|
||||
|
||||
test('a missing file is an HTML 404, like a static host', async () => {
|
||||
const r = await get(port, '/api/stats');
|
||||
assert.strictEqual(r.status, 404);
|
||||
assert.match(r.type, /^text\/html/);
|
||||
});
|
||||
|
||||
test('never serves outside the root', async () => {
|
||||
for (const p of ['/../cs-static-secret.txt', '/%2e%2e/cs-static-secret.txt', '/icons/..%2f..%2fcs-static-secret.txt', '/%00']) {
|
||||
const r = await get(port, p);
|
||||
assert.strictEqual(r.status, 404, p);
|
||||
assert.ok(!r.body.includes('secret'), p);
|
||||
}
|
||||
assert.strictEqual(mod.resolveFile(root, '/../../etc/passwd'), null);
|
||||
});
|
||||
|
||||
test('only GET and HEAD', async () => {
|
||||
assert.strictEqual((await get(port, '/', 'POST')).status, 405);
|
||||
const h = await get(port, '/', 'HEAD');
|
||||
assert.strictEqual(h.status, 200);
|
||||
assert.strictEqual(h.body, '');
|
||||
});
|
||||
|
||||
test('parses its arguments and rejects unknown ones', () => {
|
||||
assert.deepStrictEqual(mod.parseArgs(['--root', 'x', '--port', '9000']), { root: 'x', port: 9000, host: '127.0.0.1' });
|
||||
assert.throws(() => mod.parseArgs(['--proxy', 'y']), /unknown argument/);
|
||||
assert.throws(() => mod.parseArgs(['--port', 'abc']), /bad --port/);
|
||||
});
|
||||
|
||||
await chain;
|
||||
server.close();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
fs.rmSync(path.join(path.dirname(root), 'cs-static-secret.txt'), { force: true });
|
||||
console.log(`\ndev-static: ${passed} passed, ${failed} failed`);
|
||||
if (failed) process.exit(1);
|
||||
})();
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -63,6 +64,7 @@ function makeSandbox() {
|
||||
ctx.window.addEventListener = () => {};
|
||||
ctx.window.dispatchEvent = () => {};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* Unit tests for frontend helper functions (tested via VM sandbox) */
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const vm = require('vm');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
@@ -86,6 +87,7 @@ function makeSandbox() {
|
||||
requestAnimationFrame: (cb) => setTimeout(cb, 0),
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
@@ -3940,6 +3942,7 @@ console.log('\n=== channels.js: formatHashHex (issue #465) ===');
|
||||
const match = chSource.match(/function formatHashHex\(hash\)\s*\{[^}]+\}/);
|
||||
assert.ok(match, 'should extract formatHashHex');
|
||||
const ctx = vm.createContext({});
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(match[0], ctx);
|
||||
const fmt = vm.runInContext('formatHashHex', ctx);
|
||||
assert.strictEqual(fmt(10), '0x0A');
|
||||
@@ -5283,6 +5286,7 @@ console.log('\n=== app.js: routeTypeName/payloadTypeName edge cases ===');
|
||||
const helperSource = fs.readFileSync('public/packet-helpers.js', 'utf8');
|
||||
const helperCtx = { window: {}, JSON, Array, Object, console, process };
|
||||
vm.createContext(helperCtx);
|
||||
loadApiBase(helperCtx);
|
||||
vm.runInContext(helperSource, helperCtx);
|
||||
const getParsedPath = helperCtx.window.getParsedPath;
|
||||
const getParsedDecoded = helperCtx.window.getParsedDecoded;
|
||||
@@ -5458,6 +5462,7 @@ console.log('\n=== app.js: routeTypeName/payloadTypeName edge cases ===');
|
||||
|
||||
const helperSource = fs.readFileSync('public/packet-helpers.js', 'utf8');
|
||||
const ctx = vm.createContext({ window: {}, console, JSON, Array, Object });
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(helperSource, ctx);
|
||||
const getParsedPath = ctx.window.getParsedPath;
|
||||
const getParsedDecoded = ctx.window.getParsedDecoded;
|
||||
@@ -6826,6 +6831,7 @@ console.log('\n=== analytics.js: renderCollisionsFromServer collision table ==='
|
||||
sb.self = sb.window;
|
||||
sb.globalThis = sb.window;
|
||||
const ctx = vm.createContext(sb);
|
||||
loadApiBase(ctx);
|
||||
const hopSrc = fs.readFileSync(REPO_ROOT + '/public/hop-display.js', 'utf8');
|
||||
vm.runInContext(hopSrc, ctx);
|
||||
return ctx;
|
||||
@@ -6975,6 +6981,7 @@ console.log('\n=== roles.js: Map Tile Config Parsing ===');
|
||||
};
|
||||
sb.window.document = sb.document; sb.self = sb.window; sb.globalThis = sb.window;
|
||||
const ctx1504 = vm.createContext(sb);
|
||||
loadApiBase(ctx1504);
|
||||
vm.runInContext(fs.readFileSync(REPO_ROOT + '/public/hop-display.js', 'utf8'), ctx1504);
|
||||
const HD = ctx1504.window.HopDisplay;
|
||||
|
||||
@@ -7579,6 +7586,7 @@ console.log('\n=== observers.js: healthStatus (configurable thresholds) ===');
|
||||
const ctx = { window: {}, Date };
|
||||
if (healthThresholds) ctx.window.HEALTH_THRESHOLDS = healthThresholds;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(healthStatusSrc + '\n; result = healthStatus(lastSeen);', Object.assign(ctx, { lastSeen, result: null }));
|
||||
return ctx.result;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -56,6 +57,7 @@ function makeSandbox() {
|
||||
registerPage: (name, handler) => { registeredPages[name] = handler; },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const assert = require('assert');
|
||||
@@ -32,6 +33,7 @@ function loadRoles(config) {
|
||||
fetch: () => Promise.resolve({ json: () => Promise.resolve(config || {}) }),
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(ROLES_JS, ctx);
|
||||
// roles.js reads HEALTH_THRESHOLDS as a bare global; window.X does not create one here.
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
|
||||
@@ -71,6 +72,7 @@ function loadPage() {
|
||||
registerPage: () => {},
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
const loadFile = f => {
|
||||
vm.runInContext(fs.readFileSync(REPO_ROOT + '/public/' + f, 'utf8'), ctx, { filename: f });
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -74,6 +75,7 @@ function makeSandbox() {
|
||||
RegionFilter: { init(){}, getSelected: () => null, onChange: () => {}, offChange: () => {}, regionQueryString: () => '', getRegionParam: () => '' },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const vm = require('vm');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
@@ -92,6 +93,7 @@ function makeSandbox() {
|
||||
ctx.makeColumnsResizable = () => {};
|
||||
ctx.debounce = (fn) => fn;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
function loadInCtx(ctx, file) {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -88,6 +89,7 @@ function loadMapInternals() {
|
||||
};
|
||||
ctx.window.L = ctx.L;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
for (const f of ['public/roles.js', 'public/map.js']) {
|
||||
vm.runInContext(fs.readFileSync(path.join(REPO_ROOT, f), 'utf8'), ctx, { filename: f });
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -120,6 +121,7 @@ let env;
|
||||
try {
|
||||
env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
} catch (e) {
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -116,6 +117,7 @@ console.log('\n=== #1412 A: server-config nodeColors does NOT clobber preset ROL
|
||||
{
|
||||
const env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
|
||||
@@ -152,6 +154,7 @@ console.log('\n=== #1412 B: early-overrides path also stays out of ROLE_COLORS o
|
||||
{
|
||||
const env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
env.sandbox.window.MeshCorePresets.applyPreset('deut');
|
||||
@@ -176,6 +179,7 @@ console.log('\n=== #1412 C: explicit setRoleColorOverride() still wins (user cus
|
||||
{
|
||||
const env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
env.sandbox.window.MeshCorePresets.applyPreset('deut');
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -95,6 +96,7 @@ let env;
|
||||
try {
|
||||
env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
} catch (e) {
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -121,6 +122,7 @@ console.log('\n=== #1438 FINAL B: user override → --mc-role-{role} reflects us
|
||||
{
|
||||
const env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
env.sandbox.window.MeshCorePresets.applyPreset('deut');
|
||||
@@ -153,6 +155,7 @@ console.log('\n=== #1438 FINAL C: server-only key does NOT clobber --mc-role-* (
|
||||
{
|
||||
const env = makeSandbox();
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
env.sandbox.window.MeshCorePresets.applyPreset('deut');
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -109,6 +110,7 @@ console.log('\n=== #1446 Scenario 1: cold boot with empty localStorage → no pr
|
||||
{
|
||||
const env = makeSandbox({});
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
// After cb-presets.js auto-init: with no stored preset, body must NOT carry
|
||||
@@ -129,6 +131,7 @@ console.log('\n=== #1446 Scenario 2: server config.nodeColors → --mc-role-X (n
|
||||
{
|
||||
const env = makeSandbox({});
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
vm.runInContext(cv2Src, env.sandbox);
|
||||
@@ -143,6 +146,7 @@ console.log('\n=== #1446 Scenario 3: user override > active CB preset (body inli
|
||||
{
|
||||
const env = makeSandbox({});
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
env.sandbox.window.MeshCorePresets.applyPreset('deut');
|
||||
@@ -160,6 +164,7 @@ console.log('\n=== #1446 Scenario 4: clear override → reverts to active CB pre
|
||||
{
|
||||
const env = makeSandbox({});
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
env.sandbox.window.MeshCorePresets.applyPreset('deut');
|
||||
@@ -183,6 +188,7 @@ console.log('\n=== #1446 Scenario 5: clear preset → reverts to server config /
|
||||
{
|
||||
const env = makeSandbox({ 'meshcore-cb-preset': 'deut' });
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
vm.runInContext(cv2Src, env.sandbox);
|
||||
@@ -212,6 +218,7 @@ console.log('\n=== #1446 Scenario 6: backward compat — existing localStorage p
|
||||
{
|
||||
const env = makeSandbox({ 'meshcore-cb-preset': 'deut' });
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
// cb-presets auto-init must have applied deut from storage.
|
||||
@@ -247,6 +254,7 @@ console.log('\n=== #1446 Scenario 9: customize-v2 applyCSS writes user override
|
||||
{
|
||||
const env = makeSandbox({ 'meshcore-cb-preset': 'deut' });
|
||||
vm.createContext(env.sandbox);
|
||||
loadApiBase(env.sandbox);
|
||||
vm.runInContext(rolesSrc, env.sandbox);
|
||||
vm.runInContext(presetsSrc, env.sandbox);
|
||||
vm.runInContext(cv2Src, env.sandbox);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const vm = require('vm');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -97,6 +98,7 @@ function makeSandbox(opts) {
|
||||
ctx.window.document = ctx.document;
|
||||
ctx.globalThis = ctx;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
// After context creation, make the sandbox global object also be `window`
|
||||
// so `window.X = ...` in roles.js makes X a bare global the same file
|
||||
// can reference. We do this by copying assignments back — simpler: install
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -49,6 +50,7 @@ function makeSandbox() {
|
||||
ctx.window.location = ctx.location;
|
||||
ctx.window.localStorage = ctx.localStorage;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
function load(ctx, file) {
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -65,6 +66,7 @@ function makeSandbox() {
|
||||
ctx.window.location = ctx.location;
|
||||
ctx.window.localStorage = ctx.localStorage;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
function load(ctx, file) {
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const vm = require('vm');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -57,6 +58,7 @@ function makeSandbox(theme) {
|
||||
ctx.window.document = ctx.document;
|
||||
ctx.globalThis = ctx;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
const src = fs.readFileSync(path.join(REPO_ROOT, 'public', 'roles.js'), 'utf8');
|
||||
vm.runInContext(src, ctx, { filename: 'public/roles.js' });
|
||||
// Mirror window.* back so bare-name refs inside roles.js (TILE_DARK etc.) resolve.
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -54,6 +55,7 @@ function makeSandbox() {
|
||||
registerPage: (name, handler) => { registeredPages[name] = handler; },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
const { createCipheriv, createHmac, createHash } = require('crypto');
|
||||
@@ -51,6 +52,7 @@ function loadPathHashSize() {
|
||||
fetch: () => new Promise(() => {}),
|
||||
};
|
||||
vm.createContext(appCtx);
|
||||
loadApiBase(appCtx);
|
||||
vm.runInContext(fs.readFileSync('public/app.js', 'utf8'), appCtx);
|
||||
return appCtx.pathHashSize;
|
||||
}
|
||||
@@ -125,6 +127,7 @@ function makeChannelsSandbox(apiImpl) {
|
||||
};
|
||||
ctx.window.matchMedia = ctx.matchMedia;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
for (const file of ['public/vendor/aes-ecb.js', 'public/channel-decrypt.js', 'public/channels.js']) {
|
||||
vm.runInContext(fs.readFileSync(file, 'utf8'), ctx);
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -50,6 +51,7 @@ function makeSandbox(stored) {
|
||||
};
|
||||
ctx.window.L = ctx.L;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync('public/roles.js', 'utf8'), ctx);
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
// map.js's render path (index.html order) uses the tile-provider module's
|
||||
@@ -360,6 +362,7 @@ async function makePage(opts) {
|
||||
};
|
||||
ctx.window.L = L;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync('public/roles.js', 'utf8'), ctx);
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
// Same tile-provider stubs as the first harness above — map.js page render
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -56,6 +57,7 @@ function makeSandbox() {
|
||||
registerPage: (name, handler) => { registeredPages[name] = handler; },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const assert = require('assert');
|
||||
@@ -60,6 +61,7 @@ function loadAnalyticsHelpers() {
|
||||
};
|
||||
sandbox.window = sandbox;
|
||||
vm.createContext(sandbox);
|
||||
loadApiBase(sandbox);
|
||||
vm.runInContext(fs.readFileSync(path.join(REPO_ROOT, 'public/analytics.js'), 'utf8'), sandbox);
|
||||
return sandbox;
|
||||
}
|
||||
@@ -147,6 +149,7 @@ function loadApi(responses) {
|
||||
};
|
||||
sandbox.window = sandbox;
|
||||
vm.createContext(sandbox);
|
||||
loadApiBase(sandbox);
|
||||
vm.runInContext(fs.readFileSync(path.join(REPO_ROOT, 'public/app.js'), 'utf8'), sandbox);
|
||||
return { sandbox, calls };
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -49,6 +50,7 @@ function makeSandbox() {
|
||||
};
|
||||
ctx.window.L = ctx.L;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync('public/roles.js', 'utf8'), ctx);
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
vm.runInContext(fs.readFileSync('public/map.js', 'utf8'), ctx);
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
|
||||
@@ -23,6 +24,7 @@ function load(file) {
|
||||
parseInt, parseFloat, isNaN,
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
loadApiBase(sandbox);
|
||||
vm.runInContext(fs.readFileSync(REPO_ROOT + '/public/' + file, 'utf8'), sandbox);
|
||||
return sandbox;
|
||||
}
|
||||
@@ -101,6 +103,7 @@ function loadDisplay() {
|
||||
},
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
loadApiBase(sandbox);
|
||||
vm.runInContext(fs.readFileSync(REPO_ROOT + '/public/hop-display.js', 'utf8'), sandbox);
|
||||
return { HopDisplay: sandbox.window.HopDisplay, appended };
|
||||
}
|
||||
@@ -157,6 +160,7 @@ function loadPackets() {
|
||||
registerPage: () => {},
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
const loadFile = f => {
|
||||
vm.runInContext(fs.readFileSync(REPO_ROOT + '/public/' + f, 'utf8'), ctx, { filename: f });
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
@@ -53,6 +54,7 @@ function load() {
|
||||
// The battery card of whatever page is on screen.
|
||||
['batteryStatusBadge', 'batteryEmpty', 'batteryChart'].forEach((id) => { els[id] = mkEl(); });
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(SRC, ctx);
|
||||
// The shared #app container; time-range buttons are wired after a render.
|
||||
const buttons = {};
|
||||
@@ -92,6 +94,7 @@ function loadRouter() {
|
||||
ctx.addEventListener = (t, fn) => { listeners[t] = fn; };
|
||||
ctx.dispatchEvent = () => {};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, '..', '..', 'public/roles.js'), 'utf8'), ctx);
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, '..', '..', 'public/app.js'), 'utf8'), ctx);
|
||||
const go = (hash) => { ctx.location.hash = hash; listeners.hashchange(); };
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
@@ -44,6 +45,7 @@ function load(hash, opts) {
|
||||
ctx.registerPage = (name, p) => { if (name === 'account') page = p; };
|
||||
ctx.window = Object.assign({ CSAuth, addEventListener(t, fn) { listeners[t] = fn; } }, {});
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(SRC, ctx);
|
||||
// The shared #app container, counting every render into it.
|
||||
const app = { writes: [], set innerHTML(v) { this.writes.push(v); this._html = v; }, get innerHTML() { return this._html; } };
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -79,6 +80,7 @@ function makeSandbox() {
|
||||
RegionFilter: { init(){}, getSelected: () => null, onChange: () => {}, offChange: () => {}, regionQueryString: () => '', getRegionParam: () => '' },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const vm = require('vm');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
@@ -94,6 +95,7 @@ function makeSandbox() {
|
||||
},
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -64,6 +65,7 @@ function makeSandbox() {
|
||||
};
|
||||
ctx.window.L = ctx.L;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
// Load roles for ROLE_COLORS palette
|
||||
vm.runInContext(fs.readFileSync('public/roles.js','utf8'), ctx);
|
||||
for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k];
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -60,6 +61,7 @@ const CLIENT_TTL = { nodeList: 0, analyticsRF: 0 };
|
||||
// same thresholds as the browser uses.
|
||||
const rolesCtx = { window: {}, console, Date, Infinity, document: { readyState: 'complete', createElement: () => ({ id: '' }), head: { appendChild: () => {} }, getElementById: () => null, addEventListener: () => {} }, fetch: () => Promise.resolve({ json: () => Promise.resolve({}) }) };
|
||||
require('vm').createContext(rolesCtx);
|
||||
loadApiBase(rolesCtx);
|
||||
require('vm').runInContext(fs.readFileSync(path.join(REPO_ROOT, 'public', 'roles.js'), 'utf8'), rolesCtx);
|
||||
for (const k of Object.keys(rolesCtx.window)) rolesCtx[k] = rolesCtx.window[k];
|
||||
const getHealthStatus = rolesCtx.window.getHealthStatus;
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
'use strict';
|
||||
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
@@ -48,6 +49,7 @@ function sliceVersionFns() {
|
||||
function load(fetchImpl) {
|
||||
const sandbox = { fetch: fetchImpl, console };
|
||||
vm.createContext(sandbox);
|
||||
loadApiBase(sandbox);
|
||||
vm.runInContext(sliceVersionFns() + '\nthis.fillVersion = fillVersion;', sandbox);
|
||||
return sandbox.fillVersion;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use strict';
|
||||
const REPO_ROOT = require('path').resolve(__dirname, '..', '..');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
// Unit test for #6: pan/zoom coverage redraws must be debounced so dragging the
|
||||
// map fires at most one /api/...rx-coverage request per settle, not one per
|
||||
// moveend. We load node-reach-coverage.js in a vm sandbox with controllable
|
||||
@@ -54,6 +55,7 @@ const sandbox = {
|
||||
document: { documentElement: {} },
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
loadApiBase(sandbox);
|
||||
// Define debounce IN the context so it uses the controllable timers above.
|
||||
vm.runInContext('function debounce(fn, ms){var t; return function(){var a=arguments, c=this; clearTimeout(t); t=setTimeout(function(){fn.apply(c,a);}, ms);};}', sandbox);
|
||||
vm.runInContext(code, sandbox);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -48,6 +49,7 @@ function makeSandbox() {
|
||||
registerPage: (name, handler) => { registeredPages[name] = handler; },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -56,6 +57,7 @@ function makeSandbox() {
|
||||
registerPage: (name, handler) => { registeredPages[name] = handler; },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* Unit tests for packets.js functions (tested via VM sandbox) */
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -92,6 +93,7 @@ function makeSandbox() {
|
||||
registerPage: (name, handler) => { registeredPages[name] = handler; },
|
||||
};
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* Tests for perf.js Disk I/O + Write Sources + SQLite sections (#1120) */
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -41,7 +42,8 @@ function makeSandbox() {
|
||||
function loadPerf() {
|
||||
const sb = makeSandbox();
|
||||
const code = fs.readFileSync('public/perf.js', 'utf8');
|
||||
vm.runInNewContext(code, sb.ctx);
|
||||
loadApiBase(sb.ctx);
|
||||
vm.runInContext(code, sb.ctx);
|
||||
return sb;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
'use strict';
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -55,7 +56,8 @@ function makeSandbox(opts = {}) {
|
||||
function loadPerf() {
|
||||
const sb = makeSandbox();
|
||||
const code = fs.readFileSync('public/perf.js', 'utf8');
|
||||
vm.runInNewContext(code, sb.ctx);
|
||||
loadApiBase(sb.ctx);
|
||||
vm.runInContext(code, sb.ctx);
|
||||
return sb;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
'use strict';
|
||||
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -122,6 +123,7 @@ function makeSandbox(opts) {
|
||||
ctx.globalThis = ctx;
|
||||
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return { ctx, elements, wsInstances, listeners, docEl };
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
'use strict';
|
||||
|
||||
const vm = require('vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('fs');
|
||||
const assert = require('assert');
|
||||
|
||||
@@ -120,6 +121,7 @@ function makeSandbox(opts) {
|
||||
ctx.globalThis = ctx;
|
||||
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
return { ctx, elements, wsInstances, listeners };
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
'use strict';
|
||||
const REPO_ROOT = require('node:path').resolve(__dirname, '..', '..');
|
||||
const vm = require('node:vm');
|
||||
const { loadApiBase } = require('./api-base-sandbox');
|
||||
const fs = require('node:fs');
|
||||
const assert = require('node:assert');
|
||||
|
||||
@@ -42,6 +43,7 @@ function buildCtx(hash, initialStorage) {
|
||||
};
|
||||
ctx.window = ctx;
|
||||
vm.createContext(ctx);
|
||||
loadApiBase(ctx);
|
||||
vm.runInContext(fs.readFileSync(REPO_ROOT + '/public/region-filter.js', 'utf8'), ctx);
|
||||
return { rf: ctx.window.RegionFilter, storage, location: ctx.location };
|
||||
}
|
||||
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user