| const fs = require('fs');
|
| const path = require('path');
|
| const { SECURITY_CONFIG, PathValidationError, SecurityError } = require('./security-config');
|
|
|
|
|
| function validateInput(target) {
|
| if (!target || typeof target !== 'string') {
|
| throw new PathValidationError('Invalid target path', target, 'INVALID_TYPE');
|
| }
|
|
|
| if (target.length > SECURITY_CONFIG.MAX_PATH_LENGTH) {
|
| throw new PathValidationError('Path too long', target, 'PATH_TOO_LONG');
|
| }
|
|
|
|
|
| const dangerousChars = /[<>"|?*\x00-\x1f]/;
|
| if (dangerousChars.test(target)) {
|
| throw new PathValidationError('Dangerous characters in path', target, 'DANGEROUS_CHARS');
|
| }
|
|
|
| return true;
|
| }
|
|
|
|
|
| function isPathSafe(targetPath) {
|
| const normalizedPath = path.resolve(targetPath);
|
|
|
|
|
| for (const forbiddenPattern of SECURITY_CONFIG.FORBIDDEN_PATHS) {
|
| if (forbiddenPattern.test(normalizedPath)) {
|
| throw new SecurityError(
|
| `Access to system directories is not allowed: ${normalizedPath}`,
|
| targetPath,
|
| 'SYSTEM_DIR_ACCESS'
|
| );
|
| }
|
| }
|
|
|
|
|
| if (normalizedPath.includes('..')) {
|
| throw new SecurityError('Path traversal is not allowed', targetPath, 'PATH_TRAVERSAL');
|
| }
|
|
|
| return true;
|
| }
|
|
|
|
|
| function sanitizePath(inputPath) {
|
| const normalizedPath = path.normalize(inputPath);
|
|
|
|
|
| if (normalizedPath.includes('\x00')) {
|
| throw new PathValidationError('Null bytes in path are not allowed', inputPath, 'NULL_BYTES');
|
| }
|
|
|
| return normalizedPath;
|
| }
|
|
|
|
|
| function checkFilePermissions(filePath, requireWrite = false) {
|
| try {
|
|
|
| fs.accessSync(filePath, fs.constants.R_OK);
|
|
|
|
|
| if (requireWrite) {
|
| fs.accessSync(filePath, fs.constants.W_OK);
|
| }
|
|
|
| return true;
|
| } catch (error) {
|
| throw new SecurityError(`Permission denied: ${filePath}`, filePath, 'PERMISSION_DENIED');
|
| }
|
| }
|
|
|
|
|
| function isAllowedExtension(filePath) {
|
| const ext = path.extname(filePath).toLowerCase();
|
| return SECURITY_CONFIG.ALLOWED_EXTENSIONS.includes(ext);
|
| }
|
|
|
|
|
| function checkFileSize(filePath) {
|
| const stats = fs.statSync(filePath);
|
| if (stats.size > SECURITY_CONFIG.MAX_FILE_SIZE) {
|
| throw new SecurityError(
|
| `File too large (${stats.size} bytes, max ${SECURITY_CONFIG.MAX_FILE_SIZE})`,
|
| filePath,
|
| 'FILE_TOO_LARGE'
|
| );
|
| }
|
| return stats;
|
| }
|
|
|
| module.exports = {
|
| validateInput,
|
| isPathSafe,
|
| sanitizePath,
|
| checkFilePermissions,
|
| isAllowedExtension,
|
| checkFileSize
|
| };
|
|
|