From 5b32936a329fe8d771e9f41d25f3bcc6c184c650 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:48:30 -0800 Subject: [PATCH 1/5] Publish PR builds from validated, extracted files The PR build validator inspected each tarball through GNU tar, but npm publish read the original tarball with its own tar parser, and the two do not always agree on an archive's contents. Reading paths from the human-readable tar listing was also fragile, for example with owner names that contain spaces. Extract each tarball once, validate the extracted files, and publish that directory so that npm publishes exactly the files that were validated. --- .github/workflows/pr-build.yml | 17 ++++----- tools/scripts/validate-pr-build.mjs | 55 +++++++++++++++++------------ 2 files changed, 41 insertions(+), 31 deletions(-) diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 31cf12fcfa45d..69838f488e79a 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -221,20 +221,21 @@ jobs: id: publish env: NPM_DIR: ${{ runner.temp }}/npm + PACKAGE_DIR: ${{ runner.temp }}/packages PRERELEASE: ${{ needs.prepare.outputs.prerelease }} MERGE_SHA: ${{ needs.prepare.outputs.merge_sha }} PACKAGES: ${{ needs.prepare.outputs.packages }} run: | set -euo pipefail - mapfile -t tarballs < <(node tools/scripts/validate-pr-build.mjs "$NPM_DIR" "$PRERELEASE" "$MERGE_SHA" "$PACKAGES") + mkdir "$PACKAGE_DIR" + mapfile -t packageDirs < <(node tools/scripts/validate-pr-build.mjs "$NPM_DIR" "$PACKAGE_DIR" "$PRERELEASE" "$MERGE_SHA" "$PACKAGES") # Trusted publishing needs npm 11.5.1 or later. npm install -g npm@11 toPublish=() - for tarball in "${tarballs[@]}"; do - manifest="$(tar -xzOf "$NPM_DIR/$tarball" package/package.json)" - name="$(jq -r .name <<< "$manifest")" - version="$(jq -r .version <<< "$manifest")" + for packageDir in "${packageDirs[@]}"; do + name="$(jq -r .name "$packageDir/package.json")" + version="$(jq -r .version "$packageDir/package.json")" if publishedHead="$(npm view "$name@$version" gitHead 2> /dev/null)" && [[ -n "$publishedHead" ]]; then if [[ "$publishedHead" != "$MERGE_SHA" ]]; then echo "$name@$version was already published from $publishedHead; request a new build." >&2 @@ -243,10 +244,10 @@ jobs: echo "$name@$version is already published." continue fi - toPublish+=("$tarball") + toPublish+=("$packageDir") done - for tarball in "${toPublish[@]}"; do - npm publish "$NPM_DIR/$tarball" --access public --tag pr + for packageDir in "${toPublish[@]}"; do + npm publish "$packageDir" --access public --tag pr --ignore-scripts done echo "version=$version" >> "$GITHUB_OUTPUT" diff --git a/tools/scripts/validate-pr-build.mjs b/tools/scripts/validate-pr-build.mjs index 68fa901132267..b35f57daac31a 100644 --- a/tools/scripts/validate-pr-build.mjs +++ b/tools/scripts/validate-pr-build.mjs @@ -3,20 +3,24 @@ // in them (including the publish manifest) is trusted; everything is checked // against values computed by the trusted part of the workflow. // -// Usage: node validate-pr-build.mjs +// Each tarball is extracted into , and the extracted files are +// validated and published; npm never reads the tarballs. +// +// Usage: node validate-pr-build.mjs // // is the JSON package list written by typescript:build-platform-matrix // when run from trusted code: { main, platforms: [...], wasm }. // -// Prints the tarball file names in publish order, one per line. +// Prints the extracted package directories in publish order, one per line. import assert from "node:assert"; import { execFileSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -const [tarballDir, prerelease, gitHead, packagesJson] = process.argv.slice(2); -assert(tarballDir && prerelease && gitHead && packagesJson, "Usage: validate-pr-build.mjs "); +const [tarballDir, outputDir, prerelease, gitHead, packagesJson] = process.argv.slice(2); +assert(tarballDir && outputDir && prerelease && gitHead && packagesJson, "Usage: validate-pr-build.mjs "); +assert.deepEqual(fs.readdirSync(outputDir), [], "Output directory must be empty"); assert.match(prerelease, /^pr\.[1-9]\d*\.[1-9]\d*$/); assert.match(gitHead, /^[0-9a-f]{40}$/); @@ -30,29 +34,34 @@ const versionPattern = new RegExp(`^\\d+\\.\\d+\\.\\d+-${prerelease.replaceAll(" // install-time meaning, so only allow what the packages actually contain. const allowedRootEntries = new Set(["LICENSE", "NOTICE.txt", "README.md", "bin", "dist", "enums", "lib", "package.json", "schemas", "vendor"]); -/** @type {Map} */ +/** @type {Map} */ const packages = new Map(); for (const filename of fs.readdirSync(tarballDir)) { if (!filename.endsWith(".tgz")) continue; - const tarball = path.join(tarballDir, filename); - // npm extracts everything under package/; reject anything that is not a - // plain file or directory there. - // Paths must be canonical and unique, since GNU tar and npm disagree on - // which duplicate wins. - const listing = execFileSync("tar", ["-tvzf", tarball], { encoding: "utf8" }).split("\n").filter(Boolean); - const entryPaths = new Set(); - for (const line of listing) { - const entryPath = line.split(/\s+/).slice(5).join(" ").replace(/\/$/, ""); - const segments = entryPath.split("/"); - assert(line[0] === "-" || line[0] === "d", `${filename}: unexpected entry type: ${line}`); - assert(segments[0] === "package" && segments.every(s => s !== "" && s !== "." && s !== ".."), `${filename}: unexpected path: ${entryPath}`); - assert(!entryPaths.has(entryPath), `${filename}: duplicate entry: ${entryPath}`); - assert(segments.length === 1 || allowedRootEntries.has(segments[1]), `${filename}: unexpected root entry: ${entryPath}`); - entryPaths.add(entryPath); + const extractDir = path.join(outputDir, filename.slice(0, -".tgz".length)); + fs.mkdirSync(extractDir); + execFileSync("tar", ["-xzf", path.join(tarballDir, filename), "-C", extractDir, "--no-same-owner", "--no-same-permissions"]); + + // Only allow plain files and directories under package/. + const pending = [extractDir]; + for (const dir of pending) { + for (const name of fs.readdirSync(dir)) { + const entryPath = path.join(dir, name); + const relativePath = path.relative(extractDir, entryPath); + const segments = relativePath.split(path.sep); + const stat = fs.lstatSync(entryPath); + assert(stat.isDirectory() || (stat.isFile() && stat.nlink === 1), `${filename}: unexpected entry type: ${relativePath}`); + assert(segments[0] === "package" && (segments.length > 1 || stat.isDirectory()), `${filename}: unexpected path: ${relativePath}`); + assert(segments.length !== 2 || allowedRootEntries.has(segments[1]), `${filename}: unexpected root entry: ${relativePath}`); + if (stat.isDirectory()) { + pending.push(entryPath); + } + } } - const manifest = JSON.parse(execFileSync("tar", ["-xzOf", tarball, "package/package.json"], { encoding: "utf8" })); + const packageDir = path.join(extractDir, "package"); + const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8")); const { name, version } = manifest; assert(expectedNames.has(name), `${filename}: unexpected package name ${name}`); assert(!packages.has(name), `${filename}: duplicate package ${name}`); @@ -71,7 +80,7 @@ for (const filename of fs.readdirSync(tarballDir)) { assert.equal(manifest.bin, undefined, `${filename}: must not declare bin`); assert.equal(manifest.optionalDependencies, undefined, `${filename}: must not declare optionalDependencies`); } - packages.set(name, { filename, version, manifest }); + packages.set(name, { packageDir, version, manifest }); } for (const name of expectedNames) { @@ -92,5 +101,5 @@ assert.deepEqual( // Platform and WASM packages first, so the main package never refers to a // version that does not exist yet. for (const name of [...platformNames, wasmName, mainName]) { - console.log(packages.get(name)?.filename); + console.log(packages.get(name)?.packageDir); } From 68ef1b431edcf67df41f2ffa8f74427a0f20be00 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:00:24 -0800 Subject: [PATCH 2/5] Only allow known package.json fields in PR builds Rejecting a fixed list of fields still allowed others that npm acts on during installation, such as "directories": { "bin": ... }. Allow only the fields the packages use. --- tools/scripts/validate-pr-build.mjs | 30 +++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/tools/scripts/validate-pr-build.mjs b/tools/scripts/validate-pr-build.mjs index b35f57daac31a..e41bee021020c 100644 --- a/tools/scripts/validate-pr-build.mjs +++ b/tools/scripts/validate-pr-build.mjs @@ -34,6 +34,30 @@ const versionPattern = new RegExp(`^\\d+\\.\\d+\\.\\d+-${prerelease.replaceAll(" // install-time meaning, so only allow what the packages actually contain. const allowedRootEntries = new Set(["LICENSE", "NOTICE.txt", "README.md", "bin", "dist", "enums", "lib", "package.json", "schemas", "vendor"]); +// Many package.json fields affect installation, so only allow the ones in use. +const allowedManifestFields = new Set([ + "author", + "bin", + "bugs", + "cpu", + "description", + "engines", + "exports", + "files", + "gitHead", + "homepage", + "keywords", + "license", + "name", + "optionalDependencies", + "os", + "preferUnplugged", + "publishConfig", + "repository", + "type", + "version", +]); + /** @type {Map} */ const packages = new Map(); for (const filename of fs.readdirSync(tarballDir)) { @@ -68,10 +92,8 @@ for (const filename of fs.readdirSync(tarballDir)) { assert.match(version, versionPattern, `${filename}: unexpected version`); assert.equal(manifest.gitHead, gitHead, `${filename}: unexpected gitHead`); assert.deepEqual(manifest.publishConfig, { access: "public", tag: "pr" }, `${filename}: unexpected publishConfig`); - // No lifecycle scripts; installing a PR build must not run code. - assert.equal(manifest.scripts, undefined, `${filename}: must not declare scripts`); - for (const field of ["dependencies", "peerDependencies", "bundleDependencies", "bundledDependencies"]) { - assert.equal(manifest[field], undefined, `${filename}: must not declare ${field}`); + for (const field of Object.keys(manifest)) { + assert(allowedManifestFields.has(field), `${filename}: unexpected package.json field ${field}`); } if (name === mainName) { assert.deepEqual(manifest.bin, { tsc: "./bin/tsc" }, `${filename}: unexpected bin`); From b7c46c56e2165e709d8203ab92fd0a7d9ac88dfa Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:00:35 -0800 Subject: [PATCH 3/5] Stop the PR build publish step when validation fails set -e does not see the exit status of a process substitution, so the step kept running after a validation failure and stopped only later because no packages were listed. --- .github/workflows/pr-build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 69838f488e79a..b64a34fb1f4b9 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -228,7 +228,9 @@ jobs: run: | set -euo pipefail mkdir "$PACKAGE_DIR" - mapfile -t packageDirs < <(node tools/scripts/validate-pr-build.mjs "$NPM_DIR" "$PACKAGE_DIR" "$PRERELEASE" "$MERGE_SHA" "$PACKAGES") + # A plain assignment, so set -e sees validation failures. + validated="$(node tools/scripts/validate-pr-build.mjs "$NPM_DIR" "$PACKAGE_DIR" "$PRERELEASE" "$MERGE_SHA" "$PACKAGES")" + mapfile -t packageDirs <<< "$validated" # Trusted publishing needs npm 11.5.1 or later. npm install -g npm@11 From 26162a4c28f11dcfa92734470c41af63e58e71cc Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:00:55 -0800 Subject: [PATCH 4/5] Don't derive PR build publish paths from tarball names npm publish parses some paths, such as those containing "@" and ":", as git URLs. Name the extraction directories by index instead. --- tools/scripts/validate-pr-build.mjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/scripts/validate-pr-build.mjs b/tools/scripts/validate-pr-build.mjs index e41bee021020c..17b7670c1836b 100644 --- a/tools/scripts/validate-pr-build.mjs +++ b/tools/scripts/validate-pr-build.mjs @@ -60,10 +60,10 @@ const allowedManifestFields = new Set([ /** @type {Map} */ const packages = new Map(); -for (const filename of fs.readdirSync(tarballDir)) { - if (!filename.endsWith(".tgz")) continue; - - const extractDir = path.join(outputDir, filename.slice(0, -".tgz".length)); +const tarballs = fs.readdirSync(tarballDir).filter(filename => filename.endsWith(".tgz")); +for (const [index, filename] of tarballs.entries()) { + // npm publish parses some paths as git URLs, so don't use the tarball name. + const extractDir = path.join(outputDir, String(index)); fs.mkdirSync(extractDir); execFileSync("tar", ["-xzf", path.join(tarballDir, filename), "-C", extractDir, "--no-same-owner", "--no-same-permissions"]); From aa3ae5fc0a92a4d556751adc6fe75a68d96057dc Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:01:23 -0800 Subject: [PATCH 5/5] Use strict assertions in the PR build validator Loose equality accepted values such as a null bin, and the version pattern accepted leading zeros, which npm removes when publishing. --- tools/scripts/validate-pr-build.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/scripts/validate-pr-build.mjs b/tools/scripts/validate-pr-build.mjs index 17b7670c1836b..7355550f42ac1 100644 --- a/tools/scripts/validate-pr-build.mjs +++ b/tools/scripts/validate-pr-build.mjs @@ -13,7 +13,7 @@ // // Prints the extracted package directories in publish order, one per line. -import assert from "node:assert"; +import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; @@ -28,7 +28,7 @@ assert.match(gitHead, /^[0-9a-f]{40}$/); const { main: mainName, platforms: platformNames, wasm: wasmName } = JSON.parse(packagesJson); assert(typeof mainName === "string" && typeof wasmName === "string" && Array.isArray(platformNames) && platformNames.length > 0, "Invalid package list"); const expectedNames = new Set([mainName, ...platformNames, wasmName]); -const versionPattern = new RegExp(`^\\d+\\.\\d+\\.\\d+-${prerelease.replaceAll(".", "\\.")}$`); +const versionPattern = new RegExp(`^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)-${prerelease.replaceAll(".", "\\.")}$`); // npm gives some root files (binding.gyp, npm-shrinkwrap.json, node_modules) // install-time meaning, so only allow what the packages actually contain.