diff --git a/.env.example b/.env.example index 22ee0e8..ca3dafc 100644 --- a/.env.example +++ b/.env.example @@ -51,31 +51,27 @@ STREAMR_CRONSCHEDULE="0 * * * *" # Every hour # CENTRAL_TRUSTED_PROXIES=127.0.0.1,::1 # One-time token from central enrollment; remove it after the credential file exists. # AGENT_ENROLLMENT_TOKEN=REPLACE_WITH_ONE_TIME_TOKEN -# Central bootstrap only; password must have at least 16 characters. +# Central bootstrap only; password must have at least 7 characters. # CENTRAL_ADMIN_USERNAME=admin # CENTRAL_ADMIN_PASSWORD=REPLACE_WITH_A_UNIQUE_LONG_PASSWORD # Loopback authenticated fallback. Never publish this port through a proxy. -# GATEWAY_FALLBACK_PORT=3001 +# GATEWAY_FALLBACK_PORT=3011 (not 3001: ChirpStack's Basic Station bridge uses it) # Gateway-owned tunnel policy; central cannot override these targets. # AGENT_SSH_PORT=22 -# AGENT_BROWSER_ALLOW_LAN=false -# AGENT_BROWSER_PORTS=80,443,3000,8080,8090 # Used only by compose.central.yaml's TLS proxy. # CENTRAL_DOMAIN=console.example.invalid +# Central with no gateway selected: ChirpStack opens this dashboard (an origin, no path), +# and Terminal signs in to this server's own SSH (password login) on CENTRAL_SSH_PORT. +# CENTRAL_CHIRPSTACK_URL=https://chirpstack.example.invalid +# CENTRAL_SSH_PORT=22 -# Optional browser image (Chromium is absent from the default gateway image). -# BROWSER_IMAGE=ghcr.io/fluxion9/console-browser:feat-centralized-console -# BROWSER_EXECUTABLE=/usr/bin/chromium +# Images are not configured here. ./auto-compose.sh uses ghcr.io// from this +# checkout's GitHub origin remote (plus -updater); pin a build with --image. -# Optional separate updater; disabled locally by default. Never mount Docker in agent. +# Optional signed updater on gateways; ./auto-compose.sh starts it when this is true and +# trusts only images signed by this checkout's repository. Never mount Docker in agent. # REMOTE_UPDATES_ENABLED=false -# UPDATER_IMAGE=ghcr.io/fluxion9/console-updater:feat-centralized-console -# UPDATER_IMAGE_REPOSITORY=ghcr.io/fluxion9/console -# UPDATER_SOURCE_REPOSITORY=fluxion9/Console # UPDATER_ALLOWED_REFS=refs/heads/main -# Explicit test-only trust: refs/heads/main,refs/heads/feat/centralized-console -# COMPOSE_PROJECT_NAME=console -# UPDATER_DEPLOY_DIRECTORY=/absolute/host/path/to/Console # UPDATER_RECONNECT_TIMEOUT_MS=180000 # Registry/API access token for gh verification, only in the updater container. # UPDATER_GITHUB_TOKEN=REPLACE_WITH_READ_ONLY_VERIFICATION_TOKEN diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6540f4c..c4803e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,7 +46,7 @@ jobs: fail-fast: false matrix: platform: [linux/amd64, linux/arm64] - variant: [console, browser, updater] + variant: [console, updater] include: - platform: linux/amd64 runner: ubuntu-latest @@ -128,7 +128,7 @@ jobs: create-manifests: strategy: matrix: - variant: [console, browser, updater] + variant: [console, updater] needs: build-platform if: github.event_name != 'pull_request' runs-on: ubuntu-latest diff --git a/Dockerfile b/Dockerfile index 7417608..15c0e40 100644 --- a/Dockerfile +++ b/Dockerfile @@ -33,17 +33,6 @@ ENTRYPOINT ["/entrypoint.sh"] # Start app CMD [ "npm", "start" ] -# Optional browser image. Default builds below never install Chromium. -FROM runtime AS browser -RUN apk add --no-cache chromium openssl \ - && mkdir -p /opt/app/.data /opt/app/src/extensions /opt/app/dist/extensions \ - && chown -R node:node /opt/app/.data /opt/app/src/extensions /opt/app/dist/extensions -ENV BROWSER_EXECUTABLE=/usr/bin/chromium -USER node -# Build-only smoke check has no target service/network. Runtime requires sandbox. -RUN timeout 30 chromium --headless --no-sandbox --disable-gpu --disable-dev-shm-usage --no-first-run --disable-background-networking --proxy-server=http://127.0.0.1:9 --dump-dom about:blank > /tmp/browser-smoke.html \ - && grep -q ' - - # Module Configuration - BACKEND_MODULES="core/arweave,core/is_on,core/prover,core/streamr" - UI_MODULES="streamr:core/streamr/ui" - - # ChirpStack Configuration - API_TOKEN=... - APPLICATION_ID=... - CHIRPSTACK_HOST=localhost - - # Contract & Network Configuration - CONTRACT_LABEL=M3ters - MAINNET_RPC=https://ethereum-sepolia-rpc.publicnode.com #alt https://eth-sepolia.g.alchemy.com/v2/ - ETHEREUM_PRIVATE_KEY="..." - ROLLUP_CONTRACT_ADDRESS="0x9a9ED9b9A9BEC10d1B5E41b1873E78d19501D5Fa" - - # Streamr Configuration - STREAMR_STREAM_ID="0x567853282663b601bfdb9203819b1fbb3fe18926/m3tering/test" - STREAMR_CRONSCHEDULE="0 * * * *" # Every hour - - # Optional: Prover Node (publishing is disabled when unset) - # PREFERRED_PROVER_NODE="https://prover.m3ter.ing" - # PROVER_CRONSCHEDULE="0 0 * * *" # Every 24 hours - ``` - -3. **Docker Build and Run** - - ```bash - sudo docker compose down - sudo docker compose up -d - ``` +One command installs and updates every setup: a standalone gateway, a central +server, or a gateway managed by central. **Full instructions: +[docs/deployment-guide.md](docs/deployment-guide.md).** + +```bash +git clone https://github.com/fluxion9/Console.git +cd Console +./auto-compose.sh # first run creates .env from the template +nano .env # fill in API_TOKEN, APPLICATION_ID, ETHEREUM_PRIVATE_KEY +./auto-compose.sh # starts Console; open http://:3000 +``` + +Set `CONSOLE_ROLE=central` or `CONSOLE_ROLE=gateway` in `.env` for the other +setups. Update any machine later with `git pull && ./auto-compose.sh`. ## Other Docker Commands @@ -644,7 +610,8 @@ survive desktop theme changes and reloads. Native content, dialogs, and terminal colors follow the chosen palette. Embedded external websites retain their own appearance controls; the containing window follows the application setting. -To update the existing Docker deployment from GitHub Actions images: +To update the existing Docker deployment from GitHub Actions images (see +[docs/deployment-guide.md](docs/deployment-guide.md) for central and managed gateways): ```sh ./auto-compose.sh @@ -655,7 +622,8 @@ To update the existing Docker deployment from GitHub Actions images: Docker and its Compose plugin must already be installed. The script identifies this checkout's Compose project and running Console image, preserves its GHCR tag -by default (otherwise `ghcr.io/m3tering/console:main`), and lets Docker select the +when it comes from this checkout's GitHub repository (otherwise it uses +`ghcr.io//:main` from the `origin` remote), and lets Docker select the native architecture from the published manifest. It pulls before stopping Console, then stops/removes only that service, starts the updated image and waits for `/healthz`. Failed readiness prints logs and restores the previous image when @@ -672,11 +640,7 @@ The old **M3ters** meter-list application has been removed from the desktop, along with its exclusive `/delete-meter` UI endpoint. The collector's database, MQTT service, and meter records are preserved. The removed M3ter Manager is no longer available. -The Browser uses an optional isolated Chromium engine inside the Console window, -including Google searches, back/forward navigation, copy/paste and touch scrolling. -No site is embedded in an iframe. Without the optional browser image it shows an -engine-unavailable message while the rest of Console remains usable. See the -[Browser deployment instructions](docs/centralized/deployment.md#optional-browser-engine). +The Browser app has been removed, along with its optional Chromium image. `compose.yaml` passes the existing `.env` into the single Console container, which hosts the collector. The update script leaves that file and persistent @@ -721,7 +685,7 @@ integration tests are complete. The default `standalone` role preserves the local collector and LAN desktop. `central` adds authenticated multi-gateway access; `gateway` keeps a local fallback Console while an outbound agent owns MQTT. The same default multi-architecture -image contains both entry points. Browser and updater are optional Docker targets. +image contains both entry points. The signed updater is an optional Docker target. The central selector identifies each gateway and displays uncertain, reconciled and pending operation counts. Stored decisions are keyed by ChirpStack event ID. @@ -730,8 +694,9 @@ reconciliation; uncertainty never generates an OFF reply or automatic second attempt. The next report supersedes an unresolved old reply. Existing revenue checks remain fail-closed for actual new decisions. -Central Terminal and ChirpStack use purpose-limited gateway tunnels. Browser local -traffic goes to the selected gateway, never central's internal network. The +Central Terminal and ChirpStack use purpose-limited gateway tunnels. +With **Central server** selected (no gateway), Terminal and ChirpStack work on +the central machine itself; see the [deployment guide](docs/deployment-guide.md#working-on-the-central-server-itself). The separate, owner-enabled updater verifies provenance and replaces Console/agent by digest together, with rollback and persistent data preservation. diff --git a/auto-compose.sh b/auto-compose.sh index 6b7f82c..28040aa 100755 --- a/auto-compose.sh +++ b/auto-compose.sh @@ -13,15 +13,98 @@ while [[ $# -gt 0 ]]; do --help|-h) echo 'Usage: ./auto-compose.sh [--project-name NAME] [--image ghcr.io/OWNER/console:TAG]' echo 'Pulls the published image for this device, updates only Console, and preserves .env and all volumes.' + echo 'CONSOLE_ROLE in .env selects standalone (default), central, or gateway (Console + agent).' exit 0 ;; *) echo "Unknown option: $1" >&2; exit 2 ;; esac done if [[ -n "$project" && ! "$project" =~ ^[a-z0-9][a-z0-9_-]*$ ]]; then echo 'Invalid Compose project name.' >&2; exit 2; fi -[[ -f .env ]] || { echo 'Missing .env: configure the existing services before deployment.' >&2; exit 1; } -command -v docker >/dev/null || { echo 'Docker must already be installed.' >&2; exit 1; } -docker compose version >/dev/null -docker info >/dev/null +if [[ ! -f .env ]]; then + [[ -f .env.example ]] || { echo 'Missing .env: configure the existing services before deployment.' >&2; exit 1; } + # First run: start from the template, readable only by its owner because it holds keys. + (umask 077; cp .env.example .env) + echo 'Created .env from .env.example (permissions 600). Fill in at least:' + echo ' API_TOKEN, APPLICATION_ID ChirpStack API token and application UUID' + echo ' ETHEREUM_PRIVATE_KEY wallet key for this Console (use a test wallet first)' + echo 'For central or gateway mode also set CONSOLE_ROLE; see docs/deployment-guide.md.' + echo 'Then run ./auto-compose.sh again.' + exit 0 +fi +# Read one .env setting without executing the file; strips surrounding quotes. +env_value() { + sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" .env | tail -1 \ + | sed -e 's/[[:space:]]*$//' -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/" +} +# Images come from the repository this checkout follows, never from .env. +if [[ -n "$(env_value CONSOLE_IMAGE)" ]]; then + echo 'Note: CONSOLE_IMAGE in .env is ignored; images follow this checkout'"'"'s GitHub repository. Remove that line, and use --image to pin a build.' +fi +# CI publishes images as ghcr.io//, named after the GitHub repository, +# so follow the repository this checkout was cloned from. +repo_image='' source_repo='' +if remote=$(git remote get-url origin 2>/dev/null); then + case "$remote" in + git@github.com:*) slug=${remote#git@github.com:} ;; + ssh://git@github.com/*) slug=${remote#ssh://git@github.com/} ;; + https://github.com/*|https://*@github.com/*) slug=${remote#*github.com/} ;; + *) slug='' ;; + esac + slug=${slug%/}; slug=${slug%.git} + if [[ "$slug" =~ ^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$ ]]; then + source_repo=$slug; repo_image="ghcr.io/$(tr '[:upper:]' '[:lower:]' <<<"$slug")" + fi +fi +# The optional updater image and its signature trust follow the same repository. +if [[ -n "$repo_image" ]]; then + export UPDATER_IMAGE="$repo_image-updater:main" + export UPDATER_IMAGE_REPOSITORY="$repo_image" UPDATER_SOURCE_REPOSITORY="$source_repo" +fi +role=$(env_value CONSOLE_ROLE | sed -n 's/^\([a-z]*\).*/\1/p') +role="${role:-standalone}" +services=(console) +# Gateway secrets must belong to the user the containers run as (root in the published image). +as_root=(); [[ "$(id -u)" -eq 0 ]] || as_root=(sudo) +secret_uid="${AGENT_SECRET_UID:-0}" +[[ "$secret_uid" =~ ^[0-9]+$ ]] || { echo 'AGENT_SECRET_UID must be a numeric user ID.' >&2; exit 2; } +has_credential() { "${as_root[@]}" test -s .data/agent/credential; } +# Template values such as API_TOKEN=... crash the Console later with an unclear error; stop now instead. +placeholders=$(sed -n -E "s/^[[:space:]]*([A-Za-z0-9_]+)[[:space:]]*=[[:space:]]*[\"']?(\.\.\.|REPLACE_WITH_[A-Za-z0-9_]*)[\"']?[[:space:]]*(#.*)?$/\1/p" .env | paste -sd, - | sed 's/,/, /g') +# Central never talks to ChirpStack, so its template ChirpStack lines may stay as they are. +if [[ "$role" == central ]]; then placeholders=$(tr -d ' ' <<<"$placeholders" | tr ',' '\n' | grep -vxE 'API_TOKEN|APPLICATION_ID' | paste -sd, - | sed 's/,/, /g' || true); fi +[[ -z "$placeholders" ]] || { echo "Replace the placeholder values in .env: $placeholders" >&2; exit 2; } +require_chirpstack() { + [[ -n "$(env_value API_TOKEN)" ]] || { echo 'Set API_TOKEN in .env to a ChirpStack API token.' >&2; exit 2; } + [[ "$(env_value APPLICATION_ID)" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]] \ + || { echo 'Set APPLICATION_ID in .env to your ChirpStack application UUID (Applications page in ChirpStack).' >&2; exit 2; } +} +case "$role" in + standalone) + require_chirpstack + compose_file=compose.yaml; default_image=${repo_image:-ghcr.io/m3tering/console}:main ;; + central) + compose_file=compose.central.yaml; default_image=${repo_image:-ghcr.io/fluxion9/console}:main + [[ -n "$(env_value CENTRAL_DOMAIN)" ]] || { echo 'Set CENTRAL_DOMAIN in .env to the DNS name pointing at this server.' >&2; exit 2; } + # The administrator is created only on first start; later starts ignore the password. + if [[ ! -s .data/central.db ]]; then + password=$(env_value CENTRAL_ADMIN_PASSWORD) + (( ${#password} >= 7 )) || { echo 'Set CENTRAL_ADMIN_PASSWORD in .env (at least 7 characters) for the first central start.' >&2; exit 2; } + fi ;; + gateway) + compose_file=compose.gateway.yaml; default_image=${repo_image:-ghcr.io/fluxion9/console}:main; services=(console agent) + central_url=$(env_value CENTRAL_URL) + insecure=$(env_value CENTRAL_ALLOW_INSECURE_DEVELOPMENT) + [[ "$central_url" =~ ^wss://[^/?#@[:space:]]+/?$ || ( "$insecure" == true && "$central_url" =~ ^ws://[^/?#@[:space:]]+/?$ ) ]] \ + || { echo 'Set CENTRAL_URL in .env to your central origin, for example wss://console.example.com (no path).' >&2; exit 2; } + require_chirpstack + if ! has_credential && [[ -z "$(env_value AGENT_ENROLLMENT_TOKEN)" ]]; then + echo 'This gateway is not enrolled yet. On central open Gateways, add this gateway, and paste its' >&2 + echo 'AGENT_ENROLLMENT_TOKEN=... line into .env. The token expires after ten minutes.' >&2; exit 2 + fi ;; + *) echo 'CONSOLE_ROLE in .env must be standalone, central or gateway.' >&2; exit 2 ;; +esac +command -v docker >/dev/null || { echo 'Docker is not installed. Install it with: curl -fsSL https://get.docker.com | sudo sh' >&2; exit 1; } +docker compose version >/dev/null 2>&1 || { echo 'The Docker Compose plugin is missing; install docker-compose-plugin.' >&2; exit 1; } +docker info >/dev/null 2>&1 || { echo 'Cannot reach Docker. Run with sudo, or: sudo usermod -aG docker "$USER" and log in again.' >&2; exit 1; } # Discover deployments belonging to this checkout, not unrelated Compose projects. if [[ -z "$project" ]]; then projects=() @@ -37,36 +120,150 @@ if [[ -z "$project" ]]; then project="${projects[0]:-$(basename "$PWD" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9_-')}" fi [[ "$project" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || { echo 'Invalid Compose project name.' >&2; exit 2; } -compose=(docker compose --project-name "$project" -f compose.yaml) +compose=(docker compose --project-name "$project" -f "$compose_file") +# Gateways: run the signed updater when the owner enabled it, or keep an existing one current. +manage_updater=false +if [[ "$role" == gateway ]] && { [[ "$(env_value REMOTE_UPDATES_ENABLED)" == true ]] || + [[ -n "$(docker ps -aq --filter "label=com.docker.compose.project=$project" --filter label=com.docker.compose.service=updater)" ]]; }; then + [[ -n "$repo_image" ]] || { echo 'Remote updates need a GitHub origin remote: the updater only trusts images signed by that repository.' >&2; exit 2; } + manage_updater=true + export COMPOSE_PROJECT_NAME="$project" UPDATER_DEPLOY_DIRECTORY="$PWD" + compose+=(-f compose.updater.yaml) +fi old_container=$("${compose[@]}" ps -aq console | head -1) -old_id='' +old_id='' old_role='' if [[ -n "$old_container" ]]; then old_id=$(docker inspect --format '{{.Image}}' "$old_container") old_ref=$(docker inspect --format '{{.Config.Image}}' "$old_container") + # The compose file that created the container says which role it ran. Its environment does not: + # .env values such as CONSOLE_ROLE leak into a standalone container through env_file. + case "$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project.config_files"}}' "$old_container")" in + *compose.gateway.yaml*) old_role=gateway ;; + *compose.central.yaml*) old_role=central ;; + *) old_role=standalone ;; + esac echo "Current Console: $old_ref ($old_id)" - if [[ -z "$image" && "$old_ref" == ghcr.io/* ]]; then image="$old_ref"; fi + # Keep the running tag or digest only for the same role (a standalone image may lack central + # support) and the same repository as this checkout (the remote may have been switched). + # The Browser app and its -browser image were removed: a -browser container moves to the normal image. + old_repo=${old_ref%@*}; old_repo=${old_repo%:*} + if [[ -z "$image" && "$old_ref" == ghcr.io/* && "$old_role" == "$role" && "$old_repo" != *-browser && + ( -z "$repo_image" || "$old_repo" == "$repo_image" ) ]]; then + image="$old_ref" + fi fi -export CONSOLE_IMAGE="${image:-ghcr.io/m3tering/console:main}" +export CONSOLE_IMAGE="${image:-$default_image}" [[ "$CONSOLE_IMAGE" =~ ^ghcr\.io/[a-z0-9._/-]+(:[a-zA-Z0-9._-]+|@sha256:[a-f0-9]{64})$ ]] || { echo 'Specify a published GHCR image with an explicit tag or digest.' >&2; exit 2; } -echo "Project: $project; update image: $CONSOLE_IMAGE" +echo "Project: $project; role: $role; update image: $CONSOLE_IMAGE" +[[ -z "$repo_image" ]] || echo "Image repository from git origin: $repo_image" "${compose[@]}" config --quiet -# Keep the old service and image until the correct architecture is downloaded. -"${compose[@]}" pull console -"${compose[@]}" stop console -"${compose[@]}" rm --force console -if ! "${compose[@]}" up --detach --no-deps --no-build --pull never --wait --wait-timeout 240 console; then - echo 'Console failed readiness. Recent logs:' >&2 - "${compose[@]}" logs --tail 80 console >&2 || true - if [[ -n "$old_id" ]]; then + +if [[ "$role" == gateway ]]; then + # Owner-only local secrets shared by Console and agent. Existing secrets are never replaced. + "${as_root[@]}" sh -c ' + set -e; uid=$1; umask 077 + mkdir -p .data/agent .data/updater + chmod 700 .data/agent .data/updater; chown "$uid" .data/agent .data/updater + for name in fallback-secret updater-secret; do + file=.data/agent/$name + [ -e "$file" ] || head -c 32 /dev/urandom | base64 | tr "+/" "-_" | tr -d "=\n" > "$file" + chmod 600 "$file"; chown "$uid" "$file" + done + if [ -e .data/agent/credential ]; then chmod 600 .data/agent/credential; chown "$uid" .data/agent/credential; fi + ' sh "$secret_uid" +fi + +# The agent counts as ready once it has stayed up without restarting and holds a credential. +# Each failure says why, so a failed deploy can be diagnosed from the script output alone. +agent_ready() { + local container status restarts check + container=$("${compose[@]}" ps -q agent | head -1) + [[ -n "$container" ]] || { echo 'Agent check: no agent container was created.' >&2; return 1; } + for (( check=1; check<=${AGENT_READY_CHECKS:-45}; check++ )); do + read -r status restarts < <(docker inspect --format '{{.State.Status}} {{.RestartCount}}' "$container") + if [[ "$status" != running || "$restarts" != 0 ]]; then + echo "Agent check: the agent stopped or restarted (status $status, restarts $restarts)." >&2; return 1 + fi + if (( check >= ${AGENT_STABLE_CHECKS:-5} )) && has_credential; then return 0; fi + sleep "${AGENT_READY_INTERVAL:-2}" + done + echo 'Agent check: the agent is running but never stored a credential; enrollment did not finish (check the token and that central is reachable).' >&2 + return 1 +} +# The gateway Console's loopback fallback port must be free once our own Console has stopped. +fallback_port=$(env_value GATEWAY_FALLBACK_PORT); fallback_port=${fallback_port:-3011} +port_busy() { command -v ss >/dev/null && [[ -n "$(ss -ltnH "sport = :$1" 2>/dev/null)" ]]; } +port_owner() { "${as_root[@]}" ss -ltnpH "sport = :$1" 2>/dev/null | sed -n 's/.*users:(("\([^"]*\)".*/\1/p' | head -1; } +# Only images that contain the agent can run the gateway pair. +image_has_agent() { docker run --rm --entrypoint test "$1" -f /opt/app/dist/agent/index.js >/dev/null 2>&1; } +deploy_failed() { + echo "${services[*]} failed readiness. Recent logs:" >&2 + "${compose[@]}" logs --tail 80 "${services[@]}" >&2 || true + if [[ -z "$old_id" ]]; then exit 1; fi + if [[ "$role" == gateway && "$old_role" == gateway ]] && ! image_has_agent "$old_id"; then + # Rolling back onto an image without the agent would leave the gateway with no working agent at all. + echo 'The previous image has no agent, so it was NOT restored; the new pair keeps running and retrying.' >&2 + echo 'Fix the problem shown above and rerun this script.' >&2 + elif [[ "$role" != gateway || "$old_role" == gateway ]]; then echo 'Restoring the previous image; persistent data has not been removed.' >&2 - CONSOLE_IMAGE="$old_id" "${compose[@]}" up --detach --no-deps --no-build --pull never --force-recreate console || true + CONSOLE_IMAGE="$old_id" "${compose[@]}" up --detach --no-deps --no-build --pull never --force-recreate "${services[@]}" || true + elif ! "${as_root[@]}" test -e .data/agent/operations.db; then + # The agent never got past enrollment, so it handled no meter reports: standalone can safely resume. + echo 'Restoring the standalone Console; the agent never started handling reports.' >&2 + "${compose[@]}" stop agent || true; "${compose[@]}" rm --force agent || true + CONSOLE_IMAGE="$old_id" docker compose --project-name "$project" -f compose.yaml up --detach --no-deps --no-build --pull never --force-recreate console || true + else + # Never run a standalone subscriber beside an agent journal: two deciders could answer one meter. + echo 'The agent has an operations journal, so standalone was NOT restarted automatically.' >&2 + echo 'Fix the problem above and rerun this script. See docs/centralized/deployment.md to return to standalone.' >&2 fi exit 1 +} + +# Keep the old service and image until the correct architecture is downloaded. +"${compose[@]}" pull "${services[@]}" +# The updater must not replace Console and agent while this script does. +if $manage_updater; then "${compose[@]}" stop updater; fi +# Stopping Console first also stops a standalone MQTT subscriber before the agent takes over. +"${compose[@]}" stop "${services[@]}" +if [[ "$role" == gateway ]] && port_busy "$fallback_port"; then + owner=$(port_owner "$fallback_port") + echo "Port $fallback_port is already used by ${owner:-another program}. The gateway Console needs it for its local fallback." >&2 + echo "Set GATEWAY_FALLBACK_PORT in .env to a free port (for example 3011 or 3101) and rerun. Nothing was changed." >&2 + # Put back whatever was running; a service that did not exist yet simply stays absent. + for service in "${services[@]}"; do "${compose[@]}" start "$service" >/dev/null 2>&1 || true; done + if $manage_updater; then "${compose[@]}" start updater >/dev/null 2>&1 || true; fi + exit 2 +fi +"${compose[@]}" rm --force "${services[@]}" +"${compose[@]}" up --detach --no-deps --no-build --pull never --wait --wait-timeout 240 "${services[@]}" || deploy_failed +if [[ "$role" == gateway ]]; then agent_ready || deploy_failed; fi +if $manage_updater; then + # Recreate so a changed REMOTE_UPDATES_ENABLED or trust setting applies; it recovers interrupted jobs on start. + { "${compose[@]}" pull updater && "${compose[@]}" up --detach --no-deps --force-recreate updater; } \ + || { echo 'Console and agent are running, but the updater did not start; remote updates are unavailable.' >&2; exit 1; } fi new_id=$(docker inspect --format '{{.Image}}' "$("${compose[@]}" ps -q console)") if [[ -n "$old_id" && "$old_id" != "$new_id" && -z "$(docker ps -aq --filter "ancestor=$old_id")" ]]; then # No force: Docker keeps images that still have other tags/references. docker image rm "$old_id" || echo 'Previous image retained because it is still referenced.' fi -"${compose[@]}" ps console +if [[ "$role" == central ]]; then + # TLS proxy (Caddy) publishes the loopback-only Console on ports 80/443. + "${compose[@]}" up --detach tls-proxy || { echo 'Console is running, but the TLS proxy failed to start; check ports 80/443.' >&2; exit 1; } +fi +"${compose[@]}" ps echo 'Console updated. Database, extension volumes and .env were preserved.' +if [[ "$role" == gateway ]]; then + echo 'Gateway agent is running. Its card on central should show Online within a minute.' + if [[ -n "$(env_value AGENT_ENROLLMENT_TOKEN)" ]]; then + echo 'Enrollment is complete: remove the AGENT_ENROLLMENT_TOKEN line from .env (it cannot be reused).' + fi +fi +if [[ "$role" == central ]]; then + admin=$(env_value CENTRAL_ADMIN_USERNAME) + echo "Central: https://$(env_value CENTRAL_DOMAIN) (sign in as ${admin:-admin})" +fi +if [[ -n "$(env_value BROWSER_ENABLED)" ]]; then + echo 'Note: the Browser app has been removed; delete the BROWSER_ENABLED line from .env.' +fi diff --git a/compose.browser.yaml b/compose.browser.yaml deleted file mode 100644 index 9abe239..0000000 --- a/compose.browser.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# Optional image override for central/standalone. Prepare data ownership for UID 1000. -services: - console: - image: ${BROWSER_IMAGE:-ghcr.io/fluxion9/console-browser:feat-centralized-console} - shm_size: 256mb - mem_limit: 2g - cpus: 2 - environment: - BROWSER_EXECUTABLE: /usr/bin/chromium diff --git a/compose.central.yaml b/compose.central.yaml index f3d7a20..a3543a8 100644 --- a/compose.central.yaml +++ b/compose.central.yaml @@ -1,7 +1,7 @@ # Opt-in central test topology; supply CENTRAL_DOMAIN and central credentials. services: console: - image: ${CONSOLE_IMAGE:-ghcr.io/fluxion9/console:feat-centralized-console} + image: ${CONSOLE_IMAGE:-ghcr.io/fluxion9/console:main} network_mode: host restart: unless-stopped env_file: [.env] diff --git a/compose.gateway.yaml b/compose.gateway.yaml index a2f131f..78736cd 100644 --- a/compose.gateway.yaml +++ b/compose.gateway.yaml @@ -1,7 +1,7 @@ # Opt-in test topology. Default compose.yaml is unchanged. services: console: - image: ${CONSOLE_IMAGE:-ghcr.io/fluxion9/console:feat-centralized-console} + image: ${CONSOLE_IMAGE:-ghcr.io/fluxion9/console:main} network_mode: host restart: unless-stopped env_file: [.env] @@ -23,7 +23,7 @@ services: start_period: 30s retries: 24 agent: - image: ${CONSOLE_IMAGE:-ghcr.io/fluxion9/console:feat-centralized-console} + image: ${CONSOLE_IMAGE:-ghcr.io/fluxion9/console:main} # Agent does not initialize extensions, contracts or a blockchain wallet. entrypoint: [node] command: [dist/agent/index.js] @@ -40,7 +40,7 @@ services: CENTRAL_DECISION_TIMEOUT_MS: ${CENTRAL_DECISION_TIMEOUT_MS:-8000} CENTRAL_RECOVERY_HEALTHY_MS: ${CENTRAL_RECOVERY_HEALTHY_MS:-15000} AGENT_QUEUE_LIMIT: ${AGENT_QUEUE_LIMIT:-10000} - GATEWAY_FALLBACK_PORT: ${GATEWAY_FALLBACK_PORT:-3001} + GATEWAY_FALLBACK_PORT: ${GATEWAY_FALLBACK_PORT:-3011} CHIRPSTACK_HOST: ${CHIRPSTACK_HOST:-localhost} APPLICATION_ID: ${APPLICATION_ID:?Set the existing ChirpStack application ID} API_TOKEN: ${API_TOKEN:?Set the existing ChirpStack API token} @@ -48,8 +48,6 @@ services: CHEFSTACK_URL: ${CHEFSTACK_URL:-} CHIRPSTACK_WEB_URL: ${CHIRPSTACK_WEB_URL:-} AGENT_SSH_PORT: ${AGENT_SSH_PORT:-22} - AGENT_BROWSER_ALLOW_LAN: ${AGENT_BROWSER_ALLOW_LAN:-false} - AGENT_BROWSER_PORTS: ${AGENT_BROWSER_PORTS:-80,443,3000,8080,8090} volumes: - ./.data/agent:/opt/app/.data/agent read_only: true diff --git a/compose.updater.yaml b/compose.updater.yaml index 98006f2..94f91ee 100644 --- a/compose.updater.yaml +++ b/compose.updater.yaml @@ -1,12 +1,13 @@ -# Add to compose.gateway.yaml only after owner review. This service alone has Docker access. +# Started by ./auto-compose.sh on gateways when REMOTE_UPDATES_ENABLED=true. This service alone has Docker access. +# Image and signature trust follow the checkout's GitHub repository; auto-compose.sh sets them. services: updater: - image: ${UPDATER_IMAGE:-ghcr.io/fluxion9/console-updater:feat-centralized-console} + image: ${UPDATER_IMAGE:?Run ./auto-compose.sh; it sets the updater image from the checkout's repository} restart: unless-stopped environment: REMOTE_UPDATES_ENABLED: ${REMOTE_UPDATES_ENABLED:-false} - UPDATER_IMAGE_REPOSITORY: ${UPDATER_IMAGE_REPOSITORY:-ghcr.io/fluxion9/console} - UPDATER_SOURCE_REPOSITORY: ${UPDATER_SOURCE_REPOSITORY:-fluxion9/Console} + UPDATER_IMAGE_REPOSITORY: ${UPDATER_IMAGE_REPOSITORY:?Run ./auto-compose.sh; it sets the trusted image repository} + UPDATER_SOURCE_REPOSITORY: ${UPDATER_SOURCE_REPOSITORY:?Run ./auto-compose.sh; it sets the trusted source repository} UPDATER_ALLOWED_REFS: ${UPDATER_ALLOWED_REFS:-refs/heads/main} UPDATER_PROJECT: ${COMPOSE_PROJECT_NAME:?Set the existing gateway Compose project name} UPDATER_DEPLOY_DIRECTORY: ${UPDATER_DEPLOY_DIRECTORY:?Set the absolute host checkout path} diff --git a/docs/centralized/current-architecture.md b/docs/centralized/current-architecture.md index bb84bcc..bad8ef0 100644 --- a/docs/centralized/current-architecture.md +++ b/docs/centralized/current-architecture.md @@ -121,7 +121,7 @@ and upgrade dispatch; agent upgrades need separate credential authentication. | Terminal `/terminal` | `ssh2` to `127.0.0.1:22`; browser supplies SSH credentials, resize and input | Keep direct local SSH | `ssh2` over purpose-limited agent TCP stream; audit sessions | | ChirpStack `/chirpstack/*` | HTTP/gRPC-Web reverse proxy to optional ChefStack/web URL or `CHIRPSTACK_HOST:8080` | Keep local streaming proxy | Same proxy through selected agent, no central local-network access | | M3ter Manager `/api/m3ter-manager/*`, live stream | Own login, MQTT observations, SQLite history, REST device/queue management | Remove | Remove | -| Browser | Explicit URLs framed; Google searches open another tab | Replace with optional remote engine; local traffic reaches this machine | Remote engine; private traffic reaches selected gateway only | +| Browser | Explicit URLs framed; Google searches open another tab | Removed | Removed | | Paint | Browser canvas, pointer drawing, undo, image export | Unchanged client-side | Unchanged client-side | | Settings / themes / toggle / desktop preferences | Local storage, four themes, icon layout, window control | Unchanged | Unchanged, with gateway selection added separately | | App feedback / actions | App-scoped dialogs, notifications, extension action calls | Unchanged | Authenticated actions; selected gateway context where relevant | diff --git a/docs/centralized/deployment.md b/docs/centralized/deployment.md index 076040a..1edade7 100644 --- a/docs/centralized/deployment.md +++ b/docs/centralized/deployment.md @@ -1,5 +1,8 @@ # Opt-in test deployment +For everyday installation and updates, follow [../deployment-guide.md](../deployment-guide.md). +This page keeps the detailed security notes and advanced options. + This branch is for isolated evaluation, not a production rollout. Read [test-plan.md](test-plan.md) for executed checks and release gates. No live gateway, meter, ChirpStack server or blockchain was contacted during implementation. @@ -13,7 +16,7 @@ With no role configured the Console stays standalone, without a Console login. Manager is removed, including telemetry/commands UI; old Manager environment variables are ignored with one warning. Its SQLite tables are preserved. Use ChirpStack's device queue for technician downlinks and your external monitoring -tool for telemetry. The Browser now uses an optional remote Chromium engine. +tool for telemetry. Manual update and rollback still use the existing script: @@ -30,7 +33,7 @@ is not authorization to run either command on production. Start from `.env.example` only on a new checkout; never overwrite an existing `.env`. Configure the existing contract/module settings for an isolated test network, plus `CENTRAL_DOMAIN`, `CENTRAL_ADMIN_USERNAME` and a unique -`CENTRAL_ADMIN_PASSWORD` of at least 16 characters. Set file permissions to 0600. +`CENTRAL_ADMIN_PASSWORD` of at least 7 characters. Set file permissions to 0600. The bootstrap user is created once; changing its environment password does not silently reset an existing account. Central does not connect directly to MQTT, SSH or ChirpStack. Existing module hooks and contract configuration are still @@ -91,7 +94,7 @@ requires revocation and a new token, not token reuse. Rotate credentials from central while connected; old/new overlap for two minutes until the agent persists and acknowledges the new credential. Revocation immediately disconnects it. -Local fallback RPC listens on 127.0.0.1:3001 and requires the shared secret. +Local fallback RPC listens on 127.0.0.1:3011 (`GATEWAY_FALLBACK_PORT`) and requires the shared secret. Never proxy that port. Gateway Console serves the existing LAN UI; the agent owns MQTT, uses a stable persistent QoS-1 session, and forwards only signed FPort 2 reports. No autonomous MQTT takeover occurs when the agent dies: restart it and @@ -104,61 +107,36 @@ tradeoff and reconciliation rules. ## Tunnel policy Gateway owners control each purpose separately. SSH defaults to 127.0.0.1:22; -ChirpStack uses the existing configured web endpoint. Browser defaults to -loopback ports 80,443,3000,8080,8090. Set `AGENT_BROWSER_PORTS` locally to adjust -that list; private LAN access additionally requires `AGENT_BROWSER_ALLOW_LAN=true`. -Metadata, Docker and fallback/SSH control ports remain blocked for Browser. +ChirpStack uses the existing configured web endpoint. No other tunnel purpose exists. Central cannot override these settings. SSH uses first-use host-key pinning and refuses changes; investigate legitimate key changes before manually removing that gateway's `central_hostkeys` record. Do not routinely disable host-key validation. -## Optional Browser engine - -The default image intentionally omits Chromium. For a central or standalone test -server, add `-f compose.browser.yaml` to its Compose commands. This selects -`ghcr.io/fluxion9/console-browser:feat-centralized-console`, an optional target of -the same Dockerfile, with Alpine Chromium/OpenSSL and a non-root runtime. Ensure -its data and extension volumes are owned by UID 1000. Do not blindly apply this -override to a managed gateway pair: both services must use the same image and -owner-file UID. Small gateways can keep Browser unavailable and use central's -engine instead. The default Console still starts and passes health checks. - -Production engine execution requires working Chromium sandbox/user namespaces. -Never enable `BROWSER_UNSANDBOXED_TEST` outside test fixtures; it is ignored unless -NODE_ENV=test. If the host cannot support the sandbox, retain the unavailable -state until host isolation is correctly configured. No privileged-container or -Docker-socket workaround is supported. Browser profiles are temporary; uploads -and downloads are disabled. Copy/paste, IME, touch scrolling and zoom are provided. -The optional Compose profile bounds the whole Console/engine to 2 GiB, 2 CPUs and -256 MiB shared memory. These are limits, not measured i.MX8 requirements. - ## Optional signed updater Only `compose.updater.yaml` mounts Docker. The agent never receives Docker access. -Set these gateway-owner variables in the existing protected `.env`: +To enable remote updates, add this to the gateway's protected `.env` and run +`./auto-compose.sh`: ```dotenv REMOTE_UPDATES_ENABLED=true -COMPOSE_PROJECT_NAME=YOUR_EXISTING_PROJECT -UPDATER_DEPLOY_DIRECTORY=/absolute/host/path/to/Console -UPDATER_IMAGE_REPOSITORY=ghcr.io/fluxion9/console -UPDATER_SOURCE_REPOSITORY=fluxion9/Console -UPDATER_ALLOWED_REFS=refs/heads/main,refs/heads/feat/centralized-console -UPDATER_RECONNECT_TIMEOUT_MS=180000 +# Optional: UPDATER_ALLOWED_REFS (default refs/heads/main), UPDATER_RECONNECT_TIMEOUT_MS ``` -The test branch must be explicitly trusted; remove it after testing. If the +The script starts the updater and keeps it current on every run. It sets the +Compose project and the absolute checkout path itself, and mounts that same path +into the updater so Compose bind mounts resolve on the Docker host. If the registry/API requires authentication, set `UPDATER_GITHUB_TOKEN` to a narrowly -scoped read token. Only the updater receives it. The exact same absolute checkout -path is mounted into the updater so Compose bind mounts resolve on the Docker -host, not a fictitious container path. - -```sh -docker compose -f compose.gateway.yaml -f compose.updater.yaml up -d -``` - -The trust identity is GitHub's OIDC issuer, source repository `fluxion9/Console`, -workflow `fluxion9/Console/.github/workflows/ci.yml`, and the allowed source refs. +scoped read token; only the updater receives it. + +The trusted repository is **not** configured in `.env`. It is taken from the +checkout's GitHub `origin` remote. For a checkout of `/` the trust +identity is GitHub's OIDC issuer, source repository `/`, workflow +`//.github/workflows/ci.yml`, and the allowed source refs. Accepted +images are `ghcr.io//@sha256:…`, and the updater image is +`ghcr.io//-updater:main`. Remote updates are refused if the checkout +has no GitHub remote. The updater itself has no built-in repository and won't +start without one. `gh attestation verify` checks signed provenance and subject digest before the updater pulls/restarts anything. The workflow attests each published platform and manifest, never pull-request builds. An unsigned/wrongly signed digest is refused. @@ -172,7 +150,7 @@ Failed readiness or no authenticated agent reconnect within the configured windo rolls back; interrupted replacement rolls back on updater restart. Failed digests are blocked from automatic retry. No general shell command/script is accepted. -Set `REMOTE_UPDATES_ENABLED=false` locally and restart only updater to disable +Set `REMOTE_UPDATES_ENABLED=false` locally and rerun `./auto-compose.sh` (or restart only the updater) to disable remote updates; central cannot override this. Rollout is manual, one gateway at a time; there is no automatic latest-main scheduler. A remote update does not rewrite `.env` image preferences: record/pin a successful image there before a later manual diff --git a/docs/centralized/design.md b/docs/centralized/design.md index 5830b1a..cec67c3 100644 --- a/docs/centralized/design.md +++ b/docs/centralized/design.md @@ -108,81 +108,9 @@ state and contiguous signed records. A decider cannot accept a new report until its replay backlog has been applied. An older committed handler remains a fence even if several intervening, unowned reports have already been superseded. -## Browser implementation and isolation - -A remote Chromium engine is required for ordinary sites: an iframe rewriting -proxy cannot generally preserve CSP, service workers, cookies and modern scripts. -Chromium is optional so the default image remains usable on small gateways. -A missing engine must be visible in the app, not cause Console startup failure. - -Traffic must use a per-session controlled proxy and isolated browser profile. -DNS must be classified and pinned at the connection boundary. In central mode, -private destinations route only through the selected agent, never through the -central network. Gateway-local `.local`/`.lan` names are resolved and pinned by the gateway -tunnel endpoint, which refuses public answers and applies its owner allowlist; -central DNS is not used for those names. Cloud metadata is always refused. Gateway allowlists remain -owner-controlled and separate by tunnel purpose. - -A blind CONNECT proxy cannot inspect the requesting origin inside TLS. Therefore -public-to-private protection cannot be claimed from destination filtering alone. -The implementation terminates CONNECT with a per-session certificate trusted -only by that Chromium process's SPKI allowlist. Upstream TLS is independently -validated. CDP pauses each request; the proxy resolves and classifies its target, -then issues a short-lived, single-use permit bound to URL, method and pinned IP. -The browser cannot choose routing headers; the proxy strips its permit upstream. -Public-page requests to private targets are refused, including redirects. An -explicit address-bar navigation or user-clicked top-level navigation may open a -local target. WebSocket handshakes use the browser-controlled Origin, previously -classified by the proxy; unknown or ambiguously classified origins are refused. -QUIC and unproxied WebRTC UDP are disabled. Service workers are bypassed. - -A rewriting iframe proxy was rejected for internet sites because framing, cookie -and script restrictions would remain. A hybrid adds two inconsistent security -and navigation models without removing Chromium's cost. The selected optional -engine provides a single CDP screencast page; target-blank links stay in it. -Profiles/cookies are temporary and deleted at close. Chromium receives a minimal -environment, excluding the Console wallet, API tokens and agent credentials. Uploads and downloads are -explicitly disabled. Copy uses the selected text and the viewer's clipboard; -paste/IME text is sent as input, never audited. Pixel streaming has no remote DOM -screen-reader semantics; this is an accessibility limitation requiring follow-up. - -The default image has no Chromium and displays an unavailable message without -breaking startup. The optional `browser` target uses Alpine Chromium and a -non-root runtime; production never adds `--no-sandbox`. Three global sessions, -one per central user, 10-minute idle and 60-minute lifetime caps, bounded CDP -queues/sockets/frame buffering, and Compose memory/CPU limits bound resource use. -An AMD64 static-page fixture measured 422 MiB summed RSS across six Chromium -processes and 0% of one CPU core over a three-second idle sample (100 Hz process -clock, Node 24.16.0 host, test-only sandbox bypass). RSS double-counts shared -pages; this is neither peak memory nor an ARM64 measurement. No i.MX8 hardware is -available, so ARM64 size/RAM/CPU and production sandbox checks remain release -gates. This cost is why Chromium is an optional image, not installed on all -gateways. The image build's offline about:blank smoke test uses a build-only sandbox bypass; -that is not evidence of production sandbox support on an i.MX8 host. - -## Deployment and verification constraints - -No production services are contacted. Contract, MQTT, ChirpStack and SSH tests use -doubles or local fixture services. No rollout is performed by this task. -The local host is AMD64; ARM64 runtime resource measurements require an ARM64 -test environment. Measurements must not be estimated and presented as observed. -Existing workflow publishing conventions are preserved; attestations will be -additive and run only when images are actually published. - -## Integrated transport and authentication - -The agent connects to `/agent` using an Authorization header. Browser sessions -are not accepted as agent credentials. The versioned operation RPC separates -`offer`, `commit`, `outcome` and `reconcile`; every envelope carries the original -ChirpStack ID and a transport request ID. The authenticated connection supplies -the gateway identity, never the message body. Duplicate commits return durable -outcomes. The loopback fallback uses the same RPC and a separate owner-only file -secret. Invalid messages are rejected before billing. Agent MQTT acknowledges -QoS 1 delivery only after the local journal has persisted the event. - Central session authentication mounts before static assets and application routes. Agent enrollment is the narrowly scoped token-authenticated exception. -Browser WebSockets require both the same origin and an unexpired human session; +Desktop WebSockets (such as Terminal) require both the same origin and an unexpired human session; active sessions are rechecked periodically. Revocation closes the agent link immediately. Credential rotation persists the replacement locally before acknowledging it on the existing link, without interrupting tunnels. A two-minute overlap covers interrupted handshakes; @@ -191,7 +119,10 @@ reconnection with the new credential also confirms rotation. The gateway selector shows cumulative uncertain/reconciled/superseded counts and current pending count. Switching gateway closes open network application windows to prevent a window from silently changing its target. Each app title identifies -the selected gateway. Managed logs omit credentials and raw signed envelopes. +the selected gateway. Choosing **Central server** clears the selection: Terminal then +uses the central host's own sshd (`CENTRAL_SSH_PORT`) and ChirpStack proxies +`CENTRAL_CHIRPSTACK_URL`. +Managed logs omit credentials and raw signed envelopes. ## SSH and ChirpStack tunnels @@ -200,7 +131,7 @@ Streams have 64 KiB credit windows, 16 KiB frames, an eight-session default cap, one MiB/s per-stream limit, and a two-minute idle timeout. Closing the link closes all streams. The SSH purpose resolves only the owner-configured loopback SSH port; ChirpStack resolves only the gateway's existing configured web endpoint. -Browser-purpose targets cannot access SSH, Docker or fallback/updater ports. +Any other tunnel purpose is refused. Central SSH2 uses the stream as its `sock`, so passwords and shell traffic are inside SSH encryption through the relay. Host keys use trust on first use and diff --git a/docs/deployment-guide.md b/docs/deployment-guide.md new file mode 100644 index 0000000..1f54523 --- /dev/null +++ b/docs/deployment-guide.md @@ -0,0 +1,374 @@ +# Deployment guide + +How to install, connect and update M3tering Console. Every setup uses the same +command, `./auto-compose.sh`. The `CONSOLE_ROLE` setting in `.env` decides what it +deploys. + +- [Pick a setup](#pick-a-setup) +- [Before you start](#before-you-start) +- [Standalone gateway](#standalone-gateway) +- [Central server](#central-server) +- [Managed gateway (connect to central)](#managed-gateway-connect-to-central) +- [Managing gateways on central](#managing-gateways-on-central) +- [Updating](#updating) +- [Going back to standalone](#going-back-to-standalone) +- [`.env` reference](#env-reference) +- [Troubleshooting](#troubleshooting) + +## Pick a setup + +| Setup | `CONSOLE_ROLE` | Runs | Use it when | +|---|---|---|---| +| Standalone gateway | *(unset)* or `standalone` | One Console, on the gateway | A single site, managed on its own LAN | +| Central server | `central` | Console behind HTTPS (Caddy) | You want one login to reach every site | +| Managed gateway | `gateway` | Console + agent, on the gateway | A site that connects to your central server | + +``` + browser ──HTTPS──▶ CENTRAL SERVER (login, billing decisions, publishing) + ▲ ▲ + outbound wss │ │ outbound wss + │ │ + MANAGED GATEWAY ─────────────┘ └──────────── MANAGED GATEWAY + Console (LAN UI, local fallback) Console + agent + agent (reads ChirpStack MQTT, replies to meters) +``` + +Gateways only make **outbound** connections to central. You never open a port on +a gateway. If central is unreachable, a managed gateway keeps billing locally and +catches up later. + +## Before you start + +On every machine: + +- **Docker with the Compose plugin.** If it's missing: + `curl -fsSL https://get.docker.com | sudo sh`, then + `sudo usermod -aG docker "$USER"` and log in again. +- **Git**, to fetch this repository. +- **At least 3 GB of free disk space.** The Console image is large. Check with `df -h /`. +- **Access to the images.** They're published to GitHub Container Registry by CI + on every push to `main`. If the package is private, log in once: + `docker login ghcr.io -u ` with a token that has `read:packages`. + +Get the code: + +```sh +git clone https://github.com/fluxion9/Console.git +cd Console +``` + +On an existing checkout, point it at this repository once: +`git remote set-url origin https://github.com/fluxion9/Console.git && git pull`. + +## Standalone gateway + +1. **Create the configuration.** On a fresh checkout, run: + ```sh + ./auto-compose.sh + ``` + This creates `.env` from the template, readable only by you, and lists the + settings you must fill in. Nothing is started yet. +2. **Fill in `.env`.** At minimum: + ```dotenv + API_TOKEN= + APPLICATION_ID= + CHIRPSTACK_HOST=localhost + ETHEREUM_PRIVATE_KEY= + ``` + Keep the template's contract and Streamr values unless you know you need + others. The script refuses to start while any `...` placeholder is left. +3. **Start it.** + ```sh + ./auto-compose.sh + ``` +4. **Open it** at `http://:3000` on the LAN. There's no login. + +## Central server + +You need a server with a public DNS name and free ports **80** and **443** (Caddy +uses them for HTTPS), plus port **3000**, which the Console uses on `localhost` +only. Check with `sudo ss -ltnp | grep -E ':(80|443|3000)\b'`. It should print nothing. + +1. Point your domain's DNS record at the server. +2. Create `.env` as in standalone step 1, then set: + ```dotenv + CONSOLE_ROLE=central + CENTRAL_DOMAIN=console.example.com + CENTRAL_ADMIN_USERNAME=admin + CENTRAL_ADMIN_PASSWORD= + ETHEREUM_PRIVATE_KEY= + ``` + Central doesn't use ChirpStack, so the template's `API_TOKEN` and + `APPLICATION_ID` lines can stay as they are. +3. Start it: + ```sh + ./auto-compose.sh + ``` +4. Open `https://console.example.com` and sign in. + +About the admin account: + +- It's created **only on the first start**. Changing `CENTRAL_ADMIN_PASSWORD` + in `.env` later does nothing. +- A password shorter than 7 characters stops the first start with a clear error. +- **To change the password**, sign in, click your initial at the top right and choose + **Change password**. Enter + your current password and the new one (at least 7 characters). Any other device + signed in to that account is signed out; you stay signed in. After five attempts + in 15 minutes, further attempts are blocked for a while. + +Central holds the wallet key that signs billing decisions. Treat the server as +sensitive, and test with a test wallet first. + +## Managed gateway (connect to central) + +The gateway needs a working ChirpStack setup (`API_TOKEN`, `APPLICATION_ID`) and +contract settings in `.env`, just like a standalone gateway. Converting an +existing standalone gateway is the usual case: keep its `.env` and add three lines. + +1. **On central**, open **Gateways**, type a name (for example the site name) and + click **Add gateway**. +2. Click **Copy** in the panel that appears. It copies three lines: + ```dotenv + CONSOLE_ROLE=gateway + CENTRAL_URL=wss://console.example.com + AGENT_ENROLLMENT_TOKEN=… + ``` +3. **On the gateway**, paste them into `.env`, then run: + ```sh + git pull + ./auto-compose.sh + ``` + The token works **once** and expires after **10 minutes**. If it expires, + click **New enrollment token** on the gateway's card. +4. Within a minute the card on central turns green and shows **Online**. +5. Delete the `AGENT_ENROLLMENT_TOKEN` line from the gateway's `.env`. The script + reminds you. The gateway has stored a permanent credential in `.data/agent/`. + +What the script does for a gateway: + +- **Checks first:** it validates `CENTRAL_URL`, the ChirpStack settings and the + token before touching Docker. +- **Creates secrets:** it creates the gateway's owner-only secret files in + `.data/agent/`. It uses `sudo`, so it may ask for your password. Existing + secrets are never replaced. +- **Switches over:** it stops the standalone Console, then starts Console and + agent together. The two never run at the same time. +- **Waits:** it checks that the agent stays up and has enrolled. + +If the first switch fails, the script restores standalone, but only if the agent +never started handling meter reports. If the agent had already started, the +script leaves things as they are and tells you, so two processes never answer the +same meter. Fix the error shown and run the script again. + +The gateway's own LAN desktop at `http://:3000` keeps working, without +a login. + +## Managing gateways on central + +Open **Gateways** from the top bar. Each gateway is a card. + +| Status | Meaning | +|---|---| +| **Online** | The agent is connected | +| **Offline** | Enrolled but not connected: check the gateway is running and can reach central | +| **Waiting to connect** | Created on central, but the gateway hasn't used its token yet | +| **Access revoked** | Its credential was cancelled; it can't connect | + +The activity tiles appear once a gateway has reported in: + +| Tile | Meaning | +|---|---| +| **MQTT** | The agent's connection to ChirpStack's broker | +| **Pending** | Reports waiting for a decision | +| **Uncertain** | Running total of replies whose delivery couldn't be confirmed. They are held, never resent automatically. | +| **Reconciled** | Uncertain replies later resolved | +| **Superseded** | Old replies replaced by a newer report from the same meter | + +| Action | What it does | +|---|---| +| **Rename** | Changes the display name. Press Enter to save, Esc to cancel. | +| **Delete** | Disconnects the gateway, destroys its credential and removes it from the list. Billing and audit history are kept. | +| **Revoke access** | Disconnects the gateway and cancels its credential, but keeps the card | +| **Rotate credential** | Issues a new credential to an online gateway without interrupting it | +| **New enrollment token** / **Re-enroll** | Issues a fresh one-time token for a gateway that isn't connected | +| **Remote updates** | Pushes a signed image to the gateway. The gateway owner enables it by adding `REMOTE_UPDATES_ENABLED=true` to `.env` and running `./auto-compose.sh`; see [advanced options](centralized/deployment.md#optional-signed-updater). | + +**Reconnecting a revoked or deleted gateway.** The gateway still holds its old, +now useless credential. Remove it before using a new token: + +```sh +sudo rm .data/agent/credential +# add the new AGENT_ENROLLMENT_TOKEN line to .env, then: +./auto-compose.sh +``` + +For a deleted gateway, first add it again on central as a new gateway. + +## Updating + +Same command on every machine: + +```sh +git pull +./auto-compose.sh +``` + +The script: + +- pulls the newest image for the tag the machine already runs; +- replaces only the Console services and waits for them to be healthy; +- restores the previous image if they aren't; +- never touches `.env`, the database or volumes. + +To run a specific build, pass its tag or digest: + +```sh +./auto-compose.sh --image ghcr.io/fluxion9/console:main +./auto-compose.sh --image ghcr.io/fluxion9/console@sha256: +``` + +**Which image is used.** The script follows the GitHub repository this checkout +was cloned from (its `origin` remote). CI publishes each repository's images +under its own name: a checkout of `fluxion9/Console` uses +`ghcr.io/fluxion9/console:main`, and a checkout of `M3tering/Console` uses +`ghcr.io/m3tering/console:main`. + +The image is chosen in this order: + +1. `--image` on the command line +2. The image already running, if it comes from the same repository and runs the + same role. This keeps a branch tag or digest you chose earlier. +3. `ghcr.io//:main` from the `origin` remote + +Images are never read from `.env`. If an old `CONSOLE_IMAGE` line is there, the +script says it's ignored; delete it. The optional updater +(`ghcr.io//-updater:main`) and the repository it trusts for signed +remote updates follow the same remote. + +To switch a machine to another repository's builds, change its remote and +update: +`git remote set-url origin https://github.com//Console.git && git pull && ./auto-compose.sh`. + +## Going back to standalone + +On the gateway: + +```sh +docker compose -f compose.gateway.yaml stop agent +``` + +1. Check the gateway's card on central shows **Pending 0** before going + further. If it doesn't, read [the reconciliation rules](centralized/design.md) + first. +2. Remove `CONSOLE_ROLE`, `CENTRAL_URL` and any token line from `.env`. +3. Run `./auto-compose.sh --image ghcr.io/fluxion9/console:main`. The `--image` + keeps the build you were running; without it, standalone uses its own default. +4. Revoke or delete the gateway on central. + +Keep `.data/agent/`. It holds the operations journal, which is needed if anything +has to be reconciled later. + +## Working on the central server itself + +The gateway menu at the top starts with **Central server**. Choose it (or never pick +a gateway) and Terminal and ChirpStack work on the central machine instead of a gateway: + +| App | With **Central server** selected | +|---|---| +| **Terminal** | SSH into the central server itself. Sign in with a Linux user and password on that server. | +| **ChirpStack** | Opens the dashboard set in `CENTRAL_CHIRPSTACK_URL`. | + +Choosing a gateway switches both back to that gateway. Open windows close when +you switch, so you never type into the wrong machine. + +Settings in central's `.env` (run `./auto-compose.sh` after changing them): + +```dotenv +CENTRAL_CHIRPSTACK_URL=https://chirpstack.example.com # address only, no path +CENTRAL_SSH_PORT=22 # only if sshd uses another port +``` + +**Terminal needs password login if your server doesn't already use it.** The Terminal signs in with a username and password, +and many cloud servers allow SSH keys only. To use it, the user needs a password +(`sudo passwd `) and sshd must accept passwords for it. For example, add this +to `/etc/ssh/sshd_config` and run `sudo systemctl reload ssh`: + +```text +Match User Address 127.0.0.1 + PasswordAuthentication yes +``` + +The `Address 127.0.0.1` line allows passwords only from the Console on the same +machine, so the internet still needs a key. + +Useful commands in the central Terminal (from the Console folder): + +```sh +docker compose -f compose.central.yaml logs -f console # central's log +docker compose -f compose.central.yaml logs -f tls-proxy # HTTPS / Caddy +docker compose -f compose.central.yaml ps +``` + +Each gateway's agent logs its enqueue results. To follow them, select that gateway, +open Terminal and run `docker compose -f compose.gateway.yaml logs -f agent` in its +Console folder. + +## `.env` reference + +Settings are needed (✓), optional (opt) or not used (–) per setup. + +| Setting | Standalone | Central | Gateway | Notes | +|---|---|---|---|---| +| `CONSOLE_ROLE` | – | `central` | `gateway` | Unset means standalone | +| `API_TOKEN` | ✓ | – | ✓ | ChirpStack API token | +| `APPLICATION_ID` | ✓ | – | ✓ | ChirpStack application UUID | +| `CHIRPSTACK_HOST` | ✓ | – | ✓ | Usually `localhost` | +| `MQTT_URL` | opt | – | opt | Defaults to `CHIRPSTACK_HOST:1883` | +| `ETHEREUM_PRIVATE_KEY` | ✓ | ✓ | ✓ | Wallet for this Console | +| `MAINNET_RPC`, `ROLLUP_CONTRACT_ADDRESS` | ✓ | ✓ | ✓ | Keep the template values unless told otherwise | +| `BACKEND_MODULES`, `UI_MODULES`, `STREAMR_*` | ✓ | ✓ | ✓ | Keep the template values | +| `PORT` | opt | opt | opt | Default `3000` | +| `CENTRAL_DOMAIN` | – | ✓ | – | DNS name for HTTPS | +| `CENTRAL_ADMIN_USERNAME` | – | opt | – | Default `admin` | +| `CENTRAL_ADMIN_PASSWORD` | – | ✓ first start | – | At least 7 characters | +| `CENTRAL_CHIRPSTACK_URL` | – | opt | – | Dashboard the ChirpStack app opens with no gateway selected | +| `CENTRAL_SSH_PORT` | – | opt | – | Central's own SSH port for Terminal; default `22` | +| `CENTRAL_URL` | – | – | ✓ | `wss://` + central domain, no path | +| `AGENT_ENROLLMENT_TOKEN` | – | – | first start | From central; remove after enrolling | +| `REMOTE_UPDATES_ENABLED` | – | – | opt | `true` makes the script run the signed updater | + +Advanced gateway settings (SSH port, queue size, remote updates) +are listed in [`.env.example`](../.env.example) and +[docs/centralized/deployment.md](centralized/deployment.md). + +## Troubleshooting + +Useful commands, using the compose file for the machine's role +(`compose.yaml`, `compose.central.yaml` or `compose.gateway.yaml`): + +```sh +docker compose -f compose.gateway.yaml ps +docker compose -f compose.gateway.yaml logs -f console +docker compose -f compose.gateway.yaml logs -f agent +``` + +| Symptom | Cause and fix | +|---|---| +| `Replace the placeholder values in .env: …` | Template values are still in `.env`. Fill in the named settings. | +| `Set APPLICATION_ID … UUID` | Copy the application's ID from ChirpStack's Applications page. | +| `Cannot reach Docker` | Run with `sudo`, or add yourself to the `docker` group and log in again. | +| `no space left on device` while pulling | The disk is full. Free space with `docker builder prune` and `docker image prune`. Check what's unused with `docker image ls` first, because locally built images can't be pulled back. Nothing running is affected by the failed pull. | +| `unauthorized` / `denied` while pulling | The image package is private, or CI hasn't published it yet. Make the package public or `docker login ghcr.io`, and check the Actions run on `main` passed. | +| Central: Console keeps restarting on first start | Usually a short `CENTRAL_ADMIN_PASSWORD`. Check `logs console`. | +| Central: HTTPS doesn't work | DNS doesn't point at the server yet, or ports 80/443 are taken. | +| Central Terminal: `SSH connection failed` | With **Central server** selected, the server's sshd refused the password. Allow password login for that user from `127.0.0.1` (see [Working on the central server itself](#working-on-the-central-server-itself)). | +| Central ChirpStack: `No ChirpStack dashboard set` | Set `CENTRAL_CHIRPSTACK_URL` in `.env` and rerun `./auto-compose.sh`, or select a gateway. | +| Gateway: `Port 3011 is already used by …` | Another program uses the gateway Console's local fallback port. Add `GATEWAY_FALLBACK_PORT=3101` (any free port) to `.env` and rerun. Older setups used 3001, which clashes with ChirpStack's Basic Station bridge. | +| Gateway: agent online once, then **Offline** for good | Usually the gateway Console couldn't start, often because of a port clash. Check `logs console` and rerun `./auto-compose.sh`; it now says what's wrong. | +| Gateway: `This gateway is not enrolled yet` | Add the `AGENT_ENROLLMENT_TOKEN` line from central. | +| Gateway: `Agent enrollment failed` in agent logs | The token expired or was already used. Get a new one from the gateway's card. | +| Gateway card stays **Waiting to connect** | The gateway can't reach central on port 443, or `CENTRAL_URL` is wrong. Try `curl -I https://console.example.com` from the gateway. | +| Gateway card shows **Offline** after a revoke/delete | Expected. To reconnect, see [Reconnecting a revoked or deleted gateway](#managing-gateways-on-central). | +| `Secret file must be owner-only` in logs | Someone changed permissions in `.data/agent/`. Run `./auto-compose.sh` again; it repairs them. | +| Script says *standalone was NOT restarted* | The agent had started handling reports when something failed. Fix the error shown and rerun; don't start standalone by hand. | diff --git a/src/agent/index.ts b/src/agent/index.ts index 667469f..ad6ffe6 100644 --- a/src/agent/index.ts +++ b/src/agent/index.ts @@ -3,7 +3,7 @@ import fs from 'fs'; import path from 'path'; import { connect, MqttClient } from 'mqtt'; import WebSocket from 'ws'; -import { requireAgentConfig } from '../central/config'; +import { requireAgentConfig, gatewayFallbackPort } from '../central/config'; import { readOwnerSecret, writeOwnerSecret } from '../central/secrets'; import { OperationJournal, eventIdentity } from '../central/operations'; import { UplinkCoordinator } from '../central/coordinator'; @@ -42,7 +42,7 @@ export async function runAgent():Promise<()=>Promise> { let updatesEnabled=false;const updateStatuses=new Map(); const stateDirectory=path.dirname(config.credentialPath); const journal=new OperationJournal(path.join(stateDirectory,'operations.db'),config.queueLimit,event=>logger.info('Operation status',event)); - const local=new LocalDecider(Number(process.env.GATEWAY_FALLBACK_PORT||3001),readOwnerSecret(config.fallbackSecretPath),config.decisionTimeoutMs); + const local=new LocalDecider(gatewayFallbackPort(),readOwnerSecret(config.fallbackSecretPath),config.decisionTimeoutMs); let socket:WebSocket|undefined,stopped=false,reconnect:ReturnType|undefined; let connectedAt=0,attempt=0,mqttState:Health['mqtt']='connecting',lastError:Health['lastError']='none'; const central=new SocketDecider(()=>socket,config.decisionTimeoutMs); diff --git a/src/browser/cdp.ts b/src/browser/cdp.ts deleted file mode 100644 index 9ef222a..0000000 --- a/src/browser/cdp.ts +++ /dev/null @@ -1,26 +0,0 @@ -import WebSocket from 'ws'; -import { EventEmitter } from 'events'; - -export class CDP extends EventEmitter { - private next=0; - private pending=new Mapvoid;reject:(error:Error)=>void;timer:ReturnType}>(); - private constructor(private socket:WebSocket){ - super();socket.on('message',bytes=>{ - try{const value=JSON.parse(bytes.toString()) as {id?:number;method?:string;params?:unknown;result?:unknown;error?:unknown}; - if(value.id){const pending=this.pending.get(value.id);if(!pending)return;this.pending.delete(value.id);clearTimeout(pending.timer);if(value.error)pending.reject(new Error('Browser engine command failed.'));else pending.resolve(value.result);} - else if(value.method)this.emit(value.method,value.params); - }catch{socket.close();} - });socket.on('close',()=>{for(const p of this.pending.values()){clearTimeout(p.timer);p.reject(new Error('Browser engine disconnected.'));}this.pending.clear();this.emit('closed');});socket.on('error',()=>socket.close()); - } - static async connect(url:string):Promise{ - const socket=new WebSocket(url,{maxPayload:8*1024*1024,handshakeTimeout:5000}); - await new Promise((resolve,reject)=>{socket.once('open',resolve);socket.once('error',reject);});return new CDP(socket); - } - call>(method:string,params:Record={}):Promise{ - if(this.socket.readyState!==WebSocket.OPEN||this.pending.size>256)return Promise.reject(new Error('Browser engine unavailable.')); - const id=++this.next; - return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.pending.delete(id);reject(new Error('Browser command timeout.'));},10000); - this.pending.set(id,{resolve:value=>resolve(value as T),reject,timer});this.socket.send(JSON.stringify({id,method,params}));}); - } - close():void{this.socket.close();} -} diff --git a/src/browser/engine.ts b/src/browser/engine.ts deleted file mode 100644 index fe230c5..0000000 --- a/src/browser/engine.ts +++ /dev/null @@ -1,158 +0,0 @@ -import fs from 'fs'; -import os from 'os'; -import path from 'path'; -import { spawn, execFile, ChildProcess } from 'child_process'; -import { promisify } from 'util'; -import { createHash, X509Certificate } from 'crypto'; -import type { Duplex } from 'stream'; -import { BrowserProxy, browserURL, browserAddress } from './proxy'; -import { CDP } from './cdp'; -import type { ConsoleRole } from '../central/config'; -import { browserProcessLifetime, removeBrowserProfile } from './lifecycle'; - -const execute=promisify(execFile); -interface Paused {requestId:string;networkId?:string;frameId:string;resourceType:string;request:{url:string;method:string;headers:Record}} -interface NetworkRequest {requestId:string;frameId:string;type:string;hasUserGesture?:boolean;redirectResponse?:unknown} -export interface EngineOptions {role:ConsoleRole;gateway?:string;executable:string;tunnel?:(host:string,port:number)=>Promise;emit:(message:Record)=>void;testUnsandboxed?:boolean} -export class BrowserEngine { - private browser?:CDP; - private directory='';private process?:ChildProcess;private proxy?:BrowserProxy;private cdp?:CDP; - private frames=new Map();private requests=new Map(); - private main='';private typed?:string;private closed=false;private ready=false; - private width=1024;private height=700;private current='about:blank';private activity=Date.now();private born=Date.now(); - private timer?:ReturnType;private queued=false; - private starting?:Promise;private stopProcess?:()=>Promise; - constructor(private options:EngineOptions){} - start():Promise{ - this.starting=this.initialize(); - return this.starting; - } - private async initialize():Promise{ - if(!path.isAbsolute(this.options.executable)||!fs.existsSync(this.options.executable))throw new Error('Browser engine not available. Install the optional browser image.'); - if(this.options.testUnsandboxed&&process.env.NODE_ENV!=='test')throw new Error('Unsandboxed browser is allowed only in test fixtures.'); - this.directory=fs.mkdtempSync(path.join(os.tmpdir(),'console-browser-'));fs.chmodSync(this.directory,0o700); - try{ - const key=path.join(this.directory,'proxy.key'),cert=path.join(this.directory,'proxy.crt'); - await execute('openssl',['req','-x509','-newkey','rsa:2048','-nodes','-keyout',key,'-out',cert,'-days','1','-subj','/CN=Console browser session'],{timeout:10000,maxBuffer:65536}); - if(this.closed)throw new Error('Browser session closed.'); - const certificate=fs.readFileSync(cert,'utf8');const spki=createHash('sha256').update(new X509Certificate(certificate).publicKey.export({type:'spki',format:'der'})).digest('base64'); - this.proxy=new BrowserProxy({role:this.options.role,gateway:this.options.gateway,key:fs.readFileSync(key,'utf8'),cert:certificate,tunnel:this.options.tunnel}); - const proxyPort=await this.proxy.listen(); - if(this.closed)throw new Error('Browser session closed.'); - const args=['--headless=new','--remote-debugging-address=127.0.0.1','--remote-debugging-port=0',`--user-data-dir=${this.directory}/profile`, - `--proxy-server=http://127.0.0.1:${proxyPort}`,'--proxy-bypass-list=<-loopback>',`--ignore-certificate-errors-spki-list=${spki}`, - '--disable-background-networking','--disable-component-update','--disable-sync','--disable-extensions','--disable-default-apps','--no-first-run', - '--force-webrtc-ip-handling-policy=disable_non_proxied_udp','--disable-quic','--disable-features=MediaRouter','--js-flags=--max-old-space-size=128','--window-size=1024,700','about:blank']; - if(this.options.testUnsandboxed)args.push('--no-sandbox'); - this.process=spawn(this.options.executable,args,{stdio:['ignore','ignore','pipe'],env:{PATH:process.env.PATH,HOME:this.directory,TMPDIR:this.directory,XDG_CACHE_HOME:path.join(this.directory,'cache'),LANG:'C.UTF-8'}}); - this.stopProcess=browserProcessLifetime(this.process); - let stderr='';this.process.stderr?.on('data',chunk=>{stderr=(stderr+chunk.toString()).slice(-8192);}); - const endpoint=await new Promise((resolve,reject)=>{ - const timeout=setTimeout(()=>{cleanup();reject(new Error('Browser engine could not start with its sandbox.'));},12000); - const poll=setInterval(()=>{const match=stderr.match(/DevTools listening on (ws:\/\/127\.0\.0\.1:\d+\/devtools\/browser\/[\w-]+)/);if(match){cleanup();resolve(match[1]);}},25); - const cleanup=()=>{clearTimeout(timeout);clearInterval(poll);}; - this.process!.once('error',()=>{cleanup();reject(new Error('Browser executable unavailable.'));}); - this.process!.once('exit',()=>{cleanup();reject(new Error('Browser engine exited. Check sandbox support.'));}); - }); - if(this.closed)throw new Error('Browser session closed.'); - const browser=this.browser=await CDP.connect(endpoint); - if(this.closed)throw new Error('Browser session closed.'); - await browser.call('Browser.setDownloadBehavior',{behavior:'deny'}); - const target=await browser.call<{targetInfos:Array<{type:string;targetId:string}>}>('Target.getTargets'); - const id=target.targetInfos.find(t=>t.type==='page')?.targetId;if(!id)throw new Error('Browser page unavailable.'); - this.cdp=await CDP.connect(endpoint.replace(/\/devtools\/browser\/.+$/,`/devtools/page/${id}`)); - if(this.closed)throw new Error('Browser session closed.'); - browser.on('Target.targetCreated',(event:{targetInfo:{targetId:string;type:string}})=>{if(event.targetInfo.type==='page'&&event.targetInfo.targetId!==id)void browser.call('Target.closeTarget',{targetId:event.targetInfo.targetId}).catch(()=>{});}); - await browser.call('Target.setDiscoverTargets',{discover:true}); - const cdp=this.cdp; - cdp.on('Fetch.requestPaused',(event:Paused)=>void this.route(event)); - cdp.on('Network.requestWillBeSent',(event:NetworkRequest)=>{this.requests.set(event.requestId,event);if(this.requests.size>512)this.requests.delete(this.requests.keys().next().value!);}); - cdp.on('Page.frameNavigated',(event:{frame:{id:string;parentId?:string;url:string}})=>{ - if(!event.frame.parentId){this.main=event.frame.id;this.current=event.frame.url;this.options.emit({type:'navigation',url:this.current});void this.status();} - }); - cdp.on('Page.frameDetached',(event:{frameId:string})=>this.frames.delete(event.frameId)); - cdp.on('Page.loadEventFired',()=>void this.status()); - cdp.on('Page.frameStartedLoading',()=>this.options.emit({type:'loading',value:true})); - cdp.on('Page.frameStoppedLoading',()=>this.options.emit({type:'loading',value:false})); - cdp.on('Page.windowOpen',(event:{url:string;userGesture:boolean})=>{if(event.userGesture)void this.navigate(event.url);}); - cdp.on('Page.screencastFrame',(frame:{data:string;sessionId:number})=>{ - this.options.emit({type:'frame',data:frame.data,width:this.width,height:this.height});void cdp.call('Page.screencastFrameAck',{sessionId:frame.sessionId}).catch(()=>{}); - }); - cdp.on('closed',()=>this.close()); - await cdp.call('Page.enable');await cdp.call('Network.enable'); - await cdp.call('Network.setBypassServiceWorker',{bypass:true}); - await cdp.call('Fetch.enable',{patterns:[{urlPattern:'*',requestStage:'Request'}]}); - await cdp.call('Page.setInterceptFileChooserDialog',{enabled:true}); - // Popup links stay in this single isolated page; no extra browser contexts. - await cdp.call('Page.addScriptToEvaluateOnNewDocument',{source:`addEventListener('click',e=>{const a=e.target.closest?.('a[target]');if(a)a.target='_self'},true);window.open=(u)=>{if(u)location.href=String(u);return window};`}); - const tree=await cdp.call<{frameTree:{frame:{id:string}}}>('Page.getFrameTree');this.main=tree.frameTree.frame.id; - await cdp.call('Page.startScreencast',{format:'jpeg',quality:75,maxWidth:1600,maxHeight:1200,everyNthFrame:1}); - if(this.closed)throw new Error('Browser session closed.'); - this.ready=true;this.options.emit({type:'ready',url:'about:blank'}); - this.timer=setInterval(()=>{if(Date.now()-this.activity>10*60000||Date.now()-this.born>60*60000)this.close();},5000);this.timer.unref(); - }catch(error){this.close();throw error;} - } - private async route(event:Paused):Promise{ - const cdp=this.cdp;if(!cdp||!this.proxy)return; - try{ - const url=browserURL(event.request.url);const network=event.networkId?this.requests.get(event.networkId):undefined; - const top=event.resourceType==='Document'&&event.frameId===this.main; - const explicit=top&&this.typed===url.href; - const clicked=top&&network?.hasUserGesture===true&&!network.redirectResponse; - const originClass=this.frames.get(event.frameId)||this.frames.get(this.main)||'none'; - if(explicit)this.typed=undefined; - const permit=await this.proxy.permit(url.href,event.request.method,{pageClass:originClass,userNavigation:explicit||clicked,topLevel:top}); - if(event.resourceType==='Document'){this.frames.set(event.frameId,permit.classification);this.proxy.registerOrigin(url.href,permit.classification);} - const headers=Object.entries(event.request.headers).filter(([name])=>name.toLowerCase()!=='x-console-request').map(([name,value])=>({name,value})); - headers.push({name:'X-Console-Request',value:permit.token});await cdp.call('Fetch.continueRequest',{requestId:event.requestId,headers}); - }catch{await cdp.call('Fetch.failRequest',{requestId:event.requestId,errorReason:'BlockedByClient'}).catch(()=>{});this.options.emit({type:'notice',message:'A request was blocked by browser network policy.'});} - } - async navigate(input:string):Promise{ - if(!this.ready||!this.cdp)throw new Error('Browser engine not ready.'); - const url=browserAddress(input);this.typed=url.href;this.activity=Date.now();await this.cdp.call('Page.navigate',{url:url.href}); - } - async action(message:Record):Promise{ - if(!this.ready||!this.cdp)throw new Error('Browser engine not ready.');this.activity=Date.now();const cdp=this.cdp; - if(message.type==='navigate'&&typeof message.url==='string')return this.navigate(message.url); - if(message.type==='reload'){if(this.current!=='about:blank')this.typed=browserURL(this.current).href;await cdp.call('Page.reload');return;} - if(message.type==='stop'){await cdp.call('Page.stopLoading');return;} - if(message.type==='history'&&(message.direction===-1||message.direction===1)){ - const h=await cdp.call<{currentIndex:number;entries:Array<{id:number;url:string}>}>('Page.getNavigationHistory');const entry=h.entries[h.currentIndex+message.direction];if(entry){if(entry.url!=='about:blank')this.typed=browserURL(entry.url).href;await cdp.call('Page.navigateToHistoryEntry',{entryId:entry.id});}return; - } - if(message.type==='resize'&&Number.isInteger(message.width)&&Number.isInteger(message.height)){ - this.width=Math.min(1600,Math.max(320,Number(message.width)));this.height=Math.min(1200,Math.max(200,Number(message.height))); - await cdp.call('Emulation.setDeviceMetricsOverride',{width:this.width,height:this.height,deviceScaleFactor:1,mobile:false});return; - } - if(message.type==='text'&&typeof message.text==='string'&&message.text.length<=8192){await cdp.call('Input.insertText',{text:message.text});return;} - if(message.type==='copy'){ - const result=await cdp.call<{result:{value?:string}}>('Runtime.evaluate',{expression:"(()=>{const e=document.activeElement;return e&&typeof e.selectionStart==='number'?String(e.value).slice(e.selectionStart,e.selectionEnd):String(getSelection())})()",returnByValue:true});this.options.emit({type:'clipboard',text:(result.result.value||'').slice(0,65536)});return; - } - if(message.type==='key'&&typeof message.key==='string'&&message.key.length<40&&['keyDown','keyUp'].includes(String(message.event))){ - await cdp.call('Input.dispatchKeyEvent',{type:message.event,key:message.key,code:typeof message.code==='string'?message.code.slice(0,40):'',modifiers:Number(message.modifiers)||0,windowsVirtualKeyCode:Number(message.keyCode)||0});return; - } - if(message.type==='pointer'&&['mousePressed','mouseReleased','mouseMoved','mouseWheel'].includes(String(message.event))&&Number.isFinite(message.x)&&Number.isFinite(message.y)){ - await cdp.call('Input.dispatchMouseEvent',{type:message.event,x:Math.max(0,Math.min(this.width,Number(message.x))),y:Math.max(0,Math.min(this.height,Number(message.y))), - button:['left','right','middle'].includes(String(message.button))?message.button:'none',clickCount:message.event==='mousePressed'||message.event==='mouseReleased'?Math.min(3,Number(message.clicks)||1):0, - deltaX:Math.max(-2000,Math.min(2000,Number(message.dx)||0)),deltaY:Math.max(-2000,Math.min(2000,Number(message.dy)||0))});return; - } - if(message.type==='zoom'&&typeof message.factor==='number'&&message.factor>=.5&&message.factor<=2){await cdp.call('Emulation.setPageScaleFactor',{pageScaleFactor:message.factor});return;} - throw new Error('Invalid browser interaction.'); - } - private async status():Promise{ - if(this.queued||!this.cdp)return;this.queued=true; - try{const title=await this.cdp.call<{result:{value?:string}}>('Runtime.evaluate',{expression:'document.title',returnByValue:true});this.options.emit({type:'navigation',url:this.current,title:(title.result.value||'Browser').slice(0,200)});}catch{}finally{this.queued=false;} - } - close():void{ - if(this.closed)return; - this.closed=true;this.ready=false;clearInterval(this.timer); - this.cdp?.close();this.browser?.close(); - // Startup may still be writing certificates or opening a CDP connection. - // Wait for it and Chromium's stdio/process closure before removing the profile. - void Promise.resolve(this.starting).catch(()=>{}).then(async()=>{ - this.cdp?.close();this.browser?.close();this.proxy?.close(); - await this.stopProcess?.(); - await removeBrowserProfile(this.directory); - }).catch(()=>console.warn('Browser session cleanup failed; temporary profile could not be removed.')); - this.options.emit({type:'closed'}); - } -} diff --git a/src/browser/lifecycle.ts b/src/browser/lifecycle.ts deleted file mode 100644 index 90c73ad..0000000 --- a/src/browser/lifecycle.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { ChildProcess } from 'child_process'; -import { promises as fs } from 'fs'; - -/** Register immediately after spawn, including failed or unexpectedly exited children. */ -export function browserProcessLifetime(child:ChildProcess):()=>Promise{ - let closed=false,stopping:Promise|undefined; - const completed=new Promise(resolve=>child.once('close',()=>{closed=true;resolve();})); - return ()=>{ - if(stopping)return stopping; - stopping=(async()=>{ - if(closed)return; - if(child.exitCode!==null||child.signalCode!==null){await completed;return;} - child.kill('SIGTERM'); - const timer=setTimeout(()=>{if(!closed)child.kill('SIGKILL');},2000); - timer.unref(); - try{await completed;}finally{clearTimeout(timer);} - })(); - return stopping; - }; -} - -export async function removeBrowserProfile(directory:string):Promise{ - // Chromium helpers can briefly finish profile writes after the main process. - // Retry asynchronously; never throw from an EventEmitter callback or block HTTP. - if(directory)await fs.rm(directory,{recursive:true,force:true,maxRetries:6,retryDelay:100}); -} diff --git a/src/browser/proxy.ts b/src/browser/proxy.ts deleted file mode 100644 index 77d798e..0000000 --- a/src/browser/proxy.ts +++ /dev/null @@ -1,154 +0,0 @@ -import http, { IncomingMessage, ServerResponse } from 'http'; -import https from 'https'; -import net from 'net'; -import tls from 'tls'; -import { Duplex } from 'stream'; -import { randomBytes } from 'crypto'; -import { resolveTarget, destinationRoute, BrowsingContext, ResolvedTarget, normalizeHost } from '../central/destinations'; -import type { ConsoleRole } from '../central/config'; - -type ProxyTarget=ResolvedTarget|{hostname:string;address:string;family:null;classification:'local'}; -interface Permit { url:string; method:string; target:ProxyTarget; route:'internet'|'local'|'agent'; expires:number } -export interface ProxyOptions { - role:ConsoleRole; gateway?:string; key:string; cert:string; - tunnel?:(address:string,port:number)=>Promise; - resolve?:(host:string)=>Promise; -} -const hop=['connection','proxy-connection','proxy-authorization','proxy-authenticate','keep-alive','transfer-encoding','upgrade','te','trailer','x-console-request']; -export function browserURL(input:string):URL { - const url=new URL(input); - if(!['http:','https:'].includes(url.protocol)||url.username||url.password||url.href.length>8192)throw new Error('Use an HTTP or HTTPS address without credentials.'); - url.hash='';return url; -} -export function browserAddress(input:string):URL { - let text=input.trim();if(!text)text='https://www.google.com/'; - if(!/^https?:\/\//i.test(text))text=/^(localhost|[\w.-]+\.[\w.-]+|\[[a-f\d:]+\])(:\d+)?([/?#]|$)/i.test(text)?`http://${text}`:`https://www.google.com/search?q=${encodeURIComponent(text)}`; - return browserURL(text); -} -/** The proxy, not page JavaScript, owns one-use request permits and pinned DNS - * results. TLS CONNECT terminates here; it is never a blind route into a LAN. */ -export class BrowserProxy { - private permits=new Map(); - private sockets=new Set(); - private contexts=new WeakMap(); - private origins=new Map>(); - private server=http.createServer((req,res)=>void this.request(req,res)); - private inner=http.createServer((req,res)=>void this.request(req,res)); - private secure:tls.SecureContext; - private closed=false; - constructor(private options:ProxyOptions){ - this.secure=tls.createSecureContext({key:options.key,cert:options.cert,minVersion:'TLSv1.2'}); - for(const server of [this.server,this.inner]){ - server.maxHeadersCount=100;server.headersTimeout=15000;server.requestTimeout=60000; - server.on('upgrade',(req,socket,head)=>void this.upgrade(req,socket as net.Socket,head)); - server.on('clientError',(_error,socket)=>socket.destroy()); - } - this.server.on('connection',socket=>{if(this.sockets.size>=32){socket.destroy();return;}this.sockets.add(socket);socket.once('close',()=>this.sockets.delete(socket));socket.setTimeout(120000,()=>socket.destroy());}); - this.server.on('connect',(req,socket,head)=>{ - try{ - const target=browserURL(`https://${req.url}/`); - if(target.pathname!=='/'||head.length)throw new Error(); - socket.write('HTTP/1.1 200 Connection Established\r\n\r\n'); - const secured=new tls.TLSSocket(socket,{isServer:true,secureContext:this.secure,ALPNProtocols:['http/1.1']}); - this.contexts.set(secured,target.origin); - secured.on('error',()=>secured.destroy());this.inner.emit('connection',secured); - }catch{socket.destroy();} - }); - } - async listen():Promise{await new Promise(resolve=>this.server.listen(0,'127.0.0.1',resolve));return (this.server.address() as net.AddressInfo).port;} - async permit(raw:string,method:string,context:BrowsingContext):Promise<{token:string;classification:'public'|'local';url:string}>{ - if(this.closed)throw new Error('Browser session closed.'); - const url=browserURL(raw),hostname=normalizeHost(url.hostname); - // Local service names belong to the selected gateway's DNS namespace. Its - // tunnel endpoint resolves, classifies and pins the address before connect; - // it refuses public results and still applies the owner's LAN/port policy. - const gatewayName=this.options.role==='central'&&(/\.(local|lan)$/.test(hostname)||hostname==='localhost'||hostname.endsWith('.localhost')); - const target:ProxyTarget=gatewayName?{hostname,address:hostname==='localhost'||hostname.endsWith('.localhost')?'127.0.0.1':hostname,family:null,classification:'local'}:await (this.options.resolve||resolveTarget)(hostname); - const route=destinationRoute(this.options.role,target,context,this.options.gateway); - for(const [token,p] of this.permits)if(p.expires=256)throw new Error('Too many browser requests.'); - const token=randomBytes(24).toString('base64url'); - this.permits.set(token,{url:url.href,method,target,route,expires:Date.now()+20000}); - return {token,classification:target.classification as 'public'|'local',url:url.href}; - } - registerOrigin(raw:string,classification:'public'|'local'):void{ - const origin=browserURL(raw).origin; - const classes=this.origins.get(origin)||new Set();classes.add(classification);this.origins.set(origin,classes); - if(this.origins.size>256)this.origins.delete(this.origins.keys().next().value!); - } - private url(req:IncomingMessage):URL { - const origin=this.contexts.get(req.socket); - const url=browserURL(origin?new URL(req.url||'/',origin).href:(req.url||'').replace(/^ws:/i,'http:').replace(/^wss:/i,'https:')); - if(origin&&url.origin!==origin)throw new Error('CONNECT authority mismatch.'); - return url; - } - private take(req:IncomingMessage,url:URL):Permit{ - const token=req.headers['x-console-request'];if(typeof token!=='string')throw new Error('Missing request provenance.'); - const permit=this.permits.get(token);this.permits.delete(token); - if(!permit||permit.expires{ - const port=Number(url.port||(url.protocol==='https:'?443:80)); - if(permit.route==='agent'){ - if(!this.options.tunnel)throw new Error('Selected gateway is unavailable.'); - return this.options.tunnel(permit.target.address,port); - } - // Central private addresses can never fall through to net.connect. - if(this.options.role==='central'&&permit.target.classification!=='public')throw new Error('Central private network is inaccessible.'); - return new Promise((resolve,reject)=>{ - const socket=net.connect({host:permit.target.address,port}); - socket.setTimeout(10000,()=>socket.destroy(new Error('Connection timed out.'))); - socket.once('error',reject);socket.once('connect',()=>{socket.setTimeout(0);resolve(socket);}); - }); - } - private async upstream(req:IncomingMessage,url:URL,permit:Permit,upgrade=false):Promise{ - const raw=await this.connect(permit,url); - let socket:Duplex=raw; - if(url.protocol==='https:')socket=tls.connect({socket:raw as net.Socket,servername:net.isIP(permit.target.hostname)?undefined:permit.target.hostname,checkServerIdentity:(_host,cert)=>tls.checkServerIdentity(permit.target.hostname,cert),rejectUnauthorized:true}); - const agent=new http.Agent({keepAlive:false});agent.createConnection=()=>socket; - const headers=this.headers(req,url);if(upgrade){headers.connection='Upgrade';headers.upgrade='websocket';} - // TLS is already on the provided stream, so the HTTP client must not wrap it again. - const upstream=http.request({method:req.method,path:url.pathname+url.search,host:'browser-stream.invalid',agent,headers}); - upstream.setTimeout(60000,()=>upstream.destroy(new Error('Browser upstream timed out.'))); - upstream.once('close',()=>agent.destroy());req.once('aborted',()=>upstream.destroy()); - return upstream; - } - private async request(req:IncomingMessage,res:ServerResponse):Promise{ - try{ - const url=this.url(req),permit=this.take(req,url),upstream=await this.upstream(req,url,permit); - upstream.on('response',response=>{const headers={...response.headers};for(const name of hop)delete headers[name];res.writeHead(response.statusCode||502,headers);response.pipe(res);response.on('error',()=>res.destroy());}); - upstream.on('error',()=>{if(!res.headersSent)res.writeHead(502);res.end('Browser destination unavailable.');}); - res.once('close',()=>upstream.destroy());req.pipe(upstream); - }catch{res.writeHead(403,{'Content-Type':'text/plain'});res.end('Browser network policy refused this request.');req.resume();} - } - private async upgrade(req:IncomingMessage,socket:net.Socket,head:Buffer):Promise{ - try{ - const url=this.url(req);let permit:Permit; - if(req.headers['x-console-request'])permit=this.take(req,url); - else{ - // WebSocket handshakes bypass CDP Fetch. Chromium owns the Origin header; - // a script cannot choose it. Only previously classified document origins - // may use this route; a public origin never authorizes private traffic. - const origin=typeof req.headers.origin==='string'?req.headers.origin:''; - const classes=this.origins.get(origin);if(!classes||classes.size!==1)throw new Error(); - const issued=await this.permit(url.href,req.method||'GET',{pageClass:[...classes][0],userNavigation:false,topLevel:false}); - req.headers['x-console-request']=issued.token;permit=this.take(req,url); - } - const upstream=await this.upstream(req,url,permit,true); - upstream.on('upgrade',(response,remote,extra)=>{ - const headers={...response.headers};delete headers['x-console-request']; - socket.write(`HTTP/1.1 ${response.statusCode} Switching Protocols\r\n`+Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')+'\r\n\r\n'); - if(extra.length)socket.write(extra);if(head.length)remote.write(head); - remote.pipe(socket).pipe(remote);socket.once('close',()=>remote.destroy());remote.once('error',()=>socket.destroy()); - }); - upstream.on('response',()=>socket.destroy());upstream.on('error',()=>socket.destroy());upstream.end(); - }catch{socket.destroy();} - } - close():void{this.closed=true;this.permits.clear();for(const socket of this.sockets)socket.destroy();this.server.close();this.inner.close();} -} diff --git a/src/browser/service.ts b/src/browser/service.ts deleted file mode 100644 index e07f3da..0000000 --- a/src/browser/service.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type http from 'http'; -import WebSocket from 'ws'; -import type { Duplex } from 'stream'; -import { registerSocket } from '../services/socket-router'; -import { RateLimit } from '../central/auth'; -import type { ConsoleRole } from '../central/config'; -import { BrowserEngine } from './engine'; - -interface BrowserServiceOptions { - role:ConsoleRole; executable?:string; testUnsandboxed?:boolean; - gateway?:(request:http.IncomingMessage)=>string|null; - owner?:(request:http.IncomingMessage)=>string; - tunnel?:(gateway:string,host:string,port:number)=>Promise; - audit?:(request:http.IncomingMessage,event:'browser-start'|'browser-end',gateway?:string)=>void; -} -export function attachBrowser(server:http.Server,options:BrowserServiceOptions):void{ - const wss=new WebSocket.Server({noServer:true,maxPayload:65536,perMessageDeflate:false}); - const engines=new Set(),owners=new Set(); - const starts=new RateLimit(12,60000); - registerSocket(server,'/browser/live',wss); - wss.on('connection',(ws,request)=>{ - const send=(message:Record)=>{if(ws.readyState===WebSocket.OPEN&&ws.bufferedAmount<2*1024*1024)ws.send(JSON.stringify(message));}; - const gateway=options.gateway?.(request)||undefined,owner=options.owner?.(request); - if(!starts.allow(owner||request.socket.remoteAddress||'local')||engines.size>=3||(owner&&owners.has(owner))){send({type:'error',message:'Browser session limit reached. Close another Browser window and retry.'});ws.close();return;} - if(options.role==='central'&&!gateway){send({type:'error',message:'Select a gateway before opening Browser.'});ws.close();return;} - const engine=new BrowserEngine({role:options.role,gateway,executable:options.executable||process.env.BROWSER_EXECUTABLE||'/usr/bin/chromium', - tunnel:options.tunnel&&gateway?(host,port)=>options.tunnel!(gateway,host,port):undefined,testUnsandboxed:options.testUnsandboxed,emit:message=>{send(message);if(message.type==='closed')ws.close();}}); - engines.add(engine);if(owner)owners.add(owner);let audited=false; - const limiter=new RateLimit(240,1000,1);let active=0; - ws.on('message',data=>{ - if(!limiter.allow('input')||active>32){ws.close(1008,'Browser interaction limit');return;} - try{const value:unknown=JSON.parse(data.toString());if(!value||typeof value!=='object'||Array.isArray(value))throw new Error(); - active++;void engine.action(value as Record).catch(()=>send({type:'notice',message:'Browser action unavailable.'})).finally(()=>active--); - }catch{ws.close(1008,'Invalid browser interaction');} - }); - const cleanup=()=>{engine.close();engines.delete(engine);if(owner)owners.delete(owner);if(audited){audited=false;options.audit?.(request,'browser-end',gateway);}}; - ws.once('close',cleanup);ws.on('error',cleanup); - void engine.start().then(()=>{if(ws.readyState!==WebSocket.OPEN){cleanup();return;}audited=true;options.audit?.(request,'browser-start',gateway);}) - .catch(()=>{send({type:'error',message:'Browser engine not available. Install the optional browser image with Chromium and working sandbox support.'});cleanup();ws.close();}); - }); - server.once('close',()=>{for(const engine of engines)engine.close();for(const ws of wss.clients)ws.terminate();wss.close();}); -} diff --git a/src/central/auth.ts b/src/central/auth.ts index 5397e09..dd24a4d 100644 --- a/src/central/auth.ts +++ b/src/central/auth.ts @@ -5,9 +5,10 @@ import { TLSSocket } from 'tls'; import type { IdentityStore, SessionIdentity } from './identity-store'; import { hashPassword, verifyPassword } from './secrets'; import { isSameOrigin } from '../services/auth'; +import { loginPage, loginPolicy, LoginView } from './login-page'; const cookieName = '__Host-console_session'; -const loginPage = `Sign in · M3tering Console

