fix(security): run git/npm without a shell, validate refs/commits/URLs/package names, escape generated imports (#2571); fetch pinned commits on update (#2559)

This commit is contained in:
saberzero1 committed 2026-11-07 21:37:20 +01:00
1 parent 3c18be8c71
commit 8eae6a1277
8 files changed
+454 -75

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Security: plugin commands no longer build shell commands from plugin sources, refs, pinned commits or package names (#2571). git and npm run with argument arrays, refs/commits/URLs/package names are validated (so a value can't be read as an option either), and generated plugin imports are written as escaped string literals. A source such as `github:owner/repo#main;cmd` used to run `cmd`; it is now rejected as an invalid ref. Also fixes restoring a plugin pinned in `quartz.lock.json` to a commit that is no longer its branch tip (#2559).
+13 -5
View File
@@ -17,6 +17,7 @@ import { randomUUID } from "crypto"
import { Mutex } from "async-mutex"
import { CreateArgv } from "./args.js"
import { describeQuartzCheckout } from "./compat.js"
import { git } from "./subprocess.js"
import { globby } from "globby"
import {
exitIfCancel,
@@ -305,9 +306,7 @@ See the [documentation](https://quartz.jzhao.xyz) for how to get started.
await handlePluginResolve()
// setup remote
execSync(`git remote show upstream || git remote add upstream ${QUARTZ_SOURCE_REPO}`, {
stdio: "ignore",
})
ensureUpstreamRemote()
outro(`You're all set! Not sure what to do next? Try:
• Customizing Quartz a bit more by editing \`quartz.config.yaml\`
@@ -611,6 +610,15 @@ export async function handleBuild(argv) {
}
}
/** Add the `upstream` remote (the official Quartz repository) unless it exists. */
function ensureUpstreamRemote() {
try {
git(["remote", "get-url", UPSTREAM_NAME])
} catch {
git(["remote", "add", UPSTREAM_NAME, QUARTZ_SOURCE_REPO])
}
}
/**
* Handles `npx quartz upgrade`
* Upgrades the Quartz framework itself by pulling latest changes from upstream.
@@ -621,7 +629,7 @@ export async function handleUpgrade(argv) {
console.log(`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)} \n`)
const fromCommit = describeQuartzCheckout().commit
console.log("Backing up your content")
execSync(`git remote show upstream || git remote add upstream ${QUARTZ_SOURCE_REPO}`)
ensureUpstreamRemote()
await stashContentFolder(contentFolder)
const lockfileBackup = LOCKFILE_PATH + ".bak"
@@ -642,7 +650,7 @@ export async function handleUpgrade(argv) {
if (hasLockfile) {
try {
fs.copyFileSync(lockfileBackup, LOCKFILE_PATH)
execSync(`git add ${LOCKFILE_PATH}`)
git(["add", "--", LOCKFILE_PATH])
const remaining = execSync("git diff --name-only --diff-filter=U", {
encoding: "utf-8",
}).trim()
+66 -36
View File
@@ -1,8 +1,7 @@
import fs from "fs"
import path from "path"
import os from "os"
import { exec as execCb, execSync } from "child_process"
import { styleText, promisify } from "util"
import { styleText } from "util"
import {
readPluginsJson,
writePluginsJson,
@@ -42,6 +41,17 @@ import {
formatQuartzVersion,
readQuartzVersion,
} from "./compat.js"
import {
assertCommit,
assertNpmSpec,
assertRef,
assertRepoUrl,
gitAsync,
isIdentifier,
jsString,
npm,
npmAsync,
} from "./subprocess.js"
import {
builtinMessage,
describeBuiltins,
@@ -52,8 +62,6 @@ import {
const INTERNAL_EXPORTS = new Set(["manifest", "default"])
const execAsync = promisify(execCb)
/** Mark the current CLI invocation as failed (non-zero exit) without aborting. */
function markFailed() {
process.exitCode = 1
@@ -140,21 +148,43 @@ function readEntryPackageJson(source) {
}
}
/** `git ls-remote <repo> <ref or HEAD>` for a lockfile entry. */
function lsRemote(entry) {
const ref = entry.ref ? `refs/heads/${assertRef(entry.ref)}` : "HEAD"
return gitAsync(["ls-remote", assertRepoUrl(entry.resolved), ref])
}
/** Shallow-clone `url` into `dir`, then move to `commit` if it is not the tip. */
async function cloneAtCommitAsync({ url, ref, commit, dir }) {
const branchArg = ref ? ` --branch ${ref}` : ""
await execAsync(`git clone --depth 1${branchArg} "${url}" "${dir}"`)
await gitAsync([
"clone",
"--depth",
"1",
...(ref ? ["--branch", assertRef(ref)] : []),
"--",
assertRepoUrl(url),
dir,
])
if (commit && commit !== "unknown" && commit !== "local") {
const { stdout } = await execAsync("git rev-parse HEAD", { cwd: dir })
const { stdout } = await gitAsync(["rev-parse", "HEAD"], { cwd: dir })
if (stdout.trim() !== commit) {
await execAsync(`git fetch --depth 1 origin ${commit}`, { cwd: dir })
await execAsync(`git checkout --quiet ${commit}`, { cwd: dir })
await checkoutPinnedCommitAsync(dir, commit)
}
}
const { stdout } = await execAsync("git rev-parse HEAD", { cwd: dir })
const { stdout } = await gitAsync(["rev-parse", "HEAD"], { cwd: dir })
return stdout.trim()
}
/**
* Move a shallow clone to a pinned commit. The commit is fetched by SHA (GitHub and most hosts
* allow fetching reachable commits), so a pin that is no longer the branch tip works (#2559).
*/
async function checkoutPinnedCommitAsync(dir, commit) {
assertCommit(commit)
await gitAsync(["fetch", "--depth", "1", "origin", commit], { cwd: dir })
await gitAsync(["checkout", "--quiet", commit], { cwd: dir })
}
/**
* Clone a repository and copy one subdirectory of it into `pluginDir`.
* When `commit` is given (lockfile pin) that commit is checked out first.
@@ -191,12 +221,12 @@ async function buildPluginAsync(pluginDir, name) {
try {
const skipBuild = !needsBuild(pluginDir)
console.log(styleText("cyan", ` → ${name}: installing dependencies...`))
await execAsync("npm install --ignore-scripts", { cwd: pluginDir })
await npmAsync(["install", "--ignore-scripts"], { cwd: pluginDir })
if (!skipBuild) {
console.log(styleText("cyan", ` → ${name}: building...`))
await execAsync("npm run build", { cwd: pluginDir })
await npmAsync(["run", "build"], { cwd: pluginDir })
}
await execAsync("npm prune --omit=dev", { cwd: pluginDir })
await npmAsync(["prune", "--omit=dev"], { cwd: pluginDir })
linkPeerPlugins(pluginDir)
if (!hasLoadableEntryPoint(pluginDir)) {
console.log(
@@ -416,7 +446,11 @@ async function regeneratePluginIndex() {
const passthrough = named.filter((n) => !isOverridableExport(n, dtsContent))
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) {
pluginExports.set(pluginName, { overridable, passthrough, types })
pluginExports.set(pluginName, {
overridable: overridable.filter(isIdentifier),
passthrough: passthrough.filter(isIdentifier),
types: types.filter(isIdentifier),
})
for (const n of [...overridable, ...passthrough]) {
nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
}
@@ -432,7 +466,7 @@ async function regeneratePluginIndex() {
// Type re-exports
for (const [pluginName, { types }] of pluginExports) {
if (types.length > 0) {
lines.push(`export type { ${types.join(", ")} } from "./${pluginName}"`)
lines.push(`export type { ${types.join(", ")} } from ${jsString(`./${pluginName}`)}`)
}
}
@@ -441,7 +475,7 @@ async function regeneratePluginIndex() {
if (passthrough.length === 0) continue
const unique = passthrough.filter((n) => (nameCount.get(n) ?? 0) === 1)
if (unique.length > 0) {
lines.push(`export { ${unique.join(", ")} } from "./${pluginName}"`)
lines.push(`export { ${unique.join(", ")} } from ${jsString(`./${pluginName}`)}`)
}
}
lines.push("")
@@ -452,11 +486,10 @@ async function regeneratePluginIndex() {
)
for (const [pluginName, { overridable }] of pluginExports) {
if (overridable.length === 0) continue
const escapedName = pluginName.replace(/"/g, '\\"')
lines.push(` "${escapedName}": {`)
lines.push(` ${jsString(pluginName)}: {`)
for (const n of overridable) {
lines.push(
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides("${escapedName}", args[0] as Record<string, unknown>); },`,
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides(${jsString(pluginName)}, args[0] as Record<string, unknown>); },`,
)
}
lines.push(` },`)
@@ -472,9 +505,8 @@ async function regeneratePluginIndex() {
const conflicting = overridable.filter((n) => (nameCount.get(n) ?? 0) > 1)
if (unique.length > 0) {
const escapedName = pluginName.replace(/"/g, '\\"')
for (const n of unique) {
lines.push(`export const ${n} = plugins["${escapedName}"].${n}`)
lines.push(`export const ${n} = plugins[${jsString(pluginName)}].${n}`)
}
}
@@ -626,8 +658,7 @@ export async function handlePluginInstallUnified({
})
}
const lsRemoteRef = row.entry.ref ? `refs/heads/${row.entry.ref}` : "HEAD"
return execAsync(`git ls-remote "${row.entry.resolved}" ${lsRemoteRef}`)
return lsRemote(row.entry)
.then(({ stdout }) => {
const latestCommit = stdout.split("\t")[0].trim()
const isCurrent = latestCommit === row.entry.commit
@@ -693,10 +724,9 @@ export async function handlePluginInstallUnified({
console.log()
if (!dryRun) {
try {
execSync(`npm install ${missingNpm.join(" ")}`, {
npm(["install", ...missingNpm.map(assertNpmSpec)], {
cwd: process.cwd(),
stdio: "inherit",
timeout: 600_000,
})
console.log(styleText("green", `✓ Installed ${missingNpm.length} npm plugin(s)`))
} catch {
@@ -1198,14 +1228,15 @@ export async function handlePluginInstallUnified({
console.log(styleText("gray", `✓ ${name} rebuilt (subdir: ${entry.subdir})`))
}
} else {
const fetchRef = entry.ref || ""
const resetTarget = entry.ref ? `origin/${entry.ref}` : "origin/HEAD"
await execAsync(`git fetch --depth 1 origin${fetchRef ? " " + fetchRef : ""}`, {
const fetchRef = entry.ref ? assertRef(entry.ref) : undefined
await gitAsync(["fetch", "--depth", "1", "origin", ...(fetchRef ? [fetchRef] : [])], {
cwd: pluginDir,
})
await gitAsync(["reset", "--hard", fetchRef ? `origin/${fetchRef}` : "origin/HEAD"], {
cwd: pluginDir,
})
await execAsync(`git reset --hard ${resetTarget}`, { cwd: pluginDir })
const { stdout } = await execAsync("git rev-parse HEAD", { cwd: pluginDir })
const { stdout } = await gitAsync(["rev-parse", "HEAD"], { cwd: pluginDir })
const newCommit = stdout.trim()
if (newCommit !== entry.commit) {
entry.commit = newCommit
@@ -1384,9 +1415,9 @@ export async function handlePluginInstallUnified({
try {
if (action === "update") {
console.log(styleText("cyan", ` → ${name}: updating to ${entry.commit.slice(0, 7)}...`))
const fetchRef = entry.ref ? ` ${entry.ref}` : ""
await execAsync(`git fetch --depth 1 origin${fetchRef}`, { cwd: pluginDir })
await execAsync(`git reset --hard ${entry.commit}`, { cwd: pluginDir })
// fetch the pinned commit itself: it need not be the branch tip (#2559)
await checkoutPinnedCommitAsync(pluginDir, entry.commit)
await gitAsync(["reset", "--hard", entry.commit], { cwd: pluginDir })
pluginsToBuild.push({ name, pluginDir })
installed++
} else {
@@ -1558,7 +1589,7 @@ export async function handlePluginAdd(
continue
}
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
execSync(`npm install ${parsed.name}`, { cwd: process.cwd(), stdio: "inherit" })
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
const configSource = nameOverride ? { repo: parsed.name, name: nameOverride } : parsed.name
const pluginDir = path.join(process.cwd(), "node_modules", ...parsed.name.split("/"))
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
@@ -2375,8 +2406,7 @@ export async function handlePluginStatus() {
})
}
const lsRemoteRef = row.entry.ref ? `refs/heads/${row.entry.ref}` : "HEAD"
return execAsync(`git ls-remote "${row.entry.resolved}" ${lsRemoteRef}`)
return lsRemote(row.entry)
.then(({ stdout }) => {
const latestCommit = stdout.split("\t")[0].trim()
const status = latestCommit === row.entry.commit ? "up_to_date" : "update_available"
+31
View File
@@ -0,0 +1,31 @@
import type { StdioOptions } from "node:child_process"
export interface RunOptions {
cwd?: string
env?: NodeJS.ProcessEnv
stdio?: StdioOptions
timeout?: number
}
export const GIT_TIMEOUT_MS: number
export const NPM_TIMEOUT_MS: number
export function assertCommit(commit: unknown): string
export function assertRef(ref: unknown): string
export function assertRepoUrl(url: unknown): string
export function assertNpmSpec(spec: unknown): string
export function git(args: string[], opts?: RunOptions): string
export function gitAsync(
args: string[],
opts?: RunOptions,
): Promise<{ stdout: string; stderr: string }>
export function npm(args: string[], opts?: RunOptions): string
export function npmAsync(
args: string[],
opts?: RunOptions,
): Promise<{ stdout: string; stderr: string }>
export function jsString(value: unknown): string
export function isIdentifier(name: unknown): boolean
export function npmCommand(
args: string[],
platform?: string,
): { file: string; args: string[]; shell: boolean }
+146
View File
@@ -0,0 +1,146 @@
/**
* Running git and npm safely (#2571).
*
* Plugin sources, refs, pinned commits and package names come from quartz.config.yaml,
* quartz.lock.json and the command line. They are passed to git/npm as argument arrays, never
* through a shell, so `;`, `$(…)`, quotes and spaces are inert. Values that end up as positional
* arguments are also validated (or placed after `--`), because a value starting with `-` would
* otherwise be read as an option: `git fetch origin --upload-pack=<cmd>` runs <cmd> even without
* a shell.
*
* npm is `npm.cmd` on Windows, which Node only runs through a shell (CVE-2024-27980). There,
* every argument must pass a strict whitelist first.
*/
import { execFile, execFileSync } from "node:child_process"
import { promisify } from "node:util"
const execFileAsync = promisify(execFile)
export const GIT_TIMEOUT_MS = 120_000
export const NPM_TIMEOUT_MS = 600_000
const MAX_BUFFER = 64 * 1024 * 1024
/** A full or abbreviated commit SHA (as written to quartz.lock.json). */
export function assertCommit(commit) {
if (typeof commit !== "string" || !/^[0-9a-f]{7,64}$/i.test(commit)) {
throw new Error(`Invalid commit ${JSON.stringify(commit)}: expected a hexadecimal SHA`)
}
return commit
}
/**
* A branch or tag name. Follows `git check-ref-format` closely enough to reject everything that
* could be an option or isn't a ref: no leading `-`, no whitespace or control characters, none of
* `~ ^ : ? * [ \`, no `..`, `@{`, `//`, trailing `/`, `.` or `.lock`.
*/
export function assertRef(ref) {
const invalid =
typeof ref !== "string" ||
ref === "" ||
ref === "@" ||
ref.startsWith("-") ||
ref.startsWith("/") ||
/[\s\x00-\x1f\x7f~^:?*[\\]/.test(ref) ||
ref.includes("..") ||
ref.includes("@{") ||
ref.includes("//") ||
/(^|\/)\./.test(ref) ||
/[/.]$/.test(ref) ||
ref.endsWith(".lock")
if (invalid) throw new Error(`Invalid git ref ${JSON.stringify(ref)}`)
return ref
}
/** A repository URL or path for git (never an option). */
export function assertRepoUrl(url) {
if (typeof url !== "string" || url === "" || url.startsWith("-") || /[\x00-\x1f\x7f]/.test(url)) {
throw new Error(`Invalid repository ${JSON.stringify(url)}`)
}
return url
}
// no leading "-" (it would be read as an npm option), "." or "_"
const NPM_NAME = /^(?:@[a-z0-9~][a-z0-9._~-]*\/)?[a-z0-9~][a-z0-9._~-]*$/
// a version or range after the name: 1.2.3, ^1.2, >=1 <2, latest, npm:alias@1 is not accepted
const NPM_VERSION = /^[0-9A-Za-z.^~<>=*|+ -]+$/
/** An npm package spec: `name`, `@scope/name`, optionally `@<version or range or tag>`. */
export function assertNpmSpec(spec) {
if (typeof spec !== "string") throw new Error(`Invalid npm package ${JSON.stringify(spec)}`)
const at = spec.lastIndexOf("@")
const hasVersion = at > 0
const name = hasVersion ? spec.slice(0, at) : spec
const version = hasVersion ? spec.slice(at + 1) : undefined
if (
!NPM_NAME.test(name) ||
name.length > 214 ||
(version !== undefined && (version === "" || !NPM_VERSION.test(version)))
) {
throw new Error(`Invalid npm package ${JSON.stringify(spec)}`)
}
return spec
}
function options(opts = {}, timeout) {
return {
cwd: opts.cwd,
env: opts.env,
encoding: "utf8",
stdio: opts.stdio ?? "pipe",
timeout: opts.timeout ?? timeout,
maxBuffer: MAX_BUFFER,
windowsHide: true,
}
}
/** Run git synchronously; returns stdout ("" with stdio: "inherit"). */
export function git(args, opts) {
return execFileSync("git", args, options(opts, GIT_TIMEOUT_MS)) ?? ""
}
/** Run git; resolves to { stdout, stderr }. */
export function gitAsync(args, opts) {
const { stdio: _stdio, ...rest } = options(opts, GIT_TIMEOUT_MS)
return execFileAsync("git", args, rest)
}
// Characters allowed in an npm argument that must go through cmd.exe on Windows. Each argument
// is wrapped in double quotes, inside which spaces and < > | are literal; `"`, `%` and `!` (the
// characters cmd.exe still interprets there) are never allowed.
const WINDOWS_SHELL_SAFE = /^[A-Za-z0-9@._/:=+~^,<>|* -]+$/
export function npmCommand(args, platform = process.platform) {
if (platform !== "win32") return { file: "npm", args, shell: false }
const quoted = args.map((arg) => {
if (!WINDOWS_SHELL_SAFE.test(arg)) {
throw new Error(`Refusing to pass ${JSON.stringify(arg)} to npm through the Windows shell`)
}
return `"${arg}"`
})
return { file: "npm.cmd", args: quoted, shell: true }
}
/** Run npm synchronously; returns stdout ("" with stdio: "inherit"). */
export function npm(args, opts) {
const cmd = npmCommand(args)
return (
execFileSync(cmd.file, cmd.args, { ...options(opts, NPM_TIMEOUT_MS), shell: cmd.shell }) ?? ""
)
}
/** Run npm; resolves to { stdout, stderr }. */
export function npmAsync(args, opts) {
const cmd = npmCommand(args)
const { stdio: _stdio, ...rest } = options(opts, NPM_TIMEOUT_MS)
return execFileAsync(cmd.file, cmd.args, { ...rest, shell: cmd.shell })
}
/** A string literal for generated TypeScript/JavaScript source. */
export function jsString(value) {
return JSON.stringify(String(value))
}
/** Whether a name is a plain JavaScript identifier (safe to write into generated source). */
export function isIdentifier(name) {
return typeof name === "string" && /^[A-Za-z_$][\w$]*$/.test(name)
}
+136
View File
@@ -0,0 +1,136 @@
import test, { describe } from "node:test"
import assert from "node:assert"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import {
assertCommit,
assertNpmSpec,
assertRef,
assertRepoUrl,
git,
isIdentifier,
jsString,
npmCommand,
} from "./subprocess.js"
describe("validation (#2571)", () => {
test("commits must be hex SHAs", () => {
assert.strictEqual(
assertCommit("9a899bd8cce7cfc1ebfc68e4bd7ab6b4c6fcfd6f"),
"9a899bd8cce7cfc1ebfc68e4bd7ab6b4c6fcfd6f",
)
assert.strictEqual(assertCommit("9a899bd"), "9a899bd")
for (const bad of ["--upload-pack=touch x", "main", "9a89 9bd", "", undefined, "abc;id"]) {
assert.throws(() => assertCommit(bad), /Invalid commit/, String(bad))
}
})
test("refs: branch and tag names, never options or shell syntax", () => {
for (const ok of ["main", "v5", "feature/x", "release-1.2", "v1.2.3", "dev_mode"]) {
assert.strictEqual(assertRef(ok), ok)
}
for (const bad of [
"main;touch pwned",
"--upload-pack=touch pwned",
"-b",
"a b",
"a..b",
"a~1",
"a^",
"a:b",
"a\\b",
"x.lock",
"a/",
".hidden",
"a/.b",
"@",
"a@{1}",
"",
]) {
assert.throws(() => assertRef(bad), /Invalid git ref/, bad)
}
})
test("repository URLs can't be options", () => {
assert.strictEqual(
assertRepoUrl("https://github.com/quartz-community/graph.git"),
"https://github.com/quartz-community/graph.git",
)
assert.throws(() => assertRepoUrl("--upload-pack=touch pwned"), /Invalid repository/)
assert.throws(() => assertRepoUrl("https://x\ny"), /Invalid repository/)
})
test("npm package specs", () => {
for (const ok of [
"@quartz-community/graph",
"sharp",
"sharp@0.34.1",
"sharp@^0.34.0",
"sharp@>=0.33.0 <1",
"@scope/pkg@latest",
]) {
assert.strictEqual(assertNpmSpec(ok), ok)
}
for (const bad of [
"@scope/pkg;touch pwned",
"$(id)",
"@scope/pkg@1.0.0;id",
"pkg@",
"--global",
"-g",
"@-scope/pkg",
"Pkg",
"@scope/pkg@`id`",
"pkg@npm:evil",
]) {
assert.throws(() => assertNpmSpec(bad), /Invalid npm package/, bad)
}
})
})
describe("npmCommand", () => {
test("no shell outside Windows; arguments untouched", () => {
assert.deepStrictEqual(npmCommand(["install", "sharp@>=0.33 <1"], "linux"), {
file: "npm",
args: ["install", "sharp@>=0.33 <1"],
shell: false,
})
})
test("on Windows every argument is quoted, and cmd.exe metacharacters are refused", () => {
assert.deepStrictEqual(npmCommand(["install", "sharp@>=0.33 <1"], "win32"), {
file: "npm.cmd",
args: ['"install"', '"sharp@>=0.33 <1"'],
shell: true,
})
for (const bad of ['a"b', "%PATH%", "a&b", "a!b", "a\nb"]) {
assert.throws(() => npmCommand(["install", bad], "win32"), /Refusing/, bad)
}
})
})
describe("generated source", () => {
test("jsString escapes everything", () => {
assert.strictEqual(jsString(`./a"b\\c`), '"./a\\"b\\\\c"')
assert.strictEqual(jsString("x\n"), '"x\\n"')
})
test("isIdentifier", () => {
assert.ok(isIdentifier("Graph"))
assert.ok(isIdentifier("_x$1"))
for (const bad of ["1a", "a-b", "a b", "a;b", 'x"', ""]) assert.ok(!isIdentifier(bad), bad)
})
})
describe("git runs without a shell", () => {
test("shell syntax in arguments is inert", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-subprocess-"))
const marker = path.join(dir, "pwned")
git(["init", "-q", dir])
// As one argument, `$(touch …)` reaches git literally (an invalid config key), nothing runs.
assert.throws(() => git(["-C", dir, "config", "--get", `x.$(touch ${marker})`]))
assert.ok(!fs.existsSync(marker))
fs.rmSync(dir, { recursive: true, force: true })
})
})
@@ -24,6 +24,10 @@ import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild"
import { write } from "./helpers"
/**
* Content hash for cache-busting file names (`postscript-<hash>.js`). Not a password or security
* hash: code scanners flagging a "weak hash" here can be dismissed (#2571).
*/
function hashContent(content: string | Buffer): string {
return createHash("sha256").update(content).digest("hex").slice(0, 8)
}
+53 -34
View File
@@ -1,6 +1,15 @@
import fs from "fs"
import path from "path"
import { execSync } from "child_process"
import {
assertCommit,
assertNpmSpec,
assertRef,
assertRepoUrl,
git as runGit,
jsString,
isIdentifier,
npm,
} from "../../cli/subprocess.js"
import git from "isomorphic-git"
import http from "isomorphic-git/http/node"
import { styleText } from "util"
@@ -63,17 +72,27 @@ export function readLockedCommit(
}
}
/** `git clone --depth 1 [--branch <ref>] -- <repo> <dir>`, with ref and repo validated. */
export function cloneArgs(repo: string, ref: string | undefined, dir: string): string[] {
return [
"clone",
"--depth",
"1",
...(ref ? ["--branch", assertRef(ref)] : []),
"--",
assertRepoUrl(repo),
dir,
]
}
/** Move a fresh shallow clone to the lockfile-pinned commit. Warns (and keeps the tip) on failure. */
function checkoutLockedCommit(dir: string, commit: string, name: string): void {
try {
const head = execSync("git rev-parse HEAD", { cwd: dir, encoding: "utf-8" }).trim()
assertCommit(commit)
const head = runGit(["rev-parse", "HEAD"], { cwd: dir }).trim()
if (head === commit) return
execSync(`git fetch --depth 1 origin ${commit}`, {
cwd: dir,
stdio: "pipe",
timeout: GIT_TIMEOUT_MS,
})
execSync(`git checkout --quiet ${commit}`, { cwd: dir, stdio: "pipe", timeout: 60_000 })
runGit(["fetch", "--depth", "1", "origin", commit], { cwd: dir, timeout: GIT_TIMEOUT_MS })
runGit(["checkout", "--quiet", commit], { cwd: dir, timeout: 60_000 })
} catch {
console.warn(
styleText("yellow", `⚠`) +
@@ -273,7 +292,7 @@ export function installNativeDeps(
}
if (uniqueRanges.length === 1) {
installArgs.push(`${pkg}@${JSON.stringify(uniqueRanges[0])}`)
installArgs.push(assertNpmSpec(`${pkg}@${uniqueRanges[0]}`))
} else {
if (options.verbose) {
console.warn(
@@ -282,7 +301,7 @@ export function installNativeDeps(
)
}
// Use first range; npm will fail if truly incompatible
installArgs.push(`${pkg}@${JSON.stringify(uniqueRanges[0])}`)
installArgs.push(assertNpmSpec(`${pkg}@${uniqueRanges[0]}`))
}
}
@@ -296,7 +315,7 @@ export function installNativeDeps(
}
try {
execSync(`npm install --no-save ${installArgs.join(" ")}`, {
npm(["install", "--no-save", ...installArgs], {
cwd: process.cwd(),
stdio: options.verbose ? "inherit" : "pipe",
timeout: 120_000,
@@ -434,7 +453,7 @@ function buildInstalledPlugin(pluginDir: string, name: string, verbose?: boolean
if (verbose) {
console.log(styleText("cyan", `→`), `${name}: installing dependencies...`)
}
execSync("npm install --ignore-scripts", {
npm(["install", "--ignore-scripts"], {
cwd: pluginDir,
stdio: verbose ? "inherit" : "pipe",
timeout: 120_000,
@@ -444,14 +463,14 @@ function buildInstalledPlugin(pluginDir: string, name: string, verbose?: boolean
if (verbose) {
console.log(styleText("cyan", `→`), `${name}: building...`)
}
execSync("npm run build", {
npm(["run", "build"], {
cwd: pluginDir,
stdio: verbose ? "inherit" : "pipe",
timeout: 120_000,
})
}
execSync("npm prune --omit=dev", {
npm(["prune", "--omit=dev"], {
cwd: pluginDir,
stdio: verbose ? "inherit" : "pipe",
timeout: 60_000,
@@ -576,11 +595,7 @@ export async function installPlugin(
fs.rmSync(tmpDir, { recursive: true })
}
const branchArg = spec.ref ? ` --branch ${spec.ref}` : ""
execSync(`git clone --depth 1${branchArg} "${spec.repo}" "${tmpDir}"`, {
stdio: "pipe",
timeout: GIT_TIMEOUT_MS,
})
runGit(cloneArgs(spec.repo, spec.ref, tmpDir), { timeout: GIT_TIMEOUT_MS })
const locked = readLockedCommit(spec)
if (locked) checkoutLockedCommit(tmpDir, locked, spec.name)
@@ -593,11 +608,7 @@ export async function installPlugin(
fs.renameSync(subdirPath, pluginDir)
fs.rmSync(tmpDir, { recursive: true })
} else {
const branchArg = spec.ref ? ` --branch ${spec.ref}` : ""
execSync(`git clone --depth 1${branchArg} "${spec.repo}" "${pluginDir}"`, {
stdio: "pipe",
timeout: GIT_TIMEOUT_MS,
})
runGit(cloneArgs(spec.repo, spec.ref, pluginDir), { timeout: GIT_TIMEOUT_MS })
const locked = readLockedCommit(spec)
if (locked) checkoutLockedCommit(pluginDir, locked, spec.name)
}
@@ -1037,7 +1048,11 @@ export async function regeneratePluginIndex(
const passthrough = named.filter((n) => !isOverridableExport(n, dtsContent))
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) {
pluginExports.set(pluginName, { overridable, passthrough, types })
pluginExports.set(pluginName, {
overridable: overridable.filter(isIdentifier),
passthrough: passthrough.filter(isIdentifier),
types: types.filter(isIdentifier),
})
importPath.set(pluginName, `./${pluginName}`)
for (const n of [...overridable, ...passthrough]) {
nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
@@ -1095,7 +1110,11 @@ export async function regeneratePluginIndex(
const key = npmPkg.replace(/^@/, "").replace(/\//g, "__")
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) {
pluginExports.set(key, { overridable, passthrough, types })
pluginExports.set(key, {
overridable: overridable.filter(isIdentifier),
passthrough: passthrough.filter(isIdentifier),
types: types.filter(isIdentifier),
})
importPath.set(key, npmPkg)
for (const n of [...overridable, ...passthrough]) {
nameCount.set(n, (nameCount.get(n) ?? 0) + 1)
@@ -1111,15 +1130,17 @@ export async function regeneratePluginIndex(
for (const [pluginKey, { types }] of pluginExports) {
if (types.length > 0) {
lines.push(`export type { ${types.join(", ")} } from "${importPath.get(pluginKey)}"`)
const safe = types.filter(isIdentifier)
if (safe.length > 0)
lines.push(`export type { ${safe.join(", ")} } from ${jsString(importPath.get(pluginKey))}`)
}
}
for (const [pluginKey, { passthrough }] of pluginExports) {
if (passthrough.length === 0) continue
const unique = passthrough.filter((n) => (nameCount.get(n) ?? 0) === 1)
const unique = passthrough.filter((n) => (nameCount.get(n) ?? 0) === 1 && isIdentifier(n))
if (unique.length > 0) {
lines.push(`export { ${unique.join(", ")} } from "${importPath.get(pluginKey)}"`)
lines.push(`export { ${unique.join(", ")} } from ${jsString(importPath.get(pluginKey))}`)
}
}
lines.push("")
@@ -1130,11 +1151,10 @@ export async function regeneratePluginIndex(
)
for (const [pluginName, { overridable }] of pluginExports) {
if (overridable.length === 0) continue
const escapedName = pluginName.replace(/"/g, '\\"')
lines.push(` "${escapedName}": {`)
lines.push(` ${jsString(pluginName)}: {`)
for (const n of overridable) {
lines.push(
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides("${escapedName}", args[0] as Record<string, unknown>); },`,
` ${n}: (...args: unknown[]) => { componentRegistry.setOptionOverrides(${jsString(pluginName)}, args[0] as Record<string, unknown>); },`,
)
}
lines.push(` },`)
@@ -1150,9 +1170,8 @@ export async function regeneratePluginIndex(
const conflicting = overridable.filter((n) => (nameCount.get(n) ?? 0) > 1)
if (unique.length > 0) {
const escapedName = pluginName.replace(/"/g, '\\"')
for (const n of unique) {
lines.push(`export const ${n} = plugins["${escapedName}"].${n}`)
lines.push(`export const ${n} = plugins[${jsString(pluginName)}].${n}`)
}
}