Update file-server.js

This commit is contained in:
ADARSH 2025-07-05 21:10:38 +05:30 committed by GitHub
parent b8e33fdc10
commit 17c5b93572
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -18,22 +18,25 @@ function getAllMarkdownFiles(dirPath, arrayOfFiles = []) {
getAllMarkdownFiles(fullPath, arrayOfFiles); getAllMarkdownFiles(fullPath, arrayOfFiles);
} else if (file.endsWith('.md')) { } else if (file.endsWith('.md')) {
const stats = fs.statSync(fullPath); const stats = fs.statSync(fullPath);
const relativePath = path.relative('.', fullPath);
const folderPath = path.dirname(relativePath);
arrayOfFiles.push({ arrayOfFiles.push({
name: file, name: file,
path: fullPath, path: fullPath,
relativePath: path.relative('.', fullPath), relativePath: relativePath,
folder: path.dirname(path.relative('.', fullPath)), folder: folderPath === '.' ? 'Root' : folderPath,
size: stats.size, size: stats.size,
type: 'md', type: 'md',
lastModified: stats.mtime lastModified: stats.mtime
}); });
} }
} catch (error) { } catch (error) {
// Skip files that can't be accessed console.error(`Error processing file ${fullPath}:`, error.message);
} }
}); });
} catch (error) { } catch (error) {
// Skip directories that can't be accessed console.error(`Error reading directory ${dirPath}:`, error.message);
} }
return arrayOfFiles; return arrayOfFiles;
@ -61,13 +64,23 @@ const server = http.createServer((req, res) => {
return; return;
} }
// Security check to prevent directory traversal
const resolvedPath = path.resolve(filePath);
const projectRoot = path.resolve('.');
if (!resolvedPath.startsWith(projectRoot)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Access denied');
return;
}
try { try {
const content = fs.readFileSync(filePath, 'utf8'); const content = fs.readFileSync(resolvedPath, 'utf8');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(content); res.end(content);
} catch (error) { } catch (error) {
console.error(`Error reading file ${resolvedPath}:`, error.message);
res.writeHead(404, { 'Content-Type': 'text/plain' }); res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File not found'); res.end('File not found: ' + error.message);
} }
return; return;
} }