Skip to content

Commit

Permalink
src: send a 405 for anything other than GET or HEAD
Browse files Browse the repository at this point in the history
Signed-off-by: flakey5 <[email protected]>
  • Loading branch information
flakey5 committed Nov 8, 2024
1 parent efdeb3b commit cc1ce0a
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/middleware/methodNotAllowedMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { Middleware } from './middleware';

export class MethodNotAllowedMiddleware implements Middleware {
handle(): Promise<Response> {
return Promise.resolve(new Response(undefined, { status: 405 }));
}
}
3 changes: 3 additions & 0 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import latestVersions from '../constants/latestVersions.json' assert { type: 'json' };
import { cached } from '../middleware/cacheMiddleware';
import { MethodNotAllowedMiddleware } from '../middleware/methodNotAllowedMiddleware';
import { NotFoundMiddleware } from '../middleware/notFoundMiddleware';
import { OptionsMiddleware } from '../middleware/optionsMiddleware';
import { OriginMiddleware } from '../middleware/originMiddleware';
Expand Down Expand Up @@ -52,6 +53,8 @@ export function registerRoutes(router: Router): void {
]);

router.get('*', [new NotFoundMiddleware()]);

router.all('*', [new MethodNotAllowedMiddleware()]);
}

export * from './router';
8 changes: 8 additions & 0 deletions src/routes/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ export class Router {
return this.itty.fetch(request, ctx);
}

all(endpoint: string, middlewares: Middleware[]): void {
const middlewareChain = buildMiddlewareChain(middlewares);

this.itty.all(endpoint, (req, ctx) => {
return callMiddlewareChain(middlewareChain, req, ctx);
});
}

options(endpoint: string, middlewares: Middleware[]): void {
const middlewareChain = buildMiddlewareChain(middlewares);

Expand Down
10 changes: 10 additions & 0 deletions tests/e2e/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,16 @@ describe('File Tests', () => {
assert.strictEqual(body, '{ hello:');
});

it('sends a 405 for anything other than GET or HEAD', async () => {
// Doesn't need to be all-inclusive
for (const method of ['POST', 'PATCH', 'DELETE', 'PROPFIND']) {
const res = await mf.dispatchFetch(`${url}`, {
method: method,
});
assert.strictEqual(res.status, 405, method);
}
});

// Cleanup Miniflare
after(async () => mf.dispose());
});

0 comments on commit cc1ce0a

Please sign in to comment.