fix: ensure we aren't allowing methods other than GET for static files

This commit is contained in:
Andy Burke 2025-07-31 14:53:53 -07:00
parent a9b20fea40
commit 582636ab5a
4 changed files with 50 additions and 1 deletions

View file

@ -1,7 +1,7 @@
{
"name": "@andyburke/serverus",
"description": "A flexible HTTP server for mixed content. Throw static files, markdown, Typescript and (hopefully, eventually) more into a directory and serverus can serve it up a bit more like old-school CGI.",
"version": "0.9.8",
"version": "0.10.0",
"license": "MIT",
"exports": {
".": "./serverus.ts",

1
deno.lock generated
View file

@ -94,6 +94,7 @@
"integrity": "a490169f5ccb0f3ae9c94fbc69d2cd43603f2cffb41713a85f99bbb0e3087cbc",
"dependencies": [
"jsr:@std/assert@^1.0.13",
"jsr:@std/async@^1.0.13",
"jsr:@std/data-structures",
"jsr:@std/fs",
"jsr:@std/internal@^1.0.10",

View file

@ -13,6 +13,11 @@ import * as media_types from '@std/media-types';
* @returns Either a response (a static file was requested and returned properly) or undefined if unhandled.
*/
export default async function handle_static_files(request: Request): Promise<Response | undefined> {
// we only handle GET on static files
if (request.method.toUpperCase() !== 'GET') {
return;
}
const url = new URL(request.url);
const normalized_path = path.resolve(path.normalize(url.pathname).replace(/^\/+/, ''));
if (!normalized_path.startsWith(Deno.cwd())) {

View file

@ -34,3 +34,46 @@ Deno.test({
}
}
});
Deno.test({
name: 'other methods than GET should not work on static files',
permissions: {
env: true,
read: true,
write: true,
net: true
},
fn: async () => {
let test_server_info: EPHEMERAL_SERVER | null = null;
const cwd = Deno.cwd();
try {
Deno.chdir('./tests/www');
test_server_info = await get_ephemeral_listen_server();
for await (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
const response = await fetch(`http://${test_server_info.hostname}:${test_server_info.port}/test.txt`, {
method,
body: method === 'DELETE' ? undefined : JSON.stringify({})
});
asserts.assert(!response.ok);
const body = await response.json();
asserts.assert(body);
asserts.assertEquals(body, {
error: {
cause: 'not_found',
message: 'Not found'
}
});
}
} finally {
Deno.chdir(cwd);
if (test_server_info) {
await test_server_info?.server?.stop();
}
}
}
});