MCPcopy Create free account
hub / github.com/21st-dev/1code / isPathWithinWorktree

Function isPathWithinWorktree

src/main/lib/git/security/secure-fs.ts:34–54  ·  view source on GitHub ↗

* Check if a resolved path is within the worktree boundary using path.relative(). * This is safer than string prefix matching which can have boundary bugs.

(
	worktreeReal: string,
	targetReal: string,
)

Source from the content-addressed store, hash-verified

32 * This is safer than string prefix matching which can have boundary bugs.
33 */
34function isPathWithinWorktree(
35 worktreeReal: string,
36 targetReal: string,
37): boolean {
38 if (targetReal === worktreeReal) {
39 return true;
40 }
41 const relativePath = relative(worktreeReal, targetReal);
42 // Check if path escapes worktree:
43 // - ".." means direct parent
44 // - "../" prefix means ancestor escape (use sep for cross-platform)
45 // - Absolute path means completely outside
46 // Note: Don't use startsWith("..") as it incorrectly catches "..config" directories
47 // Note: Empty relativePath ("") case is already handled by the equality check above
48 const escapesWorktree =
49 relativePath === ".." ||
50 relativePath.startsWith(`..${sep}`) ||
51 isAbsolute(relativePath);
52
53 return !escapesWorktree;
54}
55
56/**
57 * Validate that the parent directory chain stays within the worktree.

Callers 3

assertParentInWorktreeFunction · 0.85
assertRealpathInWorktreeFunction · 0.85
isSymlinkEscapingFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected