diff --git a/.github/workflows/base-image.yaml b/.github/workflows/base-image.yaml index 715f3cda49e..9de89f7ad32 100644 --- a/.github/workflows/base-image.yaml +++ b/.github/workflows/base-image.yaml @@ -65,6 +65,7 @@ on: - "scripts/security/patches/python3.13-htmlparser-cve-2026-15308.patch" - "scripts/checks/node-tar-image-scan.mts" - "scripts/patch-bundled-npm-brace-expansion.mts" + - "scripts/lib/patch-bundled-npm-ip-address.mts" - "scripts/patch-bundled-npm-tar.mts" - "scripts/upgrade-bundled-npm.mts" - "scripts/lib/sandbox-rlimits.sh" diff --git a/Dockerfile b/Dockerfile index 09eaabcd8d4..7be82551cbb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -135,6 +135,7 @@ COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts COPY scripts/lib/reviewed-npm-audit.mts /scripts/lib/reviewed-npm-audit.mts COPY scripts/lib/openclaw-npm-remediation.mts /scripts/lib/openclaw-npm-remediation.mts COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts +COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts FROM scratch AS openclaw-plugin-payload @@ -277,6 +278,15 @@ RUN if [ -n "${NEMOCLAW_CORPORATE_CA_B64}" ]; then \ # nemoclaw-start overrides it with the merged OpenShell + corporate bundle. ENV NODE_EXTRA_CA_CERTS=/usr/local/share/nemoclaw/corporate-ca.pem +# Reassert the npm-private ip-address fix for the exact final filesystem. When +# onboarding supplied a corporate CA, use it for the registry-backed download. +# hadolint ignore=DL3059 +RUN if [ -f /usr/local/share/nemoclaw/corporate-ca.pem ]; then \ + export CURL_CA_BUNDLE=/usr/local/share/nemoclaw/corporate-ca.pem; \ + fi; \ + node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts \ + --npm-root /usr/local/lib/node_modules/npm + # Harden: remove unnecessary build tools and network probes from base image (#830) # Protect runtime tools before autoremove — the GHCR base may predate the # procps/e2fsprogs/tmux additions, leaving ps/chattr/tmux absent or auto-marked. @@ -1794,6 +1804,7 @@ RUN check_metadata() { \ fi; \ } \ && check_metadata /scripts/patch-bundled-npm-brace-expansion.mts 'root:root:755' \ + && check_metadata /scripts/lib/patch-bundled-npm-ip-address.mts 'root:root:755' \ && check_metadata /scripts/patch-bundled-npm-tar.mts 'root:root:755' \ && check_metadata /opt/nemoclaw/openclaw.plugin.json 'root:root:644' \ && check_metadata /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.mts 'root:root:755' \ diff --git a/Dockerfile.base b/Dockerfile.base index 4a2b4177f15..2746fb91dcd 100644 --- a/Dockerfile.base +++ b/Dockerfile.base @@ -418,6 +418,7 @@ COPY scripts/lib/reviewed-npm-archive.mts \ scripts/lib/openclaw-npm-remediation.mts \ /scripts/lib/ COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts +COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts COPY scripts/upgrade-bundled-npm.mts /scripts/upgrade-bundled-npm.mts @@ -439,6 +440,12 @@ RUN node --experimental-strip-types /scripts/upgrade-bundled-npm.mts \ RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts \ --npm-root /usr/local/lib/node_modules/npm +# npm 11.18.0 contains ip-address 10.2.0. Replace only that private package +# with the reviewed 10.3.1 archive after the complete npm upgrade. +# hadolint ignore=DL3059 +RUN node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts \ + --npm-root /usr/local/lib/node_modules/npm + # Keep OpenClaw's jiti-generated source cache out of /tmp so provider marker # names do not persist in runtime snapshots or leak-scan inputs. ENV JITI_FS_CACHE=false diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index 6cf5107dc2c..616f4e5ad9f 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -90,6 +90,7 @@ FROM scratch AS hermes-npm-patch-payload COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts +COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts FROM scratch AS hermes-agent-payload @@ -163,6 +164,11 @@ RUN node --experimental-strip-types /scripts/patch-bundled-npm-tar.mts \ RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts \ --npm-root /usr/local/lib/node_modules/npm +# Reassert the npm-private ip-address fix for the exact final filesystem. +# hadolint ignore=DL3059 +RUN node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts \ + --npm-root /usr/local/lib/node_modules/npm + # Keep the final image contract explicit even when the published base image # changes independently of this Dockerfile. RUN set -eu; \ @@ -265,7 +271,8 @@ RUN find /opt/nemoclaw-hermes-config -type d -exec chmod 755 {} + \ && find /opt/nemoclaw-hermes-config -type f -exec chmod 444 {} + \ && chmod 444 /src/lib/tool-disclosure.ts \ && chmod 444 /scripts/lib/reviewed-npm-archive.mts /scripts/lib/openclaw-npm-remediation.mts \ - /scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-tar.mts \ + /scripts/patch-bundled-npm-brace-expansion.mts /scripts/lib/patch-bundled-npm-ip-address.mts \ + /scripts/patch-bundled-npm-tar.mts \ && chmod -R a+rX /src/lib/messaging ARG NEMOCLAW_HERMES_IMAGE_BUILD_PROBES_SHA256=284e2bf46c82f25967b86f73fbefcd97315a1284a4b079bd6f13e6153bece4b6 @@ -1063,6 +1070,7 @@ RUN check_metadata() { \ && check_absent /sandbox/.cache \ && check_metadata /sandbox/.nemoclaw 'root:root 1755' \ && check_metadata /scripts/patch-bundled-npm-brace-expansion.mts 'root:root 444' \ + && check_metadata /scripts/lib/patch-bundled-npm-ip-address.mts 'root:root 444' \ && check_metadata /scripts/patch-bundled-npm-tar.mts 'root:root 444' \ && check_metadata /opt/nemoclaw-hermes-config/generate-config.ts 'root:root 444' \ && check_metadata /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py 'root:root 755' \ diff --git a/agents/hermes/Dockerfile.base b/agents/hermes/Dockerfile.base index a9fa25e262d..c8875fb7206 100644 --- a/agents/hermes/Dockerfile.base +++ b/agents/hermes/Dockerfile.base @@ -252,6 +252,7 @@ RUN arch="$(dpkg --print-architecture)" \ COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts +COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts COPY scripts/upgrade-bundled-npm.mts /scripts/upgrade-bundled-npm.mts @@ -273,6 +274,12 @@ RUN node --experimental-strip-types /scripts/upgrade-bundled-npm.mts \ RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts \ --npm-root /usr/local/lib/node_modules/npm +# Replace npm 11.18.0's private ip-address 10.2.0 package with the +# registry- and SRI-pinned 10.3.1 release. +# hadolint ignore=DL3059 +RUN node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts \ + --npm-root /usr/local/lib/node_modules/npm + # gosu for privilege separation (gateway vs sandbox user). # Identical to OpenClaw base — pinned to 1.19 with checksum. # hadolint ignore=DL4006 diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index edd0c221299..2af5c6330c2 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -134,6 +134,7 @@ RUN discovery_contract="$(node /usr/local/lib/nemoclaw/mcp-tool-discovery-runtim COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts +COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts # The final managed image owns the shipped dependency boundary independently @@ -146,6 +147,15 @@ RUN node --experimental-strip-types /scripts/patch-bundled-npm-tar.mts \ RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts \ --npm-root /usr/local/lib/node_modules/npm +# Reassert the npm-private ip-address fix for the exact final filesystem. When +# onboarding supplied a corporate CA, use it for the registry-backed download. +# hadolint ignore=DL3059 +RUN if [ -f /usr/local/share/nemoclaw/corporate-ca.pem ]; then \ + export CURL_CA_BUNDLE=/usr/local/share/nemoclaw/corporate-ca.pem; \ + fi; \ + node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts \ + --npm-root /usr/local/lib/node_modules/npm + RUN set -eu; \ dcode_path="$(command -v dcode 2>/dev/null || true)"; \ if [ "$dcode_path" != "/usr/local/bin/dcode" ]; then \ diff --git a/agents/langchain-deepagents-code/Dockerfile.base b/agents/langchain-deepagents-code/Dockerfile.base index 152f6d7944c..8ef9adfac4e 100644 --- a/agents/langchain-deepagents-code/Dockerfile.base +++ b/agents/langchain-deepagents-code/Dockerfile.base @@ -69,6 +69,7 @@ COPY --from=perl-builder /out /tmp/nemoclaw-native-security COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts +COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts COPY scripts/upgrade-bundled-npm.mts /scripts/upgrade-bundled-npm.mts @@ -243,6 +244,12 @@ RUN node --experimental-strip-types /scripts/upgrade-bundled-npm.mts \ RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts \ --npm-root /usr/local/lib/node_modules/npm +# Replace npm 11.18.0's private ip-address 10.2.0 package with the +# registry- and SRI-pinned 10.3.1 release. +# hadolint ignore=DL3059 +RUN node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts \ + --npm-root /usr/local/lib/node_modules/npm + RUN groupadd -r sandbox \ && useradd -r -g sandbox -d /sandbox -s /bin/bash sandbox \ && usermod -a -G sandbox root \ diff --git a/scripts/lib/patch-bundled-npm-ip-address.mts b/scripts/lib/patch-bundled-npm-ip-address.mts new file mode 100755 index 00000000000..499cc72b5c0 --- /dev/null +++ b/scripts/lib/patch-bundled-npm-ip-address.mts @@ -0,0 +1,409 @@ +#!/usr/bin/env -S node --experimental-strip-types + +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import { + closeSync, + constants, + cpSync, + fstatSync, + lstatSync, + mkdirSync, + mkdtempSync, + openSync, + readdirSync, + readFileSync, + realpathSync, + renameSync, + rmSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const AFFECTED_IP_ADDRESS_VERSION = "10.2.0"; +export const FIXED_IP_ADDRESS_VERSION = "10.3.1"; +export const FIXED_IP_ADDRESS_INTEGRITY = + "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g=="; +export const FIXED_IP_ADDRESS_TARBALL = + "https://registry.npmjs.org/ip-address/-/ip-address-10.3.1.tgz"; +export const REVIEWED_NPM_VERSION = "11.18.0"; + +const REVIEWED_IP_ADDRESS_VERSIONS = new Set([ + AFFECTED_IP_ADDRESS_VERSION, + FIXED_IP_ADDRESS_VERSION, +]); + +type JsonRecord = Record; + +function record(value: unknown, label: string): JsonRecord { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error(`${label} must be a JSON object`); + } + return value as JsonRecord; +} + +function readJson(file: string, label: string): JsonRecord { + const descriptor = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + if (!fstatSync(descriptor).isFile()) throw new Error(`${label} must be a real file: ${file}`); + return record(JSON.parse(readFileSync(descriptor, "utf8")), label); + } catch (error) { + throw new Error(`${label} is invalid: ${String(error)}`); + } finally { + closeSync(descriptor); + } +} + +function realDirectory(directory: string, label: string): string { + const resolved = resolve(directory); + const metadata = lstatSync(resolved); + if (!metadata.isDirectory() || metadata.isSymbolicLink()) { + throw new Error(`${label} must be a real directory: ${resolved}`); + } + return realpathSync(resolved); +} + +function rejectUnsafeTree(root: string): void { + for (const entry of readdirSync(root, { withFileTypes: true })) { + if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) { + throw new Error(`replacement ip-address package contains an unsafe member: ${entry.name}`); + } + if (entry.isDirectory()) rejectUnsafeTree(join(root, entry.name)); + } +} + +function removeBackup(backupPath: string): void { + try { + rmSync(backupPath, { force: true, recursive: true }); + } catch (cleanupError) { + try { + rmSync(backupPath, { force: true, recursive: true }); + } catch (retryError) { + throw new AggregateError( + [cleanupError, retryError], + `verified replacement retained but affected backup cleanup failed: ${backupPath}`, + ); + } + } +} + +function isContainedBinSymlink( + nodeModulesRoot: string, + directory: string, + entryName: string, +): boolean { + if (basename(directory) !== ".bin") return false; + try { + const target = realpathSync(join(directory, entryName)); + const targetRelative = relative(nodeModulesRoot, target); + return ( + targetRelative !== "" && + targetRelative !== ".." && + !targetRelative.startsWith(`..${sep}`) && + !isAbsolute(targetRelative) && + lstatSync(target).isFile() + ); + } catch { + return false; + } +} + +function collectIpAddressVersions( + directory: string, + nodeModulesRoot: string, + versions: string[], +): void { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + if (entry.isSymbolicLink()) { + if (!isContainedBinSymlink(nodeModulesRoot, directory, entry.name)) { + throw new Error(`npm package contains an unsafe symlink: ${join(directory, entry.name)}`); + } + continue; + } + if ( + entry.isDirectory() && + (entry.name.startsWith(".ip-address.nemoclaw-stage-") || + entry.name.startsWith("ip-address.nemoclaw-backup-")) + ) { + continue; + } + if (!entry.isDirectory() && !entry.isFile()) { + throw new Error(`npm package contains an unsafe member: ${join(directory, entry.name)}`); + } + const child = join(directory, entry.name); + if (entry.isDirectory()) { + collectIpAddressVersions(child, nodeModulesRoot, versions); + continue; + } + if (entry.name !== "package.json") continue; + const manifest = readJson(child, "npm bundled package manifest"); + if (manifest.name === "ip-address") { + if (typeof manifest.version !== "string") { + throw new Error("npm bundled ip-address version is invalid"); + } + versions.push(manifest.version); + } + } +} + +function verifyIpAddressManifest(manifest: JsonRecord): string { + const version = manifest.version; + const engines = record(manifest.engines, "npm bundled ip-address engines"); + if ( + manifest.name !== "ip-address" || + typeof version !== "string" || + !REVIEWED_IP_ADDRESS_VERSIONS.has(version) || + manifest.main !== "dist/ip-address.js" || + manifest.types !== "dist/ip-address.d.ts" || + manifest.license !== "MIT" || + engines.node !== ">= 12" || + manifest.dependencies !== undefined + ) { + throw new Error( + `npm bundled ip-address identity or package contract has drifted: ${JSON.stringify({ + dependencies: manifest.dependencies, + engines, + license: manifest.license, + main: manifest.main, + types: manifest.types, + version, + })}`, + ); + } + return version; +} + +export type BundledNpmIpAddressState = Readonly<{ + ipAddressVersion: string; + npmVersion: string; + state: "affected" | "fixed"; +}>; + +export function inspectBundledNpmIpAddress(npmRoot: string): BundledNpmIpAddressState { + const root = realDirectory(npmRoot, "npm package root"); + const npmManifest = readJson(join(root, "package.json"), "npm package manifest"); + if (npmManifest.name !== "npm" || npmManifest.version !== REVIEWED_NPM_VERSION) { + throw new Error(`npm package identity has drifted; expected npm@${REVIEWED_NPM_VERSION}`); + } + + const version = verifyIpAddressManifest( + readJson( + join(root, "node_modules", "ip-address", "package.json"), + "npm bundled ip-address manifest", + ), + ); + const versions: string[] = []; + const nodeModulesRoot = realDirectory(join(root, "node_modules"), "npm node_modules root"); + collectIpAddressVersions(nodeModulesRoot, nodeModulesRoot, versions); + if (versions.length !== 1 || versions[0] !== version) { + throw new Error(`npm bundled ip-address layout has drifted: ${JSON.stringify(versions)}`); + } + + return { + ipAddressVersion: version, + npmVersion: REVIEWED_NPM_VERSION, + state: version === FIXED_IP_ADDRESS_VERSION ? "fixed" : "affected", + }; +} + +export function verifyBundledNpmIpAddress(npmRoot: string): BundledNpmIpAddressState { + const inspected = inspectBundledNpmIpAddress(npmRoot); + if (inspected.state !== "fixed") { + throw new Error( + `npm@${inspected.npmVersion} bundles affected ip-address@${inspected.ipAddressVersion}; expected ${FIXED_IP_ADDRESS_VERSION}`, + ); + } + return inspected; +} + +export function patchBundledNpmIpAddress(options: { + npmRoot: string; + replacementRoot: string; +}): BundledNpmIpAddressState { + const npmRoot = realDirectory(options.npmRoot, "npm package root"); + const replacementRoot = realDirectory(options.replacementRoot, "replacement ip-address root"); + rejectUnsafeTree(replacementRoot); + const replacementVersion = verifyIpAddressManifest( + readJson(join(replacementRoot, "package.json"), "replacement ip-address manifest"), + ); + if (replacementVersion !== FIXED_IP_ADDRESS_VERSION) { + throw new Error(`replacement package must be ip-address@${FIXED_IP_ADDRESS_VERSION}`); + } + + const current = inspectBundledNpmIpAddress(npmRoot); + if (current.state === "fixed") return current; + + const livePath = join(npmRoot, "node_modules", "ip-address"); + const transactionId = `${process.pid}-${randomBytes(8).toString("hex")}`; + const stagingRoot = mkdtempSync(join(dirname(livePath), ".ip-address.nemoclaw-stage-")); + const stagedPath = join(stagingRoot, "replacement"); + const backupPath = `${livePath}.nemoclaw-backup-${transactionId}`; + let rollbackRequired = false; + try { + cpSync(replacementRoot, stagedPath, { dereference: false, recursive: true }); + cpSync(livePath, backupPath, { + dereference: false, + errorOnExist: true, + force: false, + preserveTimestamps: true, + recursive: true, + }); + rollbackRequired = true; + rmSync(livePath, { recursive: true }); + renameSync(stagedPath, livePath); + const fixed = verifyBundledNpmIpAddress(npmRoot); + rollbackRequired = false; + removeBackup(backupPath); + return fixed; + } catch (error) { + if (rollbackRequired) { + try { + rmSync(livePath, { force: true, recursive: true }); + renameSync(backupPath, livePath); + } catch (rollbackError) { + throw new AggregateError( + [error, rollbackError], + `npm bundled ip-address rollback failed; ${backupPath} retains the original tree`, + ); + } + } + throw error; + } finally { + rmSync(stagingRoot, { force: true, recursive: true }); + } +} + +export type BundledNpmIpAddressCommandRunner = (command: string, args: readonly string[]) => void; + +function run(command: string, args: readonly string[]): void { + const result = spawnSync(command, args, { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 60_000, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error(`${command} failed: ${`${result.stdout ?? ""}${result.stderr ?? ""}`.trim()}`); + } +} + +type PreparedReplacement = Readonly<{ + cleanup: () => void; + replacementRoot: string; +}>; + +function prepareFixedIpAddressReplacement( + commandRunner: BundledNpmIpAddressCommandRunner, +): PreparedReplacement { + const rootDirectory = mkdtempSync(join(tmpdir(), "nemoclaw-npm-ip-address-")); + const archivePath = join(rootDirectory, `ip-address-${FIXED_IP_ADDRESS_VERSION}.tgz`); + const replacementRoot = join(rootDirectory, "replacement"); + try { + commandRunner("curl", [ + "--proto", + "=https", + "--tlsv1.2", + "--fail", + "--silent", + "--show-error", + "--output", + archivePath, + FIXED_IP_ADDRESS_TARBALL, + ]); + const descriptor = openSync(archivePath, constants.O_RDONLY | constants.O_NOFOLLOW); + let archiveBytes: Buffer; + try { + if (!fstatSync(descriptor).isFile()) { + throw new Error("ip-address replacement download must be a real file"); + } + archiveBytes = readFileSync(descriptor); + } finally { + closeSync(descriptor); + } + const actualIntegrity = `sha512-${createHash("sha512").update(archiveBytes).digest("base64")}`; + if (actualIntegrity !== FIXED_IP_ADDRESS_INTEGRITY) { + throw new Error( + `ip-address replacement integrity mismatch\nExpected: ${FIXED_IP_ADDRESS_INTEGRITY}\nActual: ${actualIntegrity}`, + ); + } + + mkdirSync(replacementRoot, { mode: 0o700 }); + commandRunner("tar", [ + "--extract", + "--gzip", + "--file", + archivePath, + "--directory", + replacementRoot, + "--strip-components=1", + "--no-same-owner", + "--no-same-permissions", + ]); + return { + cleanup: () => rmSync(rootDirectory, { force: true, recursive: true }), + replacementRoot, + }; + } catch (error) { + rmSync(rootDirectory, { force: true, recursive: true }); + throw error; + } +} + +export type BundledNpmIpAddressRegistryDependencies = Readonly<{ + commandRunner?: BundledNpmIpAddressCommandRunner; + prepareReplacement?: (commandRunner: BundledNpmIpAddressCommandRunner) => PreparedReplacement; +}>; + +export function patchBundledNpmIpAddressFromRegistry( + npmRoot: string, + dependencies: BundledNpmIpAddressRegistryDependencies = {}, +): BundledNpmIpAddressState { + const commandRunner = dependencies.commandRunner ?? run; + const current = inspectBundledNpmIpAddress(npmRoot); + if (current.state === "fixed") { + commandRunner("npm", ["--version"]); + commandRunner("npx", ["--version"]); + return current; + } + const prepared = (dependencies.prepareReplacement ?? prepareFixedIpAddressReplacement)( + commandRunner, + ); + try { + const result = patchBundledNpmIpAddress({ + npmRoot, + replacementRoot: prepared.replacementRoot, + }); + commandRunner("npm", ["--version"]); + commandRunner("npx", ["--version"]); + return result; + } finally { + prepared.cleanup(); + } +} + +function argument(name: string): string { + const index = process.argv.indexOf(name); + const value = index >= 0 ? process.argv[index + 1] : undefined; + if (!value || value.startsWith("--")) throw new Error(`${name} is required`); + return value; +} + +function isMainModule(): boolean { + return process.argv[1] ? fileURLToPath(import.meta.url) === resolve(process.argv[1]) : false; +} + +if (isMainModule()) { + try { + const result = patchBundledNpmIpAddressFromRegistry(argument("--npm-root")); + process.stdout.write( + `Verified npm@${result.npmVersion} bundled ip-address@${result.ipAddressVersion}\n`, + ); + } catch (error) { + console.error(`ERROR: ${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; + } +} diff --git a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts index 189cfe0d17b..350215a41bc 100644 --- a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts +++ b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts @@ -58,7 +58,7 @@ const CANONICAL_POST_GENERATOR_RUN_SHA256 = new Set([ "a0a554d474cb70087e50686d998915eae06201d6182a2410d3ccc4879e5058e6", "5af905889f94ffed2f6c371111d0589e38eed7b0de54ddb0dd68ad912a23149a", "1197b99bdb996b37a3e4e386a507dfabcdfb2c26a40b015d617f97208668187d", - "5cc53ef9c588470f325c5df8189a2eb1525140d947332ae2c0a80fccb2f36ccb", + "c0b409e1bf4d33a9e44f407c6bd9b0445b2ffd0b796823fe3cfa5989314d6603", "83567d1fa0e73bef6a3333383c13ace05e26704964ae6a7a76ee24a2f2be3d7e", "ca1f7b1cb9dd5d467f806792c4072a84ef1e6402c3e8650b6325b95cc186ccdf", "4165899eb1f0f948f8883eddf4136136caac21cee1df39b12afea7672b23a378", diff --git a/src/lib/sandbox-base-image/source-identity.test.ts b/src/lib/sandbox-base-image/source-identity.test.ts index 0362482de90..8abec5252f5 100644 --- a/src/lib/sandbox-base-image/source-identity.test.ts +++ b/src/lib/sandbox-base-image/source-identity.test.ts @@ -181,6 +181,7 @@ describe("sandbox base-image source identity", () => { "scripts/lib/reviewed-npm-archive.mts", "scripts/checks/node-tar-image-scan.mts", "scripts/patch-bundled-npm-brace-expansion.mts", + "scripts/lib/patch-bundled-npm-ip-address.mts", "scripts/patch-bundled-npm-tar.mts", "scripts/upgrade-bundled-npm.mts", agentDockerfile, diff --git a/src/lib/sandbox-base-image/source-identity.ts b/src/lib/sandbox-base-image/source-identity.ts index a5fb341fa8f..4516395609d 100644 --- a/src/lib/sandbox-base-image/source-identity.ts +++ b/src/lib/sandbox-base-image/source-identity.ts @@ -18,6 +18,7 @@ export const BASE_IMAGE_INPUT_PATHS = [ "scripts/lib/reviewed-npm-archive.mts", "scripts/checks/node-tar-image-scan.mts", "scripts/patch-bundled-npm-brace-expansion.mts", + "scripts/lib/patch-bundled-npm-ip-address.mts", "scripts/patch-bundled-npm-tar.mts", "scripts/upgrade-bundled-npm.mts", ]; diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 86808b5cc08..e08acca1373 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -357,6 +357,10 @@ function stageOptimizedSandboxBuildContext( path.join(stagedScriptsDir, "verify-wechat-runtime-lock.mts"), ); fs.mkdirSync(path.join(stagedScriptsDir, "lib"), { recursive: true }); + fs.copyFileSync( + path.join(rootDir, "scripts", "lib", "patch-bundled-npm-ip-address.mts"), + path.join(stagedScriptsDir, "lib", "patch-bundled-npm-ip-address.mts"), + ); fs.copyFileSync( path.join(rootDir, "scripts", "lib", "reviewed-npm-archive.mts"), path.join(stagedScriptsDir, "lib", "reviewed-npm-archive.mts"), diff --git a/test/bundled-npm-ip-address-dockerfile-contract.test.ts b/test/bundled-npm-ip-address-dockerfile-contract.test.ts new file mode 100644 index 00000000000..67309121327 --- /dev/null +++ b/test/bundled-npm-ip-address-dockerfile-contract.test.ts @@ -0,0 +1,84 @@ +// 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 { + FIXED_IP_ADDRESS_INTEGRITY, + FIXED_IP_ADDRESS_TARBALL, + FIXED_IP_ADDRESS_VERSION, + REVIEWED_NPM_VERSION, +} from "../scripts/lib/patch-bundled-npm-ip-address.mts"; +import { REVIEWED_NPM_VERSION as UPGRADED_NPM_VERSION } from "../scripts/upgrade-bundled-npm.mts"; + +const repoRoot = path.resolve(import.meta.dirname, ".."); +const baseDockerfiles = [ + "Dockerfile.base", + "agents/hermes/Dockerfile.base", + "agents/langchain-deepagents-code/Dockerfile.base", +] as const; +const finalDockerfiles = [ + "Dockerfile", + "agents/hermes/Dockerfile", + "agents/langchain-deepagents-code/Dockerfile", +] as const; +const copyInstruction = + "COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts"; +const patchCommand = + "node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts"; + +function instructionBody(source: string, start: number): string { + return source.slice(start).split(/\n(?=\S)/u, 1)[0] ?? ""; +} + +describe("bundled npm ip-address image remediation contract", () => { + it("binds the replacement to the reviewed npm and registry artifact", () => { + expect(REVIEWED_NPM_VERSION).toBe(UPGRADED_NPM_VERSION); + expect(REVIEWED_NPM_VERSION).toBe("11.18.0"); + expect(FIXED_IP_ADDRESS_VERSION).toBe("10.3.1"); + expect(FIXED_IP_ADDRESS_INTEGRITY).toBe( + "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g==", + ); + expect(FIXED_IP_ADDRESS_TARBALL).toBe( + "https://registry.npmjs.org/ip-address/-/ip-address-10.3.1.tgz", + ); + }); + + it.each(baseDockerfiles)("patches the reviewed npm tree after upgrading it in %s", (file) => { + const source = fs.readFileSync(path.join(repoRoot, file), "utf8"); + const copy = source.indexOf(copyInstruction); + const upgrade = source.indexOf( + "RUN node --experimental-strip-types /scripts/upgrade-bundled-npm.mts", + ); + const patch = source.indexOf(patchCommand); + + expect(copy, file).toBeGreaterThanOrEqual(0); + expect(upgrade, file).toBeGreaterThan(copy); + expect(patch, file).toBeGreaterThan(upgrade); + expect(instructionBody(source, patch), file).toContain( + "--npm-root /usr/local/lib/node_modules/npm", + ); + }); + + it.each(finalDockerfiles)("reasserts the private package fix in the completed %s", (file) => { + const source = fs.readFileSync(path.join(repoRoot, file), "utf8"); + const copy = source.indexOf(copyInstruction); + const tarPatch = source.indexOf( + "RUN node --experimental-strip-types /scripts/patch-bundled-npm-tar.mts", + ); + const bracePatch = source.indexOf( + "RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts", + ); + const ipAddressPatch = source.indexOf(patchCommand); + + expect(copy, file).toBeGreaterThanOrEqual(0); + expect(tarPatch, file).toBeGreaterThan(copy); + expect(bracePatch, file).toBeGreaterThan(tarPatch); + expect(ipAddressPatch, file).toBeGreaterThan(bracePatch); + expect(instructionBody(source, ipAddressPatch), file).toContain( + "--npm-root /usr/local/lib/node_modules/npm", + ); + }); +}); diff --git a/test/corporate-ca-build-tls-anchor.test.ts b/test/corporate-ca-build-tls-anchor.test.ts index 9fb48520bd5..1a4ca5174b6 100644 --- a/test/corporate-ca-build-tls-anchor.test.ts +++ b/test/corporate-ca-build-tls-anchor.test.ts @@ -16,25 +16,37 @@ describe("corporate proxy CA build-time TLS anchor (#6839)", () => { expect(matches).toHaveLength(1); }); - // source-shape-contract: security -- The build-time TLS trust anchor must precede the signature-verifying sigstore fetch + // source-shape-contract: security -- The build-time TLS trust anchor must precede registry and signature-verifying fetches it("decodes the CA and exports NODE_EXTRA_CA_CERTS before the reinstall audit-signatures step", () => { const argIndex = dockerfile.indexOf("ARG NEMOCLAW_CORPORATE_CA_B64="); const decodeIndex = dockerfile.indexOf('RUN if [ -n "${NEMOCLAW_CORPORATE_CA_B64}" ]; then'); const anchorIndex = dockerfile.indexOf( "ENV NODE_EXTRA_CA_CERTS=/usr/local/share/nemoclaw/corporate-ca.pem", ); + const curlAnchorIndex = dockerfile.indexOf( + "export CURL_CA_BUNDLE=/usr/local/share/nemoclaw/corporate-ca.pem", + anchorIndex, + ); + const ipAddressPatchIndex = dockerfile.indexOf( + "node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts", + curlAnchorIndex, + ); const auditSignaturesIndex = dockerfile.indexOf("mcporter-runtime audit signatures"); for (const [name, index] of Object.entries({ argIndex, decodeIndex, anchorIndex, + curlAnchorIndex, + ipAddressPatchIndex, auditSignaturesIndex, })) { expect(index, name).toBeGreaterThan(-1); } expect(argIndex).toBeLessThan(decodeIndex); expect(decodeIndex).toBeLessThan(anchorIndex); + expect(anchorIndex).toBeLessThan(curlAnchorIndex); + expect(curlAnchorIndex).toBeLessThan(ipAddressPatchIndex); expect(anchorIndex).toBeLessThan(auditSignaturesIndex); }); }); @@ -133,6 +145,14 @@ describe("DCode corporate proxy CA cold-build trust (#8119)", () => { "mcp-tool-discovery-runtime", finalDecodeIndex, ); + const curlAnchorIndex = finalDockerfile.indexOf( + "export CURL_CA_BUNDLE=/usr/local/share/nemoclaw/corporate-ca.pem", + finalDecodeIndex, + ); + const ipAddressPatchIndex = finalDockerfile.indexOf( + "node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts", + curlAnchorIndex, + ); for (const [name, index] of Object.entries({ finalFromIndex, @@ -140,6 +160,8 @@ describe("DCode corporate proxy CA cold-build trust (#8119)", () => { finalDecodeIndex, trustDirectoryIndex, runtimeProbeIndex, + curlAnchorIndex, + ipAddressPatchIndex, })) { expect(index, name).toBeGreaterThan(-1); } @@ -147,5 +169,7 @@ describe("DCode corporate proxy CA cold-build trust (#8119)", () => { expect(finalArgIndex).toBeLessThan(finalDecodeIndex); expect(finalDecodeIndex).toBeLessThan(trustDirectoryIndex); expect(trustDirectoryIndex).toBeLessThan(runtimeProbeIndex); + expect(trustDirectoryIndex).toBeLessThan(curlAnchorIndex); + expect(curlAnchorIndex).toBeLessThan(ipAddressPatchIndex); }); }); diff --git a/test/hermes-final-image-layout.test.ts b/test/hermes-final-image-layout.test.ts index 32501c846e7..93867396d2b 100644 --- a/test/hermes-final-image-layout.test.ts +++ b/test/hermes-final-image-layout.test.ts @@ -224,6 +224,7 @@ describe("Hermes final image layout", () => { copies: [ "COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts", "COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts", + "COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts", "COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts", ], }, @@ -390,6 +391,7 @@ describe("Hermes final image layout", () => { expect(modeNormalize).toBeLessThan(metadataCheck); for (const metadataContract of [ "/scripts/patch-bundled-npm-brace-expansion.mts 'root:root 444'", + "/scripts/lib/patch-bundled-npm-ip-address.mts 'root:root 444'", "/scripts/patch-bundled-npm-tar.mts 'root:root 444'", "/opt/nemoclaw-hermes-config/generate-config.ts 'root:root 444'", "/usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py 'root:root 755'", diff --git a/test/openclaw-final-image-layout.test.ts b/test/openclaw-final-image-layout.test.ts index 94dc84ccf94..f334855cac2 100644 --- a/test/openclaw-final-image-layout.test.ts +++ b/test/openclaw-final-image-layout.test.ts @@ -55,6 +55,7 @@ describe("OpenClaw final image layout", () => { "COPY scripts/lib/reviewed-npm-audit.mts /scripts/lib/reviewed-npm-audit.mts", "COPY scripts/lib/openclaw-npm-remediation.mts /scripts/lib/openclaw-npm-remediation.mts", "COPY scripts/patch-bundled-npm-brace-expansion.mts /scripts/patch-bundled-npm-brace-expansion.mts", + "COPY scripts/lib/patch-bundled-npm-ip-address.mts /scripts/lib/patch-bundled-npm-ip-address.mts", "COPY scripts/patch-bundled-npm-tar.mts /scripts/patch-bundled-npm-tar.mts", ], }, @@ -137,6 +138,7 @@ describe("OpenClaw final image layout", () => { ]); for (const metadataContract of [ "/scripts/patch-bundled-npm-brace-expansion.mts 'root:root:755'", + "/scripts/lib/patch-bundled-npm-ip-address.mts 'root:root:755'", "/scripts/patch-bundled-npm-tar.mts 'root:root:755'", "/opt/nemoclaw/openclaw.plugin.json 'root:root:644'", "/usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.mts 'root:root:755'", @@ -163,6 +165,10 @@ describe("OpenClaw final image layout", () => { finalStage, "RUN node --experimental-strip-types /scripts/patch-bundled-npm-brace-expansion.mts", ); + const ipAddressPatch = indexOfRequired( + finalStage, + "node --experimental-strip-types /scripts/lib/patch-bundled-npm-ip-address.mts", + ); const pluginInstall = indexOfRequired(finalStage, "RUN npm ci --omit=dev"); const managedMessagingUnionInstall = indexOfRequired( finalStage, @@ -201,6 +207,7 @@ describe("OpenClaw final image layout", () => { expect(dependency).toBeLessThan(tarPatch); expect(tarPatch).toBeLessThan(braceExpansionPatch); + expect(braceExpansionPatch).toBeLessThan(ipAddressPatch); expect(plugin).toBeGreaterThan(pluginInstall); expect(plugin).toBeLessThan(pluginChmod); expect(managedMessagingUnionInstall).toBeLessThan(messagingPostInstall); diff --git a/test/patch-bundled-npm-ip-address.test.ts b/test/patch-bundled-npm-ip-address.test.ts new file mode 100644 index 00000000000..45565235515 --- /dev/null +++ b/test/patch-bundled-npm-ip-address.test.ts @@ -0,0 +1,344 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + AFFECTED_IP_ADDRESS_VERSION, + FIXED_IP_ADDRESS_VERSION, + patchBundledNpmIpAddress, + patchBundledNpmIpAddressFromRegistry, + REVIEWED_NPM_VERSION, + verifyBundledNpmIpAddress, +} from "../scripts/lib/patch-bundled-npm-ip-address.mts"; + +const temporaryDirectories: string[] = []; + +function temporaryDirectory(): string { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-npm-ip-address-")); + temporaryDirectories.push(directory); + return directory; +} + +function writeJson(file: string, value: object): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`); +} + +function packageManifest(version: string): object { + return { + engines: { node: ">= 12" }, + license: "MIT", + main: "dist/ip-address.js", + name: "ip-address", + types: "dist/ip-address.d.ts", + version, + }; +} + +function fixture(ipAddressVersion: string) { + const root = temporaryDirectory(); + const npmRoot = path.join(root, "npm"); + const replacementRoot = path.join(root, "replacement"); + writeJson(path.join(npmRoot, "package.json"), { + name: "npm", + version: REVIEWED_NPM_VERSION, + }); + writeJson( + path.join(npmRoot, "node_modules", "ip-address", "package.json"), + packageManifest(ipAddressVersion), + ); + fs.writeFileSync(path.join(npmRoot, "node_modules", "ip-address", "old.js"), "old\n"); + const arboristBin = path.join(npmRoot, "node_modules", "@npmcli", "arborist", "bin", "index.js"); + fs.mkdirSync(path.dirname(arboristBin), { recursive: true }); + fs.writeFileSync(arboristBin, "#!/usr/bin/env node\n"); + const npmBin = path.join(npmRoot, "node_modules", ".bin"); + fs.mkdirSync(npmBin); + fs.symlinkSync("../@npmcli/arborist/bin/index.js", path.join(npmBin, "arborist")); + writeJson(path.join(replacementRoot, "package.json"), packageManifest(FIXED_IP_ADDRESS_VERSION)); + fs.mkdirSync(path.join(replacementRoot, "dist")); + fs.writeFileSync(path.join(replacementRoot, "dist", "ip-address.js"), "fixed\n"); + return { npmRoot, replacementRoot }; +} + +function expectAffectedTreeUnchanged(target: ReturnType): void { + expect(fs.existsSync(path.join(target.npmRoot, "node_modules", "ip-address", "old.js"))).toBe( + true, + ); +} + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + fs.rmSync(directory, { force: true, recursive: true }); + } +}); + +describe("npm bundled ip-address remediation", () => { + it("replaces the complete affected private package tree", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + + expect(patchBundledNpmIpAddress(target)).toMatchObject({ + ipAddressVersion: FIXED_IP_ADDRESS_VERSION, + npmVersion: REVIEWED_NPM_VERSION, + state: "fixed", + }); + expect(fs.existsSync(path.join(target.npmRoot, "node_modules", "ip-address", "old.js"))).toBe( + false, + ); + expect( + fs.readFileSync( + path.join(target.npmRoot, "node_modules", "ip-address", "dist", "ip-address.js"), + "utf8", + ), + ).toBe("fixed\n"); + }); + + it("does not invoke npm or npx until the private package is replaced and verified", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + const commands: string[] = []; + const postPatchAssertions: Record void> = { + npm: () => expect(verifyBundledNpmIpAddress(target.npmRoot).state).toBe("fixed"), + npx: () => expect(verifyBundledNpmIpAddress(target.npmRoot).state).toBe("fixed"), + }; + + const result = patchBundledNpmIpAddressFromRegistry(target.npmRoot, { + commandRunner(command) { + commands.push(command); + postPatchAssertions[command]?.(); + }, + prepareReplacement(commandRunner) { + commandRunner("curl", []); + commandRunner("tar", []); + return { + cleanup: () => commands.push("cleanup"), + replacementRoot: target.replacementRoot, + }; + }, + }); + + expect(result.state).toBe("fixed"); + expect(commands).toEqual(["curl", "tar", "npm", "npx", "cleanup"]); + }); + + it("does not download when npm already contains the fixed release", () => { + const target = fixture(FIXED_IP_ADDRESS_VERSION); + const commands: string[] = []; + + expect( + patchBundledNpmIpAddressFromRegistry(target.npmRoot, { + commandRunner: (command) => commands.push(command), + prepareReplacement: () => { + throw new Error("unexpected download"); + }, + }), + ).toMatchObject({ state: "fixed" }); + expect(commands).toEqual(["npm", "npx"]); + expectAffectedTreeUnchanged(target); + }); + + it("restores the original package when the replacement rename fails", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + const originalRenameSync = fs.renameSync.bind(fs); + const renameSpy = vi + .spyOn(fs, "renameSync") + .mockImplementationOnce(() => { + throw new Error("injected replacement rename failure"); + }) + .mockImplementation(originalRenameSync); + syncBuiltinESMExports(); + + try { + expect(() => patchBundledNpmIpAddress(target)).toThrow("injected replacement rename failure"); + } finally { + renameSpy.mockRestore(); + syncBuiltinESMExports(); + } + + expectAffectedTreeUnchanged(target); + expect(() => verifyBundledNpmIpAddress(target.npmRoot)).toThrow( + `affected ip-address@${AFFECTED_IP_ADDRESS_VERSION}`, + ); + }); + + it("restores the original package when post-swap verification fails", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + const livePath = path.join(target.npmRoot, "node_modules", "ip-address"); + const originalRenameSync = fs.renameSync.bind(fs); + const renameSpy = vi + .spyOn(fs, "renameSync") + .mockImplementationOnce((oldPath, newPath) => { + originalRenameSync(oldPath, newPath); + writeJson(path.join(livePath, "package.json"), { + ...packageManifest(FIXED_IP_ADDRESS_VERSION), + main: "unexpected.js", + }); + }) + .mockImplementation(originalRenameSync); + syncBuiltinESMExports(); + + try { + expect(() => patchBundledNpmIpAddress(target)).toThrow( + "npm bundled ip-address identity or package contract has drifted", + ); + } finally { + renameSpy.mockRestore(); + syncBuiltinESMExports(); + } + + expectAffectedTreeUnchanged(target); + expect(() => verifyBundledNpmIpAddress(target.npmRoot)).toThrow( + `affected ip-address@${AFFECTED_IP_ADDRESS_VERSION}`, + ); + }); + + it("keeps the verified replacement when backup cleanup is partial", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + const originalRmSync = fs.rmSync.bind(fs); + let injectedCleanupFailure = false; + const rmSpy = vi + .spyOn(fs, "rmSync") + .mockImplementationOnce(originalRmSync) + .mockImplementationOnce((targetPath) => { + injectedCleanupFailure = true; + originalRmSync(path.join(String(targetPath), "old.js"), { force: true }); + throw new Error("injected partial backup cleanup failure"); + }) + .mockImplementation(originalRmSync); + syncBuiltinESMExports(); + + try { + expect(patchBundledNpmIpAddress(target)).toMatchObject({ state: "fixed" }); + } finally { + rmSpy.mockRestore(); + syncBuiltinESMExports(); + } + + expect(injectedCleanupFailure).toBe(true); + expect(verifyBundledNpmIpAddress(target.npmRoot)).toMatchObject({ state: "fixed" }); + expect( + fs + .readdirSync(path.join(target.npmRoot, "node_modules")) + .some((entry) => entry.startsWith("ip-address.nemoclaw-backup-")), + ).toBe(false); + }); + + it("fails closed when the affected backup cannot be removed", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + const originalRmSync = fs.rmSync.bind(fs); + const rmSpy = vi + .spyOn(fs, "rmSync") + .mockImplementationOnce(originalRmSync) + .mockImplementationOnce(() => { + throw new Error("injected backup cleanup failure"); + }) + .mockImplementationOnce(() => { + throw new Error("injected backup cleanup retry failure"); + }) + .mockImplementation(originalRmSync); + syncBuiltinESMExports(); + + let failure: unknown; + try { + patchBundledNpmIpAddress(target); + } catch (error) { + failure = error; + } finally { + rmSpy.mockRestore(); + syncBuiltinESMExports(); + } + + expect(failure).toBeInstanceOf(AggregateError); + expect((failure as AggregateError).errors.map(String)).toEqual([ + "Error: injected backup cleanup failure", + "Error: injected backup cleanup retry failure", + ]); + expect(verifyBundledNpmIpAddress(target.npmRoot)).toMatchObject({ state: "fixed" }); + expect( + fs + .readdirSync(path.join(target.npmRoot, "node_modules")) + .some((entry) => entry.startsWith("ip-address.nemoclaw-backup-")), + ).toBe(true); + }); + + it("reports the original patch failure when rollback also fails", () => { + const target = fixture(AFFECTED_IP_ADDRESS_VERSION); + const livePath = path.join(target.npmRoot, "node_modules", "ip-address"); + const originalRenameSync = fs.renameSync.bind(fs); + const renameSpy = vi + .spyOn(fs, "renameSync") + .mockImplementationOnce((oldPath, newPath) => { + originalRenameSync(oldPath, newPath); + writeJson(path.join(livePath, "package.json"), { + ...packageManifest(FIXED_IP_ADDRESS_VERSION), + main: "unexpected.js", + }); + }) + .mockImplementationOnce(() => { + throw new Error("injected rollback rename failure"); + }) + .mockImplementation(originalRenameSync); + syncBuiltinESMExports(); + + let failure: unknown; + try { + patchBundledNpmIpAddress(target); + } catch (error) { + failure = error; + } finally { + renameSpy.mockRestore(); + syncBuiltinESMExports(); + } + + expect(failure).toBeInstanceOf(AggregateError); + expect((failure as AggregateError).errors.map(String)).toEqual([ + expect.stringContaining("npm bundled ip-address identity or package contract has drifted"), + "Error: injected rollback rename failure", + ]); + const backup = fs + .readdirSync(path.join(target.npmRoot, "node_modules")) + .find((entry) => entry.startsWith("ip-address.nemoclaw-backup-")); + expect(backup).toBeDefined(); + expect(fs.existsSync(path.join(target.npmRoot, "node_modules", String(backup), "old.js"))).toBe( + true, + ); + }); + + it("fails closed on npm layout drift and unsafe package members", () => { + const drifted = fixture(AFFECTED_IP_ADDRESS_VERSION); + writeJson(path.join(drifted.npmRoot, "package.json"), { name: "npm", version: "12.0.0" }); + expect(() => patchBundledNpmIpAddress(drifted)).toThrow("npm package identity has drifted"); + expectAffectedTreeUnchanged(drifted); + + const duplicate = fixture(AFFECTED_IP_ADDRESS_VERSION); + writeJson( + path.join(duplicate.npmRoot, "node_modules", "nested", "ip-address", "package.json"), + packageManifest(AFFECTED_IP_ADDRESS_VERSION), + ); + expect(() => patchBundledNpmIpAddress(duplicate)).toThrow( + "npm bundled ip-address layout has drifted", + ); + expectAffectedTreeUnchanged(duplicate); + + const unsafe = fixture(AFFECTED_IP_ADDRESS_VERSION); + fs.symlinkSync("package.json", path.join(unsafe.replacementRoot, "unsafe-link")); + expect(() => patchBundledNpmIpAddress(unsafe)).toThrow("unsafe member"); + expectAffectedTreeUnchanged(unsafe); + + const escapingBinLink = fixture(AFFECTED_IP_ADDRESS_VERSION); + const outsideNodeModules = path.join(path.dirname(escapingBinLink.npmRoot), "outside.js"); + fs.writeFileSync(outsideNodeModules, "outside\n"); + fs.symlinkSync( + "../../../outside.js", + path.join(escapingBinLink.npmRoot, "node_modules", ".bin", "escape"), + ); + expect(() => patchBundledNpmIpAddress(escapingBinLink)).toThrow( + "npm package contains an unsafe symlink", + ); + expectAffectedTreeUnchanged(escapingBinLink); + }); +}); diff --git a/test/sandbox-base-image-layout.test.ts b/test/sandbox-base-image-layout.test.ts index 40c7c08c6e4..69144b88621 100644 --- a/test/sandbox-base-image-layout.test.ts +++ b/test/sandbox-base-image-layout.test.ts @@ -20,6 +20,6 @@ describe("sandbox base image layout", () => { const layerInstructions = finalStage.match(/^(?:ADD|COPY|RUN)\b/gmu) ?? []; expect(finalStage).toContain("FROM node:22-trixie-slim@"); - expect(layerInstructions).toHaveLength(24); + expect(layerInstructions).toHaveLength(26); }); }); diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index be39b47973f..563d9a3ed91 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -153,6 +153,7 @@ describe("sandbox build context staging", () => { writeFixture(path.join("scripts", "extract-semver.sh")); writeFixture(path.join("scripts", "patch-openclaw-shared-state-permissions.mts")); writeFixture(path.join("scripts", "patch-bundled-npm-brace-expansion.mts")); + writeFixture(path.join("scripts", "lib", "patch-bundled-npm-ip-address.mts")); writeFixture(path.join("scripts", "patch-bundled-npm-tar.mts")); writeFixture(path.join("scripts", "upgrade-bundled-npm.mts")); writeFixture(path.join("scripts", "verify-wechat-runtime-lock.mts")); @@ -645,6 +646,9 @@ describe("sandbox build context staging", () => { expect( fs.existsSync(path.join(buildCtx, "scripts", "patch-bundled-npm-brace-expansion.mts")), ).toBe(true); + expect( + fs.existsSync(path.join(buildCtx, "scripts", "lib", "patch-bundled-npm-ip-address.mts")), + ).toBe(true); expect(fs.existsSync(path.join(buildCtx, "scripts", "upgrade-bundled-npm.mts"))).toBe(true); expect( fs.existsSync(path.join(buildCtx, "scripts", "checks", "node-tar-image-scan.mts")),