From 3c90fcaf199d0ee69c49baa004490d53714da0c4 Mon Sep 17 00:00:00 2001 From: SashaMIT Date: Thu, 22 Oct 2026 17:31:13 +0800 Subject: [PATCH 1/3] v1.4.5: install patched Node on update, verify TLS in gateway and scripts, pin actions - scripts/install-node.sh: nodejs.org Node 24.22.1 (SHA-256 checked) into /opt, linked into /usr/local/bin; used by update.sh, install-arm.sh, supernode bootstrap - update.sh: Node upgrade step + pm2 daemon restart; strip NODE_TLS_REJECT_UNAUTHORIZED=0 from .env - pc2-node: ignore leftover NODE_TLS_REJECT_UNAUTHORIZED=0 at boot - web-gateway: peer/DHT requests without decompression, supernode certs verified - remove curl -k / rejectUnauthorized:false from scripts and tooling - pin GitHub Actions to SHAs; permissions on main.yml; install-node CI job Co-authored-by: Cursor --- .github/workflows/build-enm-bundle.yml | 8 +- .github/workflows/main.yml | 12 +- .github/workflows/pc2-node-docker.yml | 14 +-- .github/workflows/publish-pc2-binaries.yml | 22 ++-- .github/workflows/release-please.yml | 2 +- .github/workflows/secret-scan.yml | 4 +- .github/workflows/smoke-test.yml | 71 +++++++++-- CHANGELOG.md | 12 ++ deploy/supernode-bootstrap.sh | 42 +++++-- deploy/web-gateway/index.js | 34 ++--- deploy/web-gateway/lib/peer-request.js | 70 +++++++++++ ecosystem.config.cjs | 11 +- package-lock.json | 4 +- package.json | 2 +- pc2-node/package-lock.json | 4 +- pc2-node/package.json | 2 +- pc2-node/scripts/cluster-backfill.mjs | 9 +- .../scripts/wave8-supernode-live-verify.mjs | 4 +- pc2-node/src/index.ts | 4 +- pc2-node/src/utils/tlsTrust.ts | 13 +- .../tests/unit/gateway-peer-request.test.js | 77 ++++++++++++ pc2-node/tests/unit/tls-trust.test.js | 20 +++ scripts/deploy-supernode.sh | 12 +- scripts/install-arm.sh | 26 ++-- scripts/install-node.sh | 119 ++++++++++++++++++ scripts/pc2-diagnose.sh | 2 +- scripts/setup-wireguard-client.sh | 14 ++- scripts/update.sh | 32 ++++- 28 files changed, 529 insertions(+), 117 deletions(-) create mode 100644 deploy/web-gateway/lib/peer-request.js create mode 100644 pc2-node/tests/unit/gateway-peer-request.test.js create mode 100644 scripts/install-node.sh diff --git a/.github/workflows/build-enm-bundle.yml b/.github/workflows/build-enm-bundle.yml index 5a3eebd681..01f7f4d99f 100644 --- a/.github/workflows/build-enm-bundle.yml +++ b/.github/workflows/build-enm-bundle.yml @@ -44,10 +44,10 @@ jobs: runs-on: ${{ matrix.runner }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Set up Node 20 - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '24.22.1' cache: 'npm' @@ -120,7 +120,7 @@ jobs: echo " $PUBLISHER" >> "$GITHUB_STEP_SUMMARY" - name: Upload bundle artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: elastos-node-manager-${{ steps.version.outputs.version }}-linux-${{ matrix.arch }} path: | @@ -132,7 +132,7 @@ jobs: # attached so `wget` from the deploy script can grab a stable URL. - name: Attach to GitHub Release if: startsWith(github.ref, 'refs/tags/enm-v') - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: files: | ${{ steps.version.outputs.tarball }} diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb3511340f..58167c1075 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -6,22 +6,26 @@ on: # branches: # - main +permissions: + contents: write + pull-requests: write + jobs: update-release-pr: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@a37ce9120846195fa4ece8f58b268e6043cb2f26 # v3.7.0 - name: Setup Git run: | git config user.name github-actions git config user.email github-actions@github.com - name: Check for existing PR id: find-pr - uses: juliangruber/find-pull-request-action@v1 + uses: juliangruber/find-pull-request-action@0d2ca757412e2742b5cd5ce4ff56757c65652605 # v1.12.0 with: github-token: ${{ secrets.GITHUB_TOKEN }} branch: release - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 if: steps.find-pr.outputs.number == '' with: ref: release @@ -32,7 +36,7 @@ jobs: git reset --hard main - name: Create/Update PR if: steps.find-pr.outputs.number == '' - uses: peter-evans/create-pull-request@v6 + uses: peter-evans/create-pull-request@c5a7806660adbe173f04e3e038b0ccdcd758773c # v6.1.0 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: Update release branch diff --git a/.github/workflows/pc2-node-docker.yml b/.github/workflows/pc2-node-docker.yml index 023e88a0c6..c598a6d7ca 100644 --- a/.github/workflows/pc2-node-docker.yml +++ b/.github/workflows/pc2-node-docker.yml @@ -26,29 +26,29 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '24.22.1' - name: Log in to GitHub Container Registry - uses: docker/login-action@v3 + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Set up QEMU - uses: docker/setup-qemu-action@v3 + uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 - name: Extract metadata for Docker id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0 with: images: ghcr.io/elacity/pc2-node tags: | @@ -57,7 +57,7 @@ jobs: type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }} - name: Build and push Docker image - uses: docker/build-push-action@v5 + uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0 with: context: ./pc2-node file: ./pc2-node/Dockerfile diff --git a/.github/workflows/publish-pc2-binaries.yml b/.github/workflows/publish-pc2-binaries.yml index 59838207a7..6e6f1d5d68 100644 --- a/.github/workflows/publish-pc2-binaries.yml +++ b/.github/workflows/publish-pc2-binaries.yml @@ -87,9 +87,9 @@ jobs: runs-on: macos-latest timeout-minutes: 60 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 with: go-version: '1.22' @@ -361,7 +361,7 @@ jobs: ls -la staging/ - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: darwin-assets path: staging/ @@ -382,9 +382,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 with: go-version: '1.22' @@ -409,7 +409,7 @@ jobs: cp pc2-node/bin/linux-x64/awg-quick staging/awg-quick-linux ls -la staging/ - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: linux-x64-assets path: staging/ @@ -426,9 +426,9 @@ jobs: runs-on: ubuntu-24.04-arm timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 with: go-version: '1.22' @@ -449,7 +449,7 @@ jobs: cp pc2-node/bin/linux-arm64/awg staging/awg-linux-arm64 ls -la staging/ - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: linux-arm64-assets path: staging/ @@ -466,9 +466,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: downloaded diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 82fb7f433d..06e6ef6675 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -14,6 +14,6 @@ jobs: release-please: runs-on: ubuntu-latest steps: - - uses: google-github-actions/release-please-action@v4 + - uses: google-github-actions/release-please-action@e4dc86ba9405554aeba3c6bb2d169500e7d3b4ee # v4.1.1 with: release-type: node diff --git a/.github/workflows/secret-scan.yml b/.github/workflows/secret-scan.yml index b9c7b6850c..3fcb2ed2af 100644 --- a/.github/workflows/secret-scan.yml +++ b/.github/workflows/secret-scan.yml @@ -39,12 +39,12 @@ jobs: timeout-minutes: 15 steps: - name: Checkout (full history for PR diff scan) - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - name: Run gitleaks - uses: gitleaks/gitleaks-action@v2 + uses: gitleaks/gitleaks-action@ff98106e4c7b2bc287b24eaf42907196329070c7 # v2.3.9 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Org-account license for gitleaks-action v2 (free key). Required diff --git a/.github/workflows/smoke-test.yml b/.github/workflows/smoke-test.yml index 7c9b90cd89..e36ccfc8b7 100644 --- a/.github/workflows/smoke-test.yml +++ b/.github/workflows/smoke-test.yml @@ -161,7 +161,7 @@ jobs: # error rather than an opaque clone failure), and we re-evaluate # then with a `git config insteadOf` rewrite step. - name: Checkout (without submodules — not needed by build:pc2) - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: submodules: false fetch-depth: 1 @@ -170,7 +170,7 @@ jobs: # declares engines.node >=20.18.0; we pick the latest 20.x to match # what a fresh user install of nvm or Node-via-Homebrew would land on. - name: Setup Node.js 24.22.1 - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '24.22.1' @@ -178,7 +178,7 @@ jobs: # ~6 min install down to ~90 s once the cache is warm. The cache key # mixes OS + all known lockfiles so a dep change always invalidates. - name: Cache npm + yarn caches - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: | ~/.npm @@ -612,7 +612,7 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 1 @@ -804,19 +804,19 @@ jobs: contents: read steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: submodules: false fetch-depth: 1 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 # We don't push, but the gha cache lets a successful build on commit N # reuse layers from commit N-1 to speed up the inner-loop iteration # while we're stabilising this job. - name: Build pc2-node Docker image (no push) - uses: docker/build-push-action@v5 + uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0 with: context: . file: ./pc2-node/Dockerfile @@ -989,7 +989,7 @@ jobs: # actions/checkout uses git which we just apt-installed above. # No submodules — same rationale as the existing matrix's checkout step. - name: Checkout (no submodules) - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: submodules: false fetch-depth: 1 @@ -1107,7 +1107,7 @@ jobs: # install-arm.sh will then do its OWN git clone of $PC2_BRANCH into # $PC2_DIR — that's two clones, fine in CI, the realistic user flow. - name: Checkout (for in-branch install-arm.sh) - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: submodules: false fetch-depth: 1 @@ -1270,6 +1270,59 @@ jobs: exit 1 fi + # --------------------------------------------------------------------------- + # install-node-script: the Node step update.sh runs (scripts/install-node.sh) + # against a NodeSource Node 20 + global pm2 install, which is how most + # Linux nodes were set up. + # --------------------------------------------------------------------------- + install-node-script: + name: install-node.sh upgrade (${{ matrix.arch }}) + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: ubuntu-latest + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 15 + container: + image: ubuntu:22.04 + defaults: + run: + shell: bash + steps: + - name: NodeSource Node 20 + pm2 (existing node) + run: | + set -euo pipefail + apt-get update + apt-get install -y --no-install-recommends ca-certificates curl gnupg + curl -fsSL https://deb.nodesource.com/setup_20.x | bash - + apt-get install -y nodejs + npm install -g pm2 + node -v && pm2 -v + + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 1 + + - name: Upgrade to the patched Node + run: | + set -euo pipefail + bash scripts/install-node.sh + hash -r + test "$(command -v node)" = /usr/local/bin/node + test "$(node -v)" = v24.22.1 + npm -v + pm2 -v + npm install -g pm2 >/dev/null + test -x /usr/local/bin/pm2 + + - name: Second run leaves it alone + run: bash scripts/install-node.sh | grep -q "already has the October 2026 security fixes" + # --------------------------------------------------------------------------- # summary: roll up matrix results into a single "ok / not ok" output so the # status badge + branch protection rule have one thing to point at. diff --git a/CHANGELOG.md b/CHANGELOG.md index dc39e33629..7fbb480b4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ --- +## [v1.4.5] - 2026-10-22 - Node.js upgrade on update, TLS clean-up + +Running `scripts/update.sh` on a Linux node now moves it to the patched Node.js release, and the remaining places that skipped certificate checks verify them. + +- `update.sh` installs Node.js 24.22.1 from nodejs.org (SHA-256 checked) when the node runs an unpatched Node, then restarts pm2 onto it and rebuilds native modules. Nodes on nvm, macOS or 32-bit OS are left as they are, with the command to upgrade printed. Set `PC2_SKIP_NODE_UPGRADE=1` to skip. The ARM installer and the supernode bootstrap use the same installer. +- pc2-node ignores a leftover `NODE_TLS_REJECT_UNAUTHORIZED=0` (copied into `pc2-node/.env` by older updates) and logs a warning. `update.sh` removes it from `.env` and no longer copies it. The pm2 config always sets it to `1`. +- The web gateway's DHT, gossip and registry-sync requests no longer decompress responses, and verify the Elacity supernodes' certificates. Gossip between the supernodes had been failing on certificate checks. +- The supernode bootstrap, deploy, WireGuard setup and diagnose scripts no longer use `curl -k`. The cluster backfill and supernode verify scripts no longer turn verification off. +- GitHub Actions are pinned to commit SHAs. The release-PR workflow declares its permissions. + +--- + ## [v1.4.4] - 2026-10-21 - Node.js October security release Node.js fixed a HIGH-severity Brotli decoder out-of-bounds write (CVE-2026-111497) that any Brotli-encoded `fetch` response can reach. The fix is only in Node 24.22.1, 22.23.4 and 26.12.1; Node 20, which most PC2 nodes run, gets none. This release protects nodes on any Node version and moves new installs to Node 24. diff --git a/deploy/supernode-bootstrap.sh b/deploy/supernode-bootstrap.sh index c00d7b4311..3edf083dc6 100755 --- a/deploy/supernode-bootstrap.sh +++ b/deploy/supernode-bootstrap.sh @@ -34,6 +34,8 @@ BOOTSTRAP_SUPERNODES=( "https://69.164.241.210" "https://38.242.211.112" ) +# Bootstrap supernodes are addressed by IP but serve the *.ela.city certificate. +SUPERNODE_TLS_NAME="supernode.ela.city" # Minimum requirements MIN_CORES=4 @@ -78,6 +80,13 @@ log_warn() { log "WARN: $*"; } log_err() { log "ERROR: $*"; } log_step() { echo ""; log "=== STEP: $* ==="; } +# supernode_curl https:///path [curl args...] — certificate-verified request to a bootstrap supernode +supernode_curl() { + local url="$1"; shift + local host="${url#https://}"; host="${host%%/*}" + curl --resolve "${SUPERNODE_TLS_NAME}:443:${host}" -H "Host: ${host}" "https://${SUPERNODE_TLS_NAME}${url#https://${host}}" "$@" +} + # ============================================================================ # Step 0: Pre-flight checks # ============================================================================ @@ -168,12 +177,15 @@ apt-get install -y -qq \ openjdk-17-jre-headless \ > /dev/null 2>&1 -# Install Node.js 24.x if not present -if ! command -v node &>/dev/null || [[ $(node -v | cut -d. -f1 | tr -d v) -lt 24 ]]; then - log "Installing Node.js 24.x..." - curl -fsSL https://deb.nodesource.com/setup_24.x | bash - > /dev/null 2>&1 - apt-get install -y -qq nodejs > /dev/null 2>&1 +# Install Node.js 24.22.1+ from nodejs.org (SHA-256 checked); NodeSource's +# 24.x channel lagged the October 2026 security release. +NODE_INSTALLER="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)/../scripts/install-node.sh" +if [[ ! -f "$NODE_INSTALLER" ]]; then + NODE_INSTALLER="$(mktemp)" + curl -fsSL https://raw.githubusercontent.com/Elacity/pc2.net/main/scripts/install-node.sh -o "$NODE_INSTALLER" fi +bash "$NODE_INSTALLER" || { log_err "Could not install Node.js 24.22.1"; exit 1; } +hash -r log_ok "Node.js $(node -v)" # Install Go 1.21+ for AmneziaWG compilation @@ -630,7 +642,7 @@ REGISTRY_SYNCED=false for SN_URL in "${BOOTSTRAP_SUPERNODES[@]}"; do SYNC_URL="${SN_URL/https/http}:4500/api/registry/apps" log "Trying to sync registry from ${SYNC_URL}..." - if curl -s --max-time 10 -k "$SYNC_URL" -o "${REGISTRY_DIR}/registry.json" 2>/dev/null; then + if curl -s --max-time 10 "$SYNC_URL" -o "${REGISTRY_DIR}/registry.json" 2>/dev/null; then if jq -e '.apps' "${REGISTRY_DIR}/registry.json" > /dev/null 2>&1; then REGISTRY_SYNCED=true APP_COUNT=$(jq '.apps | length' "${REGISTRY_DIR}/registry.json") @@ -647,7 +659,7 @@ fi # Create registry sync cron (every 5 minutes from primary) cat > /etc/cron.d/pc2-registry-sync << EOF -*/5 * * * * root curl -s --max-time 10 -k ${BOOTSTRAP_SUPERNODES[0]}:4500/api/registry/apps -o ${REGISTRY_DIR}/registry.json.tmp 2>/dev/null && mv ${REGISTRY_DIR}/registry.json.tmp ${REGISTRY_DIR}/registry.json 2>/dev/null || true +*/5 * * * * root curl -s --max-time 10 ${BOOTSTRAP_SUPERNODES[0]/https/http}:4500/api/registry/apps -o ${REGISTRY_DIR}/registry.json.tmp 2>/dev/null && mv ${REGISTRY_DIR}/registry.json.tmp ${REGISTRY_DIR}/registry.json 2>/dev/null || true EOF # Only start if index.js exists @@ -847,8 +859,8 @@ EOF REGISTERED=0 for SN_URL in "${BOOTSTRAP_SUPERNODES[@]}"; do log "Registering with ${SN_URL}..." - RESP=$(curl -s --max-time 10 -k \ - -X POST "${SN_URL}/api/supernodes/register" \ + RESP=$(supernode_curl "${SN_URL}/api/supernodes/register" -s --max-time 10 \ + -X POST \ -H "Content-Type: application/json" \ -d "$REGISTER_PAYLOAD" 2>/dev/null || echo '{"error":"unreachable"}') @@ -864,9 +876,13 @@ done log "Registered with ${REGISTERED}/${#BOOTSTRAP_SUPERNODES[@]} supernodes" # Setup heartbeat cron (every 2 minutes) -cat > /etc/cron.d/pc2-supernode-heartbeat << EOF -*/2 * * * * root for SN in ${BOOTSTRAP_SUPERNODES[*]}; do curl -s --max-time 5 -k -X POST "\${SN}/api/supernodes/heartbeat" -H "Content-Type: application/json" -d '{"id":"${NODE_ID}","address":"${PUBLIC_IP}","port":${BOSON_PORT},"proxyPort":${PROXY_PORT},"gatewayUrl":"https://${PUBLIC_IP}","name":"${SN_NAME}","region":"${REGION}"}' > /dev/null 2>&1; done +: > /etc/cron.d/pc2-supernode-heartbeat +for SN in "${BOOTSTRAP_SUPERNODES[@]}"; do + SN_IP="${SN#https://}" + cat >> /etc/cron.d/pc2-supernode-heartbeat << EOF +*/2 * * * * root curl -s --max-time 5 --resolve ${SUPERNODE_TLS_NAME}:443:${SN_IP} -H "Host: ${SN_IP}" -X POST "https://${SUPERNODE_TLS_NAME}/api/supernodes/heartbeat" -H "Content-Type: application/json" -d '{"id":"${NODE_ID}","address":"${PUBLIC_IP}","port":${BOSON_PORT},"proxyPort":${PROXY_PORT},"gatewayUrl":"https://${PUBLIC_IP}","name":"${SN_NAME}","region":"${REGION}"}' > /dev/null 2>&1 EOF +done log_ok "Heartbeat cron configured (every 2 min)" @@ -903,11 +919,11 @@ echo "" echo " Registration: ${REGISTERED}/${#BOOTSTRAP_SUPERNODES[@]} supernodes" echo "" echo " Next steps:" -echo " 1. Deploy gateway code: scp deploy/web-gateway/index.js root@${PUBLIC_IP}:${GW_DIR}/" +echo " 1. Deploy gateway code: scp -r deploy/web-gateway/index.js deploy/web-gateway/lib root@${PUBLIC_IP}:${GW_DIR}/" echo " 2. Deploy IPFS relay: scp deploy/ipfs-relay/index.js root@${PUBLIC_IP}:${RELAY_DIR}/" echo " 3. Deploy app registry: scp deploy/app-registry/index.js root@${PUBLIC_IP}:${REGISTRY_DIR}/" echo " 4. Set up Boson DHT: (requires Java — see docs/pc2-infrastructure/)" -echo " 5. Check health: curl -k https://${PUBLIC_IP}/api/health" +echo " 5. Check health: curl http://127.0.0.1:3080/api/health" echo "" echo " Logs: tail -f ${LOG_FILE}" echo "================================================================" diff --git a/deploy/web-gateway/index.js b/deploy/web-gateway/index.js index 7ca225882a..5203dc15c6 100644 --- a/deploy/web-gateway/index.js +++ b/deploy/web-gateway/index.js @@ -21,6 +21,7 @@ import { ProvisioningTokenStore, getProvisioningTokenFromRequest, } from "./lib/provisioning-token.js"; +import { peerRequest } from "./lib/peer-request.js"; const { createProxyServer } = httpProxy; // ============================================================================ @@ -596,15 +597,10 @@ async function queryDHT(username) { for (const endpoint of DHT_CONFIG.supernodeEndpoints) { try { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), DHT_CONFIG.queryTimeoutMs); - - const response = await fetch(`${endpoint}/dht/get?key=${encodeURIComponent(dhtKey)}`, { - signal: controller.signal, + const response = await peerRequest(`${endpoint}/dht/get?key=${encodeURIComponent(dhtKey)}`, { + timeoutMs: DHT_CONFIG.queryTimeoutMs, }); - clearTimeout(timeoutId); - if (response.ok) { const data = await response.json(); if (data && data.value) { @@ -633,11 +629,10 @@ async function storeToDHT(username, nodeInfo) { // Try to store in all supernodes for redundancy const storePromises = DHT_CONFIG.supernodeEndpoints.map(async (endpoint) => { try { - const response = await fetch(`${endpoint}/dht/put`, { + const response = await peerRequest(`${endpoint}/dht/put`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ key: dhtKey, value: nodeInfo }), - signal: AbortSignal.timeout(DHT_CONFIG.queryTimeoutMs), + body: { key: dhtKey, value: nodeInfo }, + timeoutMs: DHT_CONFIG.queryTimeoutMs, }); return response.ok; } catch { @@ -1013,15 +1008,11 @@ async function gossipSupernodes() { if (node.address === myAddress) continue; try { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 5000); - await fetch(`${node.gatewayUrl}/api/supernodes/gossip`, { + await peerRequest(`${node.gatewayUrl}/api/supernodes/gossip`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ supernodes: ourList, source: CONFIG.gatewayId }), - signal: controller.signal, + body: { supernodes: ourList, source: CONFIG.gatewayId }, + timeoutMs: 5000, }).catch(() => {}); - clearTimeout(timeout); } catch { // Gossip failures are non-critical } @@ -1042,12 +1033,7 @@ async function syncRegistryFromPeers() { if (node.address === myAddress) continue; try { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 10000); - const resp = await fetch(`${node.gatewayUrl}/api/registry/sync`, { - signal: controller.signal, - }); - clearTimeout(timeout); + const resp = await peerRequest(`${node.gatewayUrl}/api/registry/sync`, { timeoutMs: 10000 }); if (!resp.ok) continue; diff --git a/deploy/web-gateway/lib/peer-request.js b/deploy/web-gateway/lib/peer-request.js new file mode 100644 index 0000000000..aabbb19ce5 --- /dev/null +++ b/deploy/web-gateway/lib/peer-request.js @@ -0,0 +1,70 @@ +/** + * JSON requests from the gateway to Boson DHT endpoints and peer gateways. + * + * Uses http/https rather than fetch so responses are never decompressed: no + * Brotli decoder (CVE-2026-111497) on any Node version. Elacity supernodes are + * reached by IP and verified against the *.ela.city certificate they serve. + */ +import http from "http"; +import https from "https"; + +export const ELACITY_SUPERNODE_IPS = new Set(["69.164.241.210", "38.242.211.112"]); +export const ELACITY_SUPERNODE_SERVERNAME = "supernode.ela.city"; +const MAX_RESPONSE_BYTES = 10 * 1024 * 1024; + +export function peerServername(hostname) { + return ELACITY_SUPERNODE_IPS.has(hostname) ? ELACITY_SUPERNODE_SERVERNAME : undefined; +} + +/** + * @param {string} url + * @param {{ method?: string, body?: unknown, timeoutMs?: number }} [options] + * @returns {Promise<{ ok: boolean, status: number, json: () => any }>} + */ +export function peerRequest(url, { method = "GET", body, timeoutMs = 5000 } = {}) { + const target = new URL(url); + const client = target.protocol === "https:" ? https : http; + const payload = body === undefined ? undefined : JSON.stringify(body); + const headers = { "accept-encoding": "identity" }; + if (payload !== undefined) { + headers["content-type"] = "application/json"; + headers["content-length"] = Buffer.byteLength(payload); + } + + return new Promise((resolve, reject) => { + const req = client.request( + target, + { method, headers, timeout: timeoutMs, servername: peerServername(target.hostname) }, + (res) => { + const encoding = res.headers["content-encoding"]; + if (encoding && encoding !== "identity") { + res.destroy(); + reject(new Error(`Refused ${encoding}-encoded response from ${target.host}`)); + return; + } + const chunks = []; + let size = 0; + res.on("data", (chunk) => { + size += chunk.length; + if (size > MAX_RESPONSE_BYTES) { + res.destroy(new Error(`Response from ${target.host} exceeds ${MAX_RESPONSE_BYTES} bytes`)); + return; + } + chunks.push(chunk); + }); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + resolve({ + ok: res.statusCode >= 200 && res.statusCode < 300, + status: res.statusCode, + json: () => JSON.parse(text), + }); + }); + res.on("error", reject); + }, + ); + req.on("timeout", () => req.destroy(new Error(`Request to ${target.host} timed out after ${timeoutMs}ms`))); + req.on("error", reject); + req.end(payload); + }); +} diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs index b42f20d184..7ee36605b4 100644 --- a/ecosystem.config.cjs +++ b/ecosystem.config.cjs @@ -57,7 +57,7 @@ module.exports = { // Hardcoded defaults (always set): // NODE_ENV, PORT, PATH — runtime / system // LIT_BACKEND, REPLICATION_MIN/MAX — feature defaults - // NODE_TLS_REJECT_UNAUTHORIZED — TLS safety (default "1") + // NODE_TLS_REJECT_UNAUTHORIZED — TLS verification (always "1") // // Conditional opt-in vars (cluster, AI, comms credentials, RPC pool): // We use the spread pattern `...(process.env.X ? { X: process.env.X } : {})` @@ -83,13 +83,8 @@ module.exports = { SUPERNODE_CLUSTER_PIN_REPLICATION_MIN: process.env.SUPERNODE_CLUSTER_PIN_REPLICATION_MIN || "2", SUPERNODE_CLUSTER_PIN_REPLICATION_MAX: process.env.SUPERNODE_CLUSTER_PIN_REPLICATION_MAX || "2", - // ── TLS handling for self-signed cluster cert (TEMPORARY) ────────── - // Always-set with safe default "1" (verify). Operator sets to "0" in - // shell or .env to opt out (required for current cluster IP-literal - // setup until cluster.ela.city DNS + valid cert ship in v1.2.8+). - // Note: pc2-node/src/services/boson/UsernameService.ts also forces - // this to "0" at import time as belt-and-suspenders. - NODE_TLS_REJECT_UNAUTHORIZED: process.env.NODE_TLS_REJECT_UNAUTHORIZED || "1", + // Always verify TLS: an inherited "0" from the shell would disable it process-wide. + NODE_TLS_REJECT_UNAUTHORIZED: "1", // ── Opt-in: IPFS Cluster pinning (v1.2.7+) ───────────────────────── // When both URL and TOKEN are set, pc2-node forwards every successful diff --git a/package-lock.json b/package-lock.json index ee06d23823..89fe2eadd8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "elastos-desktop", - "version": "1.4.4", + "version": "1.4.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "elastos-desktop", - "version": "1.4.4", + "version": "1.4.5", "license": "AGPL-3.0-only", "workspaces": [ "src/*", diff --git a/package.json b/package.json index 0a0cb66fd2..ca871ea003 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "elastos-desktop", - "version": "1.4.4", + "version": "1.4.5", "author": "Elacity LLC", "license": "AGPL-3.0-only", "description": "PC2 - your sovereign Web3 cloud desktop that runs on your own hardware.", diff --git a/pc2-node/package-lock.json b/pc2-node/package-lock.json index 0d6ecef044..80d631098e 100644 --- a/pc2-node/package-lock.json +++ b/pc2-node/package-lock.json @@ -1,12 +1,12 @@ { "name": "@elastos/pc2-node", - "version": "1.4.4", + "version": "1.4.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@elastos/pc2-node", - "version": "1.4.4", + "version": "1.4.5", "license": "AGPL-3.0", "dependencies": { "@anthropic-ai/sdk": "^0.71.2", diff --git a/pc2-node/package.json b/pc2-node/package.json index d748629764..15cf7870e8 100644 --- a/pc2-node/package.json +++ b/pc2-node/package.json @@ -1,6 +1,6 @@ { "name": "@elastos/pc2-node", - "version": "1.4.4", + "version": "1.4.5", "description": "PC2 Production Node - Self-hosted personal cloud with ElastOS frontend built-in", "main": "dist/index.js", "type": "module", diff --git a/pc2-node/scripts/cluster-backfill.mjs b/pc2-node/scripts/cluster-backfill.mjs index f338e8d4ab..396cb5271e 100644 --- a/pc2-node/scripts/cluster-backfill.mjs +++ b/pc2-node/scripts/cluster-backfill.mjs @@ -11,7 +11,11 @@ // // Required env (already set in pc2-node ecosystem.config.cjs): // SUPERNODE_CLUSTER_PIN_URL, SUPERNODE_CLUSTER_PIN_TOKEN -// NODE_TLS_REJECT_UNAUTHORIZED=0 (until proper-cert subdomain in v1.3.x) +// Run from pc2-node/ after `npm run build`: certificates are verified with +// the same trust policy as the server (supernode IPs checked as *.ela.city). + +import { installOutboundTlsPolicy } from "../dist/utils/tlsTrust.js"; +installOutboundTlsPolicy(); // Try @photostructure/sqlite first (v1.2.7+), fall back to better-sqlite3 (v1.2.6). let Database; @@ -34,9 +38,6 @@ if (!URL || !TOKEN) { console.error("ERROR: SUPERNODE_CLUSTER_PIN_URL and _TOKEN must be set"); process.exit(1); } -if (process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0") { - console.warn("WARN: NODE_TLS_REJECT_UNAUTHORIZED is not '0'; self-signed cert may fail"); -} console.log(`Cluster URL : ${URL}`); console.log(`DB path : ${DB_PATH}`); diff --git a/pc2-node/scripts/wave8-supernode-live-verify.mjs b/pc2-node/scripts/wave8-supernode-live-verify.mjs index f7861152a5..966ce8f331 100755 --- a/pc2-node/scripts/wave8-supernode-live-verify.mjs +++ b/pc2-node/scripts/wave8-supernode-live-verify.mjs @@ -23,6 +23,8 @@ const SUPERNODES = [ 'https://69.164.241.210/api/ddrm/provision', 'https://38.242.211.112/api/ddrm/provision', ]; +// The supernodes are addressed by IP but serve the *.ela.city certificate. +const SUPERNODE_TLS_SERVERNAME = 'supernode.ela.city'; const PROVISION_ENVELOPE_DOMAIN = 'elacity.pc2.chipotle-provision.v1'; const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex'); @@ -42,7 +44,7 @@ function canonicalize(value) { function httpsGet(url) { return new Promise((resolve, reject) => { - const req = https.get(url, { rejectUnauthorized: false, timeout: 10000 }, (res) => { + const req = https.get(url, { servername: SUPERNODE_TLS_SERVERNAME, timeout: 10000 }, (res) => { if (res.statusCode !== 200) { res.resume(); return reject(new Error(`http_${res.statusCode}`)); diff --git a/pc2-node/src/index.ts b/pc2-node/src/index.ts index e2f5283653..1d73b82f0a 100644 --- a/pc2-node/src/index.ts +++ b/pc2-node/src/index.ts @@ -98,7 +98,9 @@ import { installOutboundTlsPolicy } from './utils/tlsTrust.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); -installOutboundTlsPolicy(); +if (installOutboundTlsPolicy()) { + logger.warn('Ignored NODE_TLS_REJECT_UNAUTHORIZED=0 (left by an older update); outbound TLS certificates are verified. Remove it from pc2-node/.env.'); +} // Load configuration let config: Config; diff --git a/pc2-node/src/utils/tlsTrust.ts b/pc2-node/src/utils/tlsTrust.ts index c6d51b1fc0..891626d3a0 100644 --- a/pc2-node/src/utils/tlsTrust.ts +++ b/pc2-node/src/utils/tlsTrust.ts @@ -41,11 +41,19 @@ export function supernodeServername(host: string): string | undefined { return SUPERNODE_IPS.has(host) ? SUPERNODE_TLS_SERVERNAME : undefined; } +// Older updaters copied this into pc2-node/.env; '0' turns off verification process-wide. +const TLS_VERIFY_ENV = 'NODE_TLS_REJECT_UNAUTHORIZED'; + /** * Apply the trust policy to every global `fetch` and default-agent `https` request, - * and keep Brotli responses away from global `fetch`. Call once at boot. + * and keep Brotli responses away from global `fetch`. Call once at boot, after dotenv. + * Returns true if a leftover TLS-off setting was found and removed. */ -export function installOutboundTlsPolicy(): void { +export function installOutboundTlsPolicy(): boolean { + const removedTlsOff = process.env[TLS_VERIFY_ENV] === '0'; + if (removedTlsOff) { + delete process.env[TLS_VERIFY_ENV]; + } https.globalAgent.options.ca = TRUSTED_ROOT_CERTIFICATES; const connect = buildConnector({ ca: TRUSTED_ROOT_CERTIFICATES }); setGlobalDispatcher(new Agent({ @@ -54,4 +62,5 @@ export function installOutboundTlsPolicy(): void { callback, ), }).compose(refuseBrotli)); + return removedTlsOff; } diff --git a/pc2-node/tests/unit/gateway-peer-request.test.js b/pc2-node/tests/unit/gateway-peer-request.test.js new file mode 100644 index 0000000000..c1b40a3e16 --- /dev/null +++ b/pc2-node/tests/unit/gateway-peer-request.test.js @@ -0,0 +1,77 @@ +/** + * Web gateway peer requests: JSON over http/https without response decompression. + */ + +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import zlib from 'node:zlib'; + +const { peerRequest, peerServername, ELACITY_SUPERNODE_SERVERNAME } = + await import('../../../deploy/web-gateway/lib/peer-request.js'); + +let server; +let base; + +before(async () => { + server = http.createServer((req, res) => { + if (req.url === '/br') { + res.writeHead(200, { 'content-type': 'application/json', 'content-encoding': 'br' }); + res.end(zlib.brotliCompressSync(JSON.stringify({ ok: true }))); + return; + } + if (req.url === '/slow') { + return; + } + let body = ''; + req.on('data', (chunk) => { body += chunk; }); + req.on('end', () => { + res.writeHead(req.url === '/missing' ? 404 : 200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ + method: req.method, + acceptEncoding: req.headers['accept-encoding'], + body: body ? JSON.parse(body) : null, + })); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + base = `http://127.0.0.1:${server.address().port}`; +}); + +after(() => { + server.closeAllConnections(); + server.close(); +}); + +test('GET returns parsed JSON and asks for an uncompressed body', async () => { + const res = await peerRequest(`${base}/dht/get?key=x`); + assert.equal(res.ok, true); + assert.equal(res.status, 200); + assert.deepEqual(res.json(), { method: 'GET', acceptEncoding: 'identity', body: null }); +}); + +test('POST sends the body as JSON', async () => { + const res = await peerRequest(`${base}/dht/put`, { method: 'POST', body: { key: 'k', value: 1 } }); + assert.deepEqual(res.json().body, { key: 'k', value: 1 }); +}); + +test('non-2xx responses resolve with ok=false', async () => { + const res = await peerRequest(`${base}/missing`); + assert.equal(res.ok, false); + assert.equal(res.status, 404); +}); + +test('Brotli-encoded responses are refused, not decoded', async () => { + await assert.rejects(peerRequest(`${base}/br`), /Refused br-encoded response/); +}); + +test('requests time out', async () => { + await assert.rejects(peerRequest(`${base}/slow`, { timeoutMs: 200 }), /timed out/); +}); + +test('Elacity supernode IPs verify against the ela.city name; others are unchanged', () => { + assert.equal(peerServername('69.164.241.210'), ELACITY_SUPERNODE_SERVERNAME); + assert.equal(peerServername('38.242.211.112'), ELACITY_SUPERNODE_SERVERNAME); + assert.equal(peerServername('155.138.245.211'), undefined); + assert.equal(peerServername('example.com'), undefined); +}); diff --git a/pc2-node/tests/unit/tls-trust.test.js b/pc2-node/tests/unit/tls-trust.test.js index 22ec70b95e..6d597e0dd4 100644 --- a/pc2-node/tests/unit/tls-trust.test.js +++ b/pc2-node/tests/unit/tls-trust.test.js @@ -45,3 +45,23 @@ test('installOutboundTlsPolicy sets the default https trust store', () => { installOutboundTlsPolicy(); assert.equal(https.globalAgent.options.ca, TRUSTED_ROOT_CERTIFICATES); }); + +test('installOutboundTlsPolicy removes a leftover TLS-off setting', () => { + const env = 'NODE_TLS_REJECT_UNAUTHORIZED'; + const original = process.env[env]; + try { + process.env[env] = '0'; + assert.equal(installOutboundTlsPolicy(), true); + assert.equal(process.env[env], undefined); + + process.env[env] = '1'; + assert.equal(installOutboundTlsPolicy(), false); + assert.equal(process.env[env], '1'); + } finally { + if (original === undefined) { + delete process.env[env]; + } else { + process.env[env] = original; + } + } +}); diff --git a/scripts/deploy-supernode.sh b/scripts/deploy-supernode.sh index 245e113e42..62579e58a1 100755 --- a/scripts/deploy-supernode.sh +++ b/scripts/deploy-supernode.sh @@ -187,14 +187,18 @@ run_scp() { smoke_test() { local label="$1" base_url="$2" host_header="${3:-}" local host_arg="" - [ -n "$host_header" ] && host_arg="-H Host:$host_header --resolve $host_header:443:${base_url#https://}" log "Smoke-testing $label ($base_url)" + # Reach the IP but present the domain so the certificate is verified for it. + if [ -n "$host_header" ]; then + host_arg="--resolve $host_header:443:${base_url#https://}" + base_url="https://$host_header" + fi # Test 1: /api/health local h # shellcheck disable=SC2086 - h=$(curl -sk --max-time 8 $host_arg "$base_url/api/health" -w '\n__HTTP__%{http_code}' || true) + h=$(curl -s --max-time 8 $host_arg "$base_url/api/health" -w '\n__HTTP__%{http_code}' || true) local code="${h##*__HTTP__}" if [ "$code" != "200" ]; then fail "$label: /api/health returned $code (expected 200)" @@ -208,7 +212,7 @@ smoke_test() { # Test 2: /api/supernodes # shellcheck disable=SC2086 - h=$(curl -sk --max-time 8 $host_arg "$base_url/api/supernodes" -w '\n__HTTP__%{http_code}' || true) + h=$(curl -s --max-time 8 $host_arg "$base_url/api/supernodes" -w '\n__HTTP__%{http_code}' || true) code="${h##*__HTTP__}" if [ "$code" != "200" ]; then fail "$label: /api/supernodes returned $code (expected 200)" @@ -222,7 +226,7 @@ smoke_test() { # Test 3: SEC-2 exploit MUST return 400 "Invalid username" (NOT 503, NOT root output) # shellcheck disable=SC2086 - h=$(curl -sk --max-time 8 -X POST $host_arg "$base_url/api/vless/register" \ + h=$(curl -s --max-time 8 -X POST $host_arg "$base_url/api/vless/register" \ -H 'Content-Type: application/json' \ --data-raw '{"username":"x\"; id ; echo \""}' \ -w '\n__HTTP__%{http_code}' || true) diff --git a/scripts/install-arm.sh b/scripts/install-arm.sh index 6d399bf971..c44733f8f8 100644 --- a/scripts/install-arm.sh +++ b/scripts/install-arm.sh @@ -273,19 +273,21 @@ install_nodejs() { echo "" print_step "Checking Node.js..." - if command -v node &> /dev/null; then - NODE_VERSION=$(node -v | cut -d 'v' -f 2 | cut -d '.' -f 1) - if [ "$NODE_VERSION" -ge 24 ]; then - print_ok "Node.js $(node -v) already installed" - return - fi + # Installed from nodejs.org (24.22.1+, SHA-256 checked); NodeSource's + # 24.x channel lagged the October 2026 security release. + local script_dir installer + script_dir="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)" + installer="$script_dir/install-node.sh" + if [ ! -f "$installer" ]; then + installer="$(mktemp)" + curl -fsSL "https://raw.githubusercontent.com/Elacity/pc2.net/${REPO_BRANCH}/scripts/install-node.sh" -o "$installer" fi - - print_step "Installing Node.js 24..." - curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - - sudo apt-get install -y -qq nodejs - - print_ok "Node.js $(node -v) installed" + if ! bash "$installer"; then + print_error "Could not install Node.js 24.22.1 (see message above)" + exit 1 + fi + hash -r + print_ok "Node.js $(node -v) ready" } # ───────────────────────────────────────────────────────────────────────────── diff --git a/scripts/install-node.sh b/scripts/install-node.sh new file mode 100644 index 0000000000..1c31f02f83 --- /dev/null +++ b/scripts/install-node.sh @@ -0,0 +1,119 @@ +#!/bin/bash +# +# Ensure a Node.js release with the October 2026 security fixes is the +# `node` on PATH (CVE-2026-111497 Brotli decoder OOB write and friends). +# +# Accepted as already patched: 22.23.4+ on 22.x, 24.22.1+ on 24.x, +# 26.12.1+ on 26.x. Anything else on Linux x64/arm64 gets the +# official nodejs.org build of PC2_NODE_VERSION, checked against +# SHASUMS256.txt, unpacked into /opt (root-owned) and linked into +# /usr/local/bin. NodeSource is not used because its 24.x channel +# lagged behind the security release. +# +# The new binary must run (`node -v`) before anything is linked, so an +# old glibc or an unsupported CPU leaves the existing Node untouched. +# nvm and macOS installs are never modified; the script prints the +# command to run instead. +# +# Exit codes: 0 = patched Node on PATH, 2 = left unchanged (see message). +# +# Rollback: sudo rm /usr/local/bin/{node,npm,npx,corepack} +# +# Usage: +# bash scripts/install-node.sh +# PC2_NODE_VERSION=24.22.1 bash scripts/install-node.sh + +set -euo pipefail + +PC2_NODE_VERSION="${PC2_NODE_VERSION:-24.22.1}" +NODE_DIST_URL="https://nodejs.org/dist/v${PC2_NODE_VERSION}" +LINK_DIR=/usr/local/bin + +say() { echo " $*"; } +warn() { echo " ⚠️ $*"; } + +# version_ge A B — true when A >= B (dotted numeric versions). +version_ge() { + [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" = "$2" ] +} + +node_is_patched() { + local v="$1" major="${1%%.*}" + case "$major" in + 22) version_ge "$v" 22.23.4 ;; + 24) version_ge "$v" 24.22.1 ;; + *) [ "$major" -ge 26 ] 2>/dev/null && version_ge "$v" 26.12.1 ;; + esac +} + +CURRENT="$(node -v 2>/dev/null | sed 's/^v//' || true)" +if [ -n "$CURRENT" ] && node_is_patched "$CURRENT"; then + say "Node.js v$CURRENT already has the October 2026 security fixes" + exit 0 +fi +say "Node.js ${CURRENT:+v$CURRENT }needs upgrading to v$PC2_NODE_VERSION" + +NODE_PATH_NOW="$(command -v node 2>/dev/null || true)" +if [ "$(uname -s)" != "Linux" ]; then + warn "Not Linux: install Node.js v$PC2_NODE_VERSION yourself (nodejs.org installer, or: nvm install $PC2_NODE_VERSION)" + exit 2 +fi +case "$NODE_PATH_NOW" in + */.nvm/*) + warn "Node is managed by nvm. Run: nvm install $PC2_NODE_VERSION && nvm alias default $PC2_NODE_VERSION && npm install -g pm2" + exit 2 ;; +esac + +case "$(uname -m)" in + x86_64) ARCH=x64 ;; + aarch64) ARCH=arm64 ;; + *) warn "Node.js 24 has no official build for $(uname -m) (32-bit Pi OS needs a 64-bit OS); leaving Node unchanged"; exit 2 ;; +esac + +if [ "$(id -u)" -eq 0 ]; then + SUDO="" +elif sudo -n true 2>/dev/null || sudo -v; then + SUDO="sudo" +else + warn "Need sudo to install into /opt; leaving Node unchanged" + exit 2 +fi + +NAME="node-v${PC2_NODE_VERSION}-linux-${ARCH}" +TARGET="/opt/$NAME" + +if [ ! -x "$TARGET/bin/node" ]; then + TMP="$(mktemp -d)" + trap 'rm -rf "$TMP"' EXIT + say "Downloading $NAME.tar.gz from nodejs.org..." + curl -fsSL -o "$TMP/$NAME.tar.gz" "$NODE_DIST_URL/$NAME.tar.gz" + curl -fsSL -o "$TMP/SHASUMS256.txt" "$NODE_DIST_URL/SHASUMS256.txt" + ACTUAL="$(sha256sum "$TMP/$NAME.tar.gz" | cut -d' ' -f1)" + if ! grep -qx "$ACTUAL $NAME.tar.gz" "$TMP/SHASUMS256.txt"; then + warn "SHA-256 of $NAME.tar.gz does not match nodejs.org SHASUMS256.txt; aborting" + exit 2 + fi + say "SHA-256 verified" + $SUDO tar --no-same-owner -xzf "$TMP/$NAME.tar.gz" -C /opt + $SUDO chown -R root:root "$TARGET" +fi + +if [ "$("$TARGET/bin/node" -v 2>/dev/null)" != "v$PC2_NODE_VERSION" ]; then + warn "$TARGET/bin/node does not run on this system (glibc too old?); leaving Node unchanged" + exit 2 +fi + +# Globals installed with this npm go to /usr/local so `npm i -g pm2` +# lands on PATH instead of inside /opt. +$SUDO "$TARGET/bin/node" "$TARGET/bin/npm" config set prefix /usr/local --location=global >/dev/null + +for bin in node npm npx corepack; do + $SUDO ln -sfn "$TARGET/bin/$bin" "$LINK_DIR/$bin" +done +hash -r + +if [ "$(command -v node)" != "$LINK_DIR/node" ]; then + warn "$LINK_DIR is not ahead of $(dirname "$NODE_PATH_NOW") on PATH; 'node' still resolves to $(command -v node)" + exit 2 +fi +say "✅ Node.js $(node -v) installed ($TARGET); rollback: sudo rm $LINK_DIR/{node,npm,npx,corepack}" diff --git a/scripts/pc2-diagnose.sh b/scripts/pc2-diagnose.sh index 2412c0e783..56c0bca25a 100755 --- a/scripts/pc2-diagnose.sh +++ b/scripts/pc2-diagnose.sh @@ -247,7 +247,7 @@ section "9. Cluster pin connectivity (Elacity supernode)" # any token here — we just check the endpoint is reachable. A 401 means # the cluster is up; a connection failure means the node can't reach it. run "curl Elacity supernode (expect HTTP 401 = up & auth-gated)" \ - bash -c "curl -sk -o /dev/null -w 'HTTP %{http_code}, time %{time_total}s\\n' --max-time 8 https://38.242.211.112/cluster-pin/pins" + bash -c "curl -s -o /dev/null -w 'HTTP %{http_code}, time %{time_total}s\\n' --max-time 8 --resolve supernode.ela.city:443:38.242.211.112 -H 'Host: 38.242.211.112' https://supernode.ela.city/cluster-pin/pins" section "10. Recent logs (last 200 lines, filtered for pin/cluster/ipfs/wireguard/error)" # v1.2.7.6: on macOS the launcher writes PC2 logs to diff --git a/scripts/setup-wireguard-client.sh b/scripts/setup-wireguard-client.sh index cd531204c7..0ded77321f 100755 --- a/scripts/setup-wireguard-client.sh +++ b/scripts/setup-wireguard-client.sh @@ -370,10 +370,20 @@ if [ -z "${ASSIGNED_IP:-}" ]; then fi PROVISION_BODY="$PROVISION_BODY}" - RESPONSE=$(curl -sk -w "\n%{http_code}" -X POST \ + # Elacity supernodes are reached by IP and serve the *.ela.city certificate. + GATEWAY_HOST="${GATEWAY_URL#https://}"; GATEWAY_HOST="${GATEWAY_HOST%%[:/]*}" + TLS_ARGS=() + if [[ "$GATEWAY_HOST" == "69.164.241.210" || "$GATEWAY_HOST" == "38.242.211.112" ]]; then + PROVISION_URL="https://supernode.ela.city${GATEWAY_URL#https://$GATEWAY_HOST}/api/wg/register" + TLS_ARGS=(--resolve "supernode.ela.city:443:$GATEWAY_HOST" -H "Host: $GATEWAY_HOST") + else + PROVISION_URL="$GATEWAY_URL/api/wg/register" + fi + + RESPONSE=$(curl -s -w "\n%{http_code}" -X POST ${TLS_ARGS[@]+"${TLS_ARGS[@]}"} \ -H "Content-Type: application/json" \ -d "$PROVISION_BODY" \ - "$GATEWAY_URL/api/wg/register" 2>&1) + "$PROVISION_URL" 2>&1) HTTP_CODE=$(echo "$RESPONSE" | tail -1) RESPONSE_BODY=$(echo "$RESPONSE" | sed '$d') diff --git a/scripts/update.sh b/scripts/update.sh index ff9597bfd3..ee31d86ccb 100755 --- a/scripts/update.sh +++ b/scripts/update.sh @@ -262,7 +262,6 @@ if [[ -f "$ECO_FILE" ]]; then SUPERNODE_CLUSTER_PIN_TOKEN SUPERNODE_CLUSTER_PIN_REPLICATION_MIN SUPERNODE_CLUSTER_PIN_REPLICATION_MAX - NODE_TLS_REJECT_UNAUTHORIZED ELACITY_PIN_FORWARD_URL SUPERNODE_PIN_MIRRORS ANTHROPIC_API_KEY @@ -318,6 +317,14 @@ ENV_HEADER fi fi +# Older versions of this step copied NODE_TLS_REJECT_UNAUTHORIZED=0 into +# .env, which turns off certificate checks for every outbound request. +if [[ -f "$ENV_FILE" ]] && grep -q '^NODE_TLS_REJECT_UNAUTHORIZED=0' "$ENV_FILE"; then + grep -v '^NODE_TLS_REJECT_UNAUTHORIZED=0' "$ENV_FILE" > "$ENV_FILE.tmp" || true + cat "$ENV_FILE.tmp" > "$ENV_FILE" && rm -f "$ENV_FILE.tmp" + echo "🔐 Removed NODE_TLS_REJECT_UNAUTHORIZED=0 from pc2-node/.env (certificates are verified from v1.4.3)" +fi + # ───────────────────────────────────────────────────────────────────── # Step 4: Pull latest code (force-reset, no merges) # ───────────────────────────────────────────────────────────────────── @@ -329,6 +336,29 @@ git reset --hard origin/main # Drop any half-installed asset artefacts from a broken previous run git clean -fd src/particle-auth/assets/ 2>/dev/null || true +# ───────────────────────────────────────────────────────────────────── +# Step 4b (v1.4.5): Node.js security release. +# +# Runs before npm install so native modules are rebuilt for the Node +# that will run PC2. Non-fatal: if Node can't be upgraded here (nvm, +# macOS, 32-bit OS, no sudo) the update continues on the current Node, +# which pc2-node's Brotli guard still protects. +# ───────────────────────────────────────────────────────────────────── +echo "" +echo "🟢 Step 4b: Checking Node.js security release..." +if [[ "${PC2_SKIP_NODE_UPGRADE:-0}" == "1" ]]; then + echo " Skipped (PC2_SKIP_NODE_UPGRADE=1)" +elif [[ -f "$PC2_DIR/scripts/install-node.sh" ]]; then + NODE_BEFORE="$(node -v 2>/dev/null || true)" + bash "$PC2_DIR/scripts/install-node.sh" || echo " ⚠️ Continuing on Node $(node -v); see the message above to upgrade by hand." + hash -r + # pm2 starts apps with its daemon's Node, so the daemon must restart onto the new one. + if [[ "$(node -v 2>/dev/null || true)" != "$NODE_BEFORE" ]]; then + echo " Restarting the pm2 daemon on $(node -v)..." + pm2 update >/dev/null 2>&1 || echo " ⚠️ 'pm2 update' failed; run it by hand so PC2 starts on $(node -v)." + fi +fi + # ───────────────────────────────────────────────────────────────────── # Step 5: Install at BOTH root AND pc2-node. # From ff8f890fcb12833886797f6baf35253645b8a452 Mon Sep 17 00:00:00 2001 From: SashaMIT Date: Thu, 22 Oct 2026 17:42:55 +0800 Subject: [PATCH 2/3] pc2-node: reword TLS-env warning so the bypass grep stays meaningful Co-authored-by: Cursor --- pc2-node/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pc2-node/src/index.ts b/pc2-node/src/index.ts index 1d73b82f0a..623dc0ccd3 100644 --- a/pc2-node/src/index.ts +++ b/pc2-node/src/index.ts @@ -99,7 +99,7 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); if (installOutboundTlsPolicy()) { - logger.warn('Ignored NODE_TLS_REJECT_UNAUTHORIZED=0 (left by an older update); outbound TLS certificates are verified. Remove it from pc2-node/.env.'); + logger.warn('Ignored NODE_TLS_REJECT_UNAUTHORIZED set to 0 (left by an older update); outbound TLS certificates are verified. Remove it from pc2-node/.env.'); } // Load configuration From 34b2d744e8649e23f595fcf99e40544b72d03148 Mon Sep 17 00:00:00 2001 From: SashaMIT Date: Thu, 22 Oct 2026 17:43:53 +0800 Subject: [PATCH 3/3] web-gateway: atomic registry.json writes with .bak recovery (from InterServer's live copy) Co-authored-by: Cursor --- CHANGELOG.md | 1 + deploy/web-gateway/index.js | 38 ++++++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fbb480b4f..4715bebfc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Running `scripts/update.sh` on a Linux node now moves it to the patched Node.js - `update.sh` installs Node.js 24.22.1 from nodejs.org (SHA-256 checked) when the node runs an unpatched Node, then restarts pm2 onto it and rebuilds native modules. Nodes on nvm, macOS or 32-bit OS are left as they are, with the command to upgrade printed. Set `PC2_SKIP_NODE_UPGRADE=1` to skip. The ARM installer and the supernode bootstrap use the same installer. - pc2-node ignores a leftover `NODE_TLS_REJECT_UNAUTHORIZED=0` (copied into `pc2-node/.env` by older updates) and logs a warning. `update.sh` removes it from `.env` and no longer copies it. The pm2 config always sets it to `1`. - The web gateway's DHT, gossip and registry-sync requests no longer decompress responses, and verify the Elacity supernodes' certificates. Gossip between the supernodes had been failing on certificate checks. +- The gateway writes `registry.json` atomically, keeping the previous copy as `.bak`, and recovers from `.bak` if the file is truncated. This was already running on InterServer and was missing from the repo. - The supernode bootstrap, deploy, WireGuard setup and diagnose scripts no longer use `curl -k`. The cluster backfill and supernode verify scripts no longer turn verification off. - GitHub Actions are pinned to commit SHAs. The release-PR workflow declares its permissions. diff --git a/deploy/web-gateway/index.js b/deploy/web-gateway/index.js index 5203dc15c6..d38e3e831e 100644 --- a/deploy/web-gateway/index.js +++ b/deploy/web-gateway/index.js @@ -1767,17 +1767,36 @@ async function getProxySession(endpoint) { // Load registry from disk function loadRegistry() { + // Load entries from a JSON file into the in-memory registry; returns count. + const loadFromFile = (file) => { + const data = JSON.parse(fs.readFileSync(file, "utf8")); + for (const [username, info] of Object.entries(data)) { + registry.set(username, info); + } + return registry.size; + }; try { if (!fs.existsSync(CONFIG.dataDir)) { fs.mkdirSync(CONFIG.dataDir, { recursive: true }); } if (fs.existsSync(CONFIG.registryFile)) { - const data = JSON.parse(fs.readFileSync(CONFIG.registryFile, "utf8")); - for (const [username, info] of Object.entries(data)) { - registry.set(username, info); + try { + const count = loadFromFile(CONFIG.registryFile); + console.log(`[Gateway] Loaded ${count} users from registry`); + } catch (parseErr) { + // registry.json can be truncated by an ENOSPC/interrupted write. Recover + // from the previous-good .bak instead of silently starting empty (which + // would mark every node offline until each one re-registers). + console.error("[Gateway] registry.json unreadable, trying backup:", parseErr.message); + const bak = `${CONFIG.registryFile}.bak`; + if (fs.existsSync(bak)) { + const count = loadFromFile(bak); + console.log(`[Gateway] Recovered ${count} users from registry .bak`); + } else { + console.error("[Gateway] No registry .bak available; starting empty"); + } } - console.log(`[Gateway] Loaded ${registry.size} users from registry`); } } catch (error) { console.error("[Gateway] Failed to load registry:", error); @@ -1791,7 +1810,16 @@ function saveRegistry() { for (const [username, info] of registry) { data[username] = info; } - fs.writeFileSync(CONFIG.registryFile, JSON.stringify(data, null, 2)); + // Atomic write: keep the prior file as .bak, write to a temp, then rename. + // A partial/ENOSPC write lands on the temp, never on the live registry, so + // the live file is never left truncated/corrupt. + const json = JSON.stringify(data, null, 2); + const tmp = `${CONFIG.registryFile}.tmp`; + if (fs.existsSync(CONFIG.registryFile)) { + try { fs.copyFileSync(CONFIG.registryFile, `${CONFIG.registryFile}.bak`); } catch (e) { /* best-effort backup */ } + } + fs.writeFileSync(tmp, json); + fs.renameSync(tmp, CONFIG.registryFile); } catch (error) { console.error("[Gateway] Failed to save registry:", error); }