Skip to content

Commit

Permalink
fix: handle querystring parameters in path (#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith committed Feb 17, 2021
1 parent ec49cdf commit 245b3bd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export async function processOptions(
options.serverRoot = options.path[0];
if (s.isFile()) {
const pathParts = options.path[0].split(path.sep);
options.path = [path.sep + pathParts[pathParts.length - 1]];
options.path = [path.join('.', pathParts[pathParts.length - 1])];
options.serverRoot =
pathParts.slice(0, pathParts.length - 1).join(path.sep) || '.';
} else {
Expand Down
6 changes: 4 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as fs from 'fs';
import {promisify} from 'util';
import * as marked from 'marked';
import * as mime from 'mime';
import {URL} from 'url';
import escape = require('escape-html');
import enableDestroy = require('server-destroy');

Expand Down Expand Up @@ -44,9 +45,10 @@ async function handleRequest(
root: string,
options: WebServerOptions
) {
const pathParts = req.url?.split('/') || [];
const url = new URL(req.url || '/', `http://localhost:${options.port}`);
const pathParts = url.pathname.split('/').filter(x => !!x);
const originalPath = path.join(root, ...pathParts);
if (req.url?.endsWith('/')) {
if (url.pathname.endsWith('/')) {
pathParts.push('index.html');
}
const localPath = path.join(root, ...pathParts);
Expand Down
16 changes: 15 additions & 1 deletion test/test.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ describe('server', () => {
it('should protect against path escape attacks', async () => {
const url = `${rootUrl}/../../etc/passwd`;
const res = await request({url, validateStatus: () => true});
assert.strictEqual(res.status, 500);
assert.strictEqual(res.status, 404);
});

it('should return a 404 for missing paths', async () => {
Expand All @@ -61,4 +61,18 @@ describe('server', () => {
assert.strictEqual(res.status, 200);
assert.strictEqual(res.data, contents);
});

it('should ignore query strings', async () => {
const url = `${rootUrl}/index.html?a=b`;
const res = await request({url});
assert.strictEqual(res.status, 200);
assert.strictEqual(res.data, contents);
});

it('should ignore query strings in a directory', async () => {
const url = `${rootUrl}/?a=b`;
const res = await request({url});
assert.strictEqual(res.status, 200);
assert.strictEqual(res.data, contents);
});
});

0 comments on commit 245b3bd

Please sign in to comment.