M3tering Console

Sign in to the central workspace.

`; +const validUsername = /^[A-Za-z0-9_.@-]{1,100}$/; /** Bounded fixed-window limiter. Uses the socket peer, never untrusted XFF. */ export class RateLimit { @@ -28,6 +29,8 @@ export interface CentralAuthOptions { development: boolean; trustedProxies: stri export class CentralAuth { private limiter = new RateLimit(10, 60000); private globalLimiter = new RateLimit(100, 60000, 1); + // Per account: a stolen session must not become a way to guess the current password. + private passwordLimiter = new RateLimit(5, 15 * 60000); private dummyHash: Promise = hashPassword('non-user authentication timing placeholder'); constructor(private store: IdentityStore, private options: CentralAuthOptions) {} private name(): string { return this.options.development ? 'console_dev_session' : cookieName; } @@ -55,24 +58,34 @@ export class CentralAuth { if (!isSameOrigin(req)) { res.status(403).send('Cross-site requests are not permitted.'); return; } next(); }); - app.get('/login', (_req, res) => { - res.setHeader('Content-Security-Policy', "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"); - res.type('html').send(loginPage); + app.get('/login', (req, res) => { + CentralAuth.page(res, 200, 'signed-out' in req.query ? { notice: 'You have been signed out.' } : {}); }); app.post('/login', (req, res, next) => { - if (!this.globalLimiter.allow('login') || !this.limiter.allow(req.socket.remoteAddress || 'unknown')) { res.status(429).send('Too many attempts. Try again later.'); return; } + if (!this.globalLimiter.allow('login') || !this.limiter.allow(req.socket.remoteAddress || 'unknown')) { + CentralAuth.page(res, 429, { error: 'Too many sign-in attempts. Wait a minute and try again.' }); return; + } next(); }, express.urlencoded({ extended: false, limit: '3kb', parameterLimit: 2 }), (req, res, next) => { void this.login(req, res).catch(next); }); machineRoutes?.(app); app.use(this.requireLogin); + app.get('/api/account', (_req, res) => { res.json({ username: res.locals.centralUser.username }); }); + app.post('/api/account/password', (req, res, next) => { + if (!this.passwordLimiter.allow(res.locals.centralUser.id)) { res.status(429).json({ error: 'Too many attempts. Try again in 15 minutes.' }); return; } + next(); + }, express.json({ limit: '3kb' }), (req, res, next) => { void this.changePassword(req, res).catch(next); }); app.post('/logout', (req, res) => { const session = this.session(req); this.store.endSession(this.token(req)); this.store.audit(session?.id || 'unknown', 'logout'); res.setHeader('Set-Cookie', this.cookie('', true)); - res.redirect(303, '/login'); + res.redirect(303, '/login?signed-out'); }); } + private static page(res: Response, status: number, view: LoginView): void { + res.setHeader('Content-Security-Policy', loginPolicy); + res.status(status).type('html').send(loginPage(view)); + } requireLogin = (req: Request, res: Response, next: NextFunction): void => { const session = this.session(req); if (!session) { @@ -83,14 +96,32 @@ export class CentralAuth { res.locals.centralUser = session; next(); }; + private async changePassword(req: Request, res: Response): Promise { + const session = res.locals.centralUser as SessionIdentity; + const current: unknown = req.body?.current, next: unknown = req.body?.next; + if (typeof current !== 'string' || typeof next !== 'string' || !current || !next) { + res.status(400).json({ error: 'Enter your current password and a new password.' }); return; + } + const user = this.store.user(session.username); + if (!user || !await verifyPassword(current, user.passwordHash)) { + this.store.audit(session.id, 'password-change-failure'); + res.status(400).json({ error: 'Your current password is incorrect.' }); return; + } + if (next === current) { res.status(400).json({ error: 'Choose a new password that differs from the current one.' }); return; } + let hash: string; + try { hash = await hashPassword(next); } catch { res.status(400).json({ error: 'The new password needs at least 7 characters.' }); return; } + this.store.changePassword(user.id, hash, this.token(req)); + res.json({ changed: true }); + } private async login(req: Request, res: Response): Promise { const username = typeof req.body?.username === 'string' ? req.body.username : ''; - const user = /^[A-Za-z0-9_.@-]{1,100}$/.test(username) ? this.store.user(username) : null; + const user = validUsername.test(username) ? this.store.user(username) : null; const valid = await verifyPassword(req.body?.password, user?.passwordHash || await this.dummyHash); if (!user || !valid) { // Do not audit the attacker-supplied username/password or the request body. this.store.audit('anonymous', 'login-failure'); - res.status(401).send('Invalid username or password.'); return; + // Only a well-formed username is shown again (escaped); the password never is. + CentralAuth.page(res, 401, { error: 'That username and password don’t match. Try again.', username: validUsername.test(username) ? username : '' }); return; } this.store.endSession(this.token(req)); const session = this.store.createSession(user.id); diff --git a/src/central/config.ts b/src/central/config.ts index 97b0491..226a353 100644 --- a/src/central/config.ts +++ b/src/central/config.ts @@ -2,6 +2,12 @@ import path from 'path'; import { isIP } from 'net'; export type ConsoleRole = 'standalone' | 'central' | 'gateway'; +/** Loopback port shared by the gateway Console's fallback and its agent. Not 3001: + * ChirpStack's Docker setup publishes 3001 for the Basic Station gateway bridge. */ +export const DEFAULT_GATEWAY_FALLBACK_PORT = 3011; +export function gatewayFallbackPort(env: NodeJS.ProcessEnv = process.env): number { + return Number(env.GATEWAY_FALLBACK_PORT || DEFAULT_GATEWAY_FALLBACK_PORT); +} export interface RoleConfig { role: ConsoleRole; development: boolean; @@ -65,3 +71,21 @@ export function requireAgentConfig(env: NodeJS.ProcessEnv = process.env): RoleCo } return { ...config, centralUrl: config.centralUrl, credentialPath: config.credentialPath, fallbackSecretPath: config.fallbackSecretPath }; } + +/** SSH endpoint for central's own Terminal (no gateway selected). The central + * container shares the host network, so loopback reaches the server's sshd. */ +export function centralSsh(env: NodeJS.ProcessEnv = process.env): { host: string; port: number } { + return { host: '127.0.0.1', port: integer(env, 'CENTRAL_SSH_PORT', 22, 1, 65535) }; +} + +/** ChirpStack dashboard that central's ChirpStack window shows when no gateway is selected. */ +export function centralChirpstackUrl(env: NodeJS.ProcessEnv = process.env): URL | undefined { + const raw = env.CENTRAL_CHIRPSTACK_URL?.trim(); + if (!raw) return undefined; + let url: URL; + try { url = new URL(raw); } catch { throw new Error('CENTRAL_CHIRPSTACK_URL must be an http(s) address such as https://chirpstack.example.com.'); } + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) { + throw new Error('CENTRAL_CHIRPSTACK_URL must be an http(s) origin without credentials or a path, such as https://chirpstack.example.com.'); + } + return url; +} diff --git a/src/central/destinations.ts b/src/central/destinations.ts index 20b6306..8c0be25 100644 --- a/src/central/destinations.ts +++ b/src/central/destinations.ts @@ -62,13 +62,3 @@ export async function resolveTarget(input: string, resolve: Resolver = host => l if (hostname === 'localhost' || hostname.endsWith('.localhost') || /\.(local|lan)$/.test(hostname)) target.classification = 'local'; return { ...target, family: target.family as 4 | 6 }; } - -export type BrowsingContext = { pageClass: 'public' | 'local' | 'none'; userNavigation: boolean; topLevel: boolean }; -export function destinationRoute(role: 'standalone' | 'gateway' | 'central', target: Pick, context: BrowsingContext, gateway?: string): 'internet' | 'local' | 'agent' { - if (target.classification === 'blocked') throw new Error('Destination is not permitted.'); - if (target.classification === 'public') return 'internet'; - if (!(context.userNavigation && context.topLevel) && context.pageClass !== 'local') throw new Error('Public pages cannot access private destinations.'); - if (role !== 'central') return 'local'; - if (!gateway) throw new Error('Select an online gateway before opening a local destination.'); - return 'agent'; -} diff --git a/src/central/hub.ts b/src/central/hub.ts index 1b13e62..de28bf2 100644 --- a/src/central/hub.ts +++ b/src/central/hub.ts @@ -79,13 +79,25 @@ export class GatewayHub { app.get('/api/devices/gateways',(_req,res)=>res.json({devices:this.identities.devices()})); app.post('/api/devices/:devEui/gateway',(req,res)=>{try{if(req.body?.gateway!==null&&typeof req.body?.gateway!=='string')throw new Error();this.identities.assignDevice(req.params.devEui,req.body.gateway,res.locals.centralUser.id);res.json({devices:this.identities.devices()});}catch{res.status(400).json({error:'Choose an observed device and available gateway, or null to restore discovery.'});}}); app.post('/api/gateways/select',(req,res)=>{ + const secure=this.development?'':'; Secure'; + // null deselects: Terminal and ChirpStack then work on the central server itself. + if(req.body?.id===null){res.setHeader('Set-Cookie',`console_gateway=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict${secure}`);res.json({selected:null});return;} if(typeof req.body?.id!=='string'||!this.identities.gateways().some(g=>g.id===req.body.id&&!g.revoked)){res.status(400).json({error:'Choose an available gateway.'});return;} - res.setHeader('Set-Cookie',`console_gateway=${req.body.id}; Path=/; HttpOnly; SameSite=Strict${this.development?'':'; Secure'}`);res.json({selected:req.body.id}); + res.setHeader('Set-Cookie',`console_gateway=${req.body.id}; Path=/; HttpOnly; SameSite=Strict${secure}`);res.json({selected:req.body.id}); }); app.post('/api/gateways',(req,res)=>{ try{const g=this.identities.createGateway(String(req.body?.name||''),res.locals.centralUser.id);res.status(201).json({...g,token:this.identities.enrollment(g.id,res.locals.centralUser.id)});} catch{res.status(400).json({error:'Provide a valid gateway name.'});} }); + app.post('/api/gateways/:id/rename',(req,res)=>{ + try{res.json(this.identities.renameGateway(req.params.id,String(req.body?.name??''),res.locals.centralUser.id));} + catch{res.status(400).json({error:'Provide a name of 1–100 printable characters for an existing gateway.'});} + }); + app.post('/api/gateways/:id/delete',(req,res)=>{ + try{this.identities.deleteGateway(req.params.id,res.locals.centralUser.id);}catch{res.status(404).json({error:'Gateway not found.'});return;} + // Same fencing as revocation: the credential is gone, so drop the live link and its tunnels now. + this.clearRotation(req.params.id);this.sockets.get(req.params.id)?.terminate();res.json({deleted:true}); + }); app.post('/api/gateways/:id/revoke',(req,res)=>{this.identities.revoke(req.params.id,res.locals.centralUser.id);this.sockets.get(req.params.id)?.terminate();res.json({revoked:true});}); app.post('/api/gateways/:id/enrollment',(req,res)=>{ try{res.json({token:this.identities.enrollment(req.params.id,res.locals.centralUser.id)});}catch{res.status(409).json({error:'Revoke the previous identity before enrolling again.'});} diff --git a/src/central/identity-store.ts b/src/central/identity-store.ts index 67a6159..9a40bf1 100644 --- a/src/central/identity-store.ts +++ b/src/central/identity-store.ts @@ -6,9 +6,10 @@ import { validImageDigest } from './protocol'; import type { Health } from './protocol'; export type AuditAction = 'login-success' | 'login-failure' | 'logout' | 'enrolment-created' | 'enrolled' | - 'credential-rotated' | 'credential-rotation-acknowledged' | 'credential-revoked' | - 'device-assignment' | 'state-downlink-uncertain' | 'terminal-start' | 'terminal-end' | 'browser-start' | 'browser-end' | 'state-downlink' | 'update-status'; -export interface GatewayIdentity { id: string; name: string; revoked: boolean; lastHeartbeat: number | null; version: string | null } + 'credential-rotated' | 'credential-rotation-acknowledged' | 'credential-revoked' | 'gateway-renamed' | 'gateway-deleted' | + 'password-changed' | 'password-change-failure' | + 'device-assignment' | 'state-downlink-uncertain' | 'terminal-start' | 'terminal-end' | 'state-downlink' | 'update-status'; +export interface GatewayIdentity { id: string; name: string; revoked: boolean; enrolled: boolean; lastHeartbeat: number | null; version: string | null } export interface GatewayUpdate {id:string;gateway:string;image:string;status:UpdateStatus;history:Array<{status:UpdateStatus;time:number}>} export interface DeviceGateway { devEui:string; gateway:string; observedGateway:string; overridden:boolean; lastSeen:number } export interface UserIdentity { id: string; username: string; passwordHash: string } @@ -16,6 +17,8 @@ export interface SessionIdentity { id: string; username: string; expires: number export interface IdentityStore { createGateway(name: string, actor: string): GatewayIdentity; gateways(): GatewayIdentity[]; + renameGateway(gateway: string, name: string, actor: string): GatewayIdentity; + deleteGateway(gateway: string, actor: string): void; enrollment(gateway: string, actor: string, ttlMs?: number): string; exchange(token: string): { gateway: string; credential: string } | null; authenticateAgent(credential: string): string | null; @@ -23,6 +26,7 @@ export interface IdentityStore { acknowledgeRotation(gateway: string, credential: string): boolean; revoke(gateway: string, actor: string): void; addUser(username: string, passwordHash: string): void; + changePassword(user: string, passwordHash: string, keepSession: string): void; user(username: string): UserIdentity | null; createSession(user: string, ttlMs?: number): string; session(token: string): SessionIdentity | null; @@ -75,23 +79,55 @@ export class SqliteIdentityStore implements IdentityStore { CREATE TABLE IF NOT EXISTS central_hostkeys(gateway TEXT PRIMARY KEY REFERENCES central_gateways(id),hash TEXT NOT NULL); INSERT OR IGNORE INTO central_schema VALUES (1); `))(); + // Version 2: deleted gateways are hidden and fenced, but their history is kept. + const columns = (this.db.prepare('PRAGMA table_info(central_gateways)').all() as Array<{ name: string }>).map(column => column.name); + if (!columns.includes('deleted')) this.db.transaction(() => { + this.db.exec('ALTER TABLE central_gateways ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0'); + this.db.exec('INSERT OR IGNORE INTO central_schema VALUES (2)'); + })(); } - createGateway(name: string, actor: string): GatewayIdentity { + private static gatewayName(name: string): string { if (!name.trim() || name.length > 100 || /[\x00-\x1f]/.test(name)) throw new Error('Gateway name must contain 1–100 printable characters.'); + return name.trim(); + } + createGateway(name: string, actor: string): GatewayIdentity { + const clean = SqliteIdentityStore.gatewayName(name); const id = randomUUID(); - this.db.prepare('INSERT INTO central_gateways (id,name) VALUES (?,?)').run(id, name.trim()); + this.db.prepare('INSERT INTO central_gateways (id,name) VALUES (?,?)').run(id, clean); this.audit(actor, 'enrolment-created', id); - return { id, name: name.trim(), revoked: false, lastHeartbeat: null, version: null }; + return { id, name: clean, revoked: false, enrolled: false, lastHeartbeat: null, version: null }; } gateways(): GatewayIdentity[] { - return (this.db.prepare('SELECT id,name,revoked,lastHeartbeat,version FROM central_gateways ORDER BY name').all() as - Array & { revoked: number }>).map(row => ({ ...row, revoked: !!row.revoked })); + return (this.db.prepare(`SELECT id,name,revoked,credentialHash IS NOT NULL AS enrolled,lastHeartbeat,version + FROM central_gateways WHERE deleted=0 ORDER BY name COLLATE NOCASE`).all() as + Array & { revoked: number; enrolled: number }>) + .map(row => ({ ...row, revoked: !!row.revoked, enrolled: !!row.enrolled })); + } + renameGateway(gateway: string, name: string, actor: string): GatewayIdentity { + const clean = SqliteIdentityStore.gatewayName(name); + return this.db.transaction(() => { + if (!this.db.prepare('UPDATE central_gateways SET name=? WHERE id=? AND deleted=0').run(clean, gateway).changes) throw new Error('Gateway not found.'); + this.audit(actor, 'gateway-renamed', gateway, clean); + return this.gateways().find(g => g.id === gateway)!; + })(); + } + /** Removes a gateway from use: its credential and pending enrollments are destroyed + * and device pins released. Rows are kept so billing, audit and outcome history stay intact. */ + deleteGateway(gateway: string, actor: string): void { + this.db.transaction(() => { + const result = this.db.prepare(`UPDATE central_gateways SET deleted=1,revoked=1,credentialHash=NULL,previousHash=NULL,previousUntil=NULL + WHERE id=? AND deleted=0`).run(gateway); + if (!result.changes) throw new Error('Gateway not found.'); + this.db.prepare('DELETE FROM central_enrollments WHERE gateway=?').run(gateway); + this.db.prepare('UPDATE central_devices SET overrideGateway=NULL WHERE overrideGateway=?').run(gateway); + this.audit(actor, 'gateway-deleted', gateway); + })(); } enrollment(gateway: string, actor: string, ttlMs = 10 * 60000): string { if (!Number.isInteger(ttlMs) || ttlMs < 1000 || ttlMs > 3600000) throw new Error('Invalid enrollment lifetime.'); const token = newSecret(); this.db.transaction(() => { - const row = this.db.prepare('SELECT credentialHash,revoked FROM central_gateways WHERE id=?').get(gateway) as { credentialHash: string | null; revoked: number } | undefined; + const row = this.db.prepare('SELECT credentialHash,revoked FROM central_gateways WHERE id=? AND deleted=0').get(gateway) as { credentialHash: string | null; revoked: number } | undefined; if (!row || (row.credentialHash && !row.revoked)) throw new Error('Revoke an enrolled gateway before replacing its identity.'); this.db.prepare('DELETE FROM central_enrollments WHERE gateway=? OR expires<=?').run(gateway, this.now()); this.db.prepare('INSERT INTO central_enrollments (tokenHash,gateway,expires) VALUES (?,?,?)').run(hashSecret(token), gateway, this.now() + ttlMs); @@ -149,6 +185,15 @@ export class SqliteIdentityStore implements IdentityStore { if (!/^[A-Za-z0-9_.@-]{1,100}$/.test(username) || !/^scrypt\$[a-f0-9]{32}\$[a-f0-9]{128}$/.test(passwordHash)) throw new Error('Invalid user or password hash.'); this.db.prepare('INSERT INTO central_users VALUES (?,?,?)').run(randomUUID(), username, passwordHash); } + /** Replaces a password hash and ends every other session of that user; keepSession stays signed in. */ + changePassword(user: string, passwordHash: string, keepSession: string): void { + if (!/^scrypt\$[a-f0-9]{32}\$[a-f0-9]{128}$/.test(passwordHash)) throw new Error('Invalid password hash.'); + this.db.transaction(() => { + if (!this.db.prepare('UPDATE central_users SET passwordHash=? WHERE id=?').run(passwordHash, user).changes) throw new Error('User not found.'); + this.db.prepare('DELETE FROM central_sessions WHERE userId=? AND tokenHash<>?').run(user, hashSecret(keepSession)); + this.audit(user, 'password-changed'); + })(); + } user(username: string): UserIdentity | null { return this.db.prepare('SELECT * FROM central_users WHERE username=?').get(username) as UserIdentity | undefined || null; } diff --git a/src/central/login-page.ts b/src/central/login-page.ts new file mode 100644 index 0000000..53f6bfe --- /dev/null +++ b/src/central/login-page.ts @@ -0,0 +1,95 @@ +import { createHash } from 'crypto'; + +/** Central sign-in page. Served before authentication, so it cannot load the desktop's + * static CSS; everything is inline and allowed by an exact hash. No scripts at all. */ +const css = ` +:root{--ink:#1f332c;--muted:#5f6f67;--accent:#316a4d;--accent-ink:#fff;--card:#fbfcfa;--field:#fff;--line:#cdd6cb; + --danger:#a53a43;--danger-bg:#fbeeee;--ok-bg:#eaf4ee;--shadow:0 30px 80px #04191433,0 2px 10px #04191418;color-scheme:light} +@media (prefers-color-scheme:dark){:root{--ink:#eef2ef;--muted:#a9b7b0;--accent:#7cc39a;--accent-ink:#0f241a;--card:#1d2925; + --field:#15201c;--line:#36463f;--danger:#f19aa1;--danger-bg:#3a2226;--ok-bg:#1f3a2b;--shadow:0 30px 80px #0008;color-scheme:dark}} +*{box-sizing:border-box} +html,body{margin:0;min-height:100%} +body{min-height:100dvh;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(0,1fr);color:var(--ink); + font:15px/1.5 Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; + background:radial-gradient(ellipse at 15% 85%,#3f7a5c 0%,transparent 55%),radial-gradient(ellipse at 85% 10%,#2b5f63 0%,transparent 50%), + linear-gradient(140deg,#0d2a25 0%,#173c39 55%,#24524a 100%)} +.hero{display:flex;flex-direction:column;justify-content:space-between;padding:48px 56px;color:#eaf3ee} +.brand{display:flex;align-items:center;gap:12px;font-weight:600;font-size:16px} +.mark{display:grid;place-items:center;width:44px;height:44px;border-radius:12px;background:#eaf3ee;color:#173c39;font-weight:700;font-size:17px;letter-spacing:-.5px} +.brand small{display:block;font-weight:400;font-size:13px;color:#b8cec3} +.eyebrow{font-size:12px;letter-spacing:.16em;color:#a9c7b8;margin:0 0 14px} +.hero h2{font-size:clamp(34px,4.4vw,56px);line-height:1.05;letter-spacing:-.02em;margin:0;font-weight:650} +.hero p.lede{max-width:30em;color:#c9dbd2;margin:18px 0 0} +.hero footer{font-size:13px;color:#a9c7b8} +main{display:grid;place-items:center;padding:32px} +.card{width:min(410px,100%);background:var(--card);border-radius:20px;padding:36px 34px 30px;box-shadow:var(--shadow)} +.card .mark{display:none} +h1{font-size:24px;line-height:1.2;margin:0 0 6px;letter-spacing:-.01em} +.sub{margin:0 0 24px;color:var(--muted)} +.alert{display:flex;gap:10px;align-items:flex-start;margin:0 0 20px;padding:12px 14px;border-radius:12px;font-size:14px} +.alert::before{flex:none;display:grid;place-items:center;width:20px;height:20px;border-radius:50%;font-weight:700;font-size:12px;margin-top:1px} +.alert.error{background:var(--danger-bg);color:var(--danger)} +.alert.error::before{content:"!";background:var(--danger);color:var(--card)} +.alert.ok{background:var(--ok-bg);color:var(--accent)} +.alert.ok::before{content:"✓";background:var(--accent);color:var(--accent-ink)} +form{display:grid;gap:16px} +label{display:grid;gap:6px;font-size:13px;font-weight:600} +input{width:100%;height:46px;padding:0 14px;border:1px solid var(--line);border-radius:11px;background:var(--field);color:var(--ink); + font:inherit;font-size:15px;transition:border-color .15s,box-shadow .15s} +input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 4px color-mix(in srgb,var(--accent) 22%,transparent)} +button{margin-top:6px;height:48px;border:0;border-radius:11px;background:var(--accent);color:var(--accent-ink);font:inherit;font-weight:600; + font-size:15px;cursor:pointer;transition:filter .15s,transform .05s} +button:hover{filter:brightness(1.07)} +button:active{transform:translateY(1px)} +button:focus-visible{outline:3px solid color-mix(in srgb,var(--accent) 45%,transparent);outline-offset:3px} +.note{display:flex;align-items:center;gap:8px;margin:22px 0 0;padding-top:18px;border-top:1px solid var(--line);font-size:12.5px;color:var(--muted)} +.note::before{content:"";flex:none;width:8px;height:8px;border-radius:50%;background:var(--accent)} +@media (max-width:860px){ + body{grid-template-columns:1fr} + .hero{display:none} + main{padding:24px 16px;align-content:center} + .card{padding:30px 22px 24px} + .card .mark{display:grid;margin-bottom:18px} +} +@media (prefers-reduced-motion:reduce){*{transition:none!important}} +`; + +const favicon = 'data:image/svg+xml,' + encodeURIComponent( + '' + + 'm³'); + +export const loginPolicy = `default-src 'none'; style-src 'sha256-${createHash('sha256').update(css).digest('base64')}'; ` + + "img-src data:; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"; + +const escape = (value: string): string => value.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`); + +export interface LoginView { error?: string; notice?: string; username?: string } +export function loginPage({ error, notice, username = '' }: LoginView = {}): string { + const message = error ? `` + : notice ? `

