Skip to content

Commit 40b778d

Browse files
authored
Fix path traversal vulnerability in static file serving (#13)
Fixes #10
1 parent 41de05d commit 40b778d

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

backend.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import fs from 'fs/promises';
22
import http from 'http';
3+
import path from 'path';
34
import rssParser from './rss-parser.js';
45
import jsonToRss from './json-to-rss.js';
56

@@ -159,8 +160,13 @@ class Server {
159160
async serveStatic(req, res) {
160161
const [url] = req.url.split('?');
161162
const filePath = url === '/' ? '/index.html' : url;
162-
const fileExt = filePath.slice(filePath.lastIndexOf('.')+1);
163-
this.sendResponse(res, { contentType: this.extToMime(fileExt), data: await fs.readFile(`./public${filePath}`) });
163+
const publicDir = path.resolve('./public');
164+
const resolvedPath = path.resolve(publicDir, filePath.replace(/^\//, ''));
165+
if (!resolvedPath.startsWith(publicDir + path.sep)) {
166+
return this.sendResponse(res, { statusCode: 404, data: { message: 'Not found' } });
167+
}
168+
const fileExt = resolvedPath.slice(resolvedPath.lastIndexOf('.')+1);
169+
this.sendResponse(res, { contentType: this.extToMime(fileExt), data: await fs.readFile(resolvedPath) });
164170
}
165171
sendResponse(res, { statusCode=200, contentType='application/json', data }) {
166172
res.writeHead(statusCode, { 'Content-Type': contentType });

0 commit comments

Comments
 (0)