Chore/read write tools update (#5275)

* add tools warning

* Enhance file handling tools with security features

- Introduced new input parameters: workspacePath, enforceWorkspaceBoundaries, maxFileSize, and allowedExtensions for better control over file operations.
- Added validation for file paths and sizes to prevent unsafe operations.
- Implemented workspace boundary checks to restrict file access based on user-defined settings.
This commit is contained in:
Henry Heng
2025-10-08 10:56:01 +01:00
committed by GitHub
parent a0dca552a2
commit 1fb12cd931
8 changed files with 392 additions and 22 deletions
+61
View File
@@ -41,3 +41,64 @@ export const isPathTraversal = (path: string): boolean => {
return dangerousPatterns.some((pattern) => path.toLowerCase().includes(pattern))
}
/**
* Enhanced path validation for workspace-scoped file operations
* @param {string} filePath The file path to validate
* @returns {boolean} True if path traversal detected, false otherwise
*/
export const isUnsafeFilePath = (filePath: string): boolean => {
if (!filePath || typeof filePath !== 'string') {
return true
}
// Check for path traversal patterns
const dangerousPatterns = [
/\.\./, // Directory traversal (..)
/%2e%2e/i, // URL encoded ..
/%2f/i, // URL encoded /
/%5c/i, // URL encoded \
/\0/, // Null bytes
// eslint-disable-next-line no-control-regex
/[\x00-\x1f]/, // Control characters
/^\/[^/]/, // Absolute Unix paths (starting with /)
/^[a-zA-Z]:\\/, // Absolute Windows paths (C:\)
/^\\\\[^\\]/, // UNC paths (\\server\)
/^\\\\\?\\/ // Extended-length paths (\\?\)
]
return dangerousPatterns.some((pattern) => pattern.test(filePath))
}
/**
* Validates if a file path is within the allowed workspace boundaries
* @param {string} filePath The file path to validate
* @param {string} workspacePath The workspace base path
* @returns {boolean} True if path is within workspace, false otherwise
*/
export const isWithinWorkspace = (filePath: string, workspacePath: string): boolean => {
if (!filePath || !workspacePath) {
return false
}
try {
const path = require('path')
// Resolve both paths to absolute paths
const resolvedFilePath = path.resolve(workspacePath, filePath)
const resolvedWorkspacePath = path.resolve(workspacePath)
// Normalize paths to handle different separators
const normalizedFilePath = path.normalize(resolvedFilePath)
const normalizedWorkspacePath = path.normalize(resolvedWorkspacePath)
// Check if the file path starts with the workspace path
const relativePath = path.relative(normalizedWorkspacePath, normalizedFilePath)
// If relative path starts with '..' or is absolute, it's outside workspace
return !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
} catch (error) {
// If any error occurs during path resolution, deny access
return false
}
}