${escape(notice)}

` : ''; + const focusPassword = !!error && !!username; + return ` +Sign in · M3tering Console + + +
+
+ +

Welcome back

+

Sign in to manage your gateways.

+ ${message} +
+ + + +
+

Encrypted connection · Sessions end after 8 hours

+
+
+`; +} diff --git a/src/central/protocol.ts b/src/central/protocol.ts index 2bb69be..93dceb9 100644 --- a/src/central/protocol.ts +++ b/src/central/protocol.ts @@ -1,7 +1,7 @@ /** Versioned, bounded vocabulary. There is deliberately no command/script RPC. */ export const MAX_MESSAGE_BYTES = 65536; export const MAX_TUNNEL_CHUNK = 16384; -export type TunnelPurpose = 'ssh' | 'chirpstack' | 'browser'; +export type TunnelPurpose = 'ssh' | 'chirpstack'; export type Health = { version: string; uptime: number; mqtt: 'connected' | 'disconnected' | 'connecting'; fallback: boolean; queueDepth: number; updatesEnabled: boolean; uncertain: number; reconciled: number; superseded: number; lastError: 'none' | 'mqtt' | 'central' | 'local' | 'storage' | 'update' }; @@ -87,7 +87,7 @@ export function parseMessage(input: Buffer | string, direction: 'agent' | 'centr case 'tunnel-credit': valid = keys('id', 'bytes') && id(value.id) && integer(value.bytes, 1, 65536); break; case 'tunnel-close': valid = keys('id', 'reason') && id(value.id) && isOneOf(value.reason, ['closed', 'refused', 'timeout', 'limit', 'disconnected', 'error']); break; case 'tunnel-open': valid = direction === 'central' && keys('id', 'purpose', 'host', 'port') && id(value.id) && - isOneOf(value.purpose, ['ssh', 'chirpstack', 'browser']) && typeof value.host === 'string' && + isOneOf(value.purpose, ['ssh', 'chirpstack']) && typeof value.host === 'string' && value.host.length > 0 && value.host.length <= 253 && !/[\s\x00-\x1f/@?#%]/.test(value.host) && integer(value.port, 1, 65535); break; case 'decision': valid = direction === 'central' && keys('id', 'devEui', 'fPort', 'confirmed', 'data') && id(value.id) && typeof value.devEui === 'string' && /^[a-fA-F0-9]{16}$/.test(value.devEui) && value.fPort === 2 && value.confirmed === false && diff --git a/src/central/runtime.ts b/src/central/runtime.ts index 3fd9515..2b0cb0a 100644 --- a/src/central/runtime.ts +++ b/src/central/runtime.ts @@ -1,7 +1,8 @@ import fs from 'fs'; import path from 'path'; import type http from 'http'; -import { roleConfig } from './config'; +import { roleConfig, gatewayFallbackPort } from './config'; +import { createLogger } from '../utils/logger'; import { SqliteIdentityStore } from './identity-store'; import { CentralAuth } from './auth'; import { GatewayHub } from './hub'; @@ -52,9 +53,17 @@ export async function initializeManagedRole():Promise { if(!/^[\w-]{36}$/.test(identity))throw new Error('Agent enrollment is not ready.');return identity; }; const server=fallbackServer(processor,secret,getGateway); - const port=Number(process.env.GATEWAY_FALLBACK_PORT||3001); + const port=gatewayFallbackPort(); if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('GATEWAY_FALLBACK_PORT must be 1024–65535.'); - await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',()=>{server.off('error',reject);resolve();});}); + await new Promise((resolve,reject)=>{ + server.once('error',error=>{ + // Managed logs withhold error details, so name the problem explicitly; it is not secret. + if((error as NodeJS.ErrnoException).code==='EADDRINUSE')createLogger('[gateway]').error( + `Port ${port} on 127.0.0.1 is already used by another program. Set GATEWAY_FALLBACK_PORT in .env to a free port and redeploy.`); + reject(error); + }); + server.listen(port,'127.0.0.1',()=>{server.removeAllListeners('error');resolve();}); + }); return server; } } diff --git a/src/central/secrets.ts b/src/central/secrets.ts index 6ffc974..ac1be0d 100644 --- a/src/central/secrets.ts +++ b/src/central/secrets.ts @@ -11,7 +11,7 @@ export function equalSecretHash(secret: string, expected: string): boolean { const derive = (password: string, salt: string): Promise => new Promise((resolve, reject) => scrypt(password, salt, 64, { N: 16384, r: 8, p: 1 }, (error, value) => error ? reject(error) : resolve(value))); export async function hashPassword(password: string): Promise { - if (password.length < 16 || Buffer.byteLength(password) > 1024) throw new Error('Central passwords must contain 16–1024 bytes.'); + if (password.length < 7 || Buffer.byteLength(password) > 1024) throw new Error('Central passwords must have at least 7 characters (at most 1024 bytes).'); const salt = randomBytes(16).toString('hex'); return `scrypt$${salt}$${(await derive(password, salt)).toString('hex')}`; } diff --git a/src/central/tunnels.ts b/src/central/tunnels.ts index f71bb75..d039eff 100644 --- a/src/central/tunnels.ts +++ b/src/central/tunnels.ts @@ -4,7 +4,7 @@ import tls from 'tls'; import { randomUUID } from 'crypto'; import WebSocket from 'ws'; import { CentralMessage, TunnelMessage, TunnelPurpose, MAX_TUNNEL_CHUNK } from './protocol'; -import { normalizeHost, resolveTarget, classifyAddress } from './destinations'; +import { normalizeHost, resolveTarget } from './destinations'; import { chirpstackTarget } from '../services/chirpstack'; type Open = Extract; @@ -23,15 +23,7 @@ export async function gatewayTarget(request:Open,env:NodeJS.ProcessEnv=process.e const target=chirpstackTarget();const resolved=await resolveTarget(target.hostname); return {host:resolved.address,port:Number(target.port||(target.protocol==='https:'?443:80)),secure:target.protocol==='https:',servername:normalizeHost(target.hostname),origin:target.origin}; } - const target=await resolveTarget(request.host); - if(target.classification!=='local'||classifyAddress(target.address)!=='local')throw new Error('Browser tunnels are restricted to local destinations.'); - const loopback=target.address==='::1'||target.address.startsWith('127.')||/^::ffff:7f[\da-f]{2}:/.test(target.address); - if(!loopback&&env.AGENT_BROWSER_ALLOW_LAN!=='true')throw new Error('Gateway owner has not enabled browser access to the LAN.'); - const denied=new Set([22,Number(env.AGENT_SSH_PORT||22),2375,2376,Number(env.GATEWAY_FALLBACK_PORT||3001),Number(env.GATEWAY_UPDATER_PORT||3002)]); - if(denied.has(request.port))throw new Error('This infrastructure port is not a browser target.'); - const allowed=(env.AGENT_BROWSER_PORTS||'80,443,3000,8080,8090').split(',').map(Number); - if(!allowed.includes(request.port))throw new Error('Gateway owner has not allowed this browser port.'); - return {host:target.address,port:request.port}; + throw new Error('Unknown tunnel purpose.'); } class TunnelStream extends Duplex { diff --git a/src/index.ts b/src/index.ts index f5a60ca..480ce9e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,20 +3,23 @@ import { handleUplinks } from './services/mqtt'; import { server, startServer } from './services/server'; import { attachTerminal } from './services/ssh'; import { central, config, initializeManagedRole } from './central/runtime'; +import { centralSsh } from './central/config'; if(!central)attachTerminal(server); else { const runtime=central; - const sessions=new Map(); + const sessions=new Map(); attachTerminal(server,undefined,{ connection:async request=>{ - const gateway=runtime.hub.selected(request);if(!gateway)throw new Error('Select a gateway.'); + const gateway=runtime.hub.selected(request); + // No gateway selected: a shell on the central server itself (the container shares the host network). + if(!gateway)return centralSsh(); const sock=await runtime.hub.open(gateway,'ssh','ssh',22); return {sock,hostHash:'sha256',hostVerifier:(hash:string)=>runtime.identities.verifyHostKey(gateway,hash)}; }, audit:(request,event,session)=>{ if(event==='start'){ - const user=runtime.auth.session(request),gateway=runtime.hub.selected(request); - if(user&&gateway)sessions.set(session,{user:user.id,gateway}); + const user=runtime.auth.session(request),gateway=runtime.hub.selected(request)||undefined; + if(user)sessions.set(session,{user:user.id,gateway}); } const actor=sessions.get(session); if(actor)runtime.identities.audit(actor.user,event==='start'?'terminal-start':'terminal-end',actor.gateway,session); diff --git a/src/public/browser-home.html b/src/public/browser-home.html deleted file mode 100644 index 36206c0..0000000 --- a/src/public/browser-home.html +++ /dev/null @@ -1,4 +0,0 @@ - -Google search · Console Browser - -

Search with Google

Enter a search in the toolbar above. Google results open in a new tab because Google does not allow embedded search pages.

You can also enter an HTTP or HTTPS address to browse here. If a site blocks embedding, use “Open in new tab”.

diff --git a/src/public/css/gateways.css b/src/public/css/gateways.css index a0ff3b5..44a5ccb 100644 --- a/src/public/css/gateways.css +++ b/src/public/css/gateways.css @@ -1 +1,223 @@ -.gateway-control{display:flex;align-items:center;gap:.5rem;min-width:0}.gateway-control form{margin:0}.gateway-control select{max-width:13rem;min-width:0;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:8px;padding:.4rem}#gateway-status{position:absolute;bottom:78px;left:1rem;right:1rem;z-index:5;pointer-events:none;font:12px system-ui;color:var(--text);background:var(--surface);padding:.5rem;border-radius:8px;width:fit-content;max-width:calc(100% - 2rem)}#gateway-dialog{background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:14px;max-width:760px;width:calc(100% - 2rem);max-height:85dvh;overflow:auto;padding:1.5rem}#gateway-dialog::backdrop{background:#0008}#gateway-dialog header{display:flex;justify-content:space-between;align-items:center}#gateway-dialog h2{font-size:1.3rem}#gateway-list article{padding:1rem 0;border-bottom:1px solid var(--border)}#gateway-list article>div{display:flex;gap:.5rem;flex-wrap:wrap}#gateway-list p{font:14px system-ui}#gateway-create{display:flex;gap:1rem;align-items:end;flex-wrap:wrap;margin-top:1rem}#gateway-create label{display:grid;gap:.4rem}#gateway-enrollment code{display:block;overflow-wrap:anywhere;white-space:normal;margin-bottom:1rem}#gateway-error{color:var(--danger,#c44)}@media(max-width:600px){.gateway-control{gap:.15rem}.gateway-control select{max-width:9rem}.gateway-control button{font-size:11px}.topbar-location{display:none}#gateway-status{font-size:10px;bottom:70px}#gateway-dialog{padding:1rem}} +/* Central gateway selector and management. Colours come from the active desktop theme. */ +/* Status colours shared by the switcher, its menu and the management cards. */ +:root{--gw-online:#2f8a57;--gw-offline:#b7832f;--gw-revoked:#b5434c} +:is(.gw-switcher,.gw-current-head,.gw-option){--gw-state:var(--gw-offline)} +:is(.gw-switcher,.gw-current-head,.gw-option)[data-state="online"]{--gw-state:var(--gw-online)} +:is(.gw-switcher,.gw-current-head,.gw-option)[data-state="revoked"]{--gw-state:var(--gw-revoked)} +:is(.gw-switcher,.gw-current-head,.gw-option)[data-state="pending"]{--gw-state:var(--accent)} +.gw-switcher[data-state="none"]{--gw-state:var(--border)} +:is(.gw-switcher,.gw-current-head,.gw-option)[data-state="central"]{--gw-state:var(--accent)} +/* Central is a place, not a link state: a ring, so it never reads as "online". */ +:is(.gw-current-head,.gw-option)[data-state="central"] .gw-dot,.gw-switcher[data-state="central"] .gw-switcher-dot{background:transparent;box-shadow:inset 0 0 0 2px var(--gw-state)} + +/* Top bar: gateway switcher (centred on wide screens) and account button. */ +.gateway-control{position:absolute;left:50%;transform:translateX(-50%);display:flex;min-width:0} +.gw-switcher{display:inline-flex;align-items:center;gap:10px;min-width:0;max-width:min(320px,34vw);height:38px;padding:0 12px; + border:1px solid var(--border);border-radius:calc(var(--small-radius) * 3);background:var(--surface);color:var(--text); + box-shadow:0 1px 2px #0000000f;font:500 13px var(--font);cursor:pointer;transition:background var(--duration),border-color var(--duration),box-shadow var(--duration)} +.gw-switcher:hover{background:var(--surface-alt)} +.gw-switcher[aria-expanded="true"]{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 20%,transparent)} +.gw-switcher-dot{flex:none;width:9px;height:9px;border-radius:50%;background:var(--gw-state)} +.gw-switcher[data-state="online"] .gw-switcher-dot{box-shadow:0 0 0 3px color-mix(in srgb,var(--gw-online) 22%,transparent)} +.gw-switcher-text{display:flex;flex-direction:column;align-items:flex-start;min-width:0;line-height:1.15} +.gw-switcher-label{font-size:9.5px;letter-spacing:.09em;text-transform:uppercase;color:var(--muted)} +#gateway-switcher-name{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600} +.gw-chevron{flex:none;width:12px;height:12px;margin-left:2px;color:var(--muted);transition:transform var(--duration)} +.gw-switcher[aria-expanded="true"] .gw-chevron{transform:rotate(180deg)} +.account-button{display:grid;place-items:center;width:40px;height:40px;padding:0;border:0;border-radius:50%;background:none;cursor:pointer} +.account-avatar{display:grid;place-items:center;width:30px;height:30px;border-radius:50%;background:var(--accent);color:var(--accent-ink); + font:700 13px/1 var(--font);text-transform:uppercase;transition:box-shadow var(--duration)} +.account-button:hover .account-avatar,.account-button[aria-expanded="true"] .account-avatar{box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 25%,transparent)} +.account-avatar.is-large{width:40px;height:40px;font-size:16px} + +/* Drop-down panels under the top bar. */ +.gw-menu,.account-menu{position:fixed;z-index:600;top:calc(var(--panel-height) + env(safe-area-inset-top) + 8px); + background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:max(var(--radius),4px); + box-shadow:0 20px 50px #0b151c38,0 2px 8px #0b151c14;font:14px/1.45 var(--font);animation:gw-pop var(--duration) ease-out} +.gw-menu[hidden],.account-menu[hidden]{display:none} +@keyframes gw-pop{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}} +.gw-menu{width:380px;max-height:calc(100dvh - var(--panel-height) - env(safe-area-inset-top) - 24px);overflow:auto;padding:16px;display:grid;gap:12px} +.gw-menu-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px} +.gw-menu-head h2{margin:0;font:650 16px var(--display-font)} +.gw-menu-head p{margin:2px 0 0;font-size:12.5px;color:var(--muted)} +.gw-menu-head .quiet-button{min-height:32px;min-width:32px;padding:4px;font-size:20px;line-height:1} +.gw-current{padding:12px;border-radius:var(--small-radius);background:var(--surface-alt)} +.gw-current-head{display:flex;align-items:center;gap:10px;min-width:0} +.gw-current-head .gw-dot{flex:none;width:10px;height:10px;border-radius:50%;background:var(--gw-state)} +.gw-current-head .gw-title{display:grid;flex:1;min-width:0} +.gw-current-head .gw-name{font-size:15px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.gw-current-head small{font-size:12px;color:var(--muted)} +.gw-current-head .gw-state{color:var(--gw-state);border-color:color-mix(in srgb,var(--gw-state) 40%,transparent);background:color-mix(in srgb,var(--gw-state) 9%,var(--surface))} +.gw-menu .gw-stats{grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;margin:12px 0 0} +.gw-menu .gw-stat{padding:7px 8px;background:var(--surface)} +.gw-menu .gw-stat dt{font-size:9.5px} +.gw-menu .gw-stat dd{font-size:14px} +.gw-current .gw-muted,.gw-current-empty{margin:0;font-size:13px;color:var(--muted)} +.gw-current .gw-muted{margin-top:8px} +.gw-menu-label{margin:2px 0 -6px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)} +.gw-options{display:grid;gap:2px} +.gw-option{display:flex;align-items:center;gap:10px;width:100%;min-height:48px;padding:8px 10px;border:0;border-radius:var(--small-radius); + background:none;color:var(--text);text-align:left;font:inherit;cursor:pointer} +.gw-option:hover,.gw-option:focus-visible{background:var(--surface-alt)} +.gw-option[aria-selected="true"]{background:color-mix(in srgb,var(--accent) 10%,var(--surface))} +.gw-option .gw-dot{flex:none;width:9px;height:9px;border-radius:50%;background:var(--gw-state)} +.gw-option-text{display:grid;flex:1;min-width:0} +.gw-option-text strong{font-size:14px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.gw-option-text small{font-size:12px;color:var(--muted)} +.gw-check{flex:none;color:var(--accent);font-weight:700} +.gw-menu-foot{padding-top:12px;border-top:1px solid var(--border)} +.gw-menu-foot .nes-btn{width:100%} +.account-menu{right:16px;width:250px;padding:6px} +.account-menu-head{display:flex;align-items:center;gap:12px;padding:10px 10px 12px;margin-bottom:4px;border-bottom:1px solid var(--border)} +.account-menu-head div{display:grid;min-width:0} +.account-menu-head strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.account-menu-head small{font-size:12px;color:var(--muted)} +.account-menu form{margin:0} +.account-menu-item{display:flex;align-items:center;width:100%;min-height:42px;padding:8px 12px;border:0;border-radius:var(--small-radius); + background:none;color:var(--text);text-align:left;font:500 14px var(--font);cursor:pointer} +.account-menu-item:hover,.account-menu-item:focus-visible{background:var(--surface-alt)} +.account-menu-item.is-danger{color:var(--gw-revoked)} + +#gateway-dialog{--gw-online:#2f8a57;--gw-offline:#b7832f;--gw-revoked:#b5434c;--gw-pending:var(--accent); + width:min(820px,calc(100% - 2rem));max-width:none;max-height:88dvh;overflow:auto;padding:0; + background:var(--surface);color:var(--text);font:14px/1.5 var(--font)} +#gateway-dialog::backdrop{background:#0b151c99;backdrop-filter:blur(4px)} +#gateway-dialog h2,#gateway-dialog h3{font-family:var(--display-font);margin:0} +#gateway-dialog p{margin:0} +#gateway-dialog code{font:12.5px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace} +#gateway-dialog > :not(.gw-header){margin-left:28px;margin-right:28px} + +.gw-header{position:sticky;top:0;z-index:2;display:flex;justify-content:space-between;align-items:flex-start;gap:1rem; + padding:24px 28px 18px;background:var(--surface);border-bottom:1px solid var(--border)} +.gw-header .eyebrow{font-size:11px;letter-spacing:.12em;color:var(--muted)} +.gw-header h2{font-size:24px;margin:2px 0 4px} +.gw-summary{color:var(--muted);font-size:13px} +#gateway-dialog-close{font-size:22px;line-height:1} + +.gw-add{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.25fr);gap:20px;align-items:center;margin-top:22px; + padding:20px;background:var(--surface-alt);border:1px solid var(--border);border-radius:var(--radius)} +#gateway-dialog .gw-add h3{font-size:16px;margin-bottom:4px} +.gw-add p{color:var(--muted);font-size:13px} +#gateway-create{display:flex;gap:10px;margin:0} +#gateway-create .nes-input{flex:1;min-width:0} +#gateway-create .nes-btn{white-space:nowrap} + +.gw-enrollment{margin-top:16px;padding:20px;border:2px solid var(--accent);border-radius:var(--radius); + background:color-mix(in srgb,var(--accent) 7%,var(--surface))} +.gw-enrollment-head{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:14px} +.gw-enrollment-head h3{font-size:16px} +.gw-steps{margin:0 0 16px;padding:0;list-style:none;counter-reset:step;display:grid;gap:14px} +.gw-steps li{counter-increment:step;display:grid;grid-template-columns:28px minmax(0,1fr);column-gap:10px;row-gap:8px} +.gw-steps li::before{content:counter(step);grid-row:span 2;width:26px;height:26px;border-radius:50%;display:grid;place-items:center; + background:var(--accent);color:var(--accent-ink);font-weight:600;font-size:12px} +.gw-steps li>span{align-self:center} +.gw-token{display:flex;gap:8px;align-items:stretch;min-width:0} +.gw-token code,.gw-command{flex:1;min-width:0;display:block;padding:10px 12px;border-radius:var(--small-radius); + background:#122127;color:#e7f0ea;overflow-wrap:anywhere;user-select:all} +.gw-token-key{color:#9fc4ae} +.gw-token-line{display:block} + +#gateway-error{margin-top:14px;color:var(--gw-revoked);font-weight:500} +#gateway-error:empty{display:none} +#gateway-dialog .gw-list-title{font-size:15px;margin-top:28px;margin-bottom:12px} + +#gateway-list{display:grid;gap:14px} +.gw-card{--gw-state:var(--gw-offline);position:relative;padding:18px 18px 14px 22px;background:var(--surface); + border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 1px 2px #0000000d;overflow:hidden} +.gw-card::before{content:'';position:absolute;inset:0 auto 0 0;width:4px;background:var(--gw-state)} +.gw-card[data-state="online"]{--gw-state:var(--gw-online)} +.gw-card[data-state="revoked"]{--gw-state:var(--gw-revoked)} +.gw-card[data-state="pending"]{--gw-state:var(--gw-pending)} +.gw-card-head{display:flex;align-items:center;gap:12px;min-width:0} +.gw-dot{flex:none;width:10px;height:10px;border-radius:50%;background:var(--gw-state)} +.gw-card[data-state="online"] .gw-dot{box-shadow:0 0 0 4px color-mix(in srgb,var(--gw-online) 22%,transparent)} +.gw-title{display:grid;min-width:0;flex:1} +.gw-name{font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.gw-title small{color:var(--muted);font-size:12px} +.gw-tools{display:flex;gap:2px;margin-left:auto} +.gw-tools .quiet-button{min-height:34px;min-width:0;padding:6px 10px;font:500 12px var(--font);color:var(--muted)} +.gw-tools .quiet-button:hover{color:var(--text)} +.gw-tools .gw-danger:hover{color:var(--gw-revoked);background:color-mix(in srgb,var(--gw-revoked) 10%,transparent)} + +.gw-pill{display:inline-flex;align-items:center;white-space:nowrap;padding:3px 10px;border-radius:999px;font-size:11.5px;font-weight:600; + background:var(--surface-alt);color:var(--muted);border:1px solid var(--border)} +.gw-pill.is-on{color:var(--gw-online);border-color:color-mix(in srgb,var(--gw-online) 40%,transparent)} +.gw-pill.is-expired{color:var(--gw-revoked)} +.gw-state{color:var(--gw-state);border-color:color-mix(in srgb,var(--gw-state) 40%,transparent);background:color-mix(in srgb,var(--gw-state) 9%,var(--surface))} + +.gw-rename{display:flex;gap:8px;flex:1;min-width:0;margin:0} +.gw-rename .nes-input{flex:1;min-width:0;min-height:36px;padding:6px 10px} +.gw-rename .nes-btn{min-height:36px;padding:6px 12px} + +.gw-stats{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px;margin:16px 0 0} +.gw-actions{margin-top:14px} +.gw-stat{padding:9px 11px;background:var(--surface-alt);border-radius:var(--small-radius);min-width:0} +.gw-stat dt{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)} +.gw-stat dd{margin:2px 0 0;font-size:17px;font-weight:600;font-variant-numeric:tabular-nums;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} + +.gw-actions{display:flex;gap:8px;flex-wrap:wrap} +.gw-actions .nes-btn:disabled{opacity:.5;cursor:not-allowed} + +.gw-updates{margin-top:12px;border-top:1px solid var(--border);padding-top:10px} +.gw-updates summary{display:flex;align-items:center;gap:10px;cursor:pointer;font-weight:500;font-size:13px;list-style:none} +.gw-updates summary::-webkit-details-marker{display:none} +.gw-updates summary::before{content:'▸';color:var(--muted);transition:transform var(--duration)} +.gw-updates[open] summary::before{transform:rotate(90deg)} +#gateway-dialog .gw-updates>p,.gw-update-form,.gw-job{margin-top:10px} +.gw-muted{color:var(--muted);font-size:13px} +.gw-update-form{display:grid;gap:10px} +.gw-check{display:flex;align-items:center;gap:8px;font-size:13px} +.gw-update-form .nes-btn{justify-self:start} +.gw-job{display:flex;align-items:center;gap:10px;font-size:12px;min-width:0} +.gw-job code{flex:1;min-width:0;overflow-wrap:anywhere;color:var(--muted)} + +.gw-empty{text-align:center;padding:34px 20px;border:1px dashed var(--border);border-radius:var(--radius);color:var(--muted)} +.gw-empty strong{display:block;color:var(--text);font-size:15px;margin-bottom:4px} +#gateway-dialog .gw-note{margin-top:20px;margin-bottom:24px;padding-top:14px;border-top:1px solid var(--border);font-size:12px;color:var(--muted)} + +#gateway-confirm{width:min(440px,calc(100% - 32px))} +#gateway-confirm p{line-height:1.55} + +@media(max-width:640px){ + /* Phones: the brand mark, a switcher that takes the free space, account and settings. */ + .topbar-location,.brand > span:not(.brand-mark){display:none} + .gateway-control{position:static;transform:none;flex:1;min-width:0} + .gw-switcher{max-width:none;width:100%;height:40px} + .gw-menu{left:8px!important;right:8px;width:auto;max-height:calc(100dvh - var(--panel-height) - env(safe-area-inset-top) - 16px)} + .gw-switcher-text{flex:1} + .gw-stat dd{font-size:14px} + .account-menu{right:8px} + /* The management dialog becomes a full-screen sheet. */ + #gateway-dialog{width:100%;max-width:100%;height:100dvh;max-height:100dvh;margin:0;inset:0;border:0;border-radius:0} + #gateway-dialog > :not(.gw-header){margin-left:16px;margin-right:16px} + .gw-header{padding:18px 16px 14px} + .gw-add{grid-template-columns:1fr;gap:12px;padding:16px} + #gateway-create{flex-direction:column} + .gw-card{padding:16px 14px 12px 18px} + .gw-card-head{flex-wrap:wrap} + .gw-tools{width:100%;margin-left:22px} + .gw-stats{grid-template-columns:repeat(3,minmax(0,1fr))} + .gw-rename{flex-wrap:wrap}.gw-rename .nes-input{flex-basis:100%} + .gw-token{flex-direction:column} +} +[data-theme="retro"] #gateway-dialog h2{font-size:16px;line-height:1.6} +[data-theme="retro"] #gateway-dialog h3{font-size:11px;line-height:1.7} + +/* Account: change password */ +#account-dialog{width:min(440px,calc(100% - 2rem));padding:26px 28px} +.account-form{display:grid;gap:14px;margin:0} +.account-head{display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;margin-bottom:4px} +.account-head .eyebrow{font-size:11px;letter-spacing:.12em;color:var(--muted)} +#account-dialog h2{font-family:var(--display-font);font-size:22px;margin:2px 0 4px} +#account-dialog .account-head p{margin:0;font-size:13px;color:var(--muted)} +#account-close{font-size:22px;line-height:1} +.account-form label{display:grid;gap:6px;font:600 13px var(--font);color:var(--text)} +#account-dialog .account-hint{margin:-4px 0 0;font-size:12.5px;color:var(--muted)} +#account-dialog .account-message{margin:0;padding:10px 12px;border-radius:var(--small-radius);font-size:13px;font-weight:500} +#account-dialog .account-message:empty{display:none} +.account-message.is-error{background:color-mix(in srgb,#b5434c 12%,var(--surface));color:#b5434c} +.account-message.is-ok{background:color-mix(in srgb,#2f8a57 12%,var(--surface));color:#2f8a57} +#account-dialog .dialog-actions{margin-top:6px} +[data-theme="retro"] #account-dialog h2{font-size:15px;line-height:1.6} +[data-theme="linux"] .account-message.is-error{color:#f19aa1} +[data-theme="linux"] .account-message.is-ok{color:#8fd1a8} diff --git a/src/public/css/global.css b/src/public/css/global.css index 08b9ea7..b644452 100644 --- a/src/public/css/global.css +++ b/src/public/css/global.css @@ -91,7 +91,6 @@ small { display:block; font-size:12px; line-height:1.6; color:var(--muted); } .app-art { width:var(--icon-size); height:var(--icon-size); display:inline-flex; align-items:center; justify-content:center; border-radius:var(--icon-radius); background:linear-gradient(140deg,#eeedd4,#bbcda2); color:#35513b; box-shadow:var(--icon-shadow); flex-shrink:0; overflow:hidden; } .app-art svg { width:56%; height:56%; stroke-width:1.6; } [data-app-id="terminal"] .app-art { background:linear-gradient(140deg,#384e48,#172d28); color:#d4eeb3; } -[data-app-id="browser"] .app-art { background:linear-gradient(140deg,#a9e1e5,#497fba); color:#fff; } [data-app-id="paint"] .app-art { background:linear-gradient(140deg,#f9d79d,#d97e7c); color:#713d46; } [data-app-id="settings"] .app-art { background:linear-gradient(140deg,#e6e8e8,#9da9b1); color:#43535d; } .extension-art { background:linear-gradient(140deg,#efdc8e,#cbae43); color:#5d4c22; } @@ -169,9 +168,9 @@ label { display:block; } #xterm-terminal { flex:1; min-height:100px; padding:10px; overflow:hidden; } #terminal-status { color:var(--muted); font-size:12px; padding-top:14px; } #terminal-status p { margin-bottom:0; } -.browser-toolbar { padding:9px 16px; display:flex; align-items:center; gap:10px; background:var(--surface-alt); font-size:12px; } -.browser-toolbar a { margin-left:auto; font-size:11px; } -#browser iframe, #chirpstack iframe { border:0; width:100%; flex:1; min-height:0; background:white; } +.app-toolbar { padding:9px 16px; display:flex; align-items:center; gap:10px; background:var(--surface-alt); font-size:12px; } +.app-toolbar a { margin-left:auto; font-size:11px; } +#chirpstack iframe { border:0; width:100%; flex:1; min-height:0; background:white; } .app-art[data-icon="radio"] { background:linear-gradient(145deg,#259aa0,#145275); color:#fff; } .chirpstack-toolbar { flex-wrap:wrap; gap:8px; } .chirpstack-toolbar small { display:block; font-size:10px; color:var(--muted); } @@ -312,7 +311,7 @@ dialog::backdrop { background:#14232e88; backdrop-filter:blur(3px); }dialog h2 { .settings-layout { flex-direction:column; }.settings-nav { width:100%; padding:8px; flex-direction:row; gap:5px; border-right:0; border-bottom:1px solid var(--border); }.settings-identity,.settings-footnote { display:none; }.settings-nav button { flex:1; justify-content:center; gap:6px; padding:10px 6px; min-height:44px; font-size:11px; }.settings-nav button svg { width:16px; height:16px; }.settings-content { padding:22px 18px; } .theme-grid { gap:12px; }.theme-preview { height:90px; }.theme-card-title { font-size:11px; }.theme-card small { font-size:10px; }.theme-card-copy { padding:8px 4px; }.theme-check { flex-shrink:0; } .setting-row { gap:12px; }.setting-row select { max-width:110px; }.setting-row .nes-btn { padding:8px 10px; }.switch { width:44px; height:28px; }.switch::after { width:20px; height:20px; } - .browser-toolbar { flex-wrap:wrap; gap:6px; font-size:11px; }.input-row { flex-wrap:wrap; }.input-row button { flex:1; }.input-row input { flex-basis:160px; } + .app-toolbar { flex-wrap:wrap; gap:6px; font-size:11px; }.input-row { flex-wrap:wrap; }.input-row button { flex:1; }.input-row input { flex-basis:160px; } .nes-btn,.quiet-button { min-height:44px; }.extension-window .window-content { overflow-wrap:anywhere; }.extension-window .nes-container { padding:14px; } .publisher-stat { padding:16px; }.publisher-stat #streamr-last-publish { font-size:15px; } } @@ -350,8 +349,6 @@ dialog::backdrop { background:#14232e88; backdrop-filter:blur(3px); }dialog h2 { .paint-surface { overflow:auto; flex:1; min-height:0; padding:12px; background:var(--surface-muted); } #paint-canvas { display:block; width:100%; max-width:1200px; height:auto; background:#fff; touch-action:none; cursor:crosshair; } -#browser-search { display:flex; flex:1; gap:8px; min-width:0; } -#browser-query { flex:1; width:100%; min-width:0; } /* Feedback is positioned and clipped by its owning app, never the desktop. */ .app-notification-area { position:absolute; z-index:20; right:12px; bottom:12px; width:min(380px,calc(100% - 24px)); max-height:40%; overflow:auto; pointer-events:none; } @@ -363,4 +360,12 @@ dialog::backdrop { background:#14232e88; backdrop-filter:blur(3px); }dialog h2 { .app-dialog-layer > #mm-dialog { width:min(540px,100%); max-height:100%; } @media(max-width:700px) { .app-dialog-layer { padding:8px; } .app-dialog-layer > dialog.app-dialog { padding:18px; } } @media(max-height:500px) and (min-width:701px) { .app-dialog-layer { top:40px; } } -.browser-controls{flex-wrap:wrap;gap:6px}.browser-controls button,.browser-controls select{min-height:34px;background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:var(--small-radius);padding:4px 8px}.browser-controls #browser-search{min-width:180px}#browser-status{font:12px var(--font);padding:7px 12px;background:var(--surface-alt);color:var(--muted)}#browser-view{position:relative;flex:1;min-height:0;overflow:hidden;background:var(--surface);touch-action:none}#browser-canvas{display:block;width:100%;height:100%;object-fit:fill}#browser-input{position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:.01;border:0;padding:0;resize:none} + +/* Custom select arrow: a thin chevron (matching each theme's muted text) inset 14px from the + edge, with the same breathing room before it. :not() outranks toolbar rules that reset backgrounds. */ +:root{--select-arrow:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%2364736a' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +:root[data-theme="macos"]{--select-arrow:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23797182' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +:root[data-theme="linux"]{--select-arrow:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23afb6c4' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +:root[data-theme="windows"]{--select-arrow:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%2364748b' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +select:not([multiple]):not([size]){appearance:none;-webkit-appearance:none;padding-right:36px; + background-image:var(--select-arrow);background-position:right 14px center;background-size:10px 6px;background-repeat:no-repeat} diff --git a/src/public/js/account.js b/src/public/js/account.js new file mode 100644 index 0000000..fb9897d --- /dev/null +++ b/src/public/js/account.js @@ -0,0 +1,63 @@ +(() => { + const $=id=>document.getElementById(id); + const dialog=$('account-dialog'),form=$('password-form'),message=$('password-message'),submit=$('password-submit'); + if(!dialog||!form)return; + const show=(text,kind)=>{message.textContent=text||'';message.className=`account-message${kind?` is-${kind}`:''}`;}; + + // Account menu in the top bar: who is signed in, change password, sign out. + const button=$('account-menu-button'),menu=$('account-menu'); + const items=()=>[...menu.querySelectorAll('[role="menuitem"]')]; + function setMenu(open){ + if(open===!menu.hidden)return; + menu.hidden=!open;button.setAttribute('aria-expanded',String(open)); + if(open){document.dispatchEvent(new CustomEvent('topbar:menu',{detail:'account'}));requestAnimationFrame(()=>items()[0]?.focus());} + } + button.onclick=()=>setMenu(menu.hidden); + menu.addEventListener('keydown',event=>{ + if(event.key==='Escape'){event.stopPropagation();setMenu(false);button.focus();return;} + if(!['ArrowDown','ArrowUp'].includes(event.key))return; + const list=items(),index=list.indexOf(document.activeElement); + event.preventDefault();list[(index+(event.key==='ArrowDown'?1:-1)+list.length)%list.length].focus(); + }); + document.addEventListener('pointerdown',event=>{if(!menu.hidden&&!menu.contains(event.target)&&!button.contains(event.target))setMenu(false);}); + document.addEventListener('topbar:menu',event=>{if(event.detail!=='account')setMenu(false);}); + document.addEventListener('keydown',event=>{if(event.key==='Escape'&&!menu.hidden&&!document.querySelector('dialog[open]')){setMenu(false);button.focus();}}); + + let username=''; + void fetch('/api/account').then(response=>{ + if(response.status===401){location.assign('/login');return null;}return response.json(); + }).then(result=>{ + if(!result?.username)return;username=result.username; + const initial=username.charAt(0).toUpperCase(); + $('account-initial').textContent=initial;$('account-menu-initial').textContent=initial; + $('account-menu-name').textContent=username;button.setAttribute('aria-label',`Account menu for ${username}`); + }).catch(()=>{/* The menu still works without the name. */}); + + $('open-account').onclick=()=>{ + setMenu(false);form.reset();show('');submit.disabled=false; + $('account-user').textContent=username?`Signed in as ${username}`:'Signed in to the central workspace';$('account-username').value=username; + dialog.showModal();form.elements.current.focus(); + }; + for(const id of ['account-close','account-cancel'])$(id).onclick=()=>dialog.close(); + // Passwords never linger in a closed dialog. + dialog.addEventListener('close',()=>{form.reset();show('');}); + form.elements.confirm.addEventListener('input',()=>form.elements.confirm.setCustomValidity('')); + + form.onsubmit=async event=>{ + event.preventDefault(); + const current=form.elements.current.value,next=form.elements.next.value,confirm=form.elements.confirm.value; + if(next.length<7){show('The new password needs at least 7 characters.','error');form.elements.next.focus();return;} + if(next!==confirm){show('The new passwords don’t match.','error');form.elements.confirm.focus();return;} + if(next===current){show('Choose a new password that differs from the current one.','error');form.elements.next.focus();return;} + submit.disabled=true;show(''); + try{ + const response=await fetch('/api/account/password',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({current,next})}); + if(response.status===401){location.assign('/login');return;} + const result=await response.json().catch(()=>({})); + if(!response.ok){show(result.error||'The password could not be changed.','error'); + if(/current/i.test(result.error||'')){form.elements.current.value='';form.elements.current.focus();}return;} + form.reset();show('Password changed. Other devices signed in to this account were signed out.','ok'); + }catch{show('Couldn’t reach central. Check your connection and try again.','error');} + finally{submit.disabled=false;} + }; +})(); diff --git a/src/public/js/browser.js b/src/public/js/browser.js deleted file mode 100644 index aafd0b8..0000000 --- a/src/public/js/browser.js +++ /dev/null @@ -1,53 +0,0 @@ -(() => { - const win=document.getElementById('browser'),view=document.getElementById('browser-view'),canvas=document.getElementById('browser-canvas'),input=document.getElementById('browser-input'); - const query=document.getElementById('browser-query'),status=document.getElementById('browser-status'); - let socket,ready=false,remoteWidth=1024,remoteHeight=700,framePending=false; - const send=value=>{if(socket?.readyState===WebSocket.OPEN)socket.send(JSON.stringify(value));}; - const size=()=>{if(ready)send({type:'resize',width:Math.round(view.clientWidth),height:Math.round(view.clientHeight)});}; - function open(){ - if(socket&&[WebSocket.OPEN,WebSocket.CONNECTING].includes(socket.readyState))return; - status.textContent='Starting isolated Browser…'; - socket=new WebSocket(`${location.protocol==='https:'?'wss:':'ws:'}//${location.host}/browser/live`); - socket.onmessage=event=>{ - const message=JSON.parse(event.data); - if(message.type==='closed'&&ready){ready=false;status.textContent='Browser session ended. Close and reopen to start a new session.';} - if(message.type==='ready'){ready=true;status.textContent='Ready. Search or enter an address. Downloads and uploads are disabled.';size();} - if(message.type==='error'||message.type==='notice')status.textContent=message.message; - if(message.type==='loading')status.textContent=message.value?'Loading…':'Ready'; - if(message.type==='navigation'){ - if(message.url&&message.url!=='about:blank'&&document.activeElement!==query)query.value=message.url; - if(message.title){win.dataset.gatewayBaseTitle=`${message.title} · Browser`;const title=win.dataset.gatewayBaseTitle+(win.dataset.gatewayName?` · ${win.dataset.gatewayName}`:'');win.dataset.windowTitle=title;win.querySelector('.window-title').textContent=title;document.title=`${title} · M3tering Console`;} - } - if(message.type==='frame'&&!framePending){framePending=true;const image=new Image();image.onload=()=>{canvas.width=remoteWidth=image.width;canvas.height=remoteHeight=image.height;canvas.getContext('2d').drawImage(image,0,0);framePending=false;};image.onerror=()=>{framePending=false;};image.src=`data:image/jpeg;base64,${message.data}`;} - if(message.type==='clipboard')navigator.clipboard.writeText(message.text).then(()=>{status.textContent='Selected text copied.';}).catch(()=>{status.textContent='Clipboard permission unavailable.';}); - }; - socket.onclose=()=>{ready=false;if(status.textContent==='Starting isolated Browser…')status.textContent='Browser engine not available. Install the optional Chromium browser image.';}; - socket.onerror=()=>{status.textContent='Browser connection unavailable. Close and reopen the application to retry.';}; - } - document.getElementById('browser-search').onsubmit=event=>{event.preventDefault();try{if(/^[a-z][a-z0-9+.-]*:\/\//i.test(query.value)){const url=new URL(query.value);if(!['http:','https:'].includes(url.protocol)||url.username||url.password)throw new Error('Use an HTTP or HTTPS address without credentials.');}}catch(error){showNotification(error.message,'error',win);return;}if(ready)send({type:'navigate',url:query.value});else status.textContent='Browser engine not available yet.';}; - for(const [id,value] of [['back',{type:'history',direction:-1}],['forward',{type:'history',direction:1}],['reload',{type:'reload'}],['stop',{type:'stop'}],['home',{type:'navigate',url:'https://www.google.com/'}],['copy',{type:'copy'}]])document.getElementById(`browser-${id}`).onclick=()=>send(value); - document.getElementById('browser-zoom').onchange=event=>send({type:'zoom',factor:Number(event.target.value)}); - const point=event=>{const rect=canvas.getBoundingClientRect();return {x:(event.clientX-rect.left)*remoteWidth/rect.width,y:(event.clientY-rect.top)*remoteHeight/rect.height};}; - const button=event=>['left','middle','right'][event.button]||'none'; - let touch; - view.onpointerdown=event=>{if(!ready)return;event.preventDefault();input.focus({preventScroll:true});view.setPointerCapture(event.pointerId);if(event.pointerType==='touch'){touch={x:event.clientX,y:event.clientY,start:point(event),moved:false};return;}send({type:'pointer',event:'mousePressed',...point(event),button:button(event),clicks:event.detail||1});}; - view.onpointermove=event=>{if(touch){const dx=touch.x-event.clientX,dy=touch.y-event.clientY;if(touch.moved||Math.abs(dx)+Math.abs(dy)>6){touch.moved=true;send({type:'pointer',event:'mouseWheel',...point(event),dx,dy});touch.x=event.clientX;touch.y=event.clientY;}return;}if(ready)send({type:'pointer',event:'mouseMoved',...point(event),button:event.buttons?'left':'none'});}; - view.onpointercancel=()=>{touch=undefined;}; - view.onpointerup=event=>{if(touch){if(!touch.moved){send({type:'pointer',event:'mousePressed',...touch.start,button:'left',clicks:1});send({type:'pointer',event:'mouseReleased',...touch.start,button:'left',clicks:1});}touch=undefined;return;}if(ready)send({type:'pointer',event:'mouseReleased',...point(event),button:button(event),clicks:event.detail||1});}; - view.addEventListener('wheel',event=>{event.preventDefault();send({type:'pointer',event:'mouseWheel',...point(event),dx:event.deltaX,dy:event.deltaY});},{passive:false}); - view.oncontextmenu=event=>event.preventDefault(); - input.addEventListener('input',event=>{if(event.isComposing)return;if(input.value)send({type:'text',text:input.value});input.value='';}); - input.addEventListener('compositionend',()=>{if(input.value)send({type:'text',text:input.value});input.value='';}); - input.addEventListener('paste',event=>{event.preventDefault();send({type:'text',text:event.clipboardData.getData('text').slice(0,8192)});}); - for(const name of ['keydown','keyup'])input.addEventListener(name,event=>{ - if(event.isComposing)return; - if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='c'){event.preventDefault();if(name==='keydown')send({type:'copy'});return;} - if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='v')return; - if(event.key.length===1&&!event.ctrlKey&&!event.metaKey&&!event.altKey)return; - event.preventDefault();send({type:'key',event:name==='keydown'?'keyDown':'keyUp',key:event.key,code:event.code,keyCode:event.keyCode,modifiers:(event.altKey?1:0)|(event.ctrlKey?2:0)|(event.metaKey?4:0)|(event.shiftKey?8:0)}); - }); - new ResizeObserver(size).observe(view); - window.addEventListener('desktop:open',event=>{if(event.detail.id==='browser')open();}); - window.addEventListener('desktop:close',event=>{if(event.detail.id==='browser'){socket?.close();socket=undefined;ready=false;}}); - window.addEventListener('pagehide',()=>socket?.close()); -})(); diff --git a/src/public/js/desktop.js b/src/public/js/desktop.js index b914c98..2ac5817 100644 --- a/src/public/js/desktop.js +++ b/src/public/js/desktop.js @@ -11,7 +11,6 @@ radio: '', meter: '', terminal: '', - browser: '', paint: '', settings: '', appearance: '', diff --git a/src/public/js/gateways.js b/src/public/js/gateways.js index b1a10b3..138200b 100644 --- a/src/public/js/gateways.js +++ b/src/public/js/gateways.js @@ -1,65 +1,266 @@ (() => { - const select=document.getElementById('gateway-select'),dialog=document.getElementById('gateway-dialog'),list=document.getElementById('gateway-list'); - let gateways=[],selected=null,busy=false; - const error=message=>{document.getElementById('gateway-error').textContent=message;}; + const $=id=>document.getElementById(id); + const switcher=$('gateway-switcher'),menu=$('gateway-menu'),options=$('gateway-options'),dialog=$('gateway-dialog'),list=$('gateway-list'),confirmDialog=$('gateway-confirm'); + const NETWORK_APPS=['terminal','chirpstack'],TOKEN_LIFETIME=10*60000,CENTRAL_NAME='Central server'; + let gateways=[],selected=null,busy=false,again=false,editing=null,focusRename=false,tokenTimer=null; + const openUpdates=new Set(); + + const error=message=>{$('gateway-error').textContent=message||'';}; async function api(path,body){ const response=await fetch(path,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined}); if(response.status===401){location.assign('/login');throw new Error('Session expired.');} const result=await response.json();if(!response.ok)throw new Error(result.error||'Gateway request failed.');return result; } + // Small DOM builder; all user-provided text goes through textContent. + function el(tag,props={},...children){ + const node=document.createElement(tag); + for(const [key,value] of Object.entries(props)){ + if(value===undefined||value===false)continue; + if(key==='class')node.className=value;else if(key==='text')node.textContent=value; + else if(key.startsWith('on'))node[key]=value;else if(key in node&&key!=='list')node[key]=value;else node.setAttribute(key,value===true?'':value); + } + node.append(...children.filter(child=>child!==null&&child!==undefined&&child!==false));return node; + } + function ago(time){ + if(!time)return 'Never connected'; + const seconds=Math.max(0,Math.round((Date.now()-time)/1000)); + if(seconds<60)return 'Seen just now';if(seconds<3600)return `Seen ${Math.round(seconds/60)} min ago`; + if(seconds<86400)return `Seen ${Math.round(seconds/3600)} h ago`;return `Seen ${Math.round(seconds/86400)} d ago`; + } + function state(g){ + if(g.revoked)return ['revoked','Access revoked']; + if(!g.enrolled)return ['pending','Waiting to connect']; + return g.online?['online','Online']:['offline','Offline']; + } + function confirmAction({title,body,action}){ + $('gateway-confirm-title').textContent=title;$('gateway-confirm-body').textContent=body;$('gateway-confirm-action').textContent=action; + confirmDialog.returnValue='';confirmDialog.showModal(); + return new Promise(resolve=>confirmDialog.addEventListener('close',()=>resolve(confirmDialog.returnValue==='confirm'),{once:true})); + } + async function run(work){ + error(''); + try{await work();}catch(e){error(e.message);} + await refresh(); + } + function title(id){ - const win=document.getElementById(id),gateway=gateways.find(g=>g.id===selected);if(!win||!gateway)return; + const win=$(id);if(!win)return; + // With no gateway selected, network apps work on the central server itself. + const name=gateways.find(g=>g.id===selected)?.name||CENTRAL_NAME; win.dataset.gatewayBaseTitle ||= win.dataset.windowTitle; - win.dataset.gatewayName=gateway.name; - win.dataset.windowTitle=`${win.dataset.gatewayBaseTitle} · ${gateway.name}`; + win.dataset.gatewayName=name; + win.dataset.windowTitle=`${win.dataset.gatewayBaseTitle} · ${name}`; const label=win.querySelector('.window-title');if(label)label.textContent=win.dataset.windowTitle; document.title=`${win.dataset.windowTitle} · M3tering Console`; - document.getElementById('active-app-name').textContent=win.dataset.windowTitle; + $('active-app-name').textContent=win.dataset.windowTitle; } - function render(){ - select.replaceChildren(new Option('Select a gateway','')); - for(const gateway of gateways)if(!gateway.revoked)select.add(new Option(`${gateway.name}${gateway.online?'':' · offline'}`,gateway.id)); - select.value=selected||''; - const current=gateways.find(g=>g.id===selected),h=current?.health; - document.getElementById('gateway-status').textContent=current?`${current.name} · ${current.online?'Agent connected':'Agent offline'} · ${h?.uncertain||0} uncertain seen · ${h?.reconciled||0} reconciled · ${h?.superseded||0} superseded · ${h?.queueDepth||0} pending`:'Choose a gateway to access its applications.'; - list.replaceChildren(); - for(const g of gateways){ - const item=document.createElement('article'),name=document.createElement('strong'),status=document.createElement('p'),actions=document.createElement('div'); - name.textContent=g.name;const s=g.health; - status.textContent=`${g.revoked?'Revoked':g.online?'Connected':'Offline'} · MQTT ${s?.mqtt||'unknown'} · ${s?.queueDepth||0} pending · ${s?.uncertain||0} uncertain seen · ${s?.reconciled||0} reconciled · ${s?.superseded||0} superseded`; - for(const [action,label] of [['rotate','Rotate credential'],['revoke','Revoke access'],['enrollment','New enrollment']]){ - const button=document.createElement('button');button.className='nes-btn';button.textContent=label; - button.disabled=action==='rotate'&&(!g.online||g.revoked); - button.onclick=async()=>{try{const result=await api(`/api/gateways/${encodeURIComponent(g.id)}/${action}`,{});if(result.token)showToken(result.token);await refresh();}catch(e){error(e.message);}}; - actions.append(button); - } - const updates=document.createElement('div'),note=document.createElement('p'); - note.textContent=s?.updatesEnabled?'Remote updates enabled locally. Both Console and agent restart together.':'Updates disabled locally.';updates.append(note); - if(s?.updatesEnabled){ - const form=document.createElement('form'),image=document.createElement('input'),confirm=document.createElement('input'),label=document.createElement('label'),button=document.createElement('button'); - image.placeholder='ghcr.io/owner/console@sha256:…';image.required=true;image.setAttribute('aria-label',`Image digest for ${g.name}`);image.style.width='100%'; - confirm.type='checkbox';confirm.required=true;label.append(confirm,document.createTextNode(' Restart this gateway’s Console and agent')); - button.className='nes-btn';button.textContent='Queue signed update';button.disabled=!g.online; - form.append(image,label,button);form.onsubmit=async event=>{event.preventDefault();try{await api(`/api/gateways/${g.id}/updates`,{image:image.value.trim()});await refresh();}catch(e){error(e.message);}};updates.append(form); - } - for(const job of g.updates||[]){const row=document.createElement('p');row.textContent=`${job.status} · ${job.image}`;row.style.overflowWrap='anywhere'; - if(job.status==='queued'){const cancel=document.createElement('button');cancel.className='nes-btn';cancel.textContent='Cancel';cancel.onclick=async()=>{try{await api(`/api/gateways/${g.id}/updates/${job.id}/cancel`,{});await refresh();}catch(e){error(e.message);}};row.append(cancel);}updates.append(row); - } - item.append(name,status,actions,updates);list.append(item); + + const statTiles=(g)=>{ + const s=g.health||{},stat=(name,value,hint)=>el('div',{class:'gw-stat',title:hint},el('dt',{text:name}),el('dd',{text:String(value)})); + return el('dl',{class:'gw-stats','aria-label':`${g.name} activity`}, + stat('MQTT',s.mqtt||'—','Broker connection reported by the agent'), + stat('Pending',s.queueDepth||0,'Reports waiting for a decision'), + stat('Uncertain',s.uncertain||0,'Replies held for reconciliation (uncertain seen)'), + stat('Reconciled',s.reconciled||0,'Uncertain replies later resolved'), + stat('Superseded',s.superseded||0,'Replies replaced by a newer report')); + }; + // Top bar switcher and its menu: the only place the selected gateway's status is shown. + function renderSelector(){ + const current=gateways.find(g=>g.id===selected),online=gateways.filter(g=>g.online).length; + const summary=gateways.length?`${gateways.length} gateway${gateways.length===1?'':'s'} · ${online} online`:'No gateways yet'; + $('gateway-summary').textContent=summary;$('gateway-menu-summary').textContent=summary; + $('gateway-switcher-name').textContent=current?current.name:CENTRAL_NAME; + switcher.querySelector('.gw-switcher-label').textContent=current?'Gateway':'No gateway'; + switcher.dataset.state=current?state(current)[0]:'central'; + switcher.setAttribute('aria-label',current?`Gateway: ${current.name}, ${state(current)[1]}. Open gateway menu`:'No gateway selected; apps open on the central server. Open gateway menu'); + const card=$('gateway-current'); + if(current){ + const [kind,label]=state(current); + card.replaceChildren(el('div',{class:'gw-current-head','data-state':kind}, + el('span',{class:'gw-dot','aria-hidden':'true'}), + el('div',{class:'gw-title'},el('strong',{class:'gw-name',text:current.name}), + el('small',{text:[current.version&&`v${current.version}`,ago(current.lastHeartbeat)].filter(Boolean).join(' · ')})), + el('span',{class:'gw-pill gw-state',text:label})), + current.health?statTiles(current):el('p',{class:'gw-muted',text:'Activity appears once the agent reports in.'})); + } else card.replaceChildren(el('div',{class:'gw-current-head','data-state':'central'}, + el('span',{class:'gw-dot','aria-hidden':'true'}), + el('div',{class:'gw-title'},el('strong',{class:'gw-name',text:CENTRAL_NAME}),el('small',{text:'No gateway selected'}))), + el('p',{class:'gw-current-empty',text:'Terminal and ChirpStack open on the central server. Choose a gateway to work on it instead.'})); + const choices=gateways.filter(g=>!g.revoked); + // A refresh rebuilds the list; keep keyboard focus on the same option. + const focused=options.contains(document.activeElement)?document.activeElement.dataset.gateway:null; + const central=el('button',{class:'gw-option','data-state':'central',role:'option','aria-selected':String(!current),'data-gateway':'', + onclick:()=>void chooseGateway(null)}, + el('span',{class:'gw-dot','aria-hidden':'true'}), + el('span',{class:'gw-option-text'},el('strong',{text:CENTRAL_NAME}),el('small',{text:'No gateway · use this server'})), + !current&&el('span',{class:'gw-check','aria-hidden':'true',text:'✓'})); + options.replaceChildren(central,...(choices.length?choices.map(g=>{ + const [kind,label]=state(g),isSelected=g.id===selected; + return el('button',{class:'gw-option','data-state':kind,role:'option','aria-selected':String(isSelected),'data-gateway':g.id, + onclick:()=>void chooseGateway(g.id)}, + el('span',{class:'gw-dot','aria-hidden':'true'}), + el('span',{class:'gw-option-text'},el('strong',{text:g.name}),el('small',{text:g.online?label:`${label} · ${ago(g.lastHeartbeat)}`})), + isSelected&&el('span',{class:'gw-check','aria-hidden':'true',text:'✓'})); + }):[el('p',{class:'gw-current-empty',text:'No gateways yet. Use Manage gateways to add one.'})])); + if(focused!==null&&focused!==undefined)options.querySelector(`[data-gateway="${CSS.escape(focused)}"]`)?.focus(); + } + function placeMenu(){ + // Phones get a full-width sheet from CSS; wider screens anchor the panel under the switcher. + if(innerWidth<640){menu.style.left='';return;} + const rect=switcher.getBoundingClientRect(),width=menu.offsetWidth||380; + menu.style.left=`${Math.max(8,Math.min(innerWidth-width-8,rect.left+rect.width/2-width/2))}px`; + } + function setMenu(open){ + if(open===!menu.hidden)return; + menu.hidden=!open;switcher.setAttribute('aria-expanded',String(open)); + if(open){document.dispatchEvent(new CustomEvent('topbar:menu',{detail:'gateway'}));placeMenu();void refresh(); + requestAnimationFrame(()=>(options.querySelector('[aria-selected="true"]')||options.querySelector('button')||$('manage-gateways')).focus());} + } + async function chooseGateway(id){ + // null deselects the gateway. + if(id===selected){setMenu(false);switcher.focus();return;} + for(const app of NETWORK_APPS)Desktop.close(app); + try{await api('/api/gateways/select',{id});await refresh();setMenu(false);switcher.focus();} + catch(e){$('gateway-menu-summary').textContent=e.message;} + } + function stopEditing(){editing=null;if(list.contains(document.activeElement))document.activeElement.blur();} + function startEditing(id){editing=id;focusRename=true;render();} + function renameForm(g){ + const input=el('input',{class:'nes-input',value:g.name,maxLength:100,required:true,'aria-label':`New name for ${g.name}`,autocomplete:'off'}); + const form=el('form',{class:'gw-rename',onsubmit:event=>{event.preventDefault(); + const name=input.value.trim();if(!name||name===g.name){stopEditing();render();return;} + void run(async()=>{await api(`/api/gateways/${encodeURIComponent(g.id)}/rename`,{name});stopEditing();}); + }},input,el('button',{class:'nes-btn is-primary',text:'Save'}), + el('button',{class:'nes-btn',type:'button',text:'Cancel',onclick:()=>{stopEditing();render();}})); + input.addEventListener('keydown',event=>{if(event.key==='Escape'){event.preventDefault();event.stopPropagation();stopEditing();render();}}); + if(focusRename){focusRename=false;requestAnimationFrame(()=>{input.focus();input.select();});} + return form; + } + + function updatesPanel(g){ + const s=g.health,enabled=!!s?.updatesEnabled; + const details=el('details',{class:'gw-updates',open:openUpdates.has(g.id)}, + el('summary',{},el('span',{text:'Remote updates'}),el('span',{class:`gw-pill ${enabled?'is-on':''}`,text:enabled?'Enabled':'Disabled on gateway'}))); + details.addEventListener('toggle',()=>{details.open?openUpdates.add(g.id):openUpdates.delete(g.id);}); + if(!enabled)details.append(el('p',{class:'gw-muted',text:'The gateway owner enables remote updates locally. Central cannot turn this on.'})); + else{ + const image=el('input',{class:'nes-input',placeholder:'ghcr.io/owner/console@sha256:…',required:true,'aria-label':`Image digest for ${g.name}`}); + const check=el('input',{type:'checkbox',required:true}); + details.append(el('form',{class:'gw-update-form',onsubmit:event=>{event.preventDefault(); + void run(()=>api(`/api/gateways/${encodeURIComponent(g.id)}/updates`,{image:image.value.trim()}));}}, + image,el('label',{class:'gw-check'},check,el('span',{text:'Restart this gateway’s Console and agent'})), + el('button',{class:'nes-btn is-primary',text:'Queue signed update',disabled:!g.online}))); + } + for(const job of g.updates||[]){ + details.append(el('div',{class:'gw-job'},el('span',{class:'gw-pill',text:job.status}),el('code',{text:job.image}), + job.status==='queued'&&el('button',{class:'nes-btn',text:'Cancel',onclick:()=>void run(()=>api(`/api/gateways/${encodeURIComponent(g.id)}/updates/${encodeURIComponent(job.id)}/cancel`,{}))}))); + } + return details; + } + + function card(g){ + const [kind,label]=state(g),s=g.health||{},id=encodeURIComponent(g.id); + const heading=editing===g.id?renameForm(g):el('div',{class:'gw-title'}, + el('strong',{class:'gw-name',text:g.name}), + el('small',{text:[g.version&&`v${g.version}`,ago(g.lastHeartbeat)].filter(Boolean).join(' · ')})); + const tools=editing===g.id?null:el('div',{class:'gw-tools'}, + el('button',{class:'quiet-button',text:'Rename','aria-label':`Rename ${g.name}`,onclick:()=>startEditing(g.id)}), + el('button',{class:'quiet-button gw-danger',text:'Delete','aria-label':`Delete ${g.name}`,onclick:()=>void deleteGateway(g)})); + const stats=statTiles(g); + const actions=el('div',{class:'gw-actions'}); + if(g.enrolled&&!g.revoked){ + actions.append(el('button',{class:'nes-btn',text:'Rotate credential',disabled:!g.online,title:g.online?undefined:'The gateway must be online to rotate', + onclick:()=>void run(()=>api(`/api/gateways/${id}/rotate`,{}))}), + el('button',{class:'nes-btn',text:'Revoke access',onclick:async()=>{ + if(await confirmAction({title:`Revoke ${g.name}?`,body:'The agent is disconnected immediately and its credential stops working. You can reconnect it later with a new enrollment token.',action:'Revoke access'})) + await run(()=>api(`/api/gateways/${id}/revoke`,{}));}})); + } else { + actions.append(el('button',{class:'nes-btn is-primary',text:g.revoked?'Re-enroll with new token':'New enrollment token', + onclick:()=>void run(async()=>{const result=await api(`/api/gateways/${id}/enrollment`,{});showToken(result.token,g.name);})})); } + return el('article',{class:'gw-card','data-state':kind,'data-gateway':g.id}, + el('div',{class:'gw-card-head'},el('span',{class:'gw-dot','aria-hidden':'true'}),heading,el('span',{class:'gw-pill gw-state',text:label}),tools), + // Activity and updates only mean something once an agent has reported in. + g.health&&stats,actions,g.enrolled&&!g.revoked&&updatesPanel(g)); + } + + function render(){ + renderSelector(); + // Don't rebuild the list under someone who is typing in it (rename, image digest). + const active=document.activeElement; + if(list.contains(active)&&active.matches('input,select,textarea')&&active.type!=='checkbox')return; + if(!gateways.length){list.replaceChildren(el('div',{class:'gw-empty'},el('strong',{text:'No gateways yet'}),el('p',{text:'Add your first gateway above to get its enrollment token.'})));return;} + list.replaceChildren(...gateways.map(card)); } - async function refresh(){if(busy)return;busy=true;try{const result=await api('/api/gateways');gateways=result.gateways;selected=result.selected;render();}catch(e){error(e.message);}finally{busy=false;}} - function showToken(token){document.getElementById('gateway-enrollment').hidden=false;document.getElementById('gateway-enrollment-token').textContent=token;} - select.onchange=async()=>{ - const id=select.value;if(!id)return; - for(const app of ['terminal','chirpstack','browser'])Desktop.close(app); - try{await api('/api/gateways/select',{id});await refresh();}catch(e){error(e.message);select.value=selected||'';} + + async function refresh(){ + if(busy){again=true;return;}busy=true; + try{const result=await api('/api/gateways');gateways=result.gateways;selected=result.selected; + if(editing&&!gateways.some(g=>g.id===editing))editing=null;render();} + catch(e){error(e.message);} + finally{busy=false;if(again){again=false;void refresh();}} + } + + async function deleteGateway(g){ + const ok=await confirmAction({title:`Delete ${g.name}?`, + body:'The gateway is disconnected, its credential is destroyed and it disappears from this list. Billing records and audit history are kept. To use the device again, add it as a new gateway.', + action:'Delete gateway'}); + if(!ok)return; + await run(async()=>{ + await api(`/api/gateways/${encodeURIComponent(g.id)}/delete`,{}); + if(g.id===selected)for(const app of NETWORK_APPS)Desktop.close(app); + openUpdates.delete(g.id); + }); + } + + function clearToken(){ + clearInterval(tokenTimer);tokenTimer=null; + $('gateway-enrollment-token').textContent='';$('gateway-enrollment').hidden=true; + } + function showToken(token,name){ + clearInterval(tokenTimer); + const expires=Date.now()+TOKEN_LIFETIME,expiry=$('gateway-enrollment-expiry'); + $('gateway-enrollment-name').textContent=name||'your gateway'; + $('gateway-enrollment-url').textContent=`wss://${location.host}`; + $('gateway-enrollment-token').textContent=token;$('gateway-enrollment').hidden=false; + const tick=()=>{const left=Math.max(0,expires-Date.now()); + expiry.textContent=left?`Expires in ${Math.floor(left/60000)}:${String(Math.floor(left/1000)%60).padStart(2,'0')}`:'Expired: create a new token'; + expiry.classList.toggle('is-expired',!left);if(!left)clearInterval(tokenTimer);}; + tick();tokenTimer=setInterval(tick,1000); + $('gateway-enrollment').scrollIntoView({block:'nearest',behavior:'smooth'}); + } + + switcher.onclick=()=>setMenu(menu.hidden); + $('gateway-menu-close').onclick=()=>{setMenu(false);switcher.focus();}; + menu.addEventListener('keydown',event=>{ + if(event.key==='Escape'){event.stopPropagation();setMenu(false);switcher.focus();return;} + if(!['ArrowDown','ArrowUp'].includes(event.key))return; + const items=[...options.querySelectorAll('button')];const index=items.indexOf(document.activeElement);if(!items.length)return; + event.preventDefault();items[(index+(event.key==='ArrowDown'?1:-1)+items.length)%items.length].focus(); + }); + document.addEventListener('pointerdown',event=>{if(!menu.hidden&&!menu.contains(event.target)&&!switcher.contains(event.target))setMenu(false);}); + // Escape closes the menu wherever focus is, except inside an open dialog, which handles its own. + document.addEventListener('keydown',event=>{if(event.key==='Escape'&&!menu.hidden&&!document.querySelector('dialog[open]')){setMenu(false);switcher.focus();}}); + document.addEventListener('topbar:menu',event=>{if(event.detail!=='gateway')setMenu(false);}); + addEventListener('resize',()=>{if(!menu.hidden)placeMenu();}); + $('manage-gateways').onclick=()=>{setMenu(false);dialog.showModal();refresh();}; + $('gateway-dialog-close').onclick=()=>dialog.close(); + // The enrollment secret never outlives the dialog. + dialog.addEventListener('close',()=>{clearToken();editing=null;error('');}); + $('gateway-enrollment-dismiss').onclick=clearToken; + $('gateway-copy-token').onclick=async event=>{ + const button=event.currentTarget; + const lines=[...$('gateway-enrollment').querySelectorAll('.gw-token-line')].map(line=>line.textContent).join('\n'); + try{await navigator.clipboard.writeText(lines); + button.textContent='Copied';setTimeout(()=>{button.textContent='Copy';},1500);} + catch{error('Select and copy the token manually.');} + }; + $('gateway-create').onsubmit=async event=>{ + event.preventDefault();const form=event.target,name=String(new FormData(form).get('name')||'').trim(); + await run(async()=>{const result=await api('/api/gateways',{name});showToken(result.token,result.name);form.reset();}); }; - document.getElementById('manage-gateways').onclick=()=>{dialog.showModal();refresh();}; - document.getElementById('gateway-dialog-close').onclick=()=>dialog.close(); - dialog.addEventListener('close',()=>{document.getElementById('gateway-enrollment-token').textContent='';document.getElementById('gateway-enrollment').hidden=true;}); - document.getElementById('gateway-copy-token').onclick=()=>navigator.clipboard.writeText(document.getElementById('gateway-enrollment-token').textContent).catch(()=>error('Select and copy the token manually.')); - document.getElementById('gateway-create').onsubmit=async event=>{event.preventDefault();try{const result=await api('/api/gateways',{name:new FormData(event.target).get('name')});showToken(result.token);event.target.reset();await refresh();}catch(e){error(e.message);}}; - window.addEventListener('desktop:open',event=>{if(['terminal','chirpstack','browser'].includes(event.detail.id))title(event.detail.id);}); - const timer=setInterval(refresh,5000);window.addEventListener('pagehide',()=>clearInterval(timer));refresh(); + window.addEventListener('desktop:open',event=>{if(NETWORK_APPS.includes(event.detail.id))title(event.detail.id);}); + // Keep titles of already-open network apps in step with a rename. + const retitle=()=>{for(const app of NETWORK_APPS)if($(app)&&!$(app).hidden)title(app);}; + const timer=setInterval(()=>{void refresh().then(retitle);},5000);window.addEventListener('pagehide',()=>clearInterval(timer));refresh(); })(); diff --git a/src/services/chirpstack.ts b/src/services/chirpstack.ts index ea925f5..7444843 100644 --- a/src/services/chirpstack.ts +++ b/src/services/chirpstack.ts @@ -44,10 +44,10 @@ function unavailable(res: Response, configuration = false): void { export function proxyChirpstack(req: Request, res: Response): void { proxy(req,res); } -export function proxyChirpstackThrough(req:Request,res:Response,target:URL,agent:http.Agent):void { +export function proxyChirpstackThrough(req:Request,res:Response,target:URL,agent?:http.Agent):void { proxy(req,res,{target,agent}); } -function proxy(req:Request,res:Response,transport?:{target:URL;agent:http.Agent}):void { +function proxy(req:Request,res:Response,transport?:{target:URL;agent?:http.Agent}):void { res.setHeader('Cache-Control', 'no-store'); res.setHeader('Referrer-Policy', 'no-referrer'); res.setHeader('X-Frame-Options', 'SAMEORIGIN'); @@ -68,9 +68,10 @@ function proxy(req:Request,res:Response,transport?:{target:URL;agent:http.Agent} delete headers.referer; for (const name of Object.keys(headers)) if (name.startsWith('x-forwarded-') || name === 'forwarded') delete headers[name]; if (!/^Bearer /i.test(headers.authorization || '')) delete headers.authorization; - const wireTarget=new URL(target.href);if(transport)wireTarget.protocol='http:'; + // A tunnel agent already carries TLS (when needed), so the HTTP client must not wrap it again. + const wireTarget=new URL(target.href);if(transport?.agent)wireTarget.protocol='http:'; const upstream = (wireTarget.protocol === 'https:' ? https : http).request(wireTarget, { - method: req.method, path: req.url, headers, ...(transport?{agent:transport.agent}:{}), + method: req.method, path: req.url, headers, ...(transport?.agent?{agent:transport.agent}:{}), }, response => { const responseHeaders = cleanHeaders(response.headers); for (const name of ['set-cookie', 'www-authenticate', 'content-security-policy', 'content-security-policy-report-only', 'x-frame-options', 'cache-control', 'etag', 'last-modified']) delete responseHeaders[name]; diff --git a/src/services/server.ts b/src/services/server.ts index 5d0b07d..dfe1c77 100644 --- a/src/services/server.ts +++ b/src/services/server.ts @@ -6,8 +6,8 @@ import { proxyChirpstack, proxyChirpstackThrough } from './chirpstack'; import { createLogger } from '../utils/logger'; import { getUIComponents, invokeUIAction } from '../lib/utils'; import { central, config } from '../central/runtime'; -import { attachBrowser } from '../browser/service'; -import { protectBrowserSockets } from './socket-router'; +import { centralChirpstackUrl } from '../central/config'; +import { protectSessionSockets } from './socket-router'; const logger = createLogger('[server]'); export const app: Express = express(); @@ -30,7 +30,15 @@ app.set('views', './src/views'); central?.auth.mount(app,central.hub.machineRoutes); const gatewayHub=central?.hub; app.use('/chirpstack', gatewayHub ? (req,res) => { - const gateway=gatewayHub.selected(req);if(!gateway){res.status(409).send('Select a gateway first.');return;} + const gateway=gatewayHub.selected(req); + if(!gateway){ + // No gateway selected: show the ChirpStack dashboard configured for central. + let dashboard:URL|undefined,invalid=false;try{dashboard=centralChirpstackUrl();}catch{invalid=true;} + if(dashboard){proxyChirpstackThrough(req,res,dashboard);return;} + const heading=invalid?'CENTRAL_CHIRPSTACK_URL is not a valid address':'No ChirpStack dashboard set'; + res.status(409).type('html').send(`ChirpStack

