diff --git a/.github/actions/ci-wechat-runtime-audit/action.yaml b/.github/actions/ci-wechat-runtime-audit/action.yaml new file mode 100644 index 00000000000..31f4accf9f0 --- /dev/null +++ b/.github/actions/ci-wechat-runtime-audit/action.yaml @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: ci-wechat-runtime-audit +description: Audit a PR-provided WeChat runtime graph from trusted CI code. + +inputs: + target-root: + description: Absolute path to the checked-out target tree whose lock inputs are audited. + required: true + report-dir: + description: Report directory, absolute or relative to target-root. + required: true + +runs: + using: composite + steps: + - name: Setup production-compatible Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 + with: + node-version: "22.19.0" + + - name: Pin production npm + shell: bash + run: >- + cd "$RUNNER_TEMP" && + npm install --global npm@10.9.4 + --userconfig /dev/null + --registry https://registry.npmjs.org/ + --ignore-scripts --no-audit --no-fund + + - name: Audit locked WeChat runtime graph + shell: bash + env: + NEMOCLAW_WECHAT_AUDIT_TARGET_ROOT: ${{ inputs.target-root }} + NEMOCLAW_WECHAT_AUDIT_REPORT_DIR: ${{ inputs.report-dir }} + run: bash "$GITHUB_ACTION_PATH/audit.sh" diff --git a/.github/actions/ci-wechat-runtime-audit/audit.sh b/.github/actions/ci-wechat-runtime-audit/audit.sh new file mode 100755 index 00000000000..5220f5cc7e1 --- /dev/null +++ b/.github/actions/ci-wechat-runtime-audit/audit.sh @@ -0,0 +1,213 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -euo pipefail + +target_root="${NEMOCLAW_WECHAT_AUDIT_TARGET_ROOT:?target root is required}" +report_dir="${NEMOCLAW_WECHAT_AUDIT_REPORT_DIR:?report directory is required}" +target_root="$(cd "$target_root" && pwd -P)" +if [[ "$report_dir" != /* ]]; then + report_dir="$target_root/$report_dir" +fi +runtime_dir="$target_root/agents/openclaw/wechat-runtime" +package_json="$runtime_dir/package.json" +package_lock="$runtime_dir/package-lock.json" +npm_registry="https://registry.npmjs.org/" + +for input in "$runtime_dir" "$package_json" "$package_lock"; do + if [[ -L "$input" ]]; then + echo "WeChat runtime audit refuses symbolic-link input: $input" >&2 + exit 1 + fi +done + +# The audited checkout must not influence npm's trust or registry configuration. +for npm_config in "$target_root/.npmrc" "$runtime_dir/.npmrc"; do + if [[ -e "$npm_config" || -L "$npm_config" ]]; then + echo "WeChat runtime audit refuses target-controlled npm config: $npm_config" >&2 + exit 1 + fi +done +runtime_dir="$(cd "$runtime_dir" && pwd -P)" +case "$runtime_dir/" in + "$target_root"/*) ;; + *) + echo "WeChat runtime directory escaped the target checkout: $runtime_dir" >&2 + exit 1 + ;; +esac + +trusted_cache="$(mktemp -d "${TMPDIR:-/tmp}/nemoclaw-wechat-trusted-cache.XXXXXX")" +install_cache="$(mktemp -d "${TMPDIR:-/tmp}/nemoclaw-wechat-install-cache.XXXXXX")" +pack_dir="$(mktemp -d "${TMPDIR:-/tmp}/nemoclaw-wechat-pack.XXXXXX")" +trusted_npmrc="$(mktemp "${TMPDIR:-/tmp}/nemoclaw-wechat-npmrc.XXXXXX")" +printf 'registry=%s\n' "$npm_registry" >"$trusted_npmrc" +chmod 600 "$trusted_npmrc" + +cleanup() { + chmod -R u+w "$trusted_cache" "$install_cache" "$pack_dir" 2>/dev/null || true + rm -rf "$trusted_cache" "$install_cache" "$pack_dir" "$runtime_dir/node_modules" + rm -f "$trusted_npmrc" +} +trap cleanup EXIT + +mkdir -p "$report_dir" + +package_identity_output="$( + PACKAGE_JSON="$package_json" PACKAGE_LOCK="$package_lock" NPM_REGISTRY_ORIGIN="${npm_registry%/}" node <<'NODE' +const fs = require("node:fs"); +const packageJson = JSON.parse(fs.readFileSync(process.env.PACKAGE_JSON, "utf8")); +const packageLock = JSON.parse(fs.readFileSync(process.env.PACKAGE_LOCK, "utf8")); +const registryOrigin = process.env.NPM_REGISTRY_ORIGIN; + +function requireRegistryUrl(resolved, location) { + if (typeof resolved !== "string") { + throw new Error(`locked package lacks a resolved URL: ${location}`); + } + let parsed; + try { + parsed = new URL(resolved); + } catch { + throw new Error(`locked package has an invalid resolved URL: ${location}`); + } + if (parsed.origin !== registryOrigin || parsed.username || parsed.password) { + throw new Error(`locked package must resolve from the reviewed npm registry origin: ${location}`); + } +} + +const dependencyNames = Object.keys(packageJson.dependencies ?? {}); +if (dependencyNames.length !== 1 || dependencyNames[0] !== "@tencent-weixin/openclaw-weixin") { + throw new Error("WeChat runtime package.json must contain exactly the reviewed plugin dependency"); +} +const version = packageJson.dependencies[dependencyNames[0]]; +if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) { + throw new Error("WeChat runtime dependency must use an exact numeric version"); +} +if (packageLock.lockfileVersion !== 3) { + throw new Error(`WeChat runtime lockfileVersion must be 3, got ${packageLock.lockfileVersion}`); +} +const rootDependency = packageLock.packages?.[""]?.dependencies?.[dependencyNames[0]]; +const plugin = packageLock.packages?.[`node_modules/${dependencyNames[0]}`]; +if (rootDependency !== version || plugin?.version !== version) { + throw new Error("WeChat runtime package and lock identities do not match"); +} +if (typeof plugin.integrity !== "string" || !plugin.integrity.startsWith("sha512-")) { + throw new Error("WeChat runtime plugin lock entry must carry sha512 integrity"); +} +requireRegistryUrl(plugin.resolved, `node_modules/${dependencyNames[0]}`); +const peerRange = plugin.peerDependencies?.openclaw; +if (typeof peerRange !== "string" || peerRange.length === 0) { + throw new Error("WeChat runtime plugin lock entry must declare its OpenClaw peer range"); +} +for (const [location, record] of Object.entries(packageLock.packages ?? {})) { + if (!location.startsWith("node_modules/")) continue; + if (typeof record.version !== "string" || typeof record.integrity !== "string") { + throw new Error(`locked package lacks version or integrity: ${location}`); + } + requireRegistryUrl(record.resolved, location); +} +process.stdout.write(`${dependencyNames[0]}@${version}\n${plugin.resolved}\n${plugin.integrity}\n`); +NODE +)" +readarray -t package_identity <<<"$package_identity_output" +if [[ ${#package_identity[@]} -ne 3 ]] \ + || [[ -z "${package_identity[0]}" || -z "${package_identity[1]}" || -z "${package_identity[2]}" ]]; then + echo "ERROR: WeChat runtime package validation returned incomplete identity metadata" >&2 + exit 1 +fi +wechat_spec="${package_identity[0]}" +wechat_tarball="${package_identity[1]}" +wechat_integrity="${package_identity[2]}" + +# Materialize the exact PR-provided graph without executing dependency scripts. +npm --prefix "$runtime_dir" ci \ + --userconfig "$trusted_npmrc" \ + --registry "$npm_registry" \ + --ignore-scripts \ + --omit=dev \ + --legacy-peer-deps \ + --no-audit \ + --no-fund \ + --cache "$trusted_cache" +for package_spec in "$wechat_spec" "qrcode-terminal@0.12.0" "zod@4.4.3"; do + npm cache add "$package_spec" \ + --userconfig "$trusted_npmrc" \ + --registry "$npm_registry" \ + --cache "$trusted_cache" +done + +audit_status=0 +npm --prefix "$runtime_dir" audit \ + --userconfig "$trusted_npmrc" \ + --registry "$npm_registry" \ + --omit=dev \ + --audit-level=low \ + --json >"$report_dir/npm-audit.json" || audit_status=$? + +signature_status=0 +npm --prefix "$runtime_dir" audit signatures \ + --userconfig "$trusted_npmrc" \ + --registry "$npm_registry" \ + >"$report_dir/npm-audit-signatures.txt" 2>&1 || signature_status=$? + +# Reproduce the sandbox-user npm-pack boundary with the exact reviewed archive. +# The trusted source cache is read-only; only its short-lived copy is writable. +chmod -R a-w "$trusted_cache" +cp -R "$trusted_cache"/. "$install_cache"/ +chmod -R u+rwX,go-w "$install_cache" +npm pack "$wechat_tarball" \ + --userconfig "$trusted_npmrc" \ + --registry "$npm_registry" \ + --offline \ + --cache "$install_cache" \ + --pack-destination "$pack_dir" \ + --json >"$report_dir/npm-pack.json" + +TRUSTED_CACHE="$trusted_cache" \ + PACK_DIR="$pack_dir" \ + PACK_REPORT="$report_dir/npm-pack.json" \ + EXPECTED_INTEGRITY="$wechat_integrity" \ + node <<'NODE' +const fs = require("node:fs"); +const path = require("node:path"); + +const trustedCache = process.env.TRUSTED_CACHE; +const packDir = path.resolve(process.env.PACK_DIR); +const report = JSON.parse(fs.readFileSync(process.env.PACK_REPORT, "utf8")); +const entry = report[0] ?? {}; +if (entry.integrity !== process.env.EXPECTED_INTEGRITY) { + throw new Error(`reviewed WeChat archive integrity mismatch: ${entry.integrity ?? "missing"}`); +} +const filename = String(entry.filename ?? ""); +if (!filename || path.basename(filename) !== filename) { + throw new Error(`npm pack reported an unsafe filename: ${filename || "missing"}`); +} +const archive = path.resolve(packDir, filename); +if (!archive.startsWith(`${packDir}${path.sep}`) || !fs.statSync(archive).isFile()) { + throw new Error(`npm pack archive escaped its destination: ${filename}`); +} + +const pending = [trustedCache]; +while (pending.length > 0) { + const current = pending.pop(); + const stats = fs.lstatSync(current); + if ((stats.mode & 0o222) !== 0) { + throw new Error(`trusted WeChat cache entry remained writable: ${current}`); + } + if (stats.isDirectory()) { + for (const child of fs.readdirSync(current)) pending.push(path.join(current, child)); + } +} +NODE + +if ((audit_status != 0)); then + echo "WeChat runtime npm audit failed at audit-level=low; see $report_dir/npm-audit.json" >&2 + exit "$audit_status" +fi +if ((signature_status != 0)); then + echo "WeChat runtime npm signature audit failed; see $report_dir/npm-audit-signatures.txt" >&2 + exit "$signature_status" +fi + +echo "WeChat runtime graph, audit, signatures, and writable install-cache boundary passed." diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 4645e543fd5..6343e11a118 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -57,6 +57,30 @@ jobs: - name: Run installer integration tests uses: ./.github/actions/ci-installer-integration + wechat-runtime-audit: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Audit locked WeChat runtime graph + uses: ./.github/actions/ci-wechat-runtime-audit + with: + target-root: ${{ github.workspace }} + report-dir: artifacts/wechat-runtime-audit + + - name: Upload WeChat runtime audit evidence + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: wechat-runtime-audit-${{ github.run_id }}-${{ github.run_attempt }} + path: artifacts/wechat-runtime-audit + if-no-files-found: error + retention-days: 14 + reviewed-npm-audit: runs-on: ubuntu-latest timeout-minutes: 15 @@ -225,6 +249,7 @@ jobs: - static-checks - build-typecheck - installer-integration + - wechat-runtime-audit - reviewed-npm-audit - real-openclaw-dist-harness - cli-tests @@ -240,6 +265,7 @@ jobs: STATIC_RESULT: ${{ needs['static-checks'].result }} BUILD_TYPECHECK_RESULT: ${{ needs['build-typecheck'].result }} INSTALLER_INTEGRATION_RESULT: ${{ needs['installer-integration'].result }} + WECHAT_RUNTIME_AUDIT_RESULT: ${{ needs['wechat-runtime-audit'].result }} REVIEWED_NPM_AUDIT_RESULT: ${{ needs['reviewed-npm-audit'].result }} REAL_OPENCLAW_DIST_HARNESS_RESULT: ${{ needs['real-openclaw-dist-harness'].result }} CLI_TESTS_RESULT: ${{ needs['cli-tests'].result }} @@ -261,6 +287,7 @@ jobs: require_success "static-checks" "$STATIC_RESULT" require_success "build-typecheck" "$BUILD_TYPECHECK_RESULT" require_success "installer-integration" "$INSTALLER_INTEGRATION_RESULT" + require_success "wechat-runtime-audit" "$WECHAT_RUNTIME_AUDIT_RESULT" require_success "reviewed-npm-audit" "$REVIEWED_NPM_AUDIT_RESULT" require_success "real-openclaw-dist-harness" "$REAL_OPENCLAW_DIST_HARNESS_RESULT" require_success "cli-tests" "$CLI_TESTS_RESULT" diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 67439b169a2..ad4157fb0d7 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -194,6 +194,84 @@ jobs: shell: bash run: CI=true npx vitest run --project installer-integration + wechat-runtime-audit: + needs: changes + if: needs.changes.outputs.code == 'true' + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Checkout trusted WeChat runtime audit + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: .trusted-wechat-audit + persist-credentials: false + sparse-checkout: | + .github/actions/ci-wechat-runtime-audit + sparse-checkout-cone-mode: false + + - name: Detect trusted WeChat runtime audit + id: trusted-wechat-audit + shell: bash + run: | + if [ -f .trusted-wechat-audit/.github/actions/ci-wechat-runtime-audit/action.yaml ]; then + echo "available=true" >> "$GITHUB_OUTPUT" + else + echo "available=false" >> "$GITHUB_OUTPUT" + fi + + # One-time bootstrap for this PR only. The action is pinned to a signed, + # immutable commit that contains only the reviewed audit implementation. + # Every later PR must resolve the action from its base SHA above. + # Removal condition: delete this checkout and its paired audit step in the + # first follow-up after PR #6739 merges, before the next release tag. + - name: Checkout pinned bootstrap WeChat runtime audit + if: ${{ steps.trusted-wechat-audit.outputs.available != 'true' && github.event.pull_request.number == 6739 && github.event.pull_request.head.repo.full_name == 'HOYALIM/NemoClaw' }} + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + repository: HOYALIM/NemoClaw + ref: 0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2 + path: .trusted-wechat-audit-bootstrap + persist-credentials: false + sparse-checkout: | + .github/actions/ci-wechat-runtime-audit + sparse-checkout-cone-mode: false + + - name: Reject unavailable trusted WeChat runtime audit + if: ${{ steps.trusted-wechat-audit.outputs.available != 'true' && (github.event.pull_request.number != 6739 || github.event.pull_request.head.repo.full_name != 'HOYALIM/NemoClaw') }} + shell: bash + run: | + echo "::error::Trusted base SHA does not contain ci-wechat-runtime-audit" + exit 1 + + - name: Audit locked WeChat runtime graph + if: ${{ steps.trusted-wechat-audit.outputs.available == 'true' }} + uses: ./.trusted-wechat-audit/.github/actions/ci-wechat-runtime-audit + with: + target-root: ${{ github.workspace }} + report-dir: artifacts/wechat-runtime-audit + + - name: Audit locked WeChat runtime graph (pinned bootstrap) + if: ${{ steps.trusted-wechat-audit.outputs.available != 'true' && github.event.pull_request.number == 6739 && github.event.pull_request.head.repo.full_name == 'HOYALIM/NemoClaw' }} + uses: ./.trusted-wechat-audit-bootstrap/.github/actions/ci-wechat-runtime-audit + with: + target-root: ${{ github.workspace }} + report-dir: artifacts/wechat-runtime-audit + + - name: Upload WeChat runtime audit evidence + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: wechat-runtime-audit-${{ github.run_id }}-${{ github.run_attempt }} + path: artifacts/wechat-runtime-audit + if-no-files-found: error + retention-days: 14 + reviewed-npm-audit: needs: changes if: needs.changes.outputs.code == 'true' @@ -382,6 +460,7 @@ jobs: - static-checks - build-typecheck - installer-integration + - wechat-runtime-audit - reviewed-npm-audit - cli-tests - plugin-tests @@ -399,6 +478,7 @@ jobs: STATIC_RESULT: ${{ needs['static-checks'].result }} BUILD_TYPECHECK_RESULT: ${{ needs['build-typecheck'].result }} INSTALLER_INTEGRATION_RESULT: ${{ needs['installer-integration'].result }} + WECHAT_RUNTIME_AUDIT_RESULT: ${{ needs['wechat-runtime-audit'].result }} REVIEWED_NPM_AUDIT_RESULT: ${{ needs['reviewed-npm-audit'].result }} CLI_TESTS_RESULT: ${{ needs['cli-tests'].result }} PLUGIN_TESTS_RESULT: ${{ needs['plugin-tests'].result }} @@ -435,6 +515,7 @@ jobs: require_success "static-checks" "$STATIC_RESULT" require_success "build-typecheck" "$BUILD_TYPECHECK_RESULT" require_success "installer-integration" "$INSTALLER_INTEGRATION_RESULT" + require_success "wechat-runtime-audit" "$WECHAT_RUNTIME_AUDIT_RESULT" require_success "reviewed-npm-audit" "$REVIEWED_NPM_AUDIT_RESULT" require_success "cli-tests" "$CLI_TESTS_RESULT" require_success "plugin-tests" "$PLUGIN_TESTS_RESULT" @@ -445,6 +526,7 @@ jobs: allow_success_or_skipped "static-checks" "$STATIC_RESULT" allow_success_or_skipped "build-typecheck" "$BUILD_TYPECHECK_RESULT" allow_success_or_skipped "installer-integration" "$INSTALLER_INTEGRATION_RESULT" + allow_success_or_skipped "wechat-runtime-audit" "$WECHAT_RUNTIME_AUDIT_RESULT" allow_success_or_skipped "reviewed-npm-audit" "$REVIEWED_NPM_AUDIT_RESULT" allow_success_or_skipped "cli-tests" "$CLI_TESTS_RESULT" allow_success_or_skipped "plugin-tests" "$PLUGIN_TESTS_RESULT" diff --git a/Dockerfile b/Dockerfile index 978ecbcabf8..891ed06cd11 100644 --- a/Dockerfile +++ b/Dockerfile @@ -67,6 +67,8 @@ ARG MCPORTER_0_7_3_INTEGRITY=sha512-egoPVYqTnWb3NjRIxo+xc8OrAI0dlPrJm9pAiZx0pImu ARG MCPORTER_0_7_3_TARBALL=https://registry.npmjs.org/mcporter/-/mcporter-0.7.3.tgz COPY agents/openclaw/mcporter-runtime/package.json /usr/local/lib/nemoclaw/mcporter-runtime/package.json COPY agents/openclaw/mcporter-runtime/package-lock.json /usr/local/lib/nemoclaw/mcporter-runtime/package-lock.json +COPY agents/openclaw/wechat-runtime/package.json /usr/local/lib/nemoclaw/wechat-runtime/package.json +COPY agents/openclaw/wechat-runtime/package-lock.json /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts # OpenShell blocks the link-local EC2 Instance Metadata Service. Keep AWS SDK @@ -146,16 +148,45 @@ RUN test -f /usr/local/bin/node \ && test -z "$node_unsafe" \ && json5_unsafe="$(find -L /opt/nemoclaw/node_modules/json5 \( ! -user root -o -perm /022 \) -print -quit)" \ && test -z "$json5_unsafe" +# Reviewed-archive invariants (#5896): after npm materializes the exact lock and +# seeds resolver metadata, the shared helper re-packs every locked archive +# offline from the final cache and verifies its registry origin, committed SRI, +# and contained filename before the cache becomes immutable. +RUN npm ci --prefix /usr/local/lib/nemoclaw/wechat-runtime \ + --ignore-scripts --omit=dev --legacy-peer-deps \ + --userconfig /dev/null --registry https://registry.npmjs.org/ \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && npm cache add @tencent-weixin/openclaw-weixin@2.4.3 \ + --userconfig /dev/null --registry https://registry.npmjs.org/ \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && npm cache add qrcode-terminal@0.12.0 \ + --userconfig /dev/null --registry https://registry.npmjs.org/ \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && npm cache add zod@4.4.3 \ + --userconfig /dev/null --registry https://registry.npmjs.org/ \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && NPM_CONFIG_OFFLINE=true \ + node --experimental-strip-types /scripts/lib/reviewed-npm-archive.mts \ + --lockfile /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + --registry-origin https://registry.npmjs.org/ \ + && rm -rf /usr/local/lib/nemoclaw/wechat-runtime/node_modules \ + && chown -R root:root /usr/local/lib/nemoclaw/wechat-runtime \ + /usr/local/share/nemoclaw/wechat-npm-cache \ + && chmod -R a+rX,go-w /usr/local/lib/nemoclaw/wechat-runtime \ + /usr/local/share/nemoclaw/wechat-npm-cache COPY scripts/patch-openclaw-tool-catalog.js /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.js COPY scripts/patch-openclaw-chat-send.js /usr/local/lib/nemoclaw/patch-openclaw-chat-send.js COPY scripts/patch-openclaw-mcp-npx.mts /usr/local/lib/nemoclaw/patch-openclaw-mcp-npx.mts COPY scripts/patch-openclaw-issue-4434-diagnostics.ts /usr/local/lib/nemoclaw/patch-openclaw-issue-4434-diagnostics.ts COPY scripts/patch-openclaw-device-self-approval.ts /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.ts +COPY scripts/verify-wechat-runtime-lock.mts /usr/local/lib/nemoclaw/verify-wechat-runtime-lock.mts RUN chmod 755 /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.js \ /usr/local/lib/nemoclaw/patch-openclaw-chat-send.js \ /usr/local/lib/nemoclaw/patch-openclaw-mcp-npx.mts \ /usr/local/lib/nemoclaw/patch-openclaw-issue-4434-diagnostics.ts \ - /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.ts + /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.ts \ + /usr/local/lib/nemoclaw/verify-wechat-runtime-lock.mts # Pre-install the codex-acp package so the embedded ACPx runtime can # call the local binary instead of `npx @zed-industries/codex-acp`. @@ -1037,8 +1068,27 @@ RUN set -eu; \ fi; \ : +# The reviewed cache stays root-owned and immutable to the sandbox user. npm +# still needs a writable _cacache/tmp while OpenClaw packs the verified archive, +# so materialize a sandbox-owned throwaway copy for this RUN and remove it before +# committing the layer. Never point npm directly at the trusted source cache. # hadolint ignore=DL3059,DL4006 -RUN OPENCLAW_VERSION="${OPENCLAW_VERSION}" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts --agent openclaw --phase agent-install +RUN set -eu; \ + trusted_cache=/usr/local/share/nemoclaw/wechat-npm-cache; \ + unsafe_cache_entry="$(find -L "$trusted_cache" \( ! -user root -o -perm /022 \) -print -quit)"; \ + test -z "$unsafe_cache_entry"; \ + install_cache="$(mktemp -d /tmp/nemoclaw-wechat-npm-cache.XXXXXX)"; \ + trap 'rm -rf "$install_cache"' EXIT; \ + cp -R "$trusted_cache"/. "$install_cache"/; \ + chmod -R u+rwX,go-w "$install_cache"; \ + NEMOCLAW_WECHAT_NPM_INSTALL_CACHE="$install_cache" \ + OPENCLAW_VERSION="${OPENCLAW_VERSION}" \ + node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts --agent openclaw --phase agent-install; \ + rm -rf "$install_cache"; \ + trap - EXIT; \ + test ! -e "$install_cache"; \ + unsafe_cache_entry="$(find -L "$trusted_cache" \( ! -user root -o -perm /022 \) -print -quit)"; \ + test -z "$unsafe_cache_entry" # Lock down npm for the next RUN: the local OpenClaw plugin install must # resolve from /opt/nemoclaw and the staged plugin-runtime-deps tree without diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index fa7fc58b4fa..a7ff15c252f 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -20,6 +20,19 @@ Update it and `agents/openclaw/mcporter-runtime/package*.json` together whenever - Advisory result: `0` known vulnerabilities across the resolved production dependency graph; npm verified registry signatures for all `120` resolved packages and attestations for `12` packages. Both image paths install the committed graph with `npm ci --ignore-scripts --omit=dev` because the published package declares no install-time lifecycle script and NemoClaw needs only its already-built CLI. + +## WeChat plugin runtime graph + +- Package: `@tencent-weixin/openclaw-weixin@2.4.3`. +- Locked graph: `agents/openclaw/wechat-runtime/package-lock.json` (npm lockfile version 3). +- Lock regeneration: `npm install --package-lock-only --legacy-peer-deps --ignore-scripts --omit=dev --prefix agents/openclaw/wechat-runtime`. +- Installation boundary: the image materializes the reviewed lock into a root-owned dedicated npm cache and adds the exact package metadata needed by npm's offline resolver. Before that cache becomes immutable, the shared `scripts/lib/reviewed-npm-archive.mts` implementation re-packs every locked archive offline from the final cache and rejects registry-origin drift, metadata or packed-byte SRI drift, unsafe filenames, missing archives, and symlinks. The sandbox user copies that verified immutable source into a writable cache used for registry metadata lookup, archive packing, and the OpenClaw plugin install; no retrieval step falls back to `HOME/.npm`. The copy is deleted in the same image layer, and the trusted cache is never writable. The installer runs in offline, legacy-peer mode, then `verify-wechat-runtime-lock.mts` rejects integrity, version, dependency-set, or peer-range drift and refuses an image OpenClaw version below the plugin's locked peer minimum. +- Default CI gate: `wechat-runtime-audit` in `.github/workflows/pr.yaml` and `.github/workflows/main.yaml` invokes the reviewed `.github/actions/ci-wechat-runtime-audit` implementation. Pull requests resolve it from the base SHA. Because PR #6739's base predates the action, that PR alone may bootstrap the action from signed immutable commit `HOYALIM/NemoClaw@0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2`; every other PR fails closed if its base lacks the action. Main uses the merged action. The action uses Node `22.19.0` and npm `10.9.4`, materializes the committed graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, uploads the JSON/text reports, and exercises the exact reviewed archive through a copied writable cache while the trusted source remains read-only. Removal condition: delete the PR #6739 bootstrap checkout, its paired conditional audit step, and the bootstrap-specific test assertions in the first follow-up after this PR merges, before the next release tag; all later PRs must use the normal base-SHA action path. +- Advisory command: `npm ci --ignore-scripts --omit=dev --legacy-peer-deps --prefix agents/openclaw/wechat-runtime && npm audit --omit=dev --audit-level=low --json --prefix agents/openclaw/wechat-runtime && npm audit signatures --prefix agents/openclaw/wechat-runtime`. +- Advisory review: `2026-07-12`; result: `0` known vulnerabilities across the resolved production graph. +- Regression tests: `test/wechat-locked-install.test.ts` keeps the manifest runtime-lock paths and installer verification dispatch synchronized; `test/verify-wechat-runtime-lock.test.ts` proves the installed graph and OpenClaw peer-range compatibility fail closed; `test/wechat-runtime-audit-workflow.test.ts` keeps the Docker cache lifecycle, base-trusted required CI gate, evidence upload, audit threshold, signature verification, and real npm-pack boundary synchronized. + +The dedicated graph intentionally omits the plugin's `openclaw` peer dependency. The image already installs and integrity-verifies the reviewed OpenClaw runtime separately; auto-installing another OpenClaw copy would create a second unreviewed runtime graph. Disabling scripts also prevents transitive packages from executing lifecycle code during the trusted image build. The lock records the exact version, registry URL, and integrity for every transitive package; the top-level registry integrity check remains an independent control. diff --git a/agents/openclaw/wechat-runtime/package-lock.json b/agents/openclaw/wechat-runtime/package-lock.json new file mode 100644 index 00000000000..edcabbfb93a --- /dev/null +++ b/agents/openclaw/wechat-runtime/package-lock.json @@ -0,0 +1,52 @@ +{ + "name": "nemoclaw-wechat-runtime", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nemoclaw-wechat-runtime", + "version": "0.0.0", + "license": "Apache-2.0", + "dependencies": { + "@tencent-weixin/openclaw-weixin": "2.4.3" + }, + "engines": { + "node": ">=22.16.0" + } + }, + "node_modules/@tencent-weixin/openclaw-weixin": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@tencent-weixin/openclaw-weixin/-/openclaw-weixin-2.4.3.tgz", + "integrity": "sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw==", + "license": "MIT", + "dependencies": { + "qrcode-terminal": "0.12.0", + "zod": "^4.3.6" + }, + "engines": { + "node": ">=22" + }, + "peerDependencies": { + "openclaw": ">=2026.3.22" + } + }, + "node_modules/qrcode-terminal": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/qrcode-terminal/-/qrcode-terminal-0.12.0.tgz", + "integrity": "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ==", + "bin": { + "qrcode-terminal": "bin/qrcode-terminal.js" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/agents/openclaw/wechat-runtime/package.json b/agents/openclaw/wechat-runtime/package.json new file mode 100644 index 00000000000..6d753dff32c --- /dev/null +++ b/agents/openclaw/wechat-runtime/package.json @@ -0,0 +1,14 @@ +{ + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "name": "nemoclaw-wechat-runtime", + "version": "0.0.0", + "private": true, + "description": "Locked production dependency graph for the OpenClaw WeChat plugin", + "license": "Apache-2.0", + "dependencies": { + "@tencent-weixin/openclaw-weixin": "2.4.3" + }, + "engines": { + "node": ">=22.16.0" + } +} diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 61e23330b20..533985f57b0 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -460,6 +460,11 @@ "file": "test/vitest-watch-triggers.test.ts", "test": "registers the focused mappings at the root configuration boundary (#6692)", "category": "compatibility" + }, + { + "file": "test/wechat-runtime-audit-workflow.test.ts", + "test": "makes the trusted audit required in PR and main workflows", + "category": "security" } ] } diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 39b788f7d8e..58eb79fdd5f 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -4,6 +4,8 @@ Review date: 2026-07-03 Advisory audit revalidated: 2026-07-03 +WeChat locked-graph audit revalidated: 2026-07-12 + Scope: NemoClaw runtime pin `openclaw@2026.6.10`, runtime helper pin `@zed-industries/codex-acp@0.11.1`, optional OpenClaw plugins, and built-in messaging OpenClaw plugins. ## Issue #5591 Acceptance Mapping @@ -36,7 +38,7 @@ Issue #5591 is the dependency-update umbrella, and its proposed design has three - WeChat channel plugin package: `@tencent-weixin/openclaw-weixin@2.4.3` - WeChat channel plugin npm integrity: `sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw==` -NemoClaw enforces the main `openclaw@2026.6.10`, `@zed-industries/codex-acp@0.11.1`, and each reviewed npm plugin registry integrity and reviewed registry tarball URL, including optional OTEL/brave plugins and messaging plugins, before install. `scripts/lib/reviewed-npm-archive.mts` is the shared implementation used by the Docker build boundaries and the messaging build applier. It queries registry metadata by exact package spec, packs only the reviewed tarball URL with `npm pack --json`, requires the downloaded tarball integrity to match the committed SRI, rejects reported archive filenames that are absolute, contain path separators, equal `.` or `..`, resolve outside the fresh pack directory, are missing, or are not regular files, and returns only the verified local `.tgz` path. A production image may skip duplicate OpenClaw and locked-mcporter installation only when an official NemoClaw base carries the protected exact provenance marker described below. +NemoClaw enforces the main `openclaw@2026.6.10`, `@zed-industries/codex-acp@0.11.1`, and each reviewed npm plugin registry integrity and reviewed registry tarball URL, including optional OTEL/brave plugins and messaging plugins, before install. `scripts/lib/reviewed-npm-archive.mts` is the shared implementation used by the Docker build boundaries and the messaging build applier. It queries registry metadata by exact package spec, packs only the reviewed tarball URL with `npm pack --json`, requires the downloaded tarball integrity to match the committed SRI, rejects reported archive filenames with unsafe archive paths—including values that are absolute, contain path separators, equal `.` or `..`, or resolve outside the fresh pack directory—or files that are missing or are not regular files, and returns only the verified local `.tgz` path. A production image may skip duplicate OpenClaw and locked-mcporter installation only when an official NemoClaw base carries the protected exact provenance marker described below. ## Upstream Release Boundary @@ -70,7 +72,7 @@ This review is an advisory snapshot for the direct OpenClaw runtime package, Cod The OpenClaw 2026.6.10 bump does not newly introduce an unfrozen OpenClaw transitive graph. The reviewed `openclaw@2026.6.10` artifact ships `npm-shrinkwrap.json`; the previous reviewed `openclaw@2026.6.9` artifact also shipped `npm-shrinkwrap.json`. A spot check of the reviewed 2026.6.10 package found lockfile version `3`, `306` package entries, and no resolved package entries missing integrity metadata. The reviewed `@openclaw/diagnostics-otel@2026.6.10`, `@openclaw/brave-plugin@2026.6.10`, `@openclaw/discord@2026.6.10`, `@openclaw/slack@2026.6.10`, `@openclaw/whatsapp@2026.6.10`, and `@openclaw/msteams@2026.6.10` artifacts also ship `npm-shrinkwrap.json`. -`@zed-industries/codex-acp@0.11.1` has no declared npm dependencies, so the committed package SRI plus reviewed tarball URL fully describes its npm install input for this release. The only reviewed messaging plugin without a package-internal shrinkwrap is the existing non-OpenClaw Tencent WeChat plugin, `@tencent-weixin/openclaw-weixin@2.4.3`; it was already installed by package spec before this OpenClaw bump, and this PR adds a committed top-level SRI check for that unchanged package. NemoClaw accepts that existing WeChat transitive range risk for this dependency bump because it is not introduced by the OpenClaw version change and because default production installs now fail closed on top-level registry integrity drift, tarball-integrity drift, and unsafe archive paths. A future installer-policy PR should move third-party messaging plugins without package-internal shrinkwraps to a NemoClaw-owned lock/audit gate. +`@zed-industries/codex-acp@0.11.1` has no declared npm dependencies, so the committed package SRI plus reviewed tarball URL fully describes its npm install input for this release. At the time of this review, the only reviewed messaging plugin without a package-internal shrinkwrap was the existing non-OpenClaw Tencent WeChat plugin, `@tencent-weixin/openclaw-weixin@2.4.3`; the dependency bump accepted that transitive range risk while enforcing the top-level SRI and reviewed tarball URL. Current NemoClaw builds close that residual with a committed lock for the WeChat production graph. The image materializes the reviewed graph in a root-owned cache that the sandbox user cannot write, copies it into a disposable writable cache for the offline plugin install, verifies the installed managed graph against the committed lock, and removes the temporary cache in the same image layer. ## Slack Source Review @@ -280,9 +282,9 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr - The #4434 compatibility-shim disposition is explicitly accepted for this OpenClaw 2026.6.10 PR only: `test/issue-4434-error-fields.test.ts` verifies 3/3 fields are present in the NemoClaw-patched runtime output and 3/3 fields are missing in the upstream-shaped `openclaw@2026.6.10` output. On the next OpenClaw bump that emits equivalent fields upstream, remove `scripts/patch-openclaw-issue-4434-diagnostics.ts` in the same change and keep the full live assertions. - The assembled-image and rebuilt-sandbox proof residual is explicitly accepted for this OpenClaw 2026.6.10 dependency bump only. The checked-in real-distribution harness binds the SRI-verified package to every reviewed patch and audit marker; production image workflows run the build-argument guard before assembling the final images; `network-policy` exercises the resulting OpenShell policy; and `messaging-providers`, `hermes-discord`, `channels-add-remove`, and both `channels-stop-start` variants exercise rebuilt sandboxes, installed messaging runtimes, and keyless registered-provider reuse without credential replacement. No single lane combines the final production image, a live `host.openshell.internal` SSRF-negative matrix, and every keyless custom-provider rebuild, so a cross-boundary packaging or wiring regression remains possible even though each boundary fails closed independently. Do not describe this as one combined end-to-end proof. Remove this acceptance when the canonical E2E matrix gains that assembled-image cross-product, or re-evaluate it on the next OpenClaw bump before retaining the same split proof. - The literal issue #2478 Local Ollama plus Telegram inbound recovery residual is explicitly accepted for this OpenClaw 2026.6.10 dependency bump only. `issue-2478-crash-loop-recovery` proves repeated gateway kill/respawn, guard-chain restoration, `inference.local` availability, and soak stability through a hermetic compatible endpoint; `messaging-providers` separately imports the installed Telegram `runtime-api.js`, sends through `sendMessageTelegram`, and verifies token rewrite plus fake Bot API capture. This does not reproduce `nemotron-3-super:120b` on Local Ollama or originate a Telegram inbound update after the crash, so agent/channel-specific inbound restart behavior remains a residual rather than proven equivalence. Do not claim the literal deployment scenario from these split lanes. Remove this acceptance when a stable CI fixture drives a Telegram inbound update through the recovered Local Ollama sandbox, or re-evaluate it on the next OpenClaw bump. -- The transitive npm graph warning is dispositioned by package evidence rather than a new NemoClaw-owned lockfile in this dependency bump: the reviewed OpenClaw runtime and `@openclaw/*` plugin artifacts ship package-internal `npm-shrinkwrap.json` files with integrity metadata, `@zed-industries/codex-acp@0.11.1` has no npm dependency tree, and the only reviewed non-shrinkwrapped plugin is the pre-existing Tencent WeChat package whose top-level SRI is now enforced. A future installer-policy PR should add a NemoClaw-owned lock/audit gate for third-party messaging plugins without package-internal shrinkwraps. +- The transitive npm graph warning was accepted for this dependency bump because the reviewed OpenClaw runtime and `@openclaw/*` plugin artifacts ship package-internal `npm-shrinkwrap.json` files with integrity metadata, `@zed-industries/codex-acp@0.11.1` has no npm dependency tree, and the pre-existing Tencent WeChat package had only its top-level SRI enforced. Current NemoClaw closes the WeChat residual with `agents/openclaw/wechat-runtime/package-lock.json`, an offline install from the reviewed graph, and post-install verification of package versions, integrity metadata, the dependency set, and compatibility between the image's OpenClaw version and the plugin's locked peer range. - `src/lib/messaging/channels/manifests.test.ts` remains below the shared `test-size:check` threshold and does not need extraction in this dependency bump. -- The npm audit result in this note remains a point-in-time snapshot. Default PR and main CI now rematerialize the production-compatible graph from the reviewed local archives, audit it and the committed mcporter lock with `npm audit --omit=dev --json`, upload both raw reports, and fail at the configured `high` threshold. +- The npm audit result in this note remains a point-in-time snapshot. Default PR and main CI rematerialize the production-compatible graph from the reviewed local archives, audit it and the committed mcporter lock with `npm audit --omit=dev --json`, upload both raw reports, and fail at the configured `high` threshold. The separate `wechat-runtime-audit` gate uses Node `22.19.0` and npm `10.9.4`, installs the committed WeChat production lock with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through a copied writable cache, and uploads its evidence. Pull requests execute that WeChat audit action from the base SHA; because PR #6739's base predates the action, that PR alone may bootstrap it from signed immutable commit `HOYALIM/NemoClaw@0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2`, while every other PR fails closed if its base lacks the action. The production installer routes registry metadata lookup, archive packing, and installation through the disposable writable-cache boundary so retrieval cannot fall back to `HOME/.npm`; the trusted source cache remains read-only and the disposable copy is removed in the same image layer. - The stale nonterminal rebuild-resume repair in `src/lib/actions/sandbox/rebuild-resume-session.ts` remains a migration compatibility shim tracked against #4533's onboard FSM/resume compatibility boundary. Its removal condition is to delete it after a session-version migration proves recreate sessions are always persisted at a resumable pre-sandbox boundary; `src/lib/actions/sandbox/rebuild-resume-session.test.ts` covers the helper directly, `test/onboard-resume-provider-recovery.test.ts` carries the onboard-suite producer-level regression for `machine.state='openclaw'`, and `src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts` owns the rebuild handoff regression. - Production OpenClaw image build paths call `scripts/check-production-build-args.sh` before production `docker build` or `docker/build-push-action` use. `test/openclaw-dependency-review.test.ts` keeps that workflow contract documented. - The rebuild-reasoning cases added by this PR live in the focused `rebuild-resume-reasoning.test.ts` file; the smaller route-provenance additions remain with their `rebuild-resume-config.ts` boundary tests. diff --git a/scripts/lib/reviewed-npm-archive.mts b/scripts/lib/reviewed-npm-archive.mts index b0394599c9e..88a18687ff1 100755 --- a/scripts/lib/reviewed-npm-archive.mts +++ b/scripts/lib/reviewed-npm-archive.mts @@ -3,13 +3,14 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; -import { existsSync, lstatSync, mkdtempSync, rmSync } from "node:fs"; +import { existsSync, lstatSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { isAbsolute, join, resolve, sep } from "node:path"; import { pathToFileURL } from "node:url"; const NPM_OUTPUT_MAX_BUFFER = 16 * 1024 * 1024; -const EXACT_NPM_PACKAGE_SPEC = /^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)@[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/; +const EXACT_NPM_PACKAGE_SPEC = + /^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)@[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/; export type ReviewedNpmArchiveRequest = Readonly<{ env?: NodeJS.ProcessEnv; @@ -21,6 +22,15 @@ export type ReviewedNpmArchiveRequest = Readonly<{ tempDirectory?: string; }>; +export type ReviewedNpmCacheRequest = Readonly<{ + cacheDirectory: string; + env?: NodeJS.ProcessEnv; + lockfilePath: string; + npmExecutable?: string; + registryOrigin: string; + tempDirectory?: string; +}>; + export type ReviewedNpmMetadata = Readonly<{ integrity: string; tarballUrl: string; @@ -153,11 +163,7 @@ export function packReviewedNpmArchive( ); } return { - archivePath: resolveReviewedNpmArchivePath( - request.packageSpec, - rootDirectory, - filename, - ), + archivePath: resolveReviewedNpmArchivePath(request.packageSpec, rootDirectory, filename), rootDirectory, }; } catch (error) { @@ -170,7 +176,156 @@ export function removeReviewedNpmArchive(archive: ReviewedNpmArchive): void { rmSync(archive.rootDirectory, { recursive: true, force: true }); } -type CliOptions = ReviewedNpmArchiveRequest & Readonly<{ verifyOnly: boolean }>; +function normalizeRegistryOrigin(value: string): string { + let parsed: URL; + try { + parsed = new URL(value); + } catch { + throw new Error(`reviewed npm registry origin is invalid: ${value}`); + } + if ( + parsed.protocol !== "https:" || + parsed.username || + parsed.password || + parsed.pathname !== "/" || + parsed.search || + parsed.hash + ) { + throw new Error(`reviewed npm registry must be a credential-free HTTPS origin: ${value}`); + } + return parsed.origin; +} + +function readReviewedLockPackages( + lockfilePath: string, + registryOrigin: string, +): readonly ReviewedNpmArchiveRequest[] { + let lock: unknown; + try { + lock = JSON.parse(readFileSync(lockfilePath, "utf-8")); + } catch (error) { + throw new Error(`reviewed npm lockfile is unreadable: ${String(error)}`); + } + if (typeof lock !== "object" || lock === null || Array.isArray(lock)) { + throw new Error("reviewed npm lockfile must be a JSON object"); + } + const lockRecord = lock as Record; + if (lockRecord.lockfileVersion !== 3) { + throw new Error("reviewed npm cache requires lockfileVersion 3"); + } + const packages = lockRecord.packages; + if (typeof packages !== "object" || packages === null || Array.isArray(packages)) { + throw new Error("reviewed npm lockfile is missing its packages map"); + } + + const reviewed: ReviewedNpmArchiveRequest[] = []; + const identities = new Set(); + for (const [location, value] of Object.entries(packages)) { + if (location === "") continue; + const marker = "node_modules/"; + const nestedMarkerIndex = location.lastIndexOf(`/${marker}`); + const markerIndex = location.startsWith(marker) + ? 0 + : nestedMarkerIndex >= 0 + ? nestedMarkerIndex + 1 + : -1; + const packageName = markerIndex >= 0 ? location.slice(markerIndex + marker.length) : ""; + if (!packageName) { + throw new Error(`reviewed npm lock has an unsupported package location: ${location}`); + } + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error(`reviewed npm lock has an invalid package record: ${location}`); + } + const record = value as Record; + const version = typeof record.version === "string" ? record.version : ""; + const packageSpec = `${packageName}@${version}`; + const expectedIntegrity = typeof record.integrity === "string" ? record.integrity : ""; + const tarballUrl = typeof record.resolved === "string" ? record.resolved : ""; + requireReviewedRequest({ + expectedIntegrity, + label: `locked npm package ${packageSpec}`, + packageSpec, + tarballUrl, + }); + let parsedTarball: URL; + try { + parsedTarball = new URL(tarballUrl); + } catch { + throw new Error(`reviewed npm lock has an invalid tarball URL: ${location}`); + } + if ( + parsedTarball.origin !== registryOrigin || + parsedTarball.username || + parsedTarball.password + ) { + throw new Error(`reviewed npm lock package must use the reviewed registry: ${location}`); + } + if (identities.has(packageSpec)) { + throw new Error(`reviewed npm lock repeats package identity: ${packageSpec}`); + } + identities.add(packageSpec); + reviewed.push({ + expectedIntegrity, + label: `locked npm package ${packageSpec}`, + packageSpec, + tarballUrl, + }); + } + if (reviewed.length === 0) throw new Error("reviewed npm lock contains no packages"); + return reviewed; +} + +export function verifyReviewedNpmCache( + request: ReviewedNpmCacheRequest, + npmRunner: NpmRunner = runNpm, +): readonly string[] { + if (!isAbsolute(request.cacheDirectory)) { + throw new Error(`reviewed npm cache path must be absolute: ${request.cacheDirectory}`); + } + const cacheDirectory = resolve(request.cacheDirectory); + if (!existsSync(cacheDirectory)) { + throw new Error(`reviewed npm cache does not exist: ${cacheDirectory}`); + } + const cache = lstatSync(cacheDirectory); + if (!cache.isDirectory() || cache.isSymbolicLink()) { + throw new Error(`reviewed npm cache must be a non-symlink directory: ${cacheDirectory}`); + } + + const registryOrigin = normalizeRegistryOrigin(request.registryOrigin); + const packages = readReviewedLockPackages(request.lockfilePath, registryOrigin); + const env = { + ...process.env, + ...request.env, + NPM_CONFIG_AUDIT: "false", + NPM_CONFIG_CACHE: cacheDirectory, + NPM_CONFIG_FUND: "false", + NPM_CONFIG_IGNORE_SCRIPTS: "true", + NPM_CONFIG_OFFLINE: "true", + NPM_CONFIG_REGISTRY: `${registryOrigin}/`, + NPM_CONFIG_UPDATE_NOTIFIER: "false", + NPM_CONFIG_USERCONFIG: "/dev/null", + }; + const verified: string[] = []; + for (const reviewed of packages) { + const archive = packReviewedNpmArchive( + { + ...reviewed, + env, + npmExecutable: request.npmExecutable, + tempDirectory: request.tempDirectory, + }, + npmRunner, + ); + removeReviewedNpmArchive(archive); + verified.push(reviewed.packageSpec); + } + return verified; +} + +type ArchiveCliOptions = ReviewedNpmArchiveRequest & + Readonly<{ mode: "archive"; verifyOnly: boolean }>; +type CacheCliOptions = ReviewedNpmCacheRequest & Readonly<{ mode: "cache" }>; +type CliOptions = ArchiveCliOptions | CacheCliOptions; function parseCliOptions(argv: readonly string[]): CliOptions { const values = new Map(); @@ -192,9 +347,29 @@ function parseCliOptions(argv: readonly string[]): CliOptions { if (!value) throw new Error(`${name} is required`); return value; }; + if (values.has("--lockfile") || values.has("--cache") || values.has("--registry-origin")) { + if ( + verifyOnly || + values.has("--package-spec") || + values.has("--integrity") || + values.has("--tarball-url") || + values.has("--label") + ) { + throw new Error("reviewed npm cache verification cannot be combined with archive options"); + } + return { + cacheDirectory: required("--cache"), + lockfilePath: required("--lockfile"), + mode: "cache", + npmExecutable: process.env.NEMOCLAW_REVIEWED_NPM_EXECUTABLE, + registryOrigin: required("--registry-origin"), + tempDirectory: values.get("--temp-directory"), + }; + } return { expectedIntegrity: required("--integrity"), label: required("--label"), + mode: "archive", npmExecutable: process.env.NEMOCLAW_REVIEWED_NPM_EXECUTABLE, packageSpec: required("--package-spec"), tarballUrl: required("--tarball-url"), @@ -210,7 +385,10 @@ function isMainModule(): boolean { if (isMainModule()) { try { const options = parseCliOptions(process.argv.slice(2)); - if (options.verifyOnly) { + if (options.mode === "cache") { + const verified = verifyReviewedNpmCache(options); + process.stdout.write(`Verified ${verified.length} locked npm cache archives\n`); + } else if (options.verifyOnly) { verifyReviewedNpmMetadata(options); } else { process.stdout.write(`${packReviewedNpmArchive(options).archivePath}\n`); diff --git a/scripts/verify-wechat-runtime-lock.mts b/scripts/verify-wechat-runtime-lock.mts new file mode 100644 index 00000000000..24e90ce0656 --- /dev/null +++ b/scripts/verify-wechat-runtime-lock.mts @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +const WECHAT_PACKAGE = "@tencent-weixin/openclaw-weixin"; +const WECHAT_LOCATION = `node_modules/${WECHAT_PACKAGE}`; + +type PackageRecord = { + version?: string; + integrity?: string; + dependencies?: Record; + peerDependencies?: Record; +}; + +type PackageLock = { + packages?: Record; +}; + +function readJson(file: string): unknown { + const descriptor = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + if (!fs.fstatSync(descriptor).isFile()) { + throw new Error(`refusing unsafe package metadata path: ${file}`); + } + return JSON.parse(fs.readFileSync(descriptor, "utf8")); + } finally { + fs.closeSync(descriptor); + } +} + +function packageMetadata(file: string): PackageRecord { + const parsed = readJson(file); + const record = parsed && typeof parsed === "object" ? (parsed as PackageRecord) : {}; + const version = record.version; + if (typeof version !== "string") { + throw new Error(`package metadata has no version: ${file}`); + } + return record; +} + +export function expectedWechatGraph(lock: PackageLock): ReadonlyMap { + const graph = new Map( + Object.entries(lock.packages ?? {}).filter(([location]) => + location.startsWith("node_modules/"), + ), + ); + if (!graph.has(WECHAT_LOCATION)) { + throw new Error(`WeChat runtime lock does not contain ${WECHAT_PACKAGE}`); + } + return graph; +} + +function findInstalledLock(projectsRoot: string): string { + const matches = fs + .readdirSync(projectsRoot, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink()) + .map((entry) => path.join(projectsRoot, entry.name, "package-lock.json")) + .filter((lockFile) => { + if (!fs.existsSync(lockFile)) return false; + const lock = readJson(lockFile) as PackageLock; + return Boolean(lock.packages?.[WECHAT_LOCATION]); + }); + if (matches.length !== 1) { + throw new Error(`expected one managed WeChat npm project, found ${matches.length}`); + } + return matches[0] as string; +} + +function normalizedRecord(record: PackageRecord): PackageRecord { + return { + version: record.version, + integrity: record.integrity, + dependencies: Object.fromEntries( + Object.entries(record.dependencies ?? {}).sort(([left], [right]) => + left.localeCompare(right), + ), + ), + peerDependencies: Object.fromEntries( + Object.entries(record.peerDependencies ?? {}).sort(([left], [right]) => + left.localeCompare(right), + ), + ), + }; +} + +function numericVersion(value: string, label: string): readonly number[] { + if (!/^\d+(?:\.\d+)*$/.test(value)) { + throw new Error(`${label} must be a numeric dotted version: ${value}`); + } + return value.split(".").map(Number); +} + +export function verifyOpenClawPeerCompatibility(runtimeVersion: string, peerRange: string): void { + const minimumMatch = peerRange.match(/^>=(\d+(?:\.\d+)*)$/); + if (!minimumMatch?.[1]) { + throw new Error(`unsupported WeChat OpenClaw peer range: ${peerRange}`); + } + const runtime = numericVersion(runtimeVersion, "OpenClaw runtime version"); + const minimum = numericVersion(minimumMatch[1], "WeChat OpenClaw peer minimum"); + const width = Math.max(runtime.length, minimum.length); + for (let index = 0; index < width; index += 1) { + const runtimePart = runtime[index] ?? 0; + const minimumPart = minimum[index] ?? 0; + if (runtimePart > minimumPart) return; + if (runtimePart < minimumPart) { + throw new Error( + `OpenClaw ${runtimeVersion} does not satisfy WeChat peer dependency ${peerRange}`, + ); + } + } +} + +export function verifyWechatRuntimeLock( + lockFile: string, + projectsRoot: string, + openClawVersion: string, +): void { + const expected = expectedWechatGraph(readJson(lockFile) as PackageLock); + const installedLockFile = findInstalledLock(projectsRoot); + const installedRoot = path.dirname(installedLockFile); + const actual = expectedWechatGraph(readJson(installedLockFile) as PackageLock); + + if ([...actual.keys()].sort().join("\0") !== [...expected.keys()].sort().join("\0")) { + throw new Error("installed WeChat dependency set does not match the reviewed lock"); + } + for (const [location, expectedRecord] of expected) { + const actualRecord = actual.get(location); + if ( + JSON.stringify(normalizedRecord(actualRecord ?? {})) !== + JSON.stringify(normalizedRecord(expectedRecord)) + ) { + throw new Error(`${location} metadata does not match the reviewed lock`); + } + const packageName = location.slice("node_modules/".length); + const installedMetadata = packageMetadata( + path.join(installedRoot, location, "package.json"), + ); + if (installedMetadata.version !== expectedRecord.version) { + throw new Error( + `installed ${packageName}@${installedMetadata.version} does not match locked ${expectedRecord.version}`, + ); + } + if (location === WECHAT_LOCATION) { + const expectedPeerRange = expectedRecord.peerDependencies?.openclaw; + const installedPeerRange = installedMetadata.peerDependencies?.openclaw; + if (!expectedPeerRange || installedPeerRange !== expectedPeerRange) { + throw new Error("installed WeChat OpenClaw peer range does not match the reviewed lock"); + } + verifyOpenClawPeerCompatibility(openClawVersion, expectedPeerRange); + } + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const [, , lockFile, projectsRoot, openClawVersion] = process.argv; + if (!lockFile || !projectsRoot || !openClawVersion) { + throw new Error( + "usage: verify-wechat-runtime-lock.mts ", + ); + } + verifyWechatRuntimeLock(lockFile, projectsRoot, openClawVersion); +} diff --git a/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 2ad0b7afb45..ffd14f67bd0 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -3,9 +3,21 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; -import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + accessSync, + chmodSync, + constants, + existsSync, + lstatSync, + mkdirSync, + readFileSync, + realpathSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; import { homedir } from "node:os"; -import { dirname, join, resolve, sep } from "node:path"; +import { dirname, isAbsolute, join, resolve, sep } from "node:path"; import { pathToFileURL } from "node:url"; import { packReviewedNpmArchive } from "../../../../../scripts/lib/reviewed-npm-archive.mts"; import { discordManifest } from "../../channels/discord/manifest.ts"; @@ -14,7 +26,7 @@ import { teamsManifest } from "../../channels/teams/manifest.ts"; import { telegramManifest } from "../../channels/telegram/manifest.ts"; import { wechatManifest } from "../../channels/wechat/manifest.ts"; import { whatsappManifest } from "../../channels/whatsapp/manifest.ts"; -import type { ChannelManifest } from "../../manifest/types.ts"; +import type { ChannelAgentPackageRuntimeLockSpec, ChannelManifest } from "../../manifest/types.ts"; type Env = Record; type JsonObject = Record; @@ -116,6 +128,7 @@ type OpenClawPluginInstall = { readonly npmPackageSpec?: string; readonly integrity?: string; readonly tarballUrl?: string; + readonly runtimeLock?: ChannelAgentPackageRuntimeLockSpec; readonly pin: boolean; }; @@ -195,6 +208,28 @@ export function reviewedOpenClawPluginTarballUrlByPackageSpec( ); } +function reviewedOpenClawPluginRuntimeLocksByPackageSpec( + env: Env, + manifests: readonly ChannelManifest[], +): Readonly> { + const entries: [string, ChannelAgentPackageRuntimeLockSpec][] = []; + for (const manifest of manifests) { + for (const packageSpec of manifest.agentPackages ?? []) { + if ( + packageSpec.agent !== "openclaw" || + packageSpec.manager !== "openclaw-plugin" || + !packageSpec.runtimeLock + ) { + continue; + } + const resolvedSpec = resolveOpenClawPackageSpec(packageSpec.spec, env); + const npmPackage = requireExactNpmPackageSpec(resolvedSpec, manifest.id); + entries.push([npmPackage.packageSpec, packageSpec.runtimeLock]); + } + } + return Object.freeze(Object.fromEntries(entries)); +} + export function readMessagingBuildPlanFromEnv( env: Env, agent: MessagingAgentId, @@ -499,6 +534,7 @@ function collectOpenClawMessagingPluginInstalls( const trustedSpecs = trustedOpenClawPluginSpecsForManifests(trustedManifests, env); const reviewedIntegrity = reviewedOpenClawPluginIntegrityByPackageSpec(env, trustedManifests); const reviewedTarballUrls = reviewedOpenClawPluginTarballUrlByPackageSpec(env, trustedManifests); + const runtimeLocks = reviewedOpenClawPluginRuntimeLocksByPackageSpec(env, trustedManifests); for (const step of enabledBuildStepsForPhase(plan, "agent-install")) { if (step.kind !== "package-install") continue; if (step.value === undefined) { @@ -524,6 +560,9 @@ function collectOpenClawMessagingPluginInstalls( ...(npmPackage ? { npmPackageSpec: npmPackage.packageSpec } : {}), ...(integrity ? { integrity } : {}), ...(tarballUrl ? { tarballUrl } : {}), + ...(npmPackage && runtimeLocks[npmPackage.packageSpec] + ? { runtimeLock: runtimeLocks[npmPackage.packageSpec] } + : {}), pin: integrity !== undefined, }; const key = JSON.stringify(resolvedInstall); @@ -650,7 +689,25 @@ export function openClawDoctorEnvOverrides( export function installOpenClawMessagingPlugins(plan: MessagingBuildPlan | null, env: Env): void { for (const install of collectOpenClawMessagingPluginInstalls(plan, env)) { - const packed = packVerifiedOpenClawPluginArchive(install, env); + const installCache = install.runtimeLock + ? requireWritableRuntimeInstallCache(install.runtimeLock, env) + : undefined; + const installEnv = { + ...env, + NPM_CONFIG_IGNORE_SCRIPTS: "true", + npm_config_ignore_scripts: "true", + ...(install.runtimeLock + ? { + NPM_CONFIG_CACHE: installCache, + NPM_CONFIG_OFFLINE: String(install.runtimeLock.offline), + NPM_CONFIG_LEGACY_PEER_DEPS: String(install.runtimeLock.legacyPeerDeps), + } + : {}), + }; + // Resolve registry metadata and pack the reviewed archive through the same + // disposable cache used by OpenClaw. Selecting it after packing can leave + // fetched bytes in HOME/.npm in an earlier image layer. + const packed = packVerifiedOpenClawPluginArchive(install, installEnv); try { // Install through the `npm-pack:` spec so OpenClaw records npm // provenance (source, resolved name/version, integrity) for the @@ -659,17 +716,77 @@ export function installOpenClawMessagingPlugins(plan: MessagingBuildPlan | null, // on OpenClaw >= 2026.6.10 and crash-loops channel plugins that use // keyed state (e.g. WhatsApp). npm-pack installs always record the // exact resolved version, so `--pin` is not needed. - runCommand(["openclaw", "plugins", "install", `npm-pack:${packed.archivePath}`], { - ...env, - NPM_CONFIG_IGNORE_SCRIPTS: "true", - npm_config_ignore_scripts: "true", - }); + runCommand(["openclaw", "plugins", "install", `npm-pack:${packed.archivePath}`], installEnv); + if (install.runtimeLock) { + const openClawVersion = sanitizeOptionalString(env.OPENCLAW_VERSION); + if (!openClawVersion) { + throw new MessagingBuildApplierError( + "OPENCLAW_VERSION is required to verify the WeChat plugin peer dependency", + ); + } + runCommand( + [ + "node", + "--experimental-strip-types", + install.runtimeLock.verifierPath, + install.runtimeLock.lockFile, + install.runtimeLock.projectsRoot, + openClawVersion, + ], + installEnv, + ); + } } finally { rmSync(packed.rootDir, { recursive: true, force: true }); } } } +export function requireWritableRuntimeInstallCache( + runtimeLock: ChannelAgentPackageRuntimeLockSpec, + env: Env, +): string { + const configured = sanitizeOptionalString(env[runtimeLock.installCacheEnvKey]); + if (!configured) { + throw new MessagingBuildApplierError( + `${runtimeLock.installCacheEnvKey} must name the sandbox-writable temporary npm cache prepared from ${runtimeLock.cachePath}`, + ); + } + if (!isAbsolute(configured)) { + throw new MessagingBuildApplierError( + `${runtimeLock.installCacheEnvKey} must be an absolute path`, + ); + } + + let installCache: string; + try { + if (lstatSync(configured).isSymbolicLink()) { + throw new Error("symbolic links are not allowed"); + } + installCache = realpathSync(configured); + if (!statSync(installCache).isDirectory()) { + throw new Error("path is not a directory"); + } + accessSync(installCache, constants.R_OK | constants.W_OK | constants.X_OK); + } catch (error) { + throw new MessagingBuildApplierError( + `${runtimeLock.installCacheEnvKey} must be a writable, searchable directory: ${formatError(error)}`, + ); + } + + // Canonicalize an existing trusted root too: on macOS, for example, /var + // resolves through /private/var and must still compare equal to installCache. + const trustedCache = existsSync(runtimeLock.cachePath) + ? realpathSync(runtimeLock.cachePath) + : resolve(runtimeLock.cachePath); + if (installCache === trustedCache || installCache.startsWith(`${trustedCache}${sep}`)) { + throw new MessagingBuildApplierError( + `${runtimeLock.installCacheEnvKey} must not make the trusted npm cache writable`, + ); + } + return installCache; +} + export function runOpenClawMessagingDoctor(plan: MessagingBuildPlan | null, env: Env): void { if (!plan) return; runCommand(["openclaw", "doctor", "--fix", "--non-interactive"], { diff --git a/src/lib/messaging/channels/wechat/manifest.ts b/src/lib/messaging/channels/wechat/manifest.ts index e5b135dcebb..aece6759aa0 100644 --- a/src/lib/messaging/channels/wechat/manifest.ts +++ b/src/lib/messaging/channels/wechat/manifest.ts @@ -137,6 +137,15 @@ export const wechatManifest = { "sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw==", tarballUrl: "https://registry.npmjs.org/@tencent-weixin/openclaw-weixin/-/openclaw-weixin-2.4.3.tgz", + runtimeLock: { + cachePath: "/usr/local/share/nemoclaw/wechat-npm-cache", + installCacheEnvKey: "NEMOCLAW_WECHAT_NPM_INSTALL_CACHE", + lockFile: "/usr/local/lib/nemoclaw/wechat-runtime/package-lock.json", + projectsRoot: "/sandbox/.openclaw/npm/projects", + verifierPath: "/usr/local/lib/nemoclaw/verify-wechat-runtime-lock.mts", + offline: true, + legacyPeerDeps: true, + }, required: true, }, ], diff --git a/src/lib/messaging/manifest/types.ts b/src/lib/messaging/manifest/types.ts index 7255f9c823b..e94a806d3ea 100644 --- a/src/lib/messaging/manifest/types.ts +++ b/src/lib/messaging/manifest/types.ts @@ -203,6 +203,16 @@ export interface ChannelRuntimeSecretScanSpec { export type ChannelAgentPackageManager = "openclaw-plugin" | "hermes-uv-pip"; +export interface ChannelAgentPackageRuntimeLockSpec { + readonly cachePath: string; + readonly installCacheEnvKey: string; + readonly lockFile: string; + readonly projectsRoot: string; + readonly verifierPath: string; + readonly offline: true; + readonly legacyPeerDeps: true; +} + /** Agent package/plugin install the sandbox image build should apply. */ export interface ChannelAgentPackageSpec { readonly id: string; @@ -214,6 +224,7 @@ export interface ChannelAgentPackageSpec { readonly integrityByVersion?: Readonly>; readonly tarballUrl?: string; readonly tarballUrlByVersion?: Readonly>; + readonly runtimeLock?: ChannelAgentPackageRuntimeLockSpec; readonly required?: boolean; } diff --git a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts index 91cd8b8696f..964944f1d29 100644 --- a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts +++ b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts @@ -47,6 +47,7 @@ const CANONICAL_POST_GENERATOR_RUN_SHA256 = new Set([ "d50e094416f150f74c24f81665be08064a1c5bd23c11d29575b20379b5a58ce2", "42ef0b12e92ebe146c25367831b4ce3a2664f0fa99fd5e4fb98a8939d3af8800", "8b49e78185185f1b7e24d01631186554fef21d2300db65c9bc9998e7ec00469f", + "a0a554d474cb70087e50686d998915eae06201d6182a2410d3ccc4879e5058e6", ]); function instructionSha256(text: string): string { diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index e5c938dc09b..74870b9010e 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -40,12 +40,14 @@ function normalizeReadModesForDockerCopy(rootDir: string): void { } } -function stageMcporterRuntime(rootDir: string, buildCtx: string): void { - const sourceDir = path.join(rootDir, "agents", "openclaw", "mcporter-runtime"); - const stagedDir = path.join(buildCtx, "agents", "openclaw", "mcporter-runtime"); - fs.mkdirSync(stagedDir, { recursive: true }); - for (const fileName of ["package.json", "package-lock.json"]) { - fs.copyFileSync(path.join(sourceDir, fileName), path.join(stagedDir, fileName)); +function stageOpenClawRuntimeGraphs(rootDir: string, buildCtx: string): void { + for (const runtimeName of ["mcporter-runtime", "wechat-runtime"]) { + const sourceDir = path.join(rootDir, "agents", "openclaw", runtimeName); + const stagedDir = path.join(buildCtx, "agents", "openclaw", runtimeName); + fs.mkdirSync(stagedDir, { recursive: true }); + for (const fileName of ["package.json", "package-lock.json"]) { + fs.copyFileSync(path.join(sourceDir, fileName), path.join(stagedDir, fileName)); + } } normalizeReadModesForDockerCopy(path.join(buildCtx, "agents")); } @@ -60,7 +62,7 @@ function stageLegacySandboxBuildContext( path.join(rootDir, "tsconfig.runtime-preloads.json"), path.join(buildCtx, "tsconfig.runtime-preloads.json"), ); - stageMcporterRuntime(rootDir, buildCtx); + stageOpenClawRuntimeGraphs(rootDir, buildCtx); fs.cpSync(path.join(rootDir, "nemoclaw"), path.join(buildCtx, "nemoclaw"), { recursive: true, }); @@ -110,7 +112,7 @@ function stageOptimizedSandboxBuildContext( path.join(rootDir, "tsconfig.runtime-preloads.json"), path.join(buildCtx, "tsconfig.runtime-preloads.json"), ); - stageMcporterRuntime(rootDir, buildCtx); + stageOpenClawRuntimeGraphs(rootDir, buildCtx); fs.mkdirSync(stagedNemoclawDir, { recursive: true }); for (const fileName of [ @@ -249,6 +251,10 @@ function stageOptimizedSandboxBuildContext( path.join(rootDir, "scripts", "patch-openclaw-device-self-approval.ts"), path.join(stagedScriptsDir, "patch-openclaw-device-self-approval.ts"), ); + fs.copyFileSync( + path.join(rootDir, "scripts", "verify-wechat-runtime-lock.mts"), + path.join(stagedScriptsDir, "verify-wechat-runtime-lock.mts"), + ); fs.mkdirSync(path.join(stagedScriptsDir, "lib"), { recursive: true }); fs.copyFileSync( path.join(rootDir, "scripts", "lib", "reviewed-npm-archive.mts"), diff --git a/test/messaging-build-applier.test.ts b/test/messaging-build-applier.test.ts index fc478fba511..99b0e393aba 100644 --- a/test/messaging-build-applier.test.ts +++ b/test/messaging-build-applier.test.ts @@ -797,6 +797,7 @@ describe("messaging-build-applier.mts: agent-install", () => { const tracePath = path.join(tmp, "openclaw.trace"); const fakeOpenclaw = path.join(tmp, "openclaw"); const fakeNpm = path.join(tmp, "npm"); + const fakeNode = path.join(tmp, "node"); fs.writeFileSync( fakeOpenclaw, [ @@ -826,6 +827,16 @@ describe("messaging-build-applier.mts: agent-install", () => { ].join("\n"), { mode: 0o755 }, ); + fs.writeFileSync( + fakeNode, + [ + "#!/bin/sh", + 'printf \'verify|%s|%s\\n\' "$3" "$4" >> "$OPENCLAW_TRACE"', + "exit 0", + "", + ].join("\n"), + { mode: 0o755 }, + ); try { const planEnv = await withLegacyMessagingPlanEnvDirect( @@ -837,6 +848,7 @@ describe("messaging-build-applier.mts: agent-install", () => { OPENCLAW_WHATSAPP_2026_6_10_INTEGRITY, OPENCLAW_MSTEAMS_2026_6_10_INTEGRITY, TENCENT_WEIXIN_2_4_3_INTEGRITY, + NEMOCLAW_WECHAT_NPM_INSTALL_CACHE: tmp, OPENCLAW_VERSION: "2026.6.10", NEMOCLAW_MESSAGING_CHANNELS_B64: channelsB64([ "telegram", @@ -888,6 +900,9 @@ describe("messaging-build-applier.mts: agent-install", () => { expect(trace).toContain("plugins|install|npm-pack:"); expect(trace).toContain(`${archiveName}||||`); } + expect(trace).toContain( + "verify|/usr/local/lib/nemoclaw/wechat-runtime/package-lock.json|/sandbox/.openclaw/npm/projects", + ); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } diff --git a/test/openclaw-dependency-review.test.ts b/test/openclaw-dependency-review.test.ts index 1cc901b6857..5ee2dbeace0 100644 --- a/test/openclaw-dependency-review.test.ts +++ b/test/openclaw-dependency-review.test.ts @@ -227,6 +227,11 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { expect(review).toContain("0` critical vulnerabilities across `763` total dependencies"); expect(review).toContain("Node `v22.22.2`"); expect(review).toContain("engine requirement of `>=22.19.0`"); + expect(review).toContain( + "separate `wechat-runtime-audit` gate uses Node `22.19.0` and npm `10.9.4`", + ); + expect(review).toContain("Node `22.19.0` and npm `10.9.4`"); + expect(review).toContain("fails on any low-or-higher production advisory"); expect(review).toContain("Default PR and main CI now rematerialize"); expect(review).toContain("`npm audit --omit=dev --json`"); expect(review).toContain("configured threshold in `ci/reviewed-npm-audit.json` is `high`"); @@ -250,13 +255,11 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { expect(review).toContain("`@openclaw/msteams@2026.6.10`"); expect(review).toContain("`@zed-industries/codex-acp@0.11.1` has no declared npm dependencies"); expect(review).toContain( - "the existing non-OpenClaw Tencent WeChat plugin, `@tencent-weixin/openclaw-weixin@2.4.3`", - ); - expect(review).toContain("not introduced by the OpenClaw version change"); - expect(review).toContain("third-party messaging plugins without package-internal shrinkwraps"); - expect(review).toContain( - "The transitive npm graph warning is dispositioned by package evidence", + "only reviewed messaging plugin without a package-internal shrinkwrap was the existing non-OpenClaw Tencent WeChat plugin", ); + expect(review).toContain("Current NemoClaw builds close that residual"); + expect(review).toContain("copies it into a disposable writable cache"); + expect(review).toContain("Current NemoClaw closes the WeChat residual"); expect(review).toContain("stale nonterminal rebuild-resume repair"); expect(review).toContain("tracked against #4533"); expect(review).toContain("src/lib/actions/sandbox/rebuild-resume-session.test.ts"); @@ -313,7 +316,7 @@ messaging_build_applier=${JSON.stringify(MESSAGING_BUILD_APPLIER)} reviewed_archive_helper=scripts/lib/reviewed-npm-archive.mts boundary_marker_count="$(grep -hF 'Reviewed-archive invariants (#5896):' Dockerfile Dockerfile.base "$messaging_build_applier" | wc -l | tr -d ' ')" -test "$boundary_marker_count" -eq 4 +test "$boundary_marker_count" -eq 5 check_contains() { haystack="$1" @@ -376,6 +379,13 @@ check_contains "$(cat Dockerfile)" "stat -c '%u:%g:%a'" "runtime provenance meta check_contains "$(cat Dockerfile)" '0:0:444' "runtime provenance exact metadata" check_contains "$(cat Dockerfile)" 'rm -rf "$OPENCLAW_PROVENANCE_PATH"' "runtime provenance consumption" +wechat_cache_block="$(sed -n '/# Reviewed-archive invariants (#5896): after npm materializes the exact lock/,/# Pre-install the codex-acp package/p' Dockerfile)" +check_contains "$wechat_cache_block" '/scripts/lib/reviewed-npm-archive.mts' "WeChat cache shared helper" +check_contains "$wechat_cache_block" '--lockfile /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json' "WeChat cache reviewed lock" +check_contains "$wechat_cache_block" '--cache /usr/local/share/nemoclaw/wechat-npm-cache' "WeChat cache boundary" +check_contains "$wechat_cache_block" '--registry-origin https://registry.npmjs.org/' "WeChat reviewed registry" +check_contains "$wechat_cache_block" 'NPM_CONFIG_OFFLINE=true' "WeChat cache offline verification" + optional_plugin_block="$(sed -n '/# Install non-messaging OpenClaw plugins that need to match the runtime./,/^RUN OPENCLAW_VERSION=/p' Dockerfile)" check_contains "$optional_plugin_block" '/scripts/lib/reviewed-npm-archive.mts' "optional plugin shared helper" check_contains "$optional_plugin_block" '--package-spec "$plugin_spec" --integrity "$expected_integrity"' "optional plugin reviewed identity" @@ -408,7 +418,7 @@ check_not_contains "$optional_plugin_block" 'pack_reviewed_npm_tarball' "optiona grep -Fq 'COPY scripts/patch-openclaw-device-self-approval.ts /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.ts' Dockerfile grep -Fq 'node --experimental-strip-types /usr/local/lib/nemoclaw/patch-openclaw-device-self-approval.ts \\' Dockerfile - phase_count="$(grep -Ec '^RUN OPENCLAW_VERSION="[$][{]OPENCLAW_VERSION[}]" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier\\.mts --agent openclaw --phase (runtime-setup|agent-install|post-agent-install)$' Dockerfile)" + phase_count="$(grep -Ec -- '--phase (runtime-setup|agent-install|post-agent-install)' Dockerfile)" test "$phase_count" -eq 3 grep -Fq -- '--phase runtime-setup' Dockerfile grep -Fq -- '--phase agent-install' Dockerfile diff --git a/test/openclaw-integrity-pin-suite.ts b/test/openclaw-integrity-pin-suite.ts index b351e83e6b2..d02b2a7377b 100644 --- a/test/openclaw-integrity-pin-suite.ts +++ b/test/openclaw-integrity-pin-suite.ts @@ -366,7 +366,7 @@ function runOptionalOpenClawPluginBlock( const command = extractRunBlock( DOCKERFILE, "# Install non-messaging OpenClaw plugins that need to match the runtime.", - 'RUN OPENCLAW_VERSION="${OPENCLAW_VERSION}" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts', + "# The reviewed cache stays root-owned and immutable to the sandbox user.", ); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-plugin-integrity-")); const log = path.join(tmp, "calls.log"); diff --git a/test/openclaw-optional-plugin-build.test.ts b/test/openclaw-optional-plugin-build.test.ts index 67d4c732eef..35315e6e087 100644 --- a/test/openclaw-optional-plugin-build.test.ts +++ b/test/openclaw-optional-plugin-build.test.ts @@ -17,12 +17,9 @@ const BRAVE_TARBALL = it("pins Brave web-search and preserves its placeholder during build-time doctor", () => { const dockerfile = fs.readFileSync(path.join(ROOT, "Dockerfile"), "utf-8"); const start = dockerfile.indexOf("# Install non-messaging OpenClaw plugins"); - const end = dockerfile.indexOf( - 'RUN OPENCLAW_VERSION="${OPENCLAW_VERSION}" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts --agent openclaw --phase agent-install', - start, - ); const command = dockerfile - .slice(dockerfile.indexOf("RUN ", start) + 4, end) + .slice(start) + .split("\nRUN ", 3)[1] .split("\n") .filter((line) => !line.trimStart().startsWith("#")) .join("\n") diff --git a/test/pr-workflow-contract.test.ts b/test/pr-workflow-contract.test.ts index 8e7bdf7b674..0a3052779fc 100644 --- a/test/pr-workflow-contract.test.ts +++ b/test/pr-workflow-contract.test.ts @@ -1009,6 +1009,7 @@ describe("pull request and main workflow contracts", () => { PLUGIN_TESTS_RESULT: "success", REVIEWED_NPM_AUDIT_RESULT: "success", STATIC_RESULT: "success", + WECHAT_RUNTIME_AUDIT_RESULT: "success", }; const successfulMain = { BUILD_TYPECHECK_RESULT: "success", @@ -1020,6 +1021,7 @@ describe("pull request and main workflow contracts", () => { REVIEWED_NPM_AUDIT_RESULT: "success", REAL_OPENCLAW_DIST_HARNESS_RESULT: "success", STATIC_RESULT: "success", + WECHAT_RUNTIME_AUDIT_RESULT: "success", }; const codeSuccess = runWorkflowShellStep(prGate, successfulCode); @@ -1039,6 +1041,7 @@ describe("pull request and main workflow contracts", () => { PLUGIN_TESTS_RESULT: "skipped", REVIEWED_NPM_AUDIT_RESULT: "skipped", STATIC_RESULT: "skipped", + WECHAT_RUNTIME_AUDIT_RESULT: "skipped", }); const mainSuccess = runWorkflowShellStep(mainGate, successfulMain); const mainFailure = runWorkflowShellStep(mainGate, { diff --git a/test/reviewed-npm-archive.test.ts b/test/reviewed-npm-archive.test.ts index 596db0a22a0..9040fa37891 100644 --- a/test/reviewed-npm-archive.test.ts +++ b/test/reviewed-npm-archive.test.ts @@ -7,15 +7,22 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { packReviewedNpmArchive, - removeReviewedNpmArchive, type ReviewedNpmArchiveRequest, + type ReviewedNpmCacheRequest, + removeReviewedNpmArchive, resolveReviewedNpmArchivePath, + verifyReviewedNpmCache, verifyReviewedNpmMetadata, } from "../scripts/lib/reviewed-npm-archive.mts"; const INTEGRITY = `sha512-${"a".repeat(88)}`; const PACKAGE_SPEC = "@example/reviewed@1.2.3"; const TARBALL_URL = "https://registry.npmjs.org/@example/reviewed/-/reviewed-1.2.3.tgz"; +const WECHAT_LOCK = path.join( + import.meta.dirname, + "..", + "agents/openclaw/wechat-runtime/package-lock.json", +); const roots: string[] = []; function request(): ReviewedNpmArchiveRequest { @@ -30,6 +37,57 @@ function request(): ReviewedNpmArchiveRequest { }; } +function cacheRequest(): ReviewedNpmCacheRequest { + const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "reviewed-npm-cache-test-")); + roots.push(tempDirectory); + const cacheDirectory = path.join(tempDirectory, "cache"); + fs.mkdirSync(cacheDirectory); + return { + cacheDirectory, + lockfilePath: WECHAT_LOCK, + registryOrigin: "https://registry.npmjs.org/", + tempDirectory, + }; +} + +function cachedArchiveRunner( + calls: Array<{ args: readonly string[]; request: ReviewedNpmArchiveRequest }>, + mutation?: Readonly<{ filename?: string; integrity?: string; packageSpec: string }>, +) { + return (args: readonly string[], reviewed: ReviewedNpmArchiveRequest): string => { + calls.push({ args: [...args], request: reviewed }); + return args[0] === "view" + ? args[2] === "dist.integrity" + ? reviewed.expectedIntegrity + : reviewed.tarballUrl + : cachedArchivePackResponse(args, reviewed, mutation); + }; +} + +function cachedArchivePackResponse( + args: readonly string[], + reviewed: ReviewedNpmArchiveRequest, + mutation?: Readonly<{ filename?: string; integrity?: string; packageSpec: string }>, +): string { + const destination = args[3] as string; + const filename = + mutation?.packageSpec === reviewed.packageSpec && mutation.filename + ? mutation.filename + : `${reviewed.packageSpec.replaceAll(/[^0-9A-Za-z.-]/g, "-")}.tgz`; + !filename.includes("/") && !filename.includes("\\") + ? fs.writeFileSync(path.join(destination, filename), "reviewed cache bytes") + : undefined; + return JSON.stringify([ + { + filename, + integrity: + mutation?.packageSpec === reviewed.packageSpec && mutation.integrity + ? mutation.integrity + : reviewed.expectedIntegrity, + }, + ]); +} + afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); @@ -122,4 +180,60 @@ describe("reviewed npm archive", () => { `reported unsafe archive filename: ${filename}`, ); }); + + it("re-packs every locked cache archive offline through the shared verifier", () => { + const calls: Array<{ args: readonly string[]; request: ReviewedNpmArchiveRequest }> = []; + const reviewed = cacheRequest(); + expect(verifyReviewedNpmCache(reviewed, cachedArchiveRunner(calls))).toEqual([ + "@tencent-weixin/openclaw-weixin@2.4.3", + "qrcode-terminal@0.12.0", + "zod@4.4.3", + ]); + + expect(calls.filter(({ args }) => args[0] === "pack")).toHaveLength(3); + for (const { request: archiveRequest } of calls) { + expect(archiveRequest.env).toMatchObject({ + NPM_CONFIG_CACHE: reviewed.cacheDirectory, + NPM_CONFIG_OFFLINE: "true", + NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/", + NPM_CONFIG_USERCONFIG: "/dev/null", + }); + } + }); + + it("rejects an off-origin locked archive before npm can read the cache", () => { + const reviewed = cacheRequest(); + const lock = JSON.parse(fs.readFileSync(WECHAT_LOCK, "utf-8")); + lock.packages["node_modules/qrcode-terminal"].resolved = + "https://registry.example.test/qrcode-terminal-0.12.0.tgz"; + const lockfilePath = path.join(reviewed.tempDirectory as string, "off-origin-lock.json"); + fs.writeFileSync(lockfilePath, `${JSON.stringify(lock, null, 2)}\n`); + let npmCalled = false; + + expect(() => + verifyReviewedNpmCache({ ...reviewed, lockfilePath }, () => { + npmCalled = true; + return ""; + }), + ).toThrow("reviewed npm lock package must use the reviewed registry"); + expect(npmCalled).toBe(false); + }); + + it.each([ + { + expected: "downloaded tarball integrity mismatch", + mutation: { integrity: "sha512-drift", packageSpec: "qrcode-terminal@0.12.0" }, + name: "packed SRI drift", + }, + { + expected: "reported unsafe archive filename", + mutation: { filename: "../qrcode-terminal.tgz", packageSpec: "qrcode-terminal@0.12.0" }, + name: "an unsafe packed filename", + }, + ])("rejects $name in the final cache", ({ expected, mutation }) => { + const calls: Array<{ args: readonly string[]; request: ReviewedNpmArchiveRequest }> = []; + expect(() => + verifyReviewedNpmCache(cacheRequest(), cachedArchiveRunner(calls, mutation)), + ).toThrow(expected); + }); }); diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index a51f7f5e606..1f17c09d5ec 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -14,6 +14,10 @@ import { } from "../src/lib/sandbox/build-context"; describe("sandbox build context staging", () => { + function runtimeManifestFixture(runtimeName: string, fileName: string) { + return `${JSON.stringify({ runtimeName, fileName })}\n`; + } + function writeBuildContextFixture(sourceRoot: string) { const blueprintManifestDir = path.join( sourceRoot, @@ -31,8 +35,14 @@ describe("sandbox build context staging", () => { writeFixture("Dockerfile"); writeFixture("tsconfig.runtime-preloads.json", "{}\n"); - writeFixture(path.join("agents", "openclaw", "mcporter-runtime", "package.json"), "{}\n"); - writeFixture(path.join("agents", "openclaw", "mcporter-runtime", "package-lock.json"), "{}\n"); + for (const runtimeName of ["mcporter-runtime", "wechat-runtime"]) { + for (const fileName of ["package.json", "package-lock.json"]) { + writeFixture( + path.join("agents", "openclaw", runtimeName, fileName), + runtimeManifestFixture(runtimeName, fileName), + ); + } + } for (const fileName of [ "package.json", "package-lock.json", @@ -102,6 +112,7 @@ describe("sandbox build context staging", () => { writeFixture(path.join("scripts", "patch-openclaw-mcp-npx.mts")); writeFixture(path.join("scripts", "patch-openclaw-issue-4434-diagnostics.ts")); writeFixture(path.join("scripts", "patch-openclaw-device-self-approval.ts")); + writeFixture(path.join("scripts", "verify-wechat-runtime-lock.mts")); writeFixture(path.join("scripts", "lib", "reviewed-npm-archive.mts")); } @@ -151,15 +162,25 @@ describe("sandbox build context staging", () => { expect((fs.statSync(stagedPlugin).mode & 0o777).toString(8)).toBe("644"); } - function expectStagedMcporterRuntime(buildCtx: string) { - const runtimeDir = path.join(buildCtx, "agents", "openclaw", "mcporter-runtime"); - expect(fs.readdirSync(runtimeDir).sort()).toEqual(["package-lock.json", "package.json"]); - expect((fs.statSync(path.join(runtimeDir, "package.json")).mode & 0o777).toString(8)).toBe( - "644", - ); - expect((fs.statSync(path.join(runtimeDir, "package-lock.json")).mode & 0o777).toString(8)).toBe( - "644", - ); + function expectStagedOpenClawRuntimeGraphs(buildCtx: string, sourceRoot: string) { + for (const runtimeName of ["mcporter-runtime", "wechat-runtime"]) { + const runtimeDir = path.join(buildCtx, "agents", "openclaw", runtimeName); + expect(fs.readdirSync(runtimeDir).sort()).toEqual(["package-lock.json", "package.json"]); + for (const fileName of ["package.json", "package-lock.json"]) { + expect(fs.readFileSync(path.join(runtimeDir, fileName), "utf8")).toBe( + fs.readFileSync( + path.join(sourceRoot, "agents", "openclaw", runtimeName, fileName), + "utf8", + ), + ); + } + expect((fs.statSync(path.join(runtimeDir, "package.json")).mode & 0o777).toString(8)).toBe( + "644", + ); + expect( + (fs.statSync(path.join(runtimeDir, "package-lock.json")).mode & 0o777).toString(8), + ).toBe("644"); + } } function expectStagedToolDisclosureContract(buildCtx: string) { @@ -206,7 +227,7 @@ describe("sandbox build context staging", () => { writeBuildContextFixture(sourceRoot); const { buildCtx } = stageOptimizedSandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); - expectStagedMcporterRuntime(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx, sourceRoot); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -236,7 +257,7 @@ describe("sandbox build context staging", () => { writeBuildContextFixture(sourceRoot); const { buildCtx } = stageLegacySandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); - expectStagedMcporterRuntime(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx, sourceRoot); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -268,7 +289,7 @@ describe("sandbox build context staging", () => { const { buildCtx, stagedDockerfile } = stageOptimizedSandboxBuildContext(repoRoot, tmpDir); expectDockerfileScriptCopiesExist(buildCtx, stagedDockerfile); expect(fs.existsSync(path.join(buildCtx, "tsconfig.runtime-preloads.json"))).toBe(true); - expectStagedMcporterRuntime(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx, repoRoot); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", ".venv"))).toBe(false); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", "blueprint.yaml"))).toBe(true); expect( diff --git a/test/sandbox-provisioning-tavily.test.ts b/test/sandbox-provisioning-tavily.test.ts index b20940e1433..33597b4131f 100644 --- a/test/sandbox-provisioning-tavily.test.ts +++ b/test/sandbox-provisioning-tavily.test.ts @@ -42,7 +42,7 @@ function runPluginInstallBlock( const command = dockerRunCommandBetween( dockerfile, "# Install non-messaging OpenClaw plugins", - '# hadolint ignore=DL3059,DL4006\nRUN OPENCLAW_VERSION="${OPENCLAW_VERSION}" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts --agent openclaw --phase agent-install', + "# The reviewed cache stays root-owned and immutable to the sandbox user.", ); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-tavily-plugin-")); const logPath = path.join(tmp, "calls.log"); diff --git a/test/verify-wechat-runtime-lock.test.ts b/test/verify-wechat-runtime-lock.test.ts new file mode 100644 index 00000000000..a6f2d28a557 --- /dev/null +++ b/test/verify-wechat-runtime-lock.test.ts @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + expectedWechatGraph, + verifyOpenClawPeerCompatibility, + verifyWechatRuntimeLock, +} from "../scripts/verify-wechat-runtime-lock.mts"; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); +}); + +const packages = { + "node_modules/@tencent-weixin/openclaw-weixin": { + version: "2.4.3", + integrity: "sha512-plugin", + dependencies: { "qrcode-terminal": "0.12.0", zod: "^4.3.6" }, + peerDependencies: { openclaw: ">=2026.3.22" }, + }, + "node_modules/qrcode-terminal": { version: "0.12.0", integrity: "sha512-qr" }, + "node_modules/zod": { version: "4.4.3", integrity: "sha512-zod" }, +}; + +function writePackage( + root: string, + location: string, + record: { version: string; peerDependencies?: Record }, +): void { + const target = path.join(root, location); + fs.mkdirSync(target, { recursive: true }); + fs.writeFileSync( + path.join(target, "package.json"), + JSON.stringify({ version: record.version, peerDependencies: record.peerDependencies }), + ); +} + +function fixture(): { lockFile: string; projectsRoot: string; installedLock: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wechat-lock-")); + tempDirs.push(root); + const projectsRoot = path.join(root, "projects"); + const installedRoot = path.join(projectsRoot, "wechat-project"); + fs.mkdirSync(installedRoot, { recursive: true }); + for (const [location, record] of Object.entries(packages)) { + writePackage(installedRoot, location, record); + } + const lockFile = path.join(root, "reviewed-lock.json"); + const installedLock = path.join(installedRoot, "package-lock.json"); + fs.writeFileSync(lockFile, JSON.stringify({ packages })); + fs.writeFileSync(installedLock, JSON.stringify({ packages })); + return { lockFile, projectsRoot, installedLock }; +} + +describe("WeChat runtime dependency lock", () => { + it("derives the reviewed graph from lock metadata", () => { + expect([...expectedWechatGraph({ packages }).keys()]).toEqual(Object.keys(packages)); + }); + + it("accepts one managed npm graph that exactly matches the lock", () => { + const { lockFile, projectsRoot } = fixture(); + expect(() => verifyWechatRuntimeLock(lockFile, projectsRoot, "2026.6.10")).not.toThrow(); + }); + + it("rejects an OpenClaw runtime below the locked plugin peer minimum", () => { + expect(() => verifyOpenClawPeerCompatibility("2026.3.22", ">=2026.3.22")).not.toThrow(); + expect(() => verifyOpenClawPeerCompatibility("2026.6.10", ">=2026.3.22")).not.toThrow(); + expect(() => verifyOpenClawPeerCompatibility("2026.3.21", ">=2026.3.22")).toThrow( + /does not satisfy WeChat peer dependency/, + ); + expect(() => verifyOpenClawPeerCompatibility("2026.6.10", "^2026.3.22")).toThrow( + /unsupported WeChat OpenClaw peer range/, + ); + }); + + it("rejects lock metadata drift and an unreviewed package", () => { + const metadataDrift = fixture(); + const driftedPackages = structuredClone(packages); + driftedPackages["node_modules/zod"].integrity = "sha512-drift"; + fs.writeFileSync(metadataDrift.installedLock, JSON.stringify({ packages: driftedPackages })); + expect(() => + verifyWechatRuntimeLock(metadataDrift.lockFile, metadataDrift.projectsRoot, "2026.6.10"), + ).toThrow(/metadata does not match/); + + const extraPackage = fixture(); + fs.writeFileSync( + extraPackage.installedLock, + JSON.stringify({ + packages: { ...packages, "node_modules/unreviewed": { version: "1.0.0" } }, + }), + ); + expect(() => + verifyWechatRuntimeLock(extraPackage.lockFile, extraPackage.projectsRoot, "2026.6.10"), + ).toThrow(/dependency set does not match/); + }); +}); diff --git a/test/wechat-locked-install.test.ts b/test/wechat-locked-install.test.ts new file mode 100644 index 00000000000..5f6e5551d8b --- /dev/null +++ b/test/wechat-locked-install.test.ts @@ -0,0 +1,260 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { wechatManifest } from "../src/lib/messaging/channels/wechat/manifest.ts"; +import { + applyMessagingBuildPhase, + readMessagingBuildPlanFromEnv, + requireWritableRuntimeInstallCache, +} from "../src/lib/messaging/applier/build/messaging-build-applier.mts"; + +const WECHAT_INTEGRITY = + "sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw=="; +const WECHAT_TARBALL = + "https://registry.npmjs.org/@tencent-weixin/openclaw-weixin/-/openclaw-weixin-2.4.3.tgz"; + +function executable(file: string, contents: string): void { + fs.writeFileSync(file, contents, { mode: 0o755 }); +} + +const INVALID_INSTALL_CACHE_CASES = [ + { + name: "relative paths", + prepare: () => "relative-cache", + expected: "NEMOCLAW_WECHAT_NPM_INSTALL_CACHE must be an absolute path", + }, + { + name: "symbolic links", + prepare: (tmp: string) => { + const target = path.join(tmp, "symlink-target"); + const link = path.join(tmp, "symlink-cache"); + fs.mkdirSync(target); + fs.symlinkSync(target, link); + return link; + }, + expected: "symbolic links are not allowed", + }, + { + name: "non-directory paths", + prepare: (tmp: string) => { + const file = path.join(tmp, "cache-file"); + fs.writeFileSync(file, "not a directory"); + return file; + }, + expected: "path is not a directory", + }, + { + name: "non-writable directories", + prepare: (tmp: string) => { + const directory = path.join(tmp, "read-only-cache"); + fs.mkdirSync(directory, { mode: 0o500 }); + return directory; + }, + expected: "must be a writable, searchable directory", + }, +] as const; + +const TRUSTED_INSTALL_CACHE_CASES = [ + { + name: "the trusted cache itself", + prepare: (trustedCache: string) => trustedCache, + }, + { + name: "trusted-cache descendants", + prepare: (trustedCache: string) => { + const descendant = path.join(trustedCache, "child"); + fs.mkdirSync(descendant); + return descendant; + }, + }, +] as const; + +describe("locked WeChat plugin installation (#5896)", () => { + it("routes archive retrieval and install through the disposable offline cache", () => { + const runtimeLock = wechatManifest.agentPackages.find( + (pkg) => pkg.agent === "openclaw", + )?.runtimeLock; + expect(runtimeLock).toEqual({ + cachePath: "/usr/local/share/nemoclaw/wechat-npm-cache", + installCacheEnvKey: "NEMOCLAW_WECHAT_NPM_INSTALL_CACHE", + legacyPeerDeps: true, + lockFile: "/usr/local/lib/nemoclaw/wechat-runtime/package-lock.json", + offline: true, + projectsRoot: "/sandbox/.openclaw/npm/projects", + verifierPath: "/usr/local/lib/nemoclaw/verify-wechat-runtime-lock.mts", + }); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wechat-install-")); + const installCache = path.join(tmp, "wechat-install-cache"); + const home = path.join(tmp, "home"); + const trace = path.join(tmp, "trace"); + fs.mkdirSync(installCache); + fs.mkdirSync(home); + executable( + path.join(tmp, "npm"), + `#!/bin/sh +set -eu +printf 'npm|%s|%s|cache=%s|offline=%s\n' "$1" "\${2:-}" "$NPM_CONFIG_CACHE" "$NPM_CONFIG_OFFLINE" >> "$TRACE" +mkdir -p "$NPM_CONFIG_CACHE/_cacache/tmp" +printf '%s\n' "$1" >> "$NPM_CONFIG_CACHE/_cacache/tmp/nemoclaw-retrieval-probe" +if [ "$1" = view ] && [ "$3" = dist.integrity ]; then printf '%s\n' "$WECHAT_INTEGRITY"; exit 0; fi +if [ "$1" = view ] && [ "$3" = dist.tarball ]; then printf '%s\n' "$WECHAT_TARBALL"; exit 0; fi +if [ "$1" = pack ]; then + printf 'archive' > "$4/wechat.tgz" + printf '[{"filename":"wechat.tgz","integrity":"%s"}]\n' "$WECHAT_INTEGRITY" + exit 0 +fi +exit 1 +`, + ); + executable( + path.join(tmp, "openclaw"), + `#!/bin/sh +mkdir -p "$NPM_CONFIG_CACHE/_cacache/tmp" +printf 'writable\n' > "$NPM_CONFIG_CACHE/_cacache/tmp/nemoclaw-install-probe" +printf 'install|%s|offline=%s|peer=%s|cache=%s\n' "$3" "$NPM_CONFIG_OFFLINE" "$NPM_CONFIG_LEGACY_PEER_DEPS" "$NPM_CONFIG_CACHE" >> "$TRACE" +`, + ); + executable( + path.join(tmp, "node"), + `#!/bin/sh +printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CONFIG_OFFLINE" "$NPM_CONFIG_CACHE" >> "$TRACE" +`, + ); + + const plan = { + schemaVersion: 1, + sandboxName: "wechat-test", + agent: "openclaw", + channels: [{ channelId: "wechat", active: true }], + credentialBindings: [], + agentRender: [], + buildSteps: [ + { + channelId: "wechat", + kind: "package-install", + outputId: "openclawPluginPackage", + required: true, + value: { + manager: "openclaw-plugin", + spec: "npm:@tencent-weixin/openclaw-weixin@2.4.3", + }, + }, + ], + }; + const env = { + PATH: `${tmp}:${process.env.PATH ?? "/usr/bin:/bin"}`, + HOME: home, + TRACE: trace, + WECHAT_INTEGRITY, + WECHAT_TARBALL, + OPENCLAW_VERSION: "2026.6.10", + NEMOCLAW_WECHAT_NPM_INSTALL_CACHE: installCache, + NEMOCLAW_MESSAGING_PLAN_B64: Buffer.from(JSON.stringify(plan)).toString("base64"), + }; + + try { + const serialized = readMessagingBuildPlanFromEnv(env, "openclaw"); + expect(applyMessagingBuildPhase(serialized, "agent-install", env)).toEqual([]); + const calls = fs.readFileSync(trace, "utf8"); + expect(calls).toContain("install|npm-pack:"); + expect(calls).toContain( + `npm|view|@tencent-weixin/openclaw-weixin@2.4.3|cache=${fs.realpathSync(installCache)}|offline=true`, + ); + expect(calls).toContain( + `npm|pack|${WECHAT_TARBALL}|cache=${fs.realpathSync(installCache)}|offline=true`, + ); + expect(calls).toContain(`offline=true|peer=true|cache=${fs.realpathSync(installCache)}`); + expect(calls).toContain( + "verify|/usr/local/lib/nemoclaw/wechat-runtime/package-lock.json|/sandbox/.openclaw/npm/projects|openclaw=2026.6.10|offline=true", + ); + expect(calls).not.toContain("cache=/usr/local/share/nemoclaw/wechat-npm-cache"); + expect(fs.existsSync(path.join(home, ".npm"))).toBe(false); + expect( + fs.readFileSync( + path.join(installCache, "_cacache", "tmp", "nemoclaw-retrieval-probe"), + "utf8", + ), + ).toBe("view\nview\npack\n"); + expect( + fs.readFileSync( + path.join(installCache, "_cacache", "tmp", "nemoclaw-install-probe"), + "utf8", + ), + ).toBe("writable\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.each(INVALID_INSTALL_CACHE_CASES)("rejects $name before package tooling runs", ({ + prepare, + expected, + }) => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wechat-invalid-cache-")); + const trace = path.join(tmp, "trace"); + executable(path.join(tmp, "npm"), '#!/bin/sh\nprintf "npm\\n" >> "$TRACE"\n'); + executable(path.join(tmp, "openclaw"), '#!/bin/sh\nprintf "openclaw\\n" >> "$TRACE"\n'); + executable(path.join(tmp, "node"), '#!/bin/sh\nprintf "node\\n" >> "$TRACE"\n'); + + const plan = { + schemaVersion: 1, + sandboxName: "wechat-invalid-cache", + agent: "openclaw", + channels: [{ channelId: "wechat", active: true }], + credentialBindings: [], + agentRender: [], + buildSteps: [ + { + channelId: "wechat", + kind: "package-install", + outputId: "openclawPluginPackage", + required: true, + value: { + manager: "openclaw-plugin", + spec: "npm:@tencent-weixin/openclaw-weixin@2.4.3", + }, + }, + ], + }; + const env = { + PATH: `${tmp}:${process.env.PATH ?? "/usr/bin:/bin"}`, + TRACE: trace, + NEMOCLAW_WECHAT_NPM_INSTALL_CACHE: prepare(tmp), + NEMOCLAW_MESSAGING_PLAN_B64: Buffer.from(JSON.stringify(plan)).toString("base64"), + }; + + try { + const serialized = readMessagingBuildPlanFromEnv(env, "openclaw"); + expect(() => applyMessagingBuildPhase(serialized, "agent-install", env)).toThrow(expected); + expect(fs.existsSync(trace)).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it.each(TRUSTED_INSTALL_CACHE_CASES)("rejects $name", ({ prepare }) => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wechat-trusted-cache-")); + const trustedCache = path.join(tmp, "trusted-cache"); + fs.mkdirSync(trustedCache); + const runtimeLock = { + ...wechatManifest.agentPackages[0].runtimeLock!, + cachePath: trustedCache, + }; + + try { + expect(() => + requireWritableRuntimeInstallCache(runtimeLock, { + NEMOCLAW_WECHAT_NPM_INSTALL_CACHE: prepare(trustedCache), + }), + ).toThrow("NEMOCLAW_WECHAT_NPM_INSTALL_CACHE must not make the trusted npm cache writable"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/test/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts new file mode 100644 index 00000000000..837856ab01c --- /dev/null +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -0,0 +1,240 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { readYaml } from "./helpers/e2e-workflow-contract"; + +type WorkflowStep = { + readonly name?: string; + readonly run?: string; + readonly if?: string; + readonly uses?: string; + readonly with?: Record; + readonly env?: Record; +}; + +type WorkflowJob = { + readonly needs?: string | readonly string[]; + readonly steps?: readonly WorkflowStep[]; +}; + +type Workflow = { + readonly jobs: Record; +}; + +const repoRoot = path.join(import.meta.dirname, ".."); +const auditScript = path.join( + repoRoot, + ".github", + "actions", + "ci-wechat-runtime-audit", + "audit.sh", +); + +function runAuditValidation( + mutate: (fixture: { readonly targetRoot: string; readonly runtimeDir: string }) => void, +) { + const targetRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wechat-audit-test-")); + const runtimeDir = path.join(targetRoot, "agents", "openclaw", "wechat-runtime"); + fs.mkdirSync(runtimeDir, { recursive: true }); + for (const filename of ["package.json", "package-lock.json"]) { + fs.copyFileSync( + path.join(repoRoot, "agents", "openclaw", "wechat-runtime", filename), + path.join(runtimeDir, filename), + ); + } + + try { + mutate({ targetRoot, runtimeDir }); + return spawnSync("bash", [auditScript], { + cwd: targetRoot, + encoding: "utf8", + env: { + ...process.env, + NEMOCLAW_WECHAT_AUDIT_REPORT_DIR: "artifacts/wechat-runtime-audit", + NEMOCLAW_WECHAT_AUDIT_TARGET_ROOT: targetRoot, + PATH: `${path.join(targetRoot, "bin")}${path.delimiter}${process.env.PATH ?? ""}`, + }, + }); + } finally { + fs.rmSync(targetRoot, { force: true, recursive: true }); + } +} + +function requiredStep(job: WorkflowJob, name: string): WorkflowStep { + const step = job.steps?.find((candidate) => candidate.name === name); + expect(step, `Missing workflow step: ${name}`).toBeDefined(); + return step as WorkflowStep; +} + +describe("WeChat runtime audit and install-cache gates (#5896)", () => { + // source-shape-contract: security -- Trusted PR and main workflows must enforce the reviewed WeChat runtime audit boundary + it("makes the trusted audit required in PR and main workflows", () => { + const pr = readYaml(".github/workflows/pr.yaml"); + const main = readYaml(".github/workflows/main.yaml"); + const prJob = pr.jobs["wechat-runtime-audit"]; + const mainJob = main.jobs["wechat-runtime-audit"]; + + const trustedCheckout = requiredStep(prJob, "Checkout trusted WeChat runtime audit"); + expect(trustedCheckout.with).toMatchObject({ + ref: "${{ github.event.pull_request.base.sha }}", + path: ".trusted-wechat-audit", + "persist-credentials": false, + "sparse-checkout-cone-mode": false, + }); + expect(String(trustedCheckout.with?.["sparse-checkout"])).toContain( + ".github/actions/ci-wechat-runtime-audit", + ); + + const bootstrapCheckout = requiredStep(prJob, "Checkout pinned bootstrap WeChat runtime audit"); + expect(bootstrapCheckout.if).toBe( + "${{ steps.trusted-wechat-audit.outputs.available != 'true' && github.event.pull_request.number == 6739 && github.event.pull_request.head.repo.full_name == 'HOYALIM/NemoClaw' }}", + ); + expect(bootstrapCheckout.with).toMatchObject({ + repository: "HOYALIM/NemoClaw", + ref: "0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2", + path: ".trusted-wechat-audit-bootstrap", + "persist-credentials": false, + }); + expect(requiredStep(prJob, "Audit locked WeChat runtime graph").uses).toBe( + "./.trusted-wechat-audit/.github/actions/ci-wechat-runtime-audit", + ); + expect(requiredStep(prJob, "Audit locked WeChat runtime graph (pinned bootstrap)").uses).toBe( + "./.trusted-wechat-audit-bootstrap/.github/actions/ci-wechat-runtime-audit", + ); + expect(requiredStep(mainJob, "Audit locked WeChat runtime graph").uses).toBe( + "./.github/actions/ci-wechat-runtime-audit", + ); + + for (const [workflowName, workflow, job] of [ + ["pr", pr, prJob], + ["main", main, mainJob], + ] as const) { + const upload = requiredStep(job, "Upload WeChat runtime audit evidence"); + expect(upload.if).toBe("${{ always() }}"); + expect(upload.uses).toBe("actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a"); + expect(upload.with).toMatchObject({ + path: "artifacts/wechat-runtime-audit", + "if-no-files-found": "error", + }); + + expect(workflow.jobs.checks.needs).toContain("wechat-runtime-audit"); + const gate = requiredStep( + workflow.jobs.checks, + workflowName === "pr" ? "Verify required PR checks" : "Verify required main checks", + ); + expect(gate.env).toMatchObject({ + WECHAT_RUNTIME_AUDIT_RESULT: "${{ needs['wechat-runtime-audit'].result }}", + }); + expect(gate.run).toContain( + 'require_success "wechat-runtime-audit" "$WECHAT_RUNTIME_AUDIT_RESULT"', + ); + } + }); + + it("audits the installed graph and exercises the exact archive through a copied cache", () => { + const script = fs.readFileSync(auditScript, "utf8"); + for (const fragment of [ + 'npm --prefix "$runtime_dir" ci', + "--ignore-scripts", + "--omit=dev", + "--legacy-peer-deps", + "audit-level=low", + "audit signatures", + "npm-audit.json", + "npm-audit-signatures.txt", + 'chmod -R a-w "$trusted_cache"', + 'cp -R "$trusted_cache"/. "$install_cache"/', + 'chmod -R u+rwX,go-w "$install_cache"', + 'npm pack "$wechat_tarball"', + "--offline", + 'EXPECTED_INTEGRITY="$wechat_integrity"', + "WeChat runtime package.json must contain exactly the reviewed plugin dependency", + "WeChat runtime plugin lock entry must carry sha512 integrity", + 'npm_registry="https://registry.npmjs.org/"', + '--userconfig "$trusted_npmrc"', + '--registry "$npm_registry"', + "requireRegistryUrl(record.resolved, location)", + ]) { + expect(script).toContain(fragment); + } + + const action = fs.readFileSync( + path.join(repoRoot, ".github", "actions", "ci-wechat-runtime-audit", "action.yaml"), + "utf8", + ); + expect(action).toContain('node-version: "22.19.0"'); + expect(action).toContain('cd "$RUNNER_TEMP"'); + expect(action).toContain("npm install --global npm@10.9.4"); + expect(action).toContain("--userconfig /dev/null"); + expect(action).toContain("--registry https://registry.npmjs.org/"); + expect(action).toContain('run: bash "$GITHUB_ACTION_PATH/audit.sh"'); + }); + + it("rejects a target-controlled npm registry override", () => { + const result = runAuditValidation(({ runtimeDir }) => { + fs.writeFileSync( + path.join(runtimeDir, ".npmrc"), + "registry=https://registry.example.test/\n", + ); + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("refuses target-controlled npm config"); + }); + + it("rejects an off-origin transitive package archive", () => { + const result = runAuditValidation(({ targetRoot, runtimeDir }) => { + const lockPath = path.join(runtimeDir, "package-lock.json"); + const lock = JSON.parse(fs.readFileSync(lockPath, "utf8")); + lock.packages["node_modules/qrcode-terminal"].resolved = + "https://registry.example.test/qrcode-terminal-0.12.0.tgz"; + fs.writeFileSync(lockPath, `${JSON.stringify(lock, null, 2)}\n`); + const binDir = path.join(targetRoot, "bin"); + fs.mkdirSync(binDir); + const npm = path.join(binDir, "npm"); + fs.writeFileSync(npm, "#!/bin/sh\necho npm-should-not-run >&2\nexit 99\n"); + fs.chmodSync(npm, 0o755); + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + "locked package must resolve from the reviewed npm registry origin: node_modules/qrcode-terminal", + ); + expect(result.stderr).not.toContain("npm-should-not-run"); + }); + + it("keeps the image cache trusted and deletes the sandbox-writable copy", () => { + const dockerfile = fs.readFileSync(path.join(repoRoot, "Dockerfile"), "utf8"); + for (const fragment of [ + "chown -R root:root /usr/local/lib/nemoclaw/wechat-runtime", + "node --experimental-strip-types /scripts/lib/reviewed-npm-archive.mts", + "--lockfile /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json", + "--cache /usr/local/share/nemoclaw/wechat-npm-cache", + "--registry-origin https://registry.npmjs.org/", + "trusted_cache=/usr/local/share/nemoclaw/wechat-npm-cache", + 'install_cache="$(mktemp -d /tmp/nemoclaw-wechat-npm-cache.XXXXXX)"', + 'cp -R "$trusted_cache"/. "$install_cache"/', + 'NEMOCLAW_WECHAT_NPM_INSTALL_CACHE="$install_cache"', + 'rm -rf "$install_cache"', + 'test ! -e "$install_cache"', + ]) { + expect(dockerfile).toContain(fragment); + } + const cacheVerification = dockerfile.indexOf( + "--lockfile /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json", + ); + const cacheLockdown = dockerfile.indexOf( + "chown -R root:root /usr/local/lib/nemoclaw/wechat-runtime", + cacheVerification, + ); + expect(cacheVerification).toBeGreaterThan(-1); + expect(cacheLockdown).toBeGreaterThan(cacheVerification); + }); +});