Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/scope-default-trace-globs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ndepe": patch
---

fix: scope `@vercel/nft` wildcard glob tracing to workspace, linked package, and `node_modules` roots so `base: "/"` does not scan unreadable or unrelated host directories
15 changes: 14 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ import {
findEntryFiles,
findPackageParents,
isFile,
isInsideOrEqual,
isSubPath,
linkPackage,
readDirRecursive,
resolveAllowedTraceRoots,
resolveTracedPath,
writePackage,
} from "./utils";
Expand Down Expand Up @@ -73,11 +75,18 @@ export const nodeDepEmit = async ({
}) => {
const base = "/";
const entryFiles = await findEntryFiles(sourceDir, entryFilter);
const allowedRoots = resolveAllowedTraceRoots({
appDir,
sourceDir,
includeEntries,
});

debug("trace files start");
const fileTrace = await traceFiles({
entryFiles: entryFiles.concat(includeEntries || []),
sourceDir,
appDir,
allowedRoots,
cacheOptions: {
...cacheOptions,
cacheDir: path.resolve(appDir, cacheOptions.cacheDir),
Expand Down Expand Up @@ -137,11 +146,15 @@ export const nodeDepEmit = async ({
? path.join(match[0], "package.json")
: await pkgUp({ cwd: path.dirname(filePath) });

const isWithinAllowedSearchRoot = (manifestPath: string) =>
isSubPath(dependencySearchRoot, manifestPath) ||
allowedRoots.some((root) => isInsideOrEqual(root, manifestPath));

// Keep searching for a parent package.json with a "name" field
// Some packages use subdirectory package.json files as directory entry points with no "name" field
while (
packageJsonPath &&
isSubPath(dependencySearchRoot, packageJsonPath)
isWithinAllowedSearchRoot(packageJsonPath)
) {
const packageJson: PackageJson =
await fse.readJSON(packageJsonPath);
Expand Down
240 changes: 240 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from "node:fs";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { type NodeFileTraceOptions, nodeFileTrace } from "@vercel/nft";
Expand Down Expand Up @@ -286,15 +288,238 @@ const writeCache = async (filePath: string, cacheMap: Map<string, unknown>) => {
console.log(`write ${path.basename(filePath)} finish`);
};

const WORKSPACE_MANIFEST_FILES = [
"pnpm-workspace.yaml",
"rush.json",
"eden.monorepo.json",
"lerna.json",
];

const NODE_MODULES_PACKAGE_PATH =
/(?:^|[\\/])node_modules[\\/](?:@[^\\/*?[]+[\\/])?[^\\/*?[]+/;

const NODE_MODULES_SEGMENT = /(?:^|[\\/])node_modules(?:[\\/]|$)/;

export const isInsideOrEqual = (dir: string, candidate: string): boolean => {
const relative = path.relative(dir, candidate);
return (
relative === "" ||
(relative !== ".." &&
!relative.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relative))
);
};

function hasWorkspaceField(dir: string): boolean {
const manifestPath = path.join(dir, "package.json");
if (!fs.existsSync(manifestPath)) {
return false;
}
try {
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
workspaces?: unknown;
};
return Boolean(manifest?.workspaces);
} catch {
return false;
}
}

export function findWorkspaceRoot(entryOrDir: string): string {
let current = path.resolve(entryOrDir);
try {
if (fs.existsSync(current) && !fs.statSync(current).isDirectory()) {
current = path.dirname(current);
}
} catch {
current = path.dirname(current);
}

let nearestPackageDir: string | undefined;
let gitRootDir: string | undefined;
let outermostWorkspaceDir: string | undefined;

for (let dir = current; dir !== path.dirname(dir); dir = path.dirname(dir)) {
if (!nearestPackageDir && fs.existsSync(path.join(dir, "package.json"))) {
nearestPackageDir = dir;
}
if (!gitRootDir && fs.existsSync(path.join(dir, ".git"))) {
gitRootDir = dir;
}
if (
WORKSPACE_MANIFEST_FILES.some((file) =>
fs.existsSync(path.join(dir, file)),
) ||
hasWorkspaceField(dir)
) {
outermostWorkspaceDir = dir;
}
}

return outermostWorkspaceDir ?? gitRootDir ?? nearestPackageDir ?? current;
}

function expandRealpath(dir: string): string[] {
const resolved = path.resolve(dir);
try {
const real = fs.realpathSync(resolved);
return real === resolved ? [resolved] : [resolved, real];
} catch {
return [resolved];
}
}

function collectLinkedPackageRoots(dirs: string[]): string[] {
const linkedRoots: string[] = [];
const inspectEntry = (entryPath: string) => {
try {
if (!fs.lstatSync(entryPath).isSymbolicLink()) {
return;
}
const realTarget = fs.realpathSync(entryPath);
if (!NODE_MODULES_SEGMENT.test(realTarget)) {
linkedRoots.push(findWorkspaceRoot(realTarget));
}
} catch {
// Ignore broken or inaccessible symlinks
}
};

for (const dir of dirs) {
const nmDir = path.join(path.resolve(dir), "node_modules");
if (!fs.existsSync(nmDir)) {
continue;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(nmDir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (entry.name.startsWith(".")) {
continue;
}
const entryPath = path.join(nmDir, entry.name);
if (entry.name.startsWith("@")) {
try {
for (const scoped of fs.readdirSync(entryPath)) {
inspectEntry(path.join(entryPath, scoped));
}
} catch {
// Ignore unreadable scope dirs
}
} else {
inspectEntry(entryPath);
}
}
}

return linkedRoots;
}

export function resolveAllowedTraceRoots({
appDir,
sourceDir,
includeEntries,
}: {
appDir: string;
sourceDir: string;
includeEntries?: string[];
}): string[] {
const appWorkspaceRoot = findWorkspaceRoot(appDir);
return [
...new Set(
[
appWorkspaceRoot,
appDir,
sourceDir,
...(includeEntries ?? []).map(findWorkspaceRoot),
...collectLinkedPackageRoots([appDir, appWorkspaceRoot]),
].flatMap(expandRealpath),
),
];
}

/**
* Because `ndepe` runs `@vercel/nft` with `base: "/"` so symlinked external stores (e.g. shared
* pnpm stores) stay reachable, nft's built-in `../` boundary check is inactive. Scope wildcard
* globs (`emitAssetDirectory` / `emitWildcardRequire`) to workspace, linked-package, and
* `node_modules/<pkg>` roots while leaving concrete `require`/`import` file resolutions untouched.
*/
export function createDefaultTraceIgnore(
allowedRoots: string[],
base = "/",
): (tracedPath: string) => boolean {
const resolvedBase = path.resolve(base);
return (tracedPath: string) => {
const globIndex = tracedPath.search(/[*?[]/);
if (globIndex === -1) {
return false;
}

const prefix = tracedPath.slice(0, globIndex);
const lastSlash = Math.max(
prefix.lastIndexOf("/"),
prefix.lastIndexOf("\\"),
);
const globRoot = path.resolve(
resolvedBase,
lastSlash === -1 ? "" : prefix.slice(0, lastSlash),
);

if (allowedRoots.some((root) => isInsideOrEqual(root, globRoot))) {
return false;
}
if (NODE_MODULES_PACKAGE_PATH.test(globRoot)) {
return false;
}
return true;
};
}

function composeTraceIgnore(
defaultIgnore: (tracedPath: string) => boolean,
userIgnore: NodeFileTraceOptions["ignore"],
base: string,
sourceDir: string,
): (tracedPath: string) => boolean {
if (!userIgnore) {
return defaultIgnore;
}
if (typeof userIgnore === "function") {
return (tracedPath: string) =>
defaultIgnore(tracedPath) || Boolean(userIgnore(tracedPath));
}
const patterns = Array.isArray(userIgnore) ? userIgnore : [userIgnore];
const resolvedBase = path.resolve(base);
const resolvedIgnores = patterns.map((pattern) =>
path.relative(
resolvedBase,
path.resolve(resolvedBase || sourceDir, pattern),
),
);
const nftRequire = createRequire(import.meta.url);
const picomatch = createRequire(nftRequire.resolve("@vercel/nft"))(
"picomatch",
) as { isMatch: (str: string, patterns: string[]) => boolean };
return (tracedPath: string) =>
defaultIgnore(tracedPath) || picomatch.isMatch(tracedPath, resolvedIgnores);
}

export const traceFiles = async ({
entryFiles,
sourceDir,
appDir,
allowedRoots,
base = "/",
cacheOptions,
traceOptions,
}: {
entryFiles: string[];
sourceDir: string;
appDir?: string;
allowedRoots?: string[];
base?: string;
cacheOptions: CacheOptions;
traceOptions?: NodeFileTraceOptions;
Expand All @@ -310,11 +535,26 @@ export const traceFiles = async ({
symlinkCache: await loadCache(symlinkCacheFile, symlinkCache),
};

const effectiveAllowedRoots =
allowedRoots ??
resolveAllowedTraceRoots({
appDir: appDir ?? sourceDir,
sourceDir,
includeEntries: entryFiles,
});
const ignore = composeTraceIgnore(
createDefaultTraceIgnore(effectiveAllowedRoots, base),
traceOptions?.ignore,
base,
sourceDir,
);

const res = await nodeFileTrace(entryFiles, {
base,
processCwd: sourceDir,
cache,
...traceOptions,
ignore,
});

if (analysisCache || fileCache || symlinkCache) {
Expand Down
Loading
Loading