From af3edd7cb2e7534f231eda01ee10c2f50f8df492 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Sun, 26 Feb 2023 00:44:44 +0530 Subject: [PATCH] fix: coalesce falsy body to {} (#4929) --- server/middlewares/coaleseBody.ts | 12 ++++++++++++ server/routes/api/index.ts | 2 ++ server/routes/auth/index.ts | 2 ++ 3 files changed, 16 insertions(+) create mode 100644 server/middlewares/coaleseBody.ts diff --git a/server/middlewares/coaleseBody.ts b/server/middlewares/coaleseBody.ts new file mode 100644 index 0000000000..7d3fe76964 --- /dev/null +++ b/server/middlewares/coaleseBody.ts @@ -0,0 +1,12 @@ +import { Next } from "koa"; +import { AppContext } from "@server/types"; + +// remove after https://github.com/koajs/koa-body/issues/218 is resolved +export default function coalesceBody() { + return function coalesceBodyMiddleware(ctx: AppContext, next: Next) { + if (!ctx.request.body) { + ctx.request.body = {}; + } + return next(); + }; +} diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index d812f2048b..5fdc708741 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -7,6 +7,7 @@ import userAgent, { UserAgentContext } from "koa-useragent"; import env from "@server/env"; import { NotFoundError } from "@server/errors"; import Logger from "@server/logging/Logger"; +import coalesceBody from "@server/middlewares/coaleseBody"; import { AppState, AppContext } from "@server/types"; import apiKeys from "./apiKeys"; import attachments from "./attachments"; @@ -45,6 +46,7 @@ api.use( }, }) ); +api.use(coalesceBody()); api.use(userAgent); api.use(apiWrapper()); api.use(editor()); diff --git a/server/routes/auth/index.ts b/server/routes/auth/index.ts index 1a207f74e2..4e3a54ca2b 100644 --- a/server/routes/auth/index.ts +++ b/server/routes/auth/index.ts @@ -5,6 +5,7 @@ import bodyParser from "koa-body"; import Router from "koa-router"; import { AuthenticationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; +import coalesceBody from "@server/middlewares/coaleseBody"; import { Collection, Team, View } from "@server/models"; import AuthenticationHelper from "@server/models/helpers/AuthenticationHelper"; import { AppState, AppContext, APIContext } from "@server/types"; @@ -71,6 +72,7 @@ router.get("/redirect", auth(), async (ctx: APIContext) => { }); app.use(bodyParser()); +app.use(coalesceBody()); app.use(router.routes()); export default app;