${heading}

Select a gateway to open its ChirpStack, or set CENTRAL_CHIRPSTACK_URL in central's .env to your online ChirpStack dashboard's address (such as https://chirpstack.example.com, with no path) and run ./auto-compose.sh.

`); + return; + } void gatewayHub.open(gateway,'chirpstack','chirpstack',8080).then(stream=>{ if(req.destroyed||res.destroyed){stream.destroy();return;} const agent=new http.Agent({keepAlive:false});agent.createConnection=()=>stream; @@ -74,20 +82,7 @@ app.post('/api/actions/:moduleId/:actionId', async (req: Request, res: Response, }); export const server = http.createServer(app); -if(central){protectBrowserSockets(server,central.auth.authorize);central.hub.mount(app,server);} - -const browserRuntime=central; -const browserActors=new WeakMap(); -attachBrowser(server,{role:config.role,gateway:request=>browserRuntime?.hub.selected(request)||null, - owner:browserRuntime?request=>browserRuntime.auth.session(request)?.id||'unauthorized':undefined, - tunnel:browserRuntime?(gateway,host,port)=>browserRuntime.hub.open(gateway,'browser',host,port):undefined, - audit:browserRuntime?(request,event,gateway)=>{ - if(event==='browser-start'){const actor=browserRuntime.auth.session(request)?.id;if(actor)browserActors.set(request,actor);} - const actor=browserActors.get(request);if(actor)browserRuntime.identities.audit(actor,event,gateway); - if(event==='browser-end')browserActors.delete(request); - }:undefined, - testUnsandboxed:process.env.NODE_ENV==='test'&&process.env.BROWSER_UNSANDBOXED_TEST==='true', -}); +if(central){protectSessionSockets(server,central.auth.authorize);central.hub.mount(app,server);} export function startServer() { server.once('error', (error: NodeJS.ErrnoException) => { diff --git a/src/services/socket-router.ts b/src/services/socket-router.ts index 73e3f26..4288025 100644 --- a/src/services/socket-router.ts +++ b/src/services/socket-router.ts @@ -3,8 +3,9 @@ import { Socket } from 'net'; import WebSocket from 'ws'; import { isSameOrigin } from './auth'; const servers = new WeakMap boolean; machine: boolean }>>(); -const browserGuards = new WeakMap boolean>(); -export function protectBrowserSockets(server:http.Server,authorize:(req:http.IncomingMessage)=>boolean):void {browserGuards.set(server,authorize);} +/** Central: every non-machine socket (such as Terminal) needs a signed-in session. */ +const sessionGuards = new WeakMap boolean>(); +export function protectSessionSockets(server:http.Server,authorize:(req:http.IncomingMessage)=>boolean):void {sessionGuards.set(server,authorize);} /** Shared origin-checked upgrade boundary for terminal and application streams. */ export function registerSocket(server: http.Server, path: string, wss: WebSocket.Server, authorize?: (req: http.IncomingMessage) => boolean, machine = false): void { @@ -14,7 +15,7 @@ export function registerSocket(server: http.Server, path: string, wss: WebSocket routes = new Map(); servers.set(server, routes); server.on('upgrade', (request, socket, head) => { const target = routes!.get(request.url || ''); - const guard=browserGuards.get(server); + const guard=sessionGuards.get(server); if (!target || (!target.machine && (!isSameOrigin(request, true) || (guard && !guard(request)))) || (target.authorize && !target.authorize(request))) { socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return; } diff --git a/src/updater/index.ts b/src/updater/index.ts index 44f33f8..73b5316 100644 --- a/src/updater/index.ts +++ b/src/updater/index.ts @@ -15,8 +15,11 @@ export async function runUpdater():Promise{ if(process.env.REMOTE_UPDATES_ENABLED&&!['true','false'].includes(process.env.REMOTE_UPDATES_ENABLED))throw new Error('REMOTE_UPDATES_ENABLED must be boolean.'); const reconnectMs=Number(process.env.UPDATER_RECONNECT_TIMEOUT_MS||180000); if(!Number.isInteger(reconnectMs)||reconnectMs<1000||reconnectMs>900000)throw new Error('Invalid updater reconnect deadline.'); - const policy:UpdatePolicy={enabled:process.env.REMOTE_UPDATES_ENABLED==='true',imageRepository:process.env.UPDATER_IMAGE_REPOSITORY||'ghcr.io/fluxion9/console', - sourceRepository:process.env.UPDATER_SOURCE_REPOSITORY||'fluxion9/Console',allowedRefs:(process.env.UPDATER_ALLOWED_REFS||'refs/heads/main').split(','),project:process.env.UPDATER_PROJECT||'console',directory,reconnectMs}; + // No built-in owner: the trusted repository always comes from the deployment (auto-compose.sh derives it). + const imageRepository=process.env.UPDATER_IMAGE_REPOSITORY,sourceRepository=process.env.UPDATER_SOURCE_REPOSITORY; + if(!imageRepository||!sourceRepository)throw new Error('UPDATER_IMAGE_REPOSITORY and UPDATER_SOURCE_REPOSITORY are required.'); + const policy:UpdatePolicy={enabled:process.env.REMOTE_UPDATES_ENABLED==='true',imageRepository, + sourceRepository,allowedRefs:(process.env.UPDATER_ALLOWED_REFS||'refs/heads/main').split(','),project:process.env.UPDATER_PROJECT||'console',directory,reconnectMs}; const secret=hashSecret(readOwnerSecret(secretFile));fs.mkdirSync(state,{recursive:true,mode:0o700}); const updater=new Updater(path.join(state,'updates.db'),policy,new DockerDriver(policy,'/agent/reconnected.json')); await updater.recover(); diff --git a/src/views/index.hbs b/src/views/index.hbs index f7b03ef..554f341 100644 --- a/src/views/index.hbs +++ b/src/views/index.hbs @@ -3,18 +3,49 @@
Desktop
- {{#if central}}
{{/if}} -
+ {{#if central}}
{{/if}} +
{{#if central}}{{/if}}
{{#if central}} -

Choose a gateway to access its applications.

-

Gateways

Uncertain replies are held for reconciliation. A newer report supersedes an older unresolved reply; uncertainty never sends a relay command.

+ + + +
CENTRAL WORKSPACE

Gateways

Loading gateways…

+

Add a gateway

Name it after its site so it's easy to find. You'll get a one-time token to install on the gateway.

+ + +

Your gateways

+
+

Uncertain replies are held for reconciliation. A newer report supersedes an older unresolved reply; uncertainty never sends a relay command.

+
+ + + +

{{/if}}
- {{#each icons}} @@ -34,13 +65,8 @@

Enter your credentials to start a terminal session.

-