From 033febe900e90a1740da6f9401fd72175c62d2d6 Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Sun, 12 Jul 2026 19:33:20 -0700 Subject: [PATCH 01/25] fix(messaging): lock WeChat runtime graph Signed-off-by: Ho Lim --- Dockerfile | 18 ++- agents/openclaw/dependency-review.md | 12 ++ .../openclaw/wechat-runtime/package-lock.json | 52 ++++++++ agents/openclaw/wechat-runtime/package.json | 14 +++ scripts/verify-wechat-runtime-lock.mts | 117 ++++++++++++++++++ .../applier/build/messaging-build-applier.mts | 53 +++++++- src/lib/messaging/channels/wechat/manifest.ts | 8 ++ src/lib/messaging/manifest/types.ts | 10 ++ src/lib/sandbox/build-context.ts | 4 + test/messaging-build-applier.test.ts | 14 +++ test/sandbox-build-context.test.ts | 1 + test/verify-wechat-runtime-lock.test.ts | 83 +++++++++++++ test/wechat-locked-install.test.ts | 108 ++++++++++++++++ 13 files changed, 490 insertions(+), 4 deletions(-) create mode 100644 agents/openclaw/wechat-runtime/package-lock.json create mode 100644 agents/openclaw/wechat-runtime/package.json create mode 100644 scripts/verify-wechat-runtime-lock.mts create mode 100644 test/verify-wechat-runtime-lock.test.ts create mode 100644 test/wechat-locked-install.test.ts diff --git a/Dockerfile b/Dockerfile index cdde20c53b0..bf476dc2da8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -66,6 +66,8 @@ ARG MCPORTER_VERSION=0.7.3 ARG MCPORTER_0_7_3_INTEGRITY=sha512-egoPVYqTnWb3NjRIxo+xc8OrAI0dlPrJm9pAiZx0pImuNIV5rKhGtTnIfH/Y1ldGPVu74ibj3KR5c9U/QSdQFA== 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 # OpenShell blocks the link-local EC2 Instance Metadata Service. Keep AWS SDK # credential chains from attempting an impossible metadata discovery path. @@ -142,16 +144,30 @@ RUN npm ci --omit=dev \ && test -z "$node_unsafe" \ && json5_unsafe="$(find -L /opt/nemoclaw/node_modules/json5 \( ! -user root -o -perm /022 \) -print -quit)" \ && test -z "$json5_unsafe" +RUN npm ci --prefix /usr/local/lib/nemoclaw/wechat-runtime \ + --ignore-scripts --omit=dev --legacy-peer-deps \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && npm cache add @tencent-weixin/openclaw-weixin@2.4.3 \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && npm cache add qrcode-terminal@0.12.0 \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && npm cache add zod@4.4.3 \ + --cache /usr/local/share/nemoclaw/wechat-npm-cache \ + && rm -rf /usr/local/lib/nemoclaw/wechat-runtime/node_modules \ + && chmod -R a+rX /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`. diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index fa7fc58b4fa..f6139999a15 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -20,6 +20,18 @@ 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 dedicated npm cache and adds the exact package metadata needed by npm's offline resolver. The OpenClaw plugin installer consumes that cache in offline, legacy-peer mode, then `verify-wechat-runtime-lock.mts` rejects integrity, version, or dependency-set drift in the managed npm project. +- Advisory command: `npm audit --omit=dev --json --prefix agents/openclaw/wechat-runtime`. +- Advisory review: `2026-07-12`; result: `0` known vulnerabilities across the resolved production graph. +- Regression test: `test/wechat-locked-install.test.ts` keeps the manifest runtime-lock paths, Docker cache inputs, and installer verification dispatch 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/scripts/verify-wechat-runtime-lock.mts b/scripts/verify-wechat-runtime-lock.mts new file mode 100644 index 00000000000..68c65b35043 --- /dev/null +++ b/scripts/verify-wechat-runtime-lock.mts @@ -0,0 +1,117 @@ +// 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; +}; + +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 packageVersion(file: string): string { + const parsed = readJson(file); + const version = + parsed && typeof parsed === "object" ? (parsed as Record).version : undefined; + if (typeof version !== "string") { + throw new Error(`package metadata has no version: ${file}`); + } + return version; +} + +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), + ), + ), + }; +} + +export function verifyWechatRuntimeLock(lockFile: string, projectsRoot: 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 installedVersion = packageVersion(path.join(installedRoot, location, "package.json")); + if (installedVersion !== expectedRecord.version) { + throw new Error( + `installed ${packageName}@${installedVersion} does not match locked ${expectedRecord.version}`, + ); + } + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const [, , lockFile, projectsRoot] = process.argv; + if (!lockFile || !projectsRoot) { + throw new Error( + "usage: verify-wechat-runtime-lock.mts ", + ); + } + verifyWechatRuntimeLock(lockFile, projectsRoot); +} diff --git a/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 1e5460f1b69..7e218b2a42e 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -21,7 +21,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; @@ -123,6 +123,7 @@ type OpenClawPluginInstall = { readonly npmPackageSpec?: string; readonly integrity?: string; readonly tarballUrl?: string; + readonly runtimeLock?: ChannelAgentPackageRuntimeLockSpec; readonly pin: boolean; }; @@ -204,6 +205,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, @@ -508,6 +531,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) { @@ -533,6 +557,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); @@ -668,11 +695,31 @@ 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}`], { + const installEnv = { ...env, NPM_CONFIG_IGNORE_SCRIPTS: "true", npm_config_ignore_scripts: "true", - }); + ...(install.runtimeLock + ? { + NPM_CONFIG_CACHE: install.runtimeLock.cachePath, + NPM_CONFIG_OFFLINE: String(install.runtimeLock.offline), + NPM_CONFIG_LEGACY_PEER_DEPS: String(install.runtimeLock.legacyPeerDeps), + } + : {}), + }; + runCommand(["openclaw", "plugins", "install", `npm-pack:${packed.archivePath}`], installEnv); + if (install.runtimeLock) { + runCommand( + [ + "node", + "--experimental-strip-types", + install.runtimeLock.verifierPath, + install.runtimeLock.lockFile, + install.runtimeLock.projectsRoot, + ], + installEnv, + ); + } } finally { rmSync(packed.rootDir, { recursive: true, force: true }); } diff --git a/src/lib/messaging/channels/wechat/manifest.ts b/src/lib/messaging/channels/wechat/manifest.ts index e5b135dcebb..61753282292 100644 --- a/src/lib/messaging/channels/wechat/manifest.ts +++ b/src/lib/messaging/channels/wechat/manifest.ts @@ -137,6 +137,14 @@ 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", + 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..2139ebeef4f 100644 --- a/src/lib/messaging/manifest/types.ts +++ b/src/lib/messaging/manifest/types.ts @@ -203,6 +203,15 @@ export interface ChannelRuntimeSecretScanSpec { export type ChannelAgentPackageManager = "openclaw-plugin" | "hermes-uv-pip"; +export interface ChannelAgentPackageRuntimeLockSpec { + readonly cachePath: 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 +223,7 @@ export interface ChannelAgentPackageSpec { readonly integrityByVersion?: Readonly>; readonly tarballUrl?: string; readonly tarballUrlByVersion?: Readonly>; + readonly runtimeLock?: ChannelAgentPackageRuntimeLockSpec; readonly required?: boolean; } diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index fa2e713a587..aaab8eba2ae 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -249,6 +249,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"), + ); return { buildCtx, stagedDockerfile }; } diff --git a/test/messaging-build-applier.test.ts b/test/messaging-build-applier.test.ts index 8c05a6cf0c3..1fcb4cd837d 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( @@ -868,6 +879,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/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index 117abad18e9..078138f7dbc 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -102,6 +102,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")); } function expectDockerfileScriptCopiesExist(buildCtx: string, stagedDockerfile: string) { diff --git a/test/verify-wechat-runtime-lock.test.ts b/test/verify-wechat-runtime-lock.test.ts new file mode 100644 index 00000000000..472569a2435 --- /dev/null +++ b/test/verify-wechat-runtime-lock.test.ts @@ -0,0 +1,83 @@ +// 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, + 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" }, + }, + "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, version: string): void { + const target = path.join(root, location); + fs.mkdirSync(target, { recursive: true }); + fs.writeFileSync(path.join(target, "package.json"), JSON.stringify({ version })); +} + +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.version); + } + 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)).not.toThrow(); + }); + + 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), + ).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)).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..728ed112a9f --- /dev/null +++ b/test/wechat-locked-install.test.ts @@ -0,0 +1,108 @@ +// 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, +} 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 }); +} + +describe("locked WeChat plugin installation (#5896)", () => { + it("installs from the reviewed archive using only the dedicated offline graph", () => { + const runtimeLock = wechatManifest.agentPackages[0].runtimeLock; + expect(runtimeLock).toEqual({ + cachePath: "/usr/local/share/nemoclaw/wechat-npm-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 trace = path.join(tmp, "trace"); + executable( + path.join(tmp, "npm"), + `#!/bin/sh +set -eu +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 +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|offline=%s|cache=%s\n' "$3" "$4" "$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"}`, + TRACE: trace, + WECHAT_INTEGRITY, + WECHAT_TARBALL, + 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( + "offline=true|peer=true|cache=/usr/local/share/nemoclaw/wechat-npm-cache", + ); + expect(calls).toContain( + "verify|/usr/local/lib/nemoclaw/wechat-runtime/package-lock.json|/sandbox/.openclaw/npm/projects|offline=true", + ); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); From c233f51cc057062f5d52ff40305242365d2c48c9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 10:42:56 -0700 Subject: [PATCH 02/25] fix(build): stage WeChat runtime lock Signed-off-by: Aaron Erickson --- src/lib/sandbox/build-context.ts | 18 ++++++++++-------- test/sandbox-build-context.test.ts | 28 ++++++++++++++++------------ 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index aaab8eba2ae..84a05fac133 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 [ diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index 078138f7dbc..3dcc8ffcad3 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -33,6 +33,8 @@ describe("sandbox build context staging", () => { 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"); + writeFixture(path.join("agents", "openclaw", "wechat-runtime", "package.json"), "{}\n"); + writeFixture(path.join("agents", "openclaw", "wechat-runtime", "package-lock.json"), "{}\n"); for (const fileName of [ "package.json", "package-lock.json", @@ -151,15 +153,17 @@ 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) { + 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"]); + 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 +210,7 @@ describe("sandbox build context staging", () => { writeBuildContextFixture(sourceRoot); const { buildCtx } = stageOptimizedSandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); - expectStagedMcporterRuntime(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -236,7 +240,7 @@ describe("sandbox build context staging", () => { writeBuildContextFixture(sourceRoot); const { buildCtx } = stageLegacySandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); - expectStagedMcporterRuntime(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -268,7 +272,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); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", ".venv"))).toBe(false); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", "blueprint.yaml"))).toBe(true); expect( From 5adda46c309b0a8ed954829fd96d02098ab4b5e3 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 10:51:58 -0700 Subject: [PATCH 03/25] test(build): verify runtime manifest staging Signed-off-by: Aaron Erickson --- test/sandbox-build-context.test.ts | 32 ++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index 3dcc8ffcad3..f051a1751ea 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,10 +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"); - writeFixture(path.join("agents", "openclaw", "wechat-runtime", "package.json"), "{}\n"); - writeFixture(path.join("agents", "openclaw", "wechat-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", @@ -153,10 +161,18 @@ describe("sandbox build context staging", () => { expect((fs.statSync(stagedPlugin).mode & 0o777).toString(8)).toBe("644"); } - function expectStagedOpenClawRuntimeGraphs(buildCtx: string) { + 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", ); @@ -210,7 +226,7 @@ describe("sandbox build context staging", () => { writeBuildContextFixture(sourceRoot); const { buildCtx } = stageOptimizedSandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); - expectStagedOpenClawRuntimeGraphs(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx, sourceRoot); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -240,7 +256,7 @@ describe("sandbox build context staging", () => { writeBuildContextFixture(sourceRoot); const { buildCtx } = stageLegacySandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); - expectStagedOpenClawRuntimeGraphs(buildCtx); + expectStagedOpenClawRuntimeGraphs(buildCtx, sourceRoot); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -272,7 +288,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); - expectStagedOpenClawRuntimeGraphs(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( From 1525f8926ddf642c0e00b9f84918f4f05b595bfa Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 11:22:27 -0700 Subject: [PATCH 04/25] fix(messaging): harden WeChat locked install Signed-off-by: Aaron Erickson --- .github/workflows/main.yaml | 32 +++++ .github/workflows/pr.yaml | 35 ++++++ Dockerfile | 25 +++- agents/openclaw/dependency-review.md | 7 +- ci/source-shape-test-budget.json | 5 + scripts/checks/audit-wechat-runtime.sh | 104 ++++++++++++++++ .../applier/build/messaging-build-applier.mts | 51 +++++++- src/lib/messaging/channels/wechat/manifest.ts | 1 + src/lib/messaging/manifest/types.ts | 1 + test/messaging-build-applier.test.ts | 1 + test/wechat-locked-install.test.ts | 21 +++- test/wechat-runtime-audit-workflow.test.ts | 114 ++++++++++++++++++ 12 files changed, 387 insertions(+), 10 deletions(-) create mode 100755 scripts/checks/audit-wechat-runtime.sh create mode 100644 test/wechat-runtime-audit-workflow.test.ts diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index f832aa17e88..69604267768 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -57,6 +57,35 @@ 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: Setup production-compatible Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 + with: + node-version: "22.19.0" + + - name: Pin production npm + run: npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund + + - name: Audit locked WeChat runtime graph + run: bash scripts/checks/audit-wechat-runtime.sh 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 + real-openclaw-dist-harness: runs-on: ubuntu-latest timeout-minutes: 20 @@ -213,6 +242,7 @@ jobs: - static-checks - build-typecheck - installer-integration + - wechat-runtime-audit - real-openclaw-dist-harness - cli-tests - plugin-tests @@ -227,6 +257,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 }} REAL_OPENCLAW_DIST_HARNESS_RESULT: ${{ needs['real-openclaw-dist-harness'].result }} CLI_TESTS_RESULT: ${{ needs['cli-tests'].result }} PLUGIN_TESTS_RESULT: ${{ needs['plugin-tests'].result }} @@ -247,6 +278,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 "real-openclaw-dist-harness" "$REAL_OPENCLAW_DIST_HARNESS_RESULT" require_success "cli-tests" "$CLI_TESTS_RESULT" require_success "plugin-tests" "$PLUGIN_TESTS_RESULT" diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index f90bc98f32d..309246d86f3 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -192,6 +192,37 @@ 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: Setup production-compatible Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 + with: + node-version: "22.19.0" + + - name: Pin production npm + run: npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund + + - name: Audit locked WeChat runtime graph + run: bash scripts/checks/audit-wechat-runtime.sh 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 + cli-test-shards: needs: changes if: needs.changes.outputs.code == 'true' @@ -366,6 +397,7 @@ jobs: - static-checks - build-typecheck - installer-integration + - wechat-runtime-audit - cli-tests - plugin-tests - e2e-support @@ -382,6 +414,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 }} CLI_TESTS_RESULT: ${{ needs['cli-tests'].result }} PLUGIN_TESTS_RESULT: ${{ needs['plugin-tests'].result }} E2E_SUPPORT_RESULT: ${{ needs['e2e-support'].result }} @@ -417,6 +450,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 "cli-tests" "$CLI_TESTS_RESULT" require_success "plugin-tests" "$PLUGIN_TESTS_RESULT" require_success "e2e-support" "$E2E_SUPPORT_RESULT" @@ -426,6 +460,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 "cli-tests" "$CLI_TESTS_RESULT" allow_success_or_skipped "plugin-tests" "$PLUGIN_TESTS_RESULT" allow_success_or_skipped "e2e-support" "$E2E_SUPPORT_RESULT" diff --git a/Dockerfile b/Dockerfile index 471b53c08ad..f0d7375fb29 100644 --- a/Dockerfile +++ b/Dockerfile @@ -156,7 +156,9 @@ RUN npm ci --prefix /usr/local/lib/nemoclaw/wechat-runtime \ && npm cache add zod@4.4.3 \ --cache /usr/local/share/nemoclaw/wechat-npm-cache \ && rm -rf /usr/local/lib/nemoclaw/wechat-runtime/node_modules \ - && chmod -R a+rX /usr/local/lib/nemoclaw/wechat-runtime \ + && 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 @@ -1131,8 +1133,27 @@ RUN set -eu; \ fi; \ rm -rf "$NEMOCLAW_OPENCLAW_PLUGIN_PACK_DIR" +# 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 f6139999a15..a54ee5d9cee 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -26,10 +26,11 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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 dedicated npm cache and adds the exact package metadata needed by npm's offline resolver. The OpenClaw plugin installer consumes that cache in offline, legacy-peer mode, then `verify-wechat-runtime-lock.mts` rejects integrity, version, or dependency-set drift in the managed npm project. -- Advisory command: `npm audit --omit=dev --json --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. The sandbox user copies that immutable source into a writable cache used only for the OpenClaw plugin install, deletes the copy in the same image layer, and never writes to the trusted cache. The installer runs in offline, legacy-peer mode, then `verify-wechat-runtime-lock.mts` rejects integrity, version, or dependency-set drift in the managed npm project. +- Default CI gate: `wechat-runtime-audit` in `.github/workflows/pr.yaml` and `.github/workflows/main.yaml` uses Node `22.19.0` and npm `10.9.4`, materializes the committed graph with scripts disabled, fails on any 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. +- 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 test: `test/wechat-locked-install.test.ts` keeps the manifest runtime-lock paths, Docker cache inputs, and installer verification dispatch synchronized. +- Regression tests: `test/wechat-locked-install.test.ts` keeps the manifest runtime-lock paths and installer verification dispatch synchronized; `test/wechat-runtime-audit-workflow.test.ts` keeps the Docker cache lifecycle, 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. diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index f2da1ecf98b..ccdcf0afd28 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -455,6 +455,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 audit a required %s workflow job", + "category": "security" } ] } diff --git a/scripts/checks/audit-wechat-runtime.sh b/scripts/checks/audit-wechat-runtime.sh new file mode 100755 index 00000000000..34f7f3a0381 --- /dev/null +++ b/scripts/checks/audit-wechat-runtime.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +runtime_dir="$repo_root/agents/openclaw/wechat-runtime" +report_dir="${1:-$repo_root/artifacts/wechat-runtime-audit}" +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")" +wechat_spec="@tencent-weixin/openclaw-weixin@2.4.3" +wechat_tarball="https://registry.npmjs.org/@tencent-weixin/openclaw-weixin/-/openclaw-weixin-2.4.3.tgz" +wechat_integrity="sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw==" + +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" +} +trap cleanup EXIT + +mkdir -p "$report_dir" + +# Materialize the same production graph and cache inputs used by Dockerfile. +npm --prefix "$runtime_dir" ci \ + --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" --cache "$trusted_cache" +done + +audit_status=0 +npm --prefix "$runtime_dir" audit \ + --omit=dev \ + --audit-level=low \ + --json >"$report_dir/npm-audit.json" || audit_status=$? + +signature_status=0 +npm --prefix "$runtime_dir" audit signatures \ + >"$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" \ + --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/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 7e218b2a42e..e747355796b 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -4,12 +4,17 @@ import { spawnSync } from "node:child_process"; import { + accessSync, chmodSync, + constants, existsSync, + lstatSync, mkdirSync, mkdtempSync, readFileSync, + realpathSync, rmSync, + statSync, writeFileSync, } from "node:fs"; import { homedir, tmpdir } from "node:os"; @@ -695,13 +700,16 @@ 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. + 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: install.runtimeLock.cachePath, + NPM_CONFIG_CACHE: installCache, NPM_CONFIG_OFFLINE: String(install.runtimeLock.offline), NPM_CONFIG_LEGACY_PEER_DEPS: String(install.runtimeLock.legacyPeerDeps), } @@ -726,6 +734,47 @@ export function installOpenClawMessagingPlugins(plan: MessagingBuildPlan | null, } } +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)}`, + ); + } + + const trustedCache = 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 61753282292..aece6759aa0 100644 --- a/src/lib/messaging/channels/wechat/manifest.ts +++ b/src/lib/messaging/channels/wechat/manifest.ts @@ -139,6 +139,7 @@ export const wechatManifest = { "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", diff --git a/src/lib/messaging/manifest/types.ts b/src/lib/messaging/manifest/types.ts index 2139ebeef4f..e94a806d3ea 100644 --- a/src/lib/messaging/manifest/types.ts +++ b/src/lib/messaging/manifest/types.ts @@ -205,6 +205,7 @@ 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; diff --git a/test/messaging-build-applier.test.ts b/test/messaging-build-applier.test.ts index 1fcb4cd837d..7055d9bca41 100644 --- a/test/messaging-build-applier.test.ts +++ b/test/messaging-build-applier.test.ts @@ -848,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", diff --git a/test/wechat-locked-install.test.ts b/test/wechat-locked-install.test.ts index 728ed112a9f..5fb2d42683a 100644 --- a/test/wechat-locked-install.test.ts +++ b/test/wechat-locked-install.test.ts @@ -24,9 +24,12 @@ function executable(file: string, contents: string): void { describe("locked WeChat plugin installation (#5896)", () => { it("installs from the reviewed archive using only the dedicated offline graph", () => { - const runtimeLock = wechatManifest.agentPackages[0].runtimeLock; + 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, @@ -34,7 +37,9 @@ describe("locked WeChat plugin installation (#5896)", () => { 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 trace = path.join(tmp, "trace"); + fs.mkdirSync(installCache); executable( path.join(tmp, "npm"), `#!/bin/sh @@ -52,6 +57,8 @@ 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" `, ); @@ -87,6 +94,7 @@ printf 'verify|%s|%s|offline=%s|cache=%s\n' "$3" "$4" "$NPM_CONFIG_OFFLINE" "$NP TRACE: trace, WECHAT_INTEGRITY, WECHAT_TARBALL, + NEMOCLAW_WECHAT_NPM_INSTALL_CACHE: installCache, NEMOCLAW_MESSAGING_PLAN_B64: Buffer.from(JSON.stringify(plan)).toString("base64"), }; @@ -95,12 +103,17 @@ printf 'verify|%s|%s|offline=%s|cache=%s\n' "$3" "$4" "$NPM_CONFIG_OFFLINE" "$NP expect(applyMessagingBuildPhase(serialized, "agent-install", env)).toEqual([]); const calls = fs.readFileSync(trace, "utf8"); expect(calls).toContain("install|npm-pack:"); - expect(calls).toContain( - "offline=true|peer=true|cache=/usr/local/share/nemoclaw/wechat-npm-cache", - ); + 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|offline=true", ); + expect(calls).not.toContain("cache=/usr/local/share/nemoclaw/wechat-npm-cache"); + expect( + fs.readFileSync( + path.join(installCache, "_cacache", "tmp", "nemoclaw-install-probe"), + "utf8", + ), + ).toBe("writable\n"); } 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..cb885f4b901 --- /dev/null +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -0,0 +1,114 @@ +// 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"; + +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, ".."); + +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.each(["pr", "main"])("makes the audit a required %s workflow job", (workflowName) => { + const workflow = readYaml(`.github/workflows/${workflowName}.yaml`); + const job = workflow.jobs["wechat-runtime-audit"]; + const checks = workflow.jobs.checks; + expect(job).toBeDefined(); + + expect(requiredStep(job, "Setup production-compatible Node.js").with).toMatchObject({ + "node-version": "22.19.0", + }); + expect(requiredStep(job, "Pin production npm").run).toBe( + "npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund", + ); + expect(requiredStep(job, "Audit locked WeChat runtime graph").run).toBe( + "bash scripts/checks/audit-wechat-runtime.sh artifacts/wechat-runtime-audit", + ); + 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(checks.needs).toContain("wechat-runtime-audit"); + const gate = requiredStep( + 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( + path.join(repoRoot, "scripts", "checks", "audit-wechat-runtime.sh"), + "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"', + ]) { + expect(script).toContain(fragment); + } + }); + + 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", + "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); + } + }); +}); From 2270db91400b76fd9cb452e4a244a755fc9d6725 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 11:27:40 -0700 Subject: [PATCH 05/25] docs(security): record WeChat audit gate Signed-off-by: Aaron Erickson --- docs/security/openclaw-2026.6.10-dependency-review.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index df0283ea7d4..724eb4e9243 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 @@ -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, and the dependency set. - `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 is a manual snapshot for the reviewed lock-only graph. It is not a new CI gate; rerun the command in the Advisory Check section on the next OpenClaw/plugin bump or if npm advisory state changes before merge. Follow-up automation should add a CI job for `npm install --package-lock-only --ignore-scripts && npm audit --omit=dev --json` on the reviewed OpenClaw/plugin graph. +- The full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through the disposable writable-cache boundary while keeping the trusted source cache read-only, and uploads the audit evidence. - 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. From 5625e0babe1ca71d8b4f035ba7d307000dc1c0cf Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 11:40:32 -0700 Subject: [PATCH 06/25] test(build): cover writable WeChat cache layer Signed-off-by: Aaron Erickson --- ...ckerfile-remote-dashboard-bind-contract.ts | 1 + test/openclaw-dependency-review.test.ts | 22 ++++++++++--------- test/openclaw-integrity-pin-suite.ts | 2 +- test/pr-workflow-contract.test.ts | 3 +++ test/sandbox-provisioning-tavily.test.ts | 2 +- test/sandbox-provisioning.test.ts | 2 +- 6 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts index 1c99e899a4d..dcf5dfa9e78 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/test/openclaw-dependency-review.test.ts b/test/openclaw-dependency-review.test.ts index 9f8d9769cbf..08ac134fc34 100644 --- a/test/openclaw-dependency-review.test.ts +++ b/test/openclaw-dependency-review.test.ts @@ -224,14 +224,18 @@ describe("OpenClaw 2026.6.10 dependency review contract", () => { expect(review).toContain("Issue #4434 full live acceptance"); expect(review).toContain("code-backed for the reviewed `openclaw@2026.6.10` artifact"); expect(review).toContain("src/lib/messaging/channels/manifests.test.ts"); - expect(review).toContain("npm audit result in this note is a manual snapshot"); + expect(review).toContain( + "full OpenClaw and plugin audit result in this note remains a manual snapshot", + ); expect(review).toContain("Advisory audit revalidated: 2026-07-03"); 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( - "CI job for `npm install --package-lock-only --ignore-scripts && npm audit --omit=dev --json`", + "Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job", ); + 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("Transitive Dependency Graph Rationale"); expect(review).toContain( "The OpenClaw 2026.6.10 bump does not newly introduce an unfrozen OpenClaw transitive graph", @@ -252,13 +256,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"); @@ -364,7 +366,7 @@ 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" -optional_plugin_block="$(sed -n '/# Install non-messaging OpenClaw plugins that need to match the runtime./,/^RUN OPENCLAW_VERSION=/p' Dockerfile)" +optional_plugin_block="$(sed -n '/# Install non-messaging OpenClaw plugins that need to match the runtime./,/# The reviewed cache stays root-owned and immutable to the sandbox user./p' Dockerfile)" check_contains "$optional_plugin_block" 'npm view "$plugin_spec" dist.integrity' "optional plugin registry integrity" check_contains "$optional_plugin_block" 'npm view "$plugin_spec" dist.tarball' "optional plugin registry tarball" check_contains "$optional_plugin_block" 'npm pack "$expected_tarball" --pack-destination "$NEMOCLAW_OPENCLAW_PLUGIN_PACK_DIR" --json' "optional plugin pack" @@ -394,7 +396,7 @@ check_contains "$optional_plugin_block" 'rm -rf "$NEMOCLAW_OPENCLAW_PLUGIN_PACK_ 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 d8789d4a5c8..f54f46520fa 100644 --- a/test/openclaw-integrity-pin-suite.ts +++ b/test/openclaw-integrity-pin-suite.ts @@ -319,7 +319,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/pr-workflow-contract.test.ts b/test/pr-workflow-contract.test.ts index 1b423b633de..a13601131fb 100644 --- a/test/pr-workflow-contract.test.ts +++ b/test/pr-workflow-contract.test.ts @@ -993,6 +993,7 @@ describe("pull request and main workflow contracts", () => { INSTALLER_INTEGRATION_RESULT: "success", PLUGIN_TESTS_RESULT: "success", STATIC_RESULT: "success", + WECHAT_RUNTIME_AUDIT_RESULT: "success", }; const successfulMain = { BUILD_TYPECHECK_RESULT: "success", @@ -1003,6 +1004,7 @@ describe("pull request and main workflow contracts", () => { PLUGIN_TESTS_RESULT: "success", REAL_OPENCLAW_DIST_HARNESS_RESULT: "success", STATIC_RESULT: "success", + WECHAT_RUNTIME_AUDIT_RESULT: "success", }; const codeSuccess = runWorkflowShellStep(prGate, successfulCode); @@ -1021,6 +1023,7 @@ describe("pull request and main workflow contracts", () => { INSTALLER_INTEGRATION_RESULT: "skipped", PLUGIN_TESTS_RESULT: "skipped", STATIC_RESULT: "skipped", + WECHAT_RUNTIME_AUDIT_RESULT: "skipped", }); const mainSuccess = runWorkflowShellStep(mainGate, successfulMain); const mainFailure = runWorkflowShellStep(mainGate, { 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/sandbox-provisioning.test.ts b/test/sandbox-provisioning.test.ts index a89560aca83..995fb7ec87c 100644 --- a/test/sandbox-provisioning.test.ts +++ b/test/sandbox-provisioning.test.ts @@ -305,7 +305,7 @@ describe("sandbox provisioning: non-messaging OpenClaw plugins", () => { 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-brave-plugin-install-")); try { From 485b3c61c993188ab546cf07bfb1e85fe6e3bd89 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 12:18:08 -0700 Subject: [PATCH 07/25] ci(security): add trusted WeChat audit action Signed-off-by: Aaron Erickson --- .../ci-wechat-runtime-audit/action.yaml | 32 ++++ .../actions/ci-wechat-runtime-audit/audit.sh | 167 ++++++++++++++++++ 2 files changed, 199 insertions(+) create mode 100644 .github/actions/ci-wechat-runtime-audit/action.yaml create mode 100755 .github/actions/ci-wechat-runtime-audit/audit.sh 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..463deaa1c43 --- /dev/null +++ b/.github/actions/ci-wechat-runtime-audit/action.yaml @@ -0,0 +1,32 @@ +# 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: npm install --global npm@10.9.4 --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..6e44f28d41a --- /dev/null +++ b/.github/actions/ci-wechat-runtime-audit/audit.sh @@ -0,0 +1,167 @@ +#!/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" + +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 +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")" + +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" +} +trap cleanup EXIT + +mkdir -p "$report_dir" + +readarray -t package_identity < <( + PACKAGE_JSON="$package_json" PACKAGE_LOCK="$package_lock" 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 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"); +} +if (typeof plugin.resolved !== "string" || !plugin.resolved.startsWith("https://registry.npmjs.org/")) { + throw new Error("WeChat runtime plugin must resolve from the reviewed npm registry origin"); +} +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}`); + } +} +process.stdout.write(`${dependencyNames[0]}@${version}\n${plugin.resolved}\n${plugin.integrity}\n`); +NODE +) +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 \ + --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" --cache "$trusted_cache" +done + +audit_status=0 +npm --prefix "$runtime_dir" audit \ + --omit=dev \ + --audit-level=low \ + --json >"$report_dir/npm-audit.json" || audit_status=$? + +signature_status=0 +npm --prefix "$runtime_dir" audit signatures \ + >"$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" \ + --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." From c17fd35dd0918e7dcab4efc63eb5c6df6c4c7594 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 12:23:37 -0700 Subject: [PATCH 08/25] fix(ci): harden WeChat audit gate Signed-off-by: Aaron Erickson --- .github/workflows/main.yaml | 13 +-- .github/workflows/pr.yaml | 57 +++++++++- agents/openclaw/dependency-review.md | 4 +- ci/source-shape-test-budget.json | 2 +- .../openclaw-2026.6.10-dependency-review.md | 4 +- scripts/checks/audit-wechat-runtime.sh | 104 ------------------ scripts/verify-wechat-runtime-lock.mts | 71 ++++++++++-- .../applier/build/messaging-build-applier.mts | 7 ++ test/verify-wechat-runtime-lock.test.ts | 36 ++++-- test/wechat-locked-install.test.ts | 5 +- test/wechat-runtime-audit-workflow.test.ts | 96 +++++++++++----- 11 files changed, 224 insertions(+), 175 deletions(-) delete mode 100755 scripts/checks/audit-wechat-runtime.sh diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 69604267768..178ba38b6d2 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -66,16 +66,11 @@ jobs: with: persist-credentials: false - - name: Setup production-compatible Node.js - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 - with: - node-version: "22.19.0" - - - name: Pin production npm - run: npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund - - name: Audit locked WeChat runtime graph - run: bash scripts/checks/audit-wechat-runtime.sh artifacts/wechat-runtime-audit + 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() }} diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 309246d86f3..3e7daaeca6a 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -203,16 +203,61 @@ jobs: with: persist-credentials: false - - name: Setup production-compatible Node.js - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 + - 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. + - 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: - node-version: "22.19.0" + repository: HOYALIM/NemoClaw + ref: 485b3c61c993188ab546cf07bfb1e85fe6e3bd89 + path: .trusted-wechat-audit-bootstrap + persist-credentials: false + sparse-checkout: | + .github/actions/ci-wechat-runtime-audit + sparse-checkout-cone-mode: false - - name: Pin production npm - run: npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund + - 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 - run: bash scripts/checks/audit-wechat-runtime.sh artifacts/wechat-runtime-audit + 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() }} diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index a54ee5d9cee..c150d0c9291 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -27,10 +27,10 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that immutable source into a writable cache used only for the OpenClaw plugin install, deletes the copy in the same image layer, and never writes to the trusted cache. The installer runs in offline, legacy-peer mode, then `verify-wechat-runtime-lock.mts` rejects integrity, version, or dependency-set drift in the managed npm project. -- Default CI gate: `wechat-runtime-audit` in `.github/workflows/pr.yaml` and `.github/workflows/main.yaml` uses Node `22.19.0` and npm `10.9.4`, materializes the committed graph with scripts disabled, fails on any 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. +- 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 (with a one-time immutable bootstrap pin for PR #6739); 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 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. - 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/wechat-runtime-audit-workflow.test.ts` keeps the Docker cache lifecycle, required CI gate, evidence upload, audit threshold, signature verification, and real npm-pack boundary synchronized. +- 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. diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 780225440a1..214ae5362ab 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -463,7 +463,7 @@ }, { "file": "test/wechat-runtime-audit-workflow.test.ts", - "test": "makes the audit a required %s workflow job", + "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 724eb4e9243..01073aba451 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -282,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 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, and the dependency set. +- 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through the disposable writable-cache boundary while keeping the trusted source cache read-only, and uploads the audit evidence. +- The full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the audit action from the base SHA; PR #6739 alone bootstraps the same action from a signed immutable commit because its base predates the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through the disposable writable-cache boundary while keeping the trusted source cache read-only, and uploads the audit evidence. - 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/checks/audit-wechat-runtime.sh b/scripts/checks/audit-wechat-runtime.sh deleted file mode 100755 index 34f7f3a0381..00000000000 --- a/scripts/checks/audit-wechat-runtime.sh +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -runtime_dir="$repo_root/agents/openclaw/wechat-runtime" -report_dir="${1:-$repo_root/artifacts/wechat-runtime-audit}" -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")" -wechat_spec="@tencent-weixin/openclaw-weixin@2.4.3" -wechat_tarball="https://registry.npmjs.org/@tencent-weixin/openclaw-weixin/-/openclaw-weixin-2.4.3.tgz" -wechat_integrity="sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw==" - -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" -} -trap cleanup EXIT - -mkdir -p "$report_dir" - -# Materialize the same production graph and cache inputs used by Dockerfile. -npm --prefix "$runtime_dir" ci \ - --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" --cache "$trusted_cache" -done - -audit_status=0 -npm --prefix "$runtime_dir" audit \ - --omit=dev \ - --audit-level=low \ - --json >"$report_dir/npm-audit.json" || audit_status=$? - -signature_status=0 -npm --prefix "$runtime_dir" audit signatures \ - >"$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" \ - --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/scripts/verify-wechat-runtime-lock.mts b/scripts/verify-wechat-runtime-lock.mts index 68c65b35043..24e90ce0656 100644 --- a/scripts/verify-wechat-runtime-lock.mts +++ b/scripts/verify-wechat-runtime-lock.mts @@ -11,6 +11,7 @@ type PackageRecord = { version?: string; integrity?: string; dependencies?: Record; + peerDependencies?: Record; }; type PackageLock = { @@ -29,14 +30,14 @@ function readJson(file: string): unknown { } } -function packageVersion(file: string): string { +function packageMetadata(file: string): PackageRecord { const parsed = readJson(file); - const version = - parsed && typeof parsed === "object" ? (parsed as Record).version : undefined; + 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 version; + return record; } export function expectedWechatGraph(lock: PackageLock): ReadonlyMap { @@ -76,10 +77,46 @@ function normalizedRecord(record: PackageRecord): PackageRecord { left.localeCompare(right), ), ), + peerDependencies: Object.fromEntries( + Object.entries(record.peerDependencies ?? {}).sort(([left], [right]) => + left.localeCompare(right), + ), + ), }; } -export function verifyWechatRuntimeLock(lockFile: string, projectsRoot: string): void { +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); @@ -97,21 +134,31 @@ export function verifyWechatRuntimeLock(lockFile: string, projectsRoot: string): throw new Error(`${location} metadata does not match the reviewed lock`); } const packageName = location.slice("node_modules/".length); - const installedVersion = packageVersion(path.join(installedRoot, location, "package.json")); - if (installedVersion !== expectedRecord.version) { + const installedMetadata = packageMetadata( + path.join(installedRoot, location, "package.json"), + ); + if (installedMetadata.version !== expectedRecord.version) { throw new Error( - `installed ${packageName}@${installedVersion} does not match locked ${expectedRecord.version}`, + `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] = process.argv; - if (!lockFile || !projectsRoot) { + const [, , lockFile, projectsRoot, openClawVersion] = process.argv; + if (!lockFile || !projectsRoot || !openClawVersion) { throw new Error( - "usage: verify-wechat-runtime-lock.mts ", + "usage: verify-wechat-runtime-lock.mts ", ); } - verifyWechatRuntimeLock(lockFile, projectsRoot); + 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 e747355796b..56871267948 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -717,6 +717,12 @@ export function installOpenClawMessagingPlugins(plan: MessagingBuildPlan | null, }; 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", @@ -724,6 +730,7 @@ export function installOpenClawMessagingPlugins(plan: MessagingBuildPlan | null, install.runtimeLock.verifierPath, install.runtimeLock.lockFile, install.runtimeLock.projectsRoot, + openClawVersion, ], installEnv, ); diff --git a/test/verify-wechat-runtime-lock.test.ts b/test/verify-wechat-runtime-lock.test.ts index 472569a2435..a6f2d28a557 100644 --- a/test/verify-wechat-runtime-lock.test.ts +++ b/test/verify-wechat-runtime-lock.test.ts @@ -9,6 +9,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { expectedWechatGraph, + verifyOpenClawPeerCompatibility, verifyWechatRuntimeLock, } from "../scripts/verify-wechat-runtime-lock.mts"; @@ -23,15 +24,23 @@ const packages = { 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, version: string): void { +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 })); + fs.writeFileSync( + path.join(target, "package.json"), + JSON.stringify({ version: record.version, peerDependencies: record.peerDependencies }), + ); } function fixture(): { lockFile: string; projectsRoot: string; installedLock: string } { @@ -41,7 +50,7 @@ function fixture(): { lockFile: string; projectsRoot: string; installedLock: str const installedRoot = path.join(projectsRoot, "wechat-project"); fs.mkdirSync(installedRoot, { recursive: true }); for (const [location, record] of Object.entries(packages)) { - writePackage(installedRoot, location, record.version); + writePackage(installedRoot, location, record); } const lockFile = path.join(root, "reviewed-lock.json"); const installedLock = path.join(installedRoot, "package-lock.json"); @@ -57,7 +66,18 @@ describe("WeChat runtime dependency lock", () => { it("accepts one managed npm graph that exactly matches the lock", () => { const { lockFile, projectsRoot } = fixture(); - expect(() => verifyWechatRuntimeLock(lockFile, projectsRoot)).not.toThrow(); + 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", () => { @@ -66,7 +86,7 @@ describe("WeChat runtime dependency lock", () => { driftedPackages["node_modules/zod"].integrity = "sha512-drift"; fs.writeFileSync(metadataDrift.installedLock, JSON.stringify({ packages: driftedPackages })); expect(() => - verifyWechatRuntimeLock(metadataDrift.lockFile, metadataDrift.projectsRoot), + verifyWechatRuntimeLock(metadataDrift.lockFile, metadataDrift.projectsRoot, "2026.6.10"), ).toThrow(/metadata does not match/); const extraPackage = fixture(); @@ -76,8 +96,8 @@ describe("WeChat runtime dependency lock", () => { packages: { ...packages, "node_modules/unreviewed": { version: "1.0.0" } }, }), ); - expect(() => verifyWechatRuntimeLock(extraPackage.lockFile, extraPackage.projectsRoot)).toThrow( - /dependency set does not match/, - ); + 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 index 5fb2d42683a..af05553290e 100644 --- a/test/wechat-locked-install.test.ts +++ b/test/wechat-locked-install.test.ts @@ -65,7 +65,7 @@ printf 'install|%s|offline=%s|peer=%s|cache=%s\n' "$3" "$NPM_CONFIG_OFFLINE" "$N executable( path.join(tmp, "node"), `#!/bin/sh -printf 'verify|%s|%s|offline=%s|cache=%s\n' "$3" "$4" "$NPM_CONFIG_OFFLINE" "$NPM_CONFIG_CACHE" >> "$TRACE" +printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CONFIG_OFFLINE" "$NPM_CONFIG_CACHE" >> "$TRACE" `, ); @@ -94,6 +94,7 @@ printf 'verify|%s|%s|offline=%s|cache=%s\n' "$3" "$4" "$NPM_CONFIG_OFFLINE" "$NP 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"), }; @@ -105,7 +106,7 @@ printf 'verify|%s|%s|offline=%s|cache=%s\n' "$3" "$4" "$NPM_CONFIG_OFFLINE" "$NP expect(calls).toContain("install|npm-pack:"); 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|offline=true", + "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( diff --git a/test/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts index cb885f4b901..3c82922fb6e 100644 --- a/test/wechat-runtime-audit-workflow.test.ts +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -36,45 +36,73 @@ function requiredStep(job: WorkflowJob, name: string): 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.each(["pr", "main"])("makes the audit a required %s workflow job", (workflowName) => { - const workflow = readYaml(`.github/workflows/${workflowName}.yaml`); - const job = workflow.jobs["wechat-runtime-audit"]; - const checks = workflow.jobs.checks; - expect(job).toBeDefined(); - - expect(requiredStep(job, "Setup production-compatible Node.js").with).toMatchObject({ - "node-version": "22.19.0", + 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(requiredStep(job, "Pin production npm").run).toBe( - "npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund", - ); - expect(requiredStep(job, "Audit locked WeChat runtime graph").run).toBe( - "bash scripts/checks/audit-wechat-runtime.sh artifacts/wechat-runtime-audit", + expect(String(trustedCheckout.with?.["sparse-checkout"])).toContain( + ".github/actions/ci-wechat-runtime-audit", ); - 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(checks.needs).toContain("wechat-runtime-audit"); - const gate = requiredStep( - checks, - workflowName === "pr" ? "Verify required PR checks" : "Verify required main checks", + const bootstrapCheckout = requiredStep(prJob, "Checkout pinned bootstrap WeChat runtime audit"); + expect(bootstrapCheckout.if).toContain("github.event.pull_request.number == 6739"); + expect(bootstrapCheckout.if).toContain( + "github.event.pull_request.head.repo.full_name == 'HOYALIM/NemoClaw'", ); - expect(gate.env).toMatchObject({ - WECHAT_RUNTIME_AUDIT_RESULT: "${{ needs['wechat-runtime-audit'].result }}", + expect(bootstrapCheckout.with).toMatchObject({ + repository: "HOYALIM/NemoClaw", + ref: "485b3c61c993188ab546cf07bfb1e85fe6e3bd89", + path: ".trusted-wechat-audit-bootstrap", + "persist-credentials": false, }); - expect(gate.run).toContain( - 'require_success "wechat-runtime-audit" "$WECHAT_RUNTIME_AUDIT_RESULT"', + 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( - path.join(repoRoot, "scripts", "checks", "audit-wechat-runtime.sh"), + path.join(repoRoot, ".github", "actions", "ci-wechat-runtime-audit", "audit.sh"), "utf8", ); for (const fragment of [ @@ -92,9 +120,19 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { '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", ]) { 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("npm@10.9.4 --ignore-scripts --no-audit --no-fund"); + expect(action).toContain('run: bash "$GITHUB_ACTION_PATH/audit.sh"'); }); it("keeps the image cache trusted and deletes the sandbox-writable copy", () => { From 0377c39887a24a818227028ee32827aa14971e17 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 12:26:44 -0700 Subject: [PATCH 09/25] docs(security): clarify trusted WeChat audit Signed-off-by: Aaron Erickson --- agents/openclaw/dependency-review.md | 4 ++-- docs/security/openclaw-2026.6.10-dependency-review.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index c150d0c9291..5d479a85e01 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -26,8 +26,8 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that immutable source into a writable cache used only for the OpenClaw plugin install, deletes the copy in the same image layer, and never writes to the trusted cache. The installer runs in offline, legacy-peer mode, then `verify-wechat-runtime-lock.mts` rejects integrity, version, or dependency-set drift in the managed npm project. -- 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 (with a one-time immutable bootstrap pin for PR #6739); 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 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. +- 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. The sandbox user copies that immutable source into a writable cache used only for the OpenClaw plugin install, deletes the copy in the same image layer, and never writes to the trusted cache. 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; 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. - 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. diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 01073aba451..56370df4d9c 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -284,7 +284,7 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr - 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 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the audit action from the base SHA; PR #6739 alone bootstraps the same action from a signed immutable commit because its base predates the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through the disposable writable-cache boundary while keeping the trusted source cache read-only, and uploads the audit evidence. +- The full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through the disposable writable-cache boundary while keeping the trusted source cache read-only, and uploads the audit evidence. - 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. From 8acc86991068c8d67e141be1aa890aac0fbcaaff Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 12:31:52 -0700 Subject: [PATCH 10/25] fix(openclaw): isolate WeChat archive retrieval Signed-off-by: Aaron Erickson --- agents/openclaw/dependency-review.md | 2 +- .../openclaw-2026.6.10-dependency-review.md | 2 +- .../applier/build/messaging-build-applier.mts | 35 ++++++++++--------- test/wechat-locked-install.test.ts | 21 ++++++++++- 4 files changed, 41 insertions(+), 19 deletions(-) diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index 5d479a85e01..80ebcc50421 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -26,7 +26,7 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that immutable source into a writable cache used only for the OpenClaw plugin install, deletes the copy in the same image layer, and never writes to the trusted cache. 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. +- 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. The sandbox user copies that 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; 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. - 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. diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 56370df4d9c..268de490cc1 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -284,7 +284,7 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr - 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 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through the disposable writable-cache boundary while keeping the trusted source cache read-only, and uploads the audit evidence. +- The full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, and uploads the audit evidence. The production installer separately 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/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 56871267948..3d6a6494c70 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -691,7 +691,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 @@ -700,21 +718,6 @@ 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. - 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), - } - : {}), - }; runCommand(["openclaw", "plugins", "install", `npm-pack:${packed.archivePath}`], installEnv); if (install.runtimeLock) { const openClawVersion = sanitizeOptionalString(env.OPENCLAW_VERSION); diff --git a/test/wechat-locked-install.test.ts b/test/wechat-locked-install.test.ts index af05553290e..52749e0a503 100644 --- a/test/wechat-locked-install.test.ts +++ b/test/wechat-locked-install.test.ts @@ -23,7 +23,7 @@ function executable(file: string, contents: string): void { } describe("locked WeChat plugin installation (#5896)", () => { - it("installs from the reviewed archive using only the dedicated offline graph", () => { + it("routes archive retrieval and install through the disposable offline cache", () => { const runtimeLock = wechatManifest.agentPackages.find( (pkg) => pkg.agent === "openclaw", )?.runtimeLock; @@ -38,12 +38,17 @@ describe("locked WeChat plugin installation (#5896)", () => { }); 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 @@ -91,6 +96,7 @@ printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CON }; const env = { PATH: `${tmp}:${process.env.PATH ?? "/usr/bin:/bin"}`, + HOME: home, TRACE: trace, WECHAT_INTEGRITY, WECHAT_TARBALL, @@ -104,11 +110,24 @@ printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CON 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|@tencent-weixin/openclaw-weixin@2.4.3|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"), From e5285cd3fe90d99024bc10e494bc637092fd92c3 Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Mon, 13 Jul 2026 12:47:37 -0700 Subject: [PATCH 11/25] fix(ci): pin trusted npm registry for WeChat audit Signed-off-by: Ho Lim --- .../ci-wechat-runtime-audit/action.yaml | 7 +- .../actions/ci-wechat-runtime-audit/audit.sh | 50 ++++++++++-- test/wechat-runtime-audit-workflow.test.ts | 79 +++++++++++++++++-- 3 files changed, 125 insertions(+), 11 deletions(-) diff --git a/.github/actions/ci-wechat-runtime-audit/action.yaml b/.github/actions/ci-wechat-runtime-audit/action.yaml index 463deaa1c43..31f4accf9f0 100644 --- a/.github/actions/ci-wechat-runtime-audit/action.yaml +++ b/.github/actions/ci-wechat-runtime-audit/action.yaml @@ -22,7 +22,12 @@ runs: - name: Pin production npm shell: bash - run: npm install --global npm@10.9.4 --ignore-scripts --no-audit --no-fund + 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 diff --git a/.github/actions/ci-wechat-runtime-audit/audit.sh b/.github/actions/ci-wechat-runtime-audit/audit.sh index 6e44f28d41a..b4209949167 100755 --- a/.github/actions/ci-wechat-runtime-audit/audit.sh +++ b/.github/actions/ci-wechat-runtime-audit/audit.sh @@ -13,6 +13,7 @@ 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 @@ -20,6 +21,14 @@ for input in "$runtime_dir" "$package_json" "$package_lock"; do 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"/*) ;; @@ -32,20 +41,41 @@ 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" readarray -t package_identity < <( - PACKAGE_JSON="$package_json" PACKAGE_LOCK="$package_lock" node <<'NODE' + 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"); @@ -65,9 +95,7 @@ if (rootDependency !== version || plugin?.version !== version) { if (typeof plugin.integrity !== "string" || !plugin.integrity.startsWith("sha512-")) { throw new Error("WeChat runtime plugin lock entry must carry sha512 integrity"); } -if (typeof plugin.resolved !== "string" || !plugin.resolved.startsWith("https://registry.npmjs.org/")) { - throw new Error("WeChat runtime plugin must resolve from the reviewed npm registry origin"); -} +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"); @@ -77,6 +105,7 @@ for (const [location, record] of Object.entries(packageLock.packages ?? {})) { 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 @@ -87,6 +116,8 @@ 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 \ @@ -94,17 +125,24 @@ npm --prefix "$runtime_dir" ci \ --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" --cache "$trusted_cache" + 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. @@ -113,6 +151,8 @@ 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" \ diff --git a/test/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts index 3c82922fb6e..afdc0dcbe05 100644 --- a/test/wechat-runtime-audit-workflow.test.ts +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -1,7 +1,9 @@ // 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"; @@ -27,6 +29,42 @@ type Workflow = { }; 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, + }, + }); + } finally { + fs.rmSync(targetRoot, { force: true, recursive: true }); + } +} function requiredStep(job: WorkflowJob, name: string): WorkflowStep { const step = job.steps?.find((candidate) => candidate.name === name); @@ -101,10 +139,7 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { }); it("audits the installed graph and exercises the exact archive through a copied cache", () => { - const script = fs.readFileSync( - path.join(repoRoot, ".github", "actions", "ci-wechat-runtime-audit", "audit.sh"), - "utf8", - ); + const script = fs.readFileSync(auditScript, "utf8"); for (const fragment of [ 'npm --prefix "$runtime_dir" ci', "--ignore-scripts", @@ -122,6 +157,10 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { '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); } @@ -131,10 +170,40 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { "utf8", ); expect(action).toContain('node-version: "22.19.0"'); - expect(action).toContain("npm@10.9.4 --ignore-scripts --no-audit --no-fund"); + 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(({ 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`); + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + "locked package must resolve from the reviewed npm registry origin: node_modules/qrcode-terminal", + ); + }); + 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 [ From 7e7b50d5bd67499bc04deb52a37ae9599cdb219d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 12:52:39 -0700 Subject: [PATCH 12/25] ci(security): advance trusted WeChat audit pin Signed-off-by: Aaron Erickson --- .github/workflows/pr.yaml | 2 +- agents/openclaw/dependency-review.md | 2 +- docs/security/openclaw-2026.6.10-dependency-review.md | 2 +- test/wechat-runtime-audit-workflow.test.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 3e7daaeca6a..5727a68963b 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -231,7 +231,7 @@ jobs: uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: repository: HOYALIM/NemoClaw - ref: 485b3c61c993188ab546cf07bfb1e85fe6e3bd89 + ref: e5285cd3fe90d99024bc10e494bc637092fd92c3 path: .trusted-wechat-audit-bootstrap persist-credentials: false sparse-checkout: | diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index 80ebcc50421..b74691dfa5d 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -27,7 +27,7 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; 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. +- 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@e5285cd3fe90d99024bc10e494bc637092fd92c3`; 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. - 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. diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 268de490cc1..36ae0138cf7 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -284,7 +284,7 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr - 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 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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@485b3c61c993188ab546cf07bfb1e85fe6e3bd89`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, and uploads the audit evidence. The production installer separately 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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@e5285cd3fe90d99024bc10e494bc637092fd92c3`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, and uploads the audit evidence. The production installer separately 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/test/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts index afdc0dcbe05..09f44560c9d 100644 --- a/test/wechat-runtime-audit-workflow.test.ts +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -98,7 +98,7 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { ); expect(bootstrapCheckout.with).toMatchObject({ repository: "HOYALIM/NemoClaw", - ref: "485b3c61c993188ab546cf07bfb1e85fe6e3bd89", + ref: "e5285cd3fe90d99024bc10e494bc637092fd92c3", path: ".trusted-wechat-audit-bootstrap", "persist-credentials": false, }); From 0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 13:18:41 -0700 Subject: [PATCH 13/25] ci(security): fail closed on WeChat metadata validation Signed-off-by: Aaron Erickson --- .github/actions/ci-wechat-runtime-audit/audit.sh | 10 ++++++++-- test/wechat-runtime-audit-workflow.test.ts | 14 ++++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.github/actions/ci-wechat-runtime-audit/audit.sh b/.github/actions/ci-wechat-runtime-audit/audit.sh index b4209949167..5220f5cc7e1 100755 --- a/.github/actions/ci-wechat-runtime-audit/audit.sh +++ b/.github/actions/ci-wechat-runtime-audit/audit.sh @@ -54,7 +54,7 @@ trap cleanup EXIT mkdir -p "$report_dir" -readarray -t package_identity < <( +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")); @@ -109,7 +109,13 @@ for (const [location, record] of Object.entries(packageLock.packages ?? {})) { } 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]}" diff --git a/test/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts index 09f44560c9d..459ed0f2532 100644 --- a/test/wechat-runtime-audit-workflow.test.ts +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -59,6 +59,7 @@ function runAuditValidation( ...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 { @@ -92,9 +93,8 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { ); const bootstrapCheckout = requiredStep(prJob, "Checkout pinned bootstrap WeChat runtime audit"); - expect(bootstrapCheckout.if).toContain("github.event.pull_request.number == 6739"); - expect(bootstrapCheckout.if).toContain( - "github.event.pull_request.head.repo.full_name == 'HOYALIM/NemoClaw'", + 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", @@ -190,18 +190,24 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { }); it("rejects an off-origin transitive package archive", () => { - const result = runAuditValidation(({ runtimeDir }) => { + 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", () => { From e1d056d910527d8b7d698258866b1a764e51893f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 13:31:15 -0700 Subject: [PATCH 14/25] ci(security): execute fail-closed WeChat audit Signed-off-by: Aaron Erickson --- .github/workflows/pr.yaml | 2 +- agents/openclaw/dependency-review.md | 2 +- docs/security/openclaw-2026.6.10-dependency-review.md | 2 +- test/wechat-runtime-audit-workflow.test.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 5727a68963b..8309be77a4c 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -231,7 +231,7 @@ jobs: uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: repository: HOYALIM/NemoClaw - ref: e5285cd3fe90d99024bc10e494bc637092fd92c3 + ref: 0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2 path: .trusted-wechat-audit-bootstrap persist-credentials: false sparse-checkout: | diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index b74691dfa5d..34135781ca1 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -27,7 +27,7 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that 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@e5285cd3fe90d99024bc10e494bc637092fd92c3`; 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. +- 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. - 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. diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 36ae0138cf7..0b94b733af6 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -284,7 +284,7 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr - 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 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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@e5285cd3fe90d99024bc10e494bc637092fd92c3`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, and uploads the audit evidence. The production installer separately 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 full OpenClaw and plugin audit result in this note remains a manual snapshot. Current pull-request and main-branch CI separately require the `wechat-runtime-audit` job for the WeChat graph. Pull requests execute the 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`; every other PR fails closed if its base lacks the action. The job uses Node `22.19.0` and npm `10.9.4`, installs the committed production graph with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, and uploads the audit evidence. The production installer separately 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/test/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts index 459ed0f2532..7d740f05f2c 100644 --- a/test/wechat-runtime-audit-workflow.test.ts +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -98,7 +98,7 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { ); expect(bootstrapCheckout.with).toMatchObject({ repository: "HOYALIM/NemoClaw", - ref: "e5285cd3fe90d99024bc10e494bc637092fd92c3", + ref: "0d2256d71d5bbba3bcaaaa4d01714fa56f22d1e2", path: ".trusted-wechat-audit-bootstrap", "persist-credentials": false, }); From 455b63f8ce8900a0f552b0440c7b8475a28186e2 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:05:43 -0700 Subject: [PATCH 15/25] fix(ci): verify Ubuntu fdfind binary name Signed-off-by: Aaron Erickson --- tools/pr-review-advisor/workflow-boundary.mts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/pr-review-advisor/workflow-boundary.mts b/tools/pr-review-advisor/workflow-boundary.mts index 5c9ce59240a..dd7bbe4a17b 100644 --- a/tools/pr-review-advisor/workflow-boundary.mts +++ b/tools/pr-review-advisor/workflow-boundary.mts @@ -353,7 +353,7 @@ done < <(find "$ADVISOR_WORKDIR" -type l -print0)`; requireRunContains(errors, install, "command -v rg"); requireRunContains(errors, install, 'FD_BINARY_VERSION="$(fdfind --version)"'); requireRunContains(errors, install, 'RG_BINARY_VERSION="$(rg --version)"'); - requireRunContains(errors, install, '"$FD_BINARY_VERSION" != "fd $EXPECTED_FD_BINARY_VERSION"'); + requireRunContains(errors, install, '"$FD_BINARY_VERSION" != "fdfind $EXPECTED_FD_BINARY_VERSION"'); requireRunContains( errors, install, From 818febd23767ca6af07de60fd319ac5c3a5e4928 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:10:06 -0700 Subject: [PATCH 16/25] fix(ci): install advisor yaml dependency Signed-off-by: Aaron Erickson --- .github/workflows/pr-review-advisor.yaml | 4 +++- test/pr-review-advisor-workflow-boundary.test.ts | 2 ++ tools/pr-review-advisor/workflow-boundary.mts | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-review-advisor.yaml b/.github/workflows/pr-review-advisor.yaml index 640b8dd2524..6b3c24db71d 100644 --- a/.github/workflows/pr-review-advisor.yaml +++ b/.github/workflows/pr-review-advisor.yaml @@ -85,6 +85,8 @@ jobs: # The review ledger imports TypeBox directly. Pi 0.80.6 shrinkwraps its # own copy, so the advisor runtime must install this direct dependency. TYPEBOX_VERSION: "1.1.38" + # Consolidated E2E recommendations import the workflow-boundary parser. + YAML_VERSION: "2.8.3" FD_FIND_VERSION: "9.0.0-1" RIPGREP_VERSION: "14.1.0-1" PR_REVIEW_ADVISOR_TIMEOUT_MS: "900000" @@ -246,7 +248,7 @@ jobs: fi PI_SDK_DIR="$RUNNER_TEMP/pi-sdk" - npm install --prefix "$PI_SDK_DIR" --ignore-scripts --no-save --package-lock=false --before=2026-07-11T00:00:00.000Z "@earendil-works/pi-coding-agent@${PI_SDK_VERSION}" "typebox@${TYPEBOX_VERSION}" + npm install --prefix "$PI_SDK_DIR" --ignore-scripts --no-save --package-lock=false --before=2026-07-11T00:00:00.000Z "@earendil-works/pi-coding-agent@${PI_SDK_VERSION}" "typebox@${TYPEBOX_VERSION}" "yaml@${YAML_VERSION}" rm -rf "$ADVISOR_DIR/node_modules" ln -s "$PI_SDK_DIR/node_modules" "$ADVISOR_DIR/node_modules" diff --git a/test/pr-review-advisor-workflow-boundary.test.ts b/test/pr-review-advisor-workflow-boundary.test.ts index 8afaf30fc43..7e51cd58bcc 100644 --- a/test/pr-review-advisor-workflow-boundary.test.ts +++ b/test/pr-review-advisor-workflow-boundary.test.ts @@ -483,6 +483,7 @@ printf 'sudo %s\\n' "$*" >> "$CALL_LOG" RIPGREP_VERSION: "14.1.0-1", RUNNER_TEMP: path.join(tmp, "runner"), TYPEBOX_VERSION: "test-typebox-version", + YAML_VERSION: "test-yaml-version", }, }, ); @@ -496,6 +497,7 @@ printf 'sudo %s\\n' "$*" >> "$CALL_LOG" expect(fs.readFileSync(callLog, "utf8")).toContain("rg --version"); expect(fs.readFileSync(callLog, "utf8")).toContain("--ignore-scripts"); expect(fs.readFileSync(callLog, "utf8")).toContain("typebox@test-typebox-version"); + expect(fs.readFileSync(callLog, "utf8")).toContain("yaml@test-yaml-version"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } diff --git a/tools/pr-review-advisor/workflow-boundary.mts b/tools/pr-review-advisor/workflow-boundary.mts index dd7bbe4a17b..dab40bfa5c5 100644 --- a/tools/pr-review-advisor/workflow-boundary.mts +++ b/tools/pr-review-advisor/workflow-boundary.mts @@ -249,6 +249,7 @@ function checkAnalysisJob(errors: string[], reviewJob: WorkflowRecord): void { requireEnv(errors, "review job", reviewJob, "FD_FIND_VERSION", "9.0.0-1"); requireEnv(errors, "review job", reviewJob, "RIPGREP_VERSION", "14.1.0-1"); requireEnv(errors, "review job", reviewJob, "TYPEBOX_VERSION", "1.1.38"); + requireEnv(errors, "review job", reviewJob, "YAML_VERSION", "2.8.3"); requireEnv( errors, "review job", @@ -361,6 +362,7 @@ done < <(find "$ADVISOR_WORKDIR" -type l -print0)`; ); requireRunContains(errors, install, "--ignore-scripts"); requireRunContains(errors, install, '"typebox@${TYPEBOX_VERSION}"'); + requireRunContains(errors, install, '"yaml@${YAML_VERSION}"'); requireRunContains(errors, install, '"$ADVISOR_DIR/node_modules"'); const analyze = requireStep(errors, steps, "Run PR review advisor"); From b7a19aa0d32d4025e66876b7e0f40b8ccdeb6776 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:14:29 -0700 Subject: [PATCH 17/25] fix(ci): install advisor vitest runtime Signed-off-by: Aaron Erickson --- .github/workflows/pr-review-advisor.yaml | 4 +++- test/pr-review-advisor-workflow-boundary.test.ts | 2 ++ tools/pr-review-advisor/workflow-boundary.mts | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-review-advisor.yaml b/.github/workflows/pr-review-advisor.yaml index 6b3c24db71d..99c3aa96b6b 100644 --- a/.github/workflows/pr-review-advisor.yaml +++ b/.github/workflows/pr-review-advisor.yaml @@ -87,6 +87,8 @@ jobs: TYPEBOX_VERSION: "1.1.38" # Consolidated E2E recommendations import the workflow-boundary parser. YAML_VERSION: "2.8.3" + # Credential-free E2E discovery invokes the repository's Vitest file lister. + VITEST_VERSION: "4.1.9" FD_FIND_VERSION: "9.0.0-1" RIPGREP_VERSION: "14.1.0-1" PR_REVIEW_ADVISOR_TIMEOUT_MS: "900000" @@ -248,7 +250,7 @@ jobs: fi PI_SDK_DIR="$RUNNER_TEMP/pi-sdk" - npm install --prefix "$PI_SDK_DIR" --ignore-scripts --no-save --package-lock=false --before=2026-07-11T00:00:00.000Z "@earendil-works/pi-coding-agent@${PI_SDK_VERSION}" "typebox@${TYPEBOX_VERSION}" "yaml@${YAML_VERSION}" + npm install --prefix "$PI_SDK_DIR" --ignore-scripts --no-save --package-lock=false --before=2026-07-11T00:00:00.000Z "@earendil-works/pi-coding-agent@${PI_SDK_VERSION}" "typebox@${TYPEBOX_VERSION}" "yaml@${YAML_VERSION}" "vitest@${VITEST_VERSION}" rm -rf "$ADVISOR_DIR/node_modules" ln -s "$PI_SDK_DIR/node_modules" "$ADVISOR_DIR/node_modules" diff --git a/test/pr-review-advisor-workflow-boundary.test.ts b/test/pr-review-advisor-workflow-boundary.test.ts index 7e51cd58bcc..9f7c205d95f 100644 --- a/test/pr-review-advisor-workflow-boundary.test.ts +++ b/test/pr-review-advisor-workflow-boundary.test.ts @@ -484,6 +484,7 @@ printf 'sudo %s\\n' "$*" >> "$CALL_LOG" RUNNER_TEMP: path.join(tmp, "runner"), TYPEBOX_VERSION: "test-typebox-version", YAML_VERSION: "test-yaml-version", + VITEST_VERSION: "test-vitest-version", }, }, ); @@ -498,6 +499,7 @@ printf 'sudo %s\\n' "$*" >> "$CALL_LOG" expect(fs.readFileSync(callLog, "utf8")).toContain("--ignore-scripts"); expect(fs.readFileSync(callLog, "utf8")).toContain("typebox@test-typebox-version"); expect(fs.readFileSync(callLog, "utf8")).toContain("yaml@test-yaml-version"); + expect(fs.readFileSync(callLog, "utf8")).toContain("vitest@test-vitest-version"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } diff --git a/tools/pr-review-advisor/workflow-boundary.mts b/tools/pr-review-advisor/workflow-boundary.mts index dab40bfa5c5..3c17acc753f 100644 --- a/tools/pr-review-advisor/workflow-boundary.mts +++ b/tools/pr-review-advisor/workflow-boundary.mts @@ -250,6 +250,7 @@ function checkAnalysisJob(errors: string[], reviewJob: WorkflowRecord): void { requireEnv(errors, "review job", reviewJob, "RIPGREP_VERSION", "14.1.0-1"); requireEnv(errors, "review job", reviewJob, "TYPEBOX_VERSION", "1.1.38"); requireEnv(errors, "review job", reviewJob, "YAML_VERSION", "2.8.3"); + requireEnv(errors, "review job", reviewJob, "VITEST_VERSION", "4.1.9"); requireEnv( errors, "review job", @@ -363,6 +364,7 @@ done < <(find "$ADVISOR_WORKDIR" -type l -print0)`; requireRunContains(errors, install, "--ignore-scripts"); requireRunContains(errors, install, '"typebox@${TYPEBOX_VERSION}"'); requireRunContains(errors, install, '"yaml@${YAML_VERSION}"'); + requireRunContains(errors, install, '"vitest@${VITEST_VERSION}"'); requireRunContains(errors, install, '"$ADVISOR_DIR/node_modules"'); const analyze = requireStep(errors, steps, "Run PR review advisor"); From 81125fdab24cce6fc8ab7a14bdb6eace81f5cd83 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:22:26 -0700 Subject: [PATCH 18/25] fix(messaging): remove stale archive imports Signed-off-by: Aaron Erickson --- src/lib/messaging/applier/build/messaging-build-applier.mts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 0656585ee6f..14e995ccb37 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -10,14 +10,13 @@ import { existsSync, lstatSync, mkdirSync, - mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs"; -import { homedir, tmpdir } from "node:os"; +import { homedir } from "node:os"; import { dirname, isAbsolute, join, resolve, sep } from "node:path"; import { pathToFileURL } from "node:url"; import { packReviewedNpmArchive } from "../../../../../scripts/lib/reviewed-npm-archive.mts"; From 5521f8fe75cfd6691d89264bda27055f2b1f4ec5 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:34:39 -0700 Subject: [PATCH 19/25] test(packaging): align reviewed archive contracts Signed-off-by: Aaron Erickson --- docs/security/openclaw-2026.6.10-dependency-review.md | 2 +- test/openclaw-optional-plugin-build.test.ts | 11 ++++++----- test/wechat-locked-install.test.ts | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index ea470edb9e0..58eb79fdd5f 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -38,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 diff --git a/test/openclaw-optional-plugin-build.test.ts b/test/openclaw-optional-plugin-build.test.ts index 67d4c732eef..bece3f68587 100644 --- a/test/openclaw-optional-plugin-build.test.ts +++ b/test/openclaw-optional-plugin-build.test.ts @@ -17,12 +17,13 @@ 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 commandStart = dockerfile.indexOf("\nRUN ", start) + 1; + const end = dockerfile.indexOf("\nRUN ", commandStart + 4); + if (start < 0 || commandStart <= start || end <= commandStart) { + throw new Error("unable to isolate the reviewed optional-plugin Dockerfile transaction"); + } const command = dockerfile - .slice(dockerfile.indexOf("RUN ", start) + 4, end) + .slice(commandStart + 4, end) .split("\n") .filter((line) => !line.trimStart().startsWith("#")) .join("\n") diff --git a/test/wechat-locked-install.test.ts b/test/wechat-locked-install.test.ts index 52749e0a503..88d6e3a91ca 100644 --- a/test/wechat-locked-install.test.ts +++ b/test/wechat-locked-install.test.ts @@ -114,7 +114,7 @@ printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CON `npm|view|@tencent-weixin/openclaw-weixin@2.4.3|cache=${fs.realpathSync(installCache)}|offline=true`, ); expect(calls).toContain( - `npm|pack|@tencent-weixin/openclaw-weixin@2.4.3|cache=${fs.realpathSync(installCache)}|offline=true`, + `npm|pack|${WECHAT_TARBALL}|cache=${fs.realpathSync(installCache)}|offline=true`, ); expect(calls).toContain(`offline=true|peer=true|cache=${fs.realpathSync(installCache)}`); expect(calls).toContain( From 03286edbf02b5ff670cc77d83021c92b6e710c95 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:41:34 -0700 Subject: [PATCH 20/25] test(packaging): keep optional plugin fixture linear Signed-off-by: Aaron Erickson --- test/openclaw-optional-plugin-build.test.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/test/openclaw-optional-plugin-build.test.ts b/test/openclaw-optional-plugin-build.test.ts index bece3f68587..35315e6e087 100644 --- a/test/openclaw-optional-plugin-build.test.ts +++ b/test/openclaw-optional-plugin-build.test.ts @@ -17,13 +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 commandStart = dockerfile.indexOf("\nRUN ", start) + 1; - const end = dockerfile.indexOf("\nRUN ", commandStart + 4); - if (start < 0 || commandStart <= start || end <= commandStart) { - throw new Error("unable to isolate the reviewed optional-plugin Dockerfile transaction"); - } const command = dockerfile - .slice(commandStart + 4, end) + .slice(start) + .split("\nRUN ", 3)[1] .split("\n") .filter((line) => !line.trimStart().startsWith("#")) .join("\n") From fbf969e2a3356214f77161f3c1a88d844c0bacc6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 15:11:48 -0700 Subject: [PATCH 21/25] fix(messaging): canonicalize WeChat cache boundary Signed-off-by: Aaron Erickson --- .../applier/build/messaging-build-applier.mts | 8 +- test/wechat-locked-install.test.ts | 120 ++++++++++++++++++ 2 files changed, 126 insertions(+), 2 deletions(-) diff --git a/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 14e995ccb37..ffd14f67bd0 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -742,7 +742,7 @@ export function installOpenClawMessagingPlugins(plan: MessagingBuildPlan | null, } } -function requireWritableRuntimeInstallCache( +export function requireWritableRuntimeInstallCache( runtimeLock: ChannelAgentPackageRuntimeLockSpec, env: Env, ): string { @@ -774,7 +774,11 @@ function requireWritableRuntimeInstallCache( ); } - const trustedCache = resolve(runtimeLock.cachePath); + // 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`, diff --git a/test/wechat-locked-install.test.ts b/test/wechat-locked-install.test.ts index 88d6e3a91ca..389aa61c1eb 100644 --- a/test/wechat-locked-install.test.ts +++ b/test/wechat-locked-install.test.ts @@ -11,6 +11,7 @@ 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 = @@ -22,6 +23,58 @@ 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( @@ -138,4 +191,71 @@ printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CON 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 trustedCache = path.join(tmp, "trusted-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 }); + } + }); }); From fa09c85dd3a2dd726c47f5824ddd28a58170a54d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 15:24:27 -0700 Subject: [PATCH 22/25] test(messaging): remove stale cache fixture Signed-off-by: Aaron Erickson --- test/wechat-locked-install.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/test/wechat-locked-install.test.ts b/test/wechat-locked-install.test.ts index 389aa61c1eb..5f6e5551d8b 100644 --- a/test/wechat-locked-install.test.ts +++ b/test/wechat-locked-install.test.ts @@ -197,7 +197,6 @@ printf 'verify|%s|%s|openclaw=%s|offline=%s|cache=%s\n' "$3" "$4" "$5" "$NPM_CON expected, }) => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wechat-invalid-cache-")); - const trustedCache = path.join(tmp, "trusted-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'); From e70c9226c735f591dc6cdabe66baf14aa21a8edd Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 15:36:48 -0700 Subject: [PATCH 23/25] docs(messaging): define audit bootstrap retirement Signed-off-by: Aaron Erickson --- .github/workflows/pr.yaml | 2 ++ agents/openclaw/dependency-review.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index f0c5a0e2710..ad4157fb0d7 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -228,6 +228,8 @@ jobs: # 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 diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index 34135781ca1..6fcf66e6347 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -27,7 +27,7 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that 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. +- 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. From 6a15263affd65abf2fb70b5424cf52edccc1108f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 15:53:48 -0700 Subject: [PATCH 24/25] fix(messaging): verify final WeChat cache graph Signed-off-by: Aaron Erickson --- Dockerfile | 13 ++ agents/openclaw/dependency-review.md | 2 +- scripts/lib/reviewed-npm-archive.mts | 196 ++++++++++++++++++++- test/openclaw-dependency-review.test.ts | 9 +- test/reviewed-npm-archive.test.ts | 107 ++++++++++- test/wechat-runtime-audit-workflow.test.ts | 13 ++ 6 files changed, 328 insertions(+), 12 deletions(-) diff --git a/Dockerfile b/Dockerfile index 9cce4ddd948..891ed06cd11 100644 --- a/Dockerfile +++ b/Dockerfile @@ -148,15 +148,28 @@ 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 \ diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index 6fcf66e6347..a7ff15c252f 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -26,7 +26,7 @@ Both image paths install the committed graph with `npm ci --ignore-scripts --omi - 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. The sandbox user copies that 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. +- 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. 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/test/openclaw-dependency-review.test.ts b/test/openclaw-dependency-review.test.ts index ccee272a567..5ee2dbeace0 100644 --- a/test/openclaw-dependency-review.test.ts +++ b/test/openclaw-dependency-review.test.ts @@ -316,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" @@ -379,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" diff --git a/test/reviewed-npm-archive.test.ts b/test/reviewed-npm-archive.test.ts index 596db0a22a0..5517114e602 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,48 @@ 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 }); + if (args[0] === "view") { + return args[2] === "dist.integrity" ? reviewed.expectedIntegrity : reviewed.tarballUrl; + } + 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`; + if (!filename.includes("/") && !filename.includes("\\")) { + fs.writeFileSync(path.join(destination, filename), "reviewed cache bytes"); + } + 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 +171,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/wechat-runtime-audit-workflow.test.ts b/test/wechat-runtime-audit-workflow.test.ts index 7d740f05f2c..837856ab01c 100644 --- a/test/wechat-runtime-audit-workflow.test.ts +++ b/test/wechat-runtime-audit-workflow.test.ts @@ -214,6 +214,10 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { 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"/', @@ -223,5 +227,14 @@ describe("WeChat runtime audit and install-cache gates (#5896)", () => { ]) { 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); }); }); From 721a2a90cc4929a350bb2f02720e6e50f2632016 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 15:58:12 -0700 Subject: [PATCH 25/25] test(messaging): keep cache proof branch-free Signed-off-by: Aaron Erickson --- test/reviewed-npm-archive.test.ts | 49 ++++++++++++++++++------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/test/reviewed-npm-archive.test.ts b/test/reviewed-npm-archive.test.ts index 5517114e602..9040fa37891 100644 --- a/test/reviewed-npm-archive.test.ts +++ b/test/reviewed-npm-archive.test.ts @@ -56,29 +56,38 @@ function cachedArchiveRunner( ) { return (args: readonly string[], reviewed: ReviewedNpmArchiveRequest): string => { calls.push({ args: [...args], request: reviewed }); - if (args[0] === "view") { - return args[2] === "dist.integrity" ? reviewed.expectedIntegrity : reviewed.tarballUrl; - } - 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`; - if (!filename.includes("/") && !filename.includes("\\")) { - fs.writeFileSync(path.join(destination, filename), "reviewed cache bytes"); - } - return JSON.stringify([ - { - filename, - integrity: - mutation?.packageSpec === reviewed.packageSpec && mutation.integrity - ? mutation.integrity - : reviewed.expectedIntegrity, - }, - ]); + 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 }); });