Skip to content

Commit 53fb822

Browse files
authored
fix(package): bound installed worker artifact parsing (#126491)
* fix(package): bound worker artifact parsing Keep canonical self-contained worker bundles above the generic dist-file cap while enforcing an 80 MiB limit before installed-package verification reads or parses them. * fix(package): bound every verifier read Route the context-engine and dependency scans through one root-dist pre-read policy, exclude plugin-owned extension assets from the root marker contract, and cover the public verifier flow.
1 parent 4118f31 commit 53fb822

2 files changed

Lines changed: 115 additions & 51 deletions

File tree

‎scripts/openclaw-npm-postpublish-verify.ts‎

Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,11 @@ const PUBLISHED_BUNDLED_RUNTIME_SIDECAR_PATHS = BUNDLED_RUNTIME_SIDECAR_PATHS.fi
6969
const NODE_BUILTIN_MODULES = new Set(builtinModules.map((name) => name.replace(/^node:/u, "")));
7070
const MAX_INSTALLED_ROOT_PACKAGE_JSON_BYTES = 1024 * 1024;
7171
const MAX_INSTALLED_ROOT_DIST_JS_BYTES = 6 * 1024 * 1024;
72+
const MAX_INSTALLED_WORKER_DEPLOY_DIST_JS_BYTES = 80 * 1024 * 1024;
7273
// Keep the dependency scan bounded while allowing headroom for generated root chunks.
7374
const MAX_INSTALLED_ROOT_DIST_JS_FILES = 10_000;
7475
const ROOT_DIST_JAVASCRIPT_MODULE_FILE_RE = /\.(?:c|m)?js$/u;
75-
// These artifacts bundle their full runtime closure and have a dedicated layout/import guard.
76-
// Keep the generic parser bound on every other installed dist file.
76+
// The ~69 MB self-contained worker needs extra headroom, but synchronous read/parse stays bounded.
7777
const SELF_CONTAINED_WORKER_DEPLOY_DIST_PATHS = new Set([
7878
`worker/${WORKER_BUNDLE_ENTRY_PATH}`,
7979
`worker/${WORKER_BUNDLE_RSYNC_RECEIVER_PATH}`,
@@ -105,6 +105,10 @@ type DistJavaScriptFileListResult =
105105
| { files: string[]; limitExceeded: false }
106106
| { files: string[]; limit: number; limitExceeded: true };
107107

108+
type InstalledRootDistJavaScriptReadResult =
109+
| { error: string; ok: false }
110+
| { ok: true; relativePath: string; source: string };
111+
108112
type PublishedInstallScenario = {
109113
name: string;
110114
installSpecs: string[];
@@ -474,7 +478,7 @@ export function collectInstalledPackageErrors(params: {
474478
errors.push(...collectInstalledPluginSdkDeclarationErrors(params.packageRoot));
475479
errors.push(...collectInstalledRootDependencyManifestErrors(params.packageRoot));
476480

477-
return errors;
481+
return [...new Set(errors)];
478482
}
479483

480484
export function collectInstalledAlwaysAllowedRuntimeFacadeErrors(packageRoot: string): string[] {
@@ -534,13 +538,7 @@ export function normalizeInstalledBinaryVersion(output: string): string {
534538
return versionMatch?.[0] ?? trimmed;
535539
}
536540

537-
function listDistJavaScriptFiles(
538-
packageRoot: string,
539-
opts: {
540-
maxFiles?: number;
541-
skipRelativePath?: (relativePath: string) => boolean;
542-
} = {},
543-
): DistJavaScriptFileListResult {
541+
function listInstalledRootDistJavaScriptFiles(packageRoot: string): DistJavaScriptFileListResult {
544542
const distDir = join(packageRoot, "dist");
545543
if (!existsSync(distDir)) {
546544
return { files: [], limitExceeded: false };
@@ -563,7 +561,7 @@ function listDistJavaScriptFiles(
563561

564562
const entryPath = join(currentDir, entry.name);
565563
const relativePath = relative(distDir, entryPath).replaceAll("\\", "/");
566-
if (opts.skipRelativePath?.(relativePath)) {
564+
if (relativePath === "extensions" || relativePath.startsWith("extensions/")) {
567565
continue;
568566
}
569567
if (entry.isDirectory()) {
@@ -572,10 +570,10 @@ function listDistJavaScriptFiles(
572570
}
573571
if (entry.isFile() && ROOT_DIST_JAVASCRIPT_MODULE_FILE_RE.test(entry.name)) {
574572
files.push(entryPath);
575-
if (opts.maxFiles !== undefined && files.length > opts.maxFiles) {
573+
if (files.length > MAX_INSTALLED_ROOT_DIST_JS_FILES) {
576574
return {
577575
files,
578-
limit: opts.maxFiles,
576+
limit: MAX_INSTALLED_ROOT_DIST_JS_FILES,
579577
limitExceeded: true,
580578
};
581579
}
@@ -593,25 +591,43 @@ function formatInstalledDistFileScanLimitError(scope: string, limit: number): st
593591
return `installed package ${scope} contains more than ${limit} JavaScript files; refusing to scan unbounded package contents.`;
594592
}
595593

594+
function readInstalledRootDistJavaScriptFile(
595+
packageRoot: string,
596+
filePath: string,
597+
): InstalledRootDistJavaScriptReadResult {
598+
const relativePath = relative(join(packageRoot, "dist"), filePath).replaceAll("\\", "/");
599+
const maxBytes = SELF_CONTAINED_WORKER_DEPLOY_DIST_PATHS.has(relativePath)
600+
? MAX_INSTALLED_WORKER_DEPLOY_DIST_JS_BYTES
601+
: MAX_INSTALLED_ROOT_DIST_JS_BYTES;
602+
const fileStat = lstatSync(filePath);
603+
if (!fileStat.isFile() || fileStat.size > maxBytes) {
604+
return {
605+
error: `installed package root dist file '${relativePath}' is invalid or exceeds ${maxBytes} bytes.`,
606+
ok: false,
607+
};
608+
}
609+
return { ok: true, relativePath, source: readFileSync(filePath, "utf8") };
610+
}
611+
596612
export function collectInstalledContextEngineRuntimeErrors(packageRoot: string): string[] {
597-
const errors: string[] = [];
598-
const distFiles = listDistJavaScriptFiles(packageRoot, {
599-
maxFiles: MAX_INSTALLED_ROOT_DIST_JS_FILES,
600-
});
613+
const distFiles = listInstalledRootDistJavaScriptFiles(packageRoot);
601614
if (distFiles.limitExceeded) {
602-
return [formatInstalledDistFileScanLimitError("dist", distFiles.limit)];
615+
return [formatInstalledDistFileScanLimitError("root dist", distFiles.limit)];
603616
}
604617

618+
// The legacy marker is a root runtime bundling contract; extension assets are plugin-owned.
605619
for (const filePath of distFiles.files) {
606-
const contents = readFileSync(filePath, "utf8");
607-
if (contents.includes(LEGACY_CONTEXT_ENGINE_UNRESOLVED_RUNTIME_MARKER)) {
608-
errors.push(
620+
const file = readInstalledRootDistJavaScriptFile(packageRoot, filePath);
621+
if (!file.ok) {
622+
return [file.error];
623+
}
624+
if (file.source.includes(LEGACY_CONTEXT_ENGINE_UNRESOLVED_RUNTIME_MARKER)) {
625+
return [
609626
"installed package includes unresolved legacy context engine runtime loader; rebuild with a bundler-traceable LegacyContextEngine import.",
610-
);
611-
break;
627+
];
612628
}
613629
}
614-
return errors;
630+
return [];
615631
}
616632

617633
function collectInstalledPluginSdkDeclarationErrors(packageRoot: string): string[] {
@@ -642,14 +658,6 @@ function collectInstalledPluginSdkDeclarationErrors(packageRoot: string): string
642658
return errors;
643659
}
644660

645-
function listInstalledRootDistJavaScriptFiles(packageRoot: string): DistJavaScriptFileListResult {
646-
return listDistJavaScriptFiles(packageRoot, {
647-
maxFiles: MAX_INSTALLED_ROOT_DIST_JS_FILES,
648-
skipRelativePath: (relativePath) =>
649-
relativePath === "extensions" || relativePath.startsWith("extensions/"),
650-
});
651-
}
652-
653661
type ParsedImportSpecifiersResult =
654662
| { ok: true; specifiers: Set<string> }
655663
| { ok: false; error: string };
@@ -757,22 +765,14 @@ export function collectInstalledRootDependencyManifestErrors(packageRoot: string
757765
collectBundledExtensionRuntimeDependencyOwners(packageRoot);
758766

759767
for (const filePath of distFiles.files) {
760-
const fileStat = lstatSync(filePath);
761-
const relativePath = relative(join(packageRoot, "dist"), filePath).replaceAll("\\", "/");
762-
if (
763-
!fileStat.isFile() ||
764-
(fileStat.size > MAX_INSTALLED_ROOT_DIST_JS_BYTES &&
765-
!SELF_CONTAINED_WORKER_DEPLOY_DIST_PATHS.has(relativePath))
766-
) {
767-
return [
768-
`installed package root dist file '${relativePath}' is invalid or exceeds ${MAX_INSTALLED_ROOT_DIST_JS_BYTES} bytes.`,
769-
];
768+
const file = readInstalledRootDistJavaScriptFile(packageRoot, filePath);
769+
if (!file.ok) {
770+
return [file.error];
770771
}
771-
const source = readFileSync(filePath, "utf8");
772-
const parsedSpecifiers = extractJavaScriptImportSpecifiers(source);
772+
const parsedSpecifiers = extractJavaScriptImportSpecifiers(file.source);
773773
if (!parsedSpecifiers.ok) {
774774
return [
775-
`installed package root dist file '${relativePath}' could not be parsed for runtime dependency verification: ${parsedSpecifiers.error}.`,
775+
`installed package root dist file '${file.relativePath}' could not be parsed for runtime dependency verification: ${parsedSpecifiers.error}.`,
776776
];
777777
}
778778
for (const specifier of parsedSpecifiers.specifiers) {
@@ -785,13 +785,13 @@ export function collectInstalledRootDependencyManifestErrors(packageRoot: string
785785
isBundledExtensionOwnedRuntimeImport({
786786
dependencyName,
787787
ownersByDependency: bundledExtensionRuntimeDependencyOwners,
788-
source,
788+
source: file.source,
789789
})
790790
) {
791791
continue;
792792
}
793793
const importers = missingImporters.get(dependencyName) ?? new Set<string>();
794-
importers.add(relativePath);
794+
importers.add(file.relativePath);
795795
missingImporters.set(dependencyName, importers);
796796
}
797797
}

‎test/openclaw-npm-postpublish-verify.test.ts‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { spawnSync } from "node:child_process";
22
import { generateKeyPairSync, sign } from "node:crypto";
33
// OpenClaw npm postpublish tests validate postpublish verification behavior.
4-
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from "node:fs";
55
import { tmpdir } from "node:os";
66
import { dirname, join } from "node:path";
77
import { describe, expect, it, vi } from "vitest";
@@ -600,6 +600,32 @@ describe("collectInstalledPackageErrors", () => {
600600
);
601601
});
602602

603+
it("rejects an oversized worker before the full verifier reads its contents", () => {
604+
const packageRoot = makeInstalledPackageRoot();
605+
606+
try {
607+
writeFileSync(join(packageRoot, "package.json"), '{"version":"2026.3.23"}\n', "utf8");
608+
const workerPath = join(packageRoot, "dist", "worker", WORKER_BUNDLE_ENTRY_PATH);
609+
mkdirSync(dirname(workerPath), { recursive: true });
610+
writeFileSync(workerPath, "/* Failed to load legacy context engine runtime. */\n", "utf8");
611+
truncateSync(workerPath, 80 * 1024 * 1024 + 1);
612+
613+
const errors = collectInstalledPackageErrors({
614+
expectedVersion: "2026.3.23",
615+
installedVersion: "2026.3.23",
616+
packageRoot,
617+
});
618+
const sizeError = `installed package root dist file 'worker/${WORKER_BUNDLE_ENTRY_PATH}' is invalid or exceeds 83886080 bytes.`;
619+
620+
expect(errors.filter((error) => error === sizeError)).toEqual([sizeError]);
621+
expect(errors).not.toContain(
622+
"installed package includes unresolved legacy context engine runtime loader; rebuild with a bundler-traceable LegacyContextEngine import.",
623+
);
624+
} finally {
625+
rmSync(packageRoot, { recursive: true, force: true });
626+
}
627+
});
628+
603629
it.each(["ollama", "lmstudio"])(
604630
"rejects a missing installed bundled %s provider directory",
605631
(providerId) => {
@@ -893,14 +919,39 @@ describe("collectInstalledContextEngineRuntimeErrors", () => {
893919
}
894920
});
895921

922+
it("ignores extension-owned JavaScript assets", () => {
923+
const packageRoot = makeInstalledPackageRoot();
924+
925+
try {
926+
const viewerPath = join(
927+
packageRoot,
928+
"dist",
929+
"extensions",
930+
"diffs",
931+
"assets",
932+
"viewer-runtime.js",
933+
);
934+
mkdirSync(dirname(viewerPath), { recursive: true });
935+
writeFileSync(
936+
viewerPath,
937+
'throw new Error("Failed to load legacy context engine runtime.");\n',
938+
"utf8",
939+
);
940+
941+
expect(collectInstalledContextEngineRuntimeErrors(packageRoot)).toStrictEqual([]);
942+
} finally {
943+
rmSync(packageRoot, { recursive: true, force: true });
944+
}
945+
});
946+
896947
it("refuses unbounded packaged dist scans", () => {
897948
const packageRoot = makeInstalledPackageRoot();
898949

899950
try {
900951
writeDistJavaScriptFiles(packageRoot, INSTALLED_ROOT_DIST_JS_FILE_SCAN_LIMIT + 1);
901952

902953
expect(collectInstalledContextEngineRuntimeErrors(packageRoot)).toEqual([
903-
`installed package dist contains more than ${INSTALLED_ROOT_DIST_JS_FILE_SCAN_LIMIT} JavaScript files; refusing to scan unbounded package contents.`,
954+
`installed package root dist contains more than ${INSTALLED_ROOT_DIST_JS_FILE_SCAN_LIMIT} JavaScript files; refusing to scan unbounded package contents.`,
904955
]);
905956
} finally {
906957
rmSync(packageRoot, { recursive: true, force: true });
@@ -1184,7 +1235,15 @@ describe("collectInstalledRootDependencyManifestErrors", () => {
11841235
name: "accepts the oversized worker rsync receiver",
11851236
relativePath: `worker/${WORKER_BUNDLE_RSYNC_RECEIVER_PATH}`,
11861237
},
1187-
])("$name", ({ expected, relativePath }) => {
1238+
{
1239+
expected: [
1240+
`installed package root dist file 'worker/${WORKER_BUNDLE_ENTRY_PATH}' is invalid or exceeds 83886080 bytes.`,
1241+
],
1242+
name: "rejects the worker deploy entrypoint above its dedicated parser bound",
1243+
relativePath: `worker/${WORKER_BUNDLE_ENTRY_PATH}`,
1244+
sparseSize: 80 * 1024 * 1024 + 1,
1245+
},
1246+
])("$name", ({ expected, relativePath, sparseSize }) => {
11881247
const packageRoot = makeInstalledPackageRoot();
11891248

11901249
try {
@@ -1194,7 +1253,12 @@ describe("collectInstalledRootDependencyManifestErrors", () => {
11941253
});
11951254
const filePath = join(packageRoot, "dist", relativePath);
11961255
mkdirSync(dirname(filePath), { recursive: true });
1197-
writeFileSync(filePath, `/* ${"x".repeat(6 * 1024 * 1024)} */\n`, "utf8");
1256+
if (sparseSize) {
1257+
writeFileSync(filePath, "/*", "utf8");
1258+
truncateSync(filePath, sparseSize);
1259+
} else {
1260+
writeFileSync(filePath, `/* ${"x".repeat(6 * 1024 * 1024)} */\n`, "utf8");
1261+
}
11981262

11991263
expect(collectInstalledRootDependencyManifestErrors(packageRoot)).toEqual(expected);
12001264
} finally {

0 commit comments

Comments
 (0)