chore: Upgrade koa-helmet to v9 and koa-body to v8 (#14046)

* chore: Upgrade koa-helmet to v9 and koa-body to v8

* fix: Keep decimal parsing for pagination limit and offset
This commit is contained in:
Tom Moor authored and GitHub committed 2026-10-16 02:11:11 +00:00
1 parent f4c4018872
commit eceba73a14
20 files changed
+203 -77

No files matched your search

+5 -3
View File
@@ -141,6 +141,7 @@
"fast-deep-equal": "^3.1.3",
"fetch-retry": "^5.0.6",
"form-data": "^4.0.6",
"formidable": "^3.5.4",
"fractional-index": "^1.0.0",
"framer-motion": "^13.1.1",
"franc": "^6.2.0",
@@ -148,6 +149,7 @@
"fuse.js": "^7.5.0",
"fuzzy-search": "^3.2.1",
"glob": "^11.1.0",
"helmet": "^8.3.0",
"hot-shots": "^12.1.0",
"http-errors": "2.0.1",
"https-proxy-agent": "^7.0.6",
@@ -165,9 +167,9 @@
"katex": "^0.18.2",
"kbar": "^1.0.0",
"koa": "^3.0.3",
"koa-body": "^6.0.1",
"koa-body": "^8.0.1",
"koa-compress": "^5.2.2",
"koa-helmet": "^6.1.0",
"koa-helmet": "^9.0.0",
"koa-logger": "^3.2.1",
"koa-mount": "^4.2.0",
"koa-sslify": "5.0.1",
@@ -289,7 +291,7 @@
"@types/diff": "^5.0.9",
"@types/escape-html": "^1.0.4",
"@types/express-useragent": "^1.0.5",
"@types/formidable": "^2.0.6",
"@types/formidable": "^3.5.1",
"@types/fs-extra": "^11.0.4",
"@types/fuzzy-search": "^2.1.5",
"@types/google.analytics": "^0.0.46",
+3 -1
View File
@@ -11,6 +11,7 @@ import validateWebhook from "@server/middlewares/validateWebhook";
import { IntegrationAuthentication, Integration } from "@server/models";
import type { APIContext } from "@server/types";
import { verifyOAuthStateNonce } from "@server/utils/oauth";
import { RequestHelper } from "@server/utils/RequestHelper";
import { GitHubOAuthNonceCookie, GitHubUtils } from "../../shared/GitHubUtils";
import env from "../env";
import { GitHub } from "../github";
@@ -122,7 +123,8 @@ router.post(
},
}),
async (ctx: APIContext) => {
const { headers, body } = ctx.request;
const { headers } = ctx.request;
const body = RequestHelper.getBodyObject(ctx.request);
await new GitHubWebhookTask().schedule({
payload: body,
+3 -1
View File
@@ -13,6 +13,7 @@ import { IntegrationAuthentication, Integration } from "@server/models";
import { authorize } from "@server/policies";
import type { APIContext } from "@server/types";
import { safeEqual } from "@server/utils/crypto";
import { RequestHelper } from "@server/utils/RequestHelper";
import {
generateOAuthStateNonce,
verifyOAuthStateNonce,
@@ -354,7 +355,8 @@ router.post(
getSignatureFromHeader: getGitLabWebhookToken,
}),
async (ctx: APIContext) => {
const { headers, body } = ctx.request;
const { headers } = ctx.request;
const body = RequestHelper.getBodyObject(ctx.request);
const teamIds: Array<string | null> = ctx.state.webhookTeamIds ?? [null];
await Promise.all(
+9 -1
View File
@@ -62,7 +62,15 @@ export async function start(id: number, disconnect: () => void) {
app.use(logger((str) => Logger.info("http", str)));
}
app.use(helmet());
// Cross-origin isolation headers are left off, as attachments, avatars, and
// CDN assets are loaded across origins and from custom domains.
app.use(
helmet({
crossOriginOpenerPolicy: false,
crossOriginResourcePolicy: false,
originAgentCluster: false,
})
);
// catch errors in one place, automatically set status and response headers
onerror(app);
+10 -6
View File
@@ -1,6 +1,6 @@
import crypto from "node:crypto";
import type { Context, Next } from "koa";
import { contentSecurityPolicy } from "koa-helmet";
import helmet from "koa-helmet";
import { asyncNoop } from "es-toolkit";
import { uniq } from "es-toolkit/compat";
import env from "@server/env";
@@ -133,10 +133,8 @@ export default function createCSPMiddleware(options?: CSPOptions) {
// allow additional sources for the response, see `allowScriptSrc` and
// `allowStyleSrc`.
if (!ctx.res.headersSent) {
// Note: workerSrc is included even though it's missing from the
// koa-helmet type definitions — the underlying helmet supports it. The
// service worker is served from the same origin as the document, which
// may be a custom domain that is not present in scriptSrc.
// The service worker is served from the same origin as the document,
// which may be a custom domain that is not present in scriptSrc.
const directives = {
baseUri: ["'none'"],
defaultSrc,
@@ -164,7 +162,13 @@ export default function createCSPMiddleware(options?: CSPOptions) {
connectSrc: ["*"],
};
await contentSecurityPolicy({ directives })(ctx, asyncNoop);
// Helmet's default directives are not merged in, they include
// frame-ancestors and form-action restrictions that break embeds and
// OAuth redirects.
await helmet.contentSecurityPolicy({ useDefaults: false, directives })(
ctx,
asyncNoop
);
}
}
};
+4 -1
View File
@@ -3,6 +3,7 @@ import { Scope } from "@shared/types";
import env from "@server/env";
import AuthenticationHelper from "@shared/helpers/AuthenticationHelper";
import type { AppContext } from "@server/types";
import { RequestHelper } from "@server/utils/RequestHelper";
import {
generateRawToken,
bundleToken,
@@ -87,8 +88,10 @@ export function verifyCSRFToken() {
// Get token from header or form field depending on type
// Access the already-parsed body from koa-body middleware
const fieldVal = RequestHelper.getBodyObject(ctx.request)[CSRF.fieldName];
const inputVal =
ctx.get(CSRF.headerName) || ctx.request.body?.[CSRF.fieldName];
ctx.get(CSRF.headerName) ||
(typeof fieldVal === "string" ? fieldVal : undefined);
if (!inputVal) {
throw CSRFError("CSRF token missing from request");
+4 -1
View File
@@ -1,9 +1,12 @@
import type { Context, Next } from "koa";
import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer";
import { RequestHelper } from "@server/utils/RequestHelper";
export default function requestTracer() {
return async function requestTracerMiddleware(ctx: Context, next: Next) {
const params = ctx.request.body ?? ctx.request.query;
const params = ctx.request.body
? RequestHelper.getBodyObject(ctx.request)
: ctx.request.query;
for (const key in params) {
if (key === "id" || key.endsWith("Id")) {
+14
View File
@@ -1,4 +1,5 @@
// @vitest-isolate true
import { errors as formidableErrors } from "formidable";
import type Koa from "koa";
import { DatabaseError } from "sequelize";
import type { Mock } from "vitest";
@@ -142,6 +143,19 @@ describe("onerror", () => {
expect(ctx.body).toContain("client_closed_request");
});
it("should convert an aborted multipart upload into a client closed request", () => {
const error = new formidableErrors.default(
"Request aborted",
formidableErrors.aborted
);
app.context.onerror.call(ctx, error);
expect(requestErrorHandler).not.toHaveBeenCalled();
expect(ctx.status).toBe(499);
expect(ctx.body).toContain("client_closed_request");
});
it("should set the response status code when the response is not writable", () => {
ctx.writable = false;
+3 -3
View File
@@ -1,7 +1,7 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import formidable from "formidable";
import { errors as formidableErrors } from "formidable";
import type Koa from "koa";
import { escape, isNil, snakeCase } from "es-toolkit/compat";
import env from "@server/env";
@@ -27,8 +27,8 @@ export default function onerror(app: Koa) {
err = wrapInNativeError(err);
// Client aborted errors are a 500 by default, but 499 is more appropriate
if (err instanceof formidable.errors.FormidableError) {
if (err.internalCode === 1002) {
if (err instanceof formidableErrors.default) {
if (err.code === formidableErrors.aborted) {
err = ClientClosedRequestError();
}
} else if (
+2 -2
View File
@@ -103,7 +103,7 @@ function resolveStack(method: string): Middleware[] | undefined {
function createSubContext(
ctx: AppContext,
method: string,
body: Record<string, unknown>
body: T.BatchRequestBody
) {
const sub: AppContext = Object.create(ctx);
// A shallow copy so middleware writes (auth, transaction) don't leak between
@@ -170,7 +170,7 @@ function createSubContext(
async function dispatch(
ctx: AppContext,
method: string,
body: Record<string, unknown>
body: T.BatchRequestBody
): Promise<BatchResult> {
const stack = resolveStack(method);
if (!stack) {
+5 -1
View File
@@ -10,7 +10,7 @@ export const BatchSchema = BaseSchema.extend({
/** The RPC method to invoke, e.g. "documents.update". */
method: z.string(),
/** The request body passed to the method. */
body: z.record(z.string(), z.unknown()).optional(),
body: z.record(z.string(), z.json()).optional(),
})
)
.min(1)
@@ -21,3 +21,7 @@ export const BatchSchema = BaseSchema.extend({
});
export type BatchReq = z.infer<typeof BatchSchema>;
export type BatchRequestBody = NonNullable<
BatchReq["body"]["requests"][number]["body"]
>;
@@ -54,4 +54,38 @@ describe("#pagination", () => {
});
expect(res.status).toEqual(400);
});
it("should parse limit and offset as decimal integers", async () => {
const user = await buildUser();
const res = await server.post("/api/users.list", user, {
body: {
limit: "1e2",
offset: "2.9",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.pagination.limit).toEqual(1);
expect(body.pagination.offset).toEqual(2);
});
it("should not allow hexadecimal limit", async () => {
const user = await buildUser();
const res = await server.post("/api/users.list", user, {
body: {
limit: "0x10",
},
});
expect(res.status).toEqual(400);
});
it("should not allow non-numeric limit types", async () => {
const user = await buildUser();
const res = await server.post("/api/users.list", user, {
body: {
limit: true,
},
});
expect(res.status).toEqual(400);
});
});
+21 -7
View File
@@ -3,6 +3,7 @@ import type { Next } from "koa";
import { Pagination } from "@shared/constants";
import { InvalidRequestError } from "@server/errors";
import type { AppContext, Pagination as PaginationType } from "@server/types";
import { RequestHelper } from "@server/utils/RequestHelper";
/**
* Execute a paginated query, skipping the COUNT query for client requests by
@@ -66,20 +67,28 @@ export default function pagination() {
maxLimit: Pagination.maxLimit,
};
const query = ctx.request.query;
const body = ctx.request.body;
let limit = query.limit || body.limit;
let offset = query.offset || body.offset;
const body = RequestHelper.getBodyObject(ctx.request);
const rawLimit = query.limit || body.limit;
const rawOffset = query.offset || body.offset;
if (limit && isNaN(limit)) {
if (rawLimit && isNaN(Number(rawLimit))) {
throw InvalidRequestError(`Pagination limit must be a valid number`);
}
if (offset && isNaN(offset)) {
if (rawOffset && isNaN(Number(rawOffset))) {
throw InvalidRequestError(`Pagination offset must be a valid number`);
}
limit = parseInt(limit || opts.defaultLimit, 10);
offset = parseInt(offset || opts.defaultOffset, 10);
const limit = rawLimit ? parseInteger(rawLimit) : opts.defaultLimit;
const offset = rawOffset ? parseInteger(rawOffset) : opts.defaultOffset;
if (isNaN(limit)) {
throw InvalidRequestError(`Pagination limit must be a valid number`);
}
if (isNaN(offset)) {
throw InvalidRequestError(`Pagination offset must be a valid number`);
}
if (limit > opts.maxLimit) {
throw InvalidRequestError(
@@ -109,3 +118,8 @@ export default function pagination() {
return next();
};
}
const parseInteger = (value: unknown) =>
typeof value === "string" || typeof value === "number"
? parseInt(String(value), 10)
: NaN;
+9
View File
@@ -95,3 +95,12 @@ export const TeamsDeleteSchema = BaseSchema.extend({
});
export type TeamsDeleteSchemaReq = z.infer<typeof TeamsDeleteSchema>;
export const TeamsCreateSchema = BaseSchema.extend({
body: z.object({
/** Name of the new team */
name: z.string(),
}),
});
export type TeamsCreateSchemaReq = z.infer<typeof TeamsCreateSchema>;
+3 -2
View File
@@ -118,11 +118,12 @@ router.post(
"teams.create",
rateLimiter(RateLimiterStrategy.FivePerHour),
auth(),
validate(T.TeamsCreateSchema),
transaction(),
async (ctx: APIContext) => {
async (ctx: APIContext<T.TeamsCreateSchemaReq>) => {
const { transaction } = ctx.state;
const { user } = ctx.state.auth;
const { name } = ctx.request.body;
const { name } = ctx.input.body;
const existingTeam = await Team.scope(
"withAuthenticationProviders"
+7 -4
View File
@@ -22,6 +22,7 @@ import { TeamPreference } from "@shared/types";
import { ClientMetadataHelper } from "@server/utils/oauth/ClientMetadataHelper";
import { OAuthHelper } from "@server/utils/oauth/OAuthHelper";
import { OAuthInterface } from "@server/utils/oauth/OAuthInterface";
import { RequestHelper } from "@server/utils/RequestHelper";
import { getTeamFromContext } from "@server/utils/passport";
import oauthErrorHandler from "./middlewares/oauthErrorHandler";
import registrationAuth from "./middlewares/registrationAuth";
@@ -50,8 +51,9 @@ router.post(
auth({ type: AuthenticationType.APP }),
async (ctx) => {
const { user } = ctx.state.auth;
const clientId = ctx.request.body.client_id;
if (!clientId) {
const body = RequestHelper.getBodyObject(ctx.request);
const clientId = body.client_id;
if (typeof clientId !== "string" || !clientId) {
throw ValidationError("Missing client_id");
}
@@ -67,8 +69,9 @@ router.post(
// redirect URI, so PKCE with S256 is required.
if (
client.isCIMD &&
(!ctx.request.body.code_challenge ||
ctx.request.body.code_challenge_method?.trim() !== "S256")
(!body.code_challenge ||
typeof body.code_challenge_method !== "string" ||
body.code_challenge_method.trim() !== "S256")
) {
throw ValidationError("PKCE with code_challenge_method S256 is required");
}
+3 -3
View File
@@ -2,7 +2,7 @@ import { Server } from "node:https";
import type { BaseContext } from "koa";
import Koa from "koa";
import compress from "koa-compress";
import { dnsPrefetchControl, referrerPolicy } from "koa-helmet";
import helmet from "koa-helmet";
import mount from "koa-mount";
import enforceHttps, {
httpsResolver,
@@ -98,12 +98,12 @@ export default function init(app: Koa = new Koa(), server?: Server) {
// Allow DNS prefetching for performance, we do not care about leaking requests
// to our own CDN's
app.use(
dnsPrefetchControl({
helmet.dnsPrefetchControl({
allow: true,
})
);
app.use(
referrerPolicy({
helmet.referrerPolicy({
policy: "no-referrer",
})
);
-2
View File
@@ -1,7 +1,5 @@
declare module "styled-components-breakpoint";
declare module "formidable/lib/file";
declare module "oy-vey";
declare module "email-providers" {
+22
View File
@@ -0,0 +1,22 @@
import type { Request } from "koa";
/**
* Helper class for reading values from incoming Koa requests.
*/
export class RequestHelper {
/**
* Get the parsed body of a request when it is a JSON object, form, or
* multipart fields.
*
* @param request The incoming request.
* @returns the body, or an empty object if the body is missing or is not an
* object.
*/
public static getBodyObject(request: Request): Record<string, unknown> {
const { body } = request;
return isRecord(body) ? body : {};
}
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
+42 -39
View File
@@ -6183,7 +6183,7 @@ __metadata:
languageName: node
linkType: hard
"@types/co-body@npm:^6.1.0, @types/co-body@npm:^6.1.3":
"@types/co-body@npm:^6.1.3":
version: 6.1.3
resolution: "@types/co-body@npm:6.1.3"
dependencies:
@@ -6585,12 +6585,12 @@ __metadata:
languageName: node
linkType: hard
"@types/formidable@npm:^2.0.5, @types/formidable@npm:^2.0.6":
version: 2.0.6
resolution: "@types/formidable@npm:2.0.6"
"@types/formidable@npm:^3.5.1":
version: 3.5.1
resolution: "@types/formidable@npm:3.5.1"
dependencies:
"@types/node": "npm:*"
checksum: 10c0/2816718c407e9adf2337ca69241e29097f5e0b22f3d0a3dde1ea23a2eef2ad41ad19612a6eac895492bd746593d87278f9732b4cb354dd72df3c03e8c1ad72c3
checksum: 10c0/e942ce8ebd6e12f8751f5e138bdd5ad0efb921bf1aa48c66e8e25a548d28eb2102551a47c6b2d958bd4dc9e2f41927a201c03192c2b58f526c0fdae3b0c9589c
languageName: node
linkType: hard
@@ -8733,7 +8733,7 @@ __metadata:
languageName: node
linkType: hard
"co-body@npm:^6.1.0, co-body@npm:^6.2.0":
"co-body@npm:^6.2.0":
version: 6.2.0
resolution: "co-body@npm:6.2.0"
dependencies:
@@ -11306,15 +11306,14 @@ __metadata:
languageName: node
linkType: hard
"formidable@npm:^2.0.1":
version: 2.1.5
resolution: "formidable@npm:2.1.5"
"formidable@npm:^3.5.4":
version: 3.5.4
resolution: "formidable@npm:3.5.4"
dependencies:
"@paralleldrive/cuid2": "npm:^2.2.2"
dezalgo: "npm:^1.0.4"
once: "npm:^1.4.0"
qs: "npm:^6.11.0"
checksum: 10c0/2c68ca6cccc1ac3de497c50236631fafea8e1a09396d88b4dd2dc9db6029b5abaeb6747b8b97ebc1143cd40cf62c27ba485b8c6317088c066fc999af3ac621d4
checksum: 10c0/3a311ce57617eb8f532368e91c0f2bbfb299a0f1a35090e085bd6ca772298f196fbb0b66f0d4b5549d7bf3c5e1844439338d4402b7b6d1fedbe206ad44a931f8
languageName: node
linkType: hard
@@ -11993,10 +11992,10 @@ __metadata:
languageName: node
linkType: hard
"helmet@npm:^4.4.1":
version: 4.6.0
resolution: "helmet@npm:4.6.0"
checksum: 10c0/fe0d986fc465be0f652e67dd1feab576d9b08b797846fdac5719d5ca857977d6b1712327223a7c25695104dfde118fdf303f4a18efca7cddf0159821bf36b7f8
"helmet@npm:^8.3.0":
version: 8.3.0
resolution: "helmet@npm:8.3.0"
checksum: 10c0/69f33ca716ed3ce34f1f2f48ce8618846dfa9c89e3a15d6bccefc882541e8b028517448c6b0e7450792fd23e5580bfe6d410d4f22bedc2a94f6b1188817a059a
languageName: node
linkType: hard
@@ -13473,17 +13472,18 @@ __metadata:
languageName: node
linkType: hard
"koa-body@npm:^6.0.1":
version: 6.0.1
resolution: "koa-body@npm:6.0.1"
"koa-body@npm:^8.0.1":
version: 8.0.1
resolution: "koa-body@npm:8.0.1"
dependencies:
"@types/co-body": "npm:^6.1.0"
"@types/formidable": "npm:^2.0.5"
"@types/koa": "npm:^2.13.5"
co-body: "npm:^6.1.0"
formidable: "npm:^2.0.1"
zod: "npm:^3.19.1"
checksum: 10c0/5645dd08d2ce54171be35d3acf1764e0b3024660570a55cc2692e2f5f3256043bae136ec2dcab2860cae3be8faab99d5720c8660dec2cdff37d5413053bbcee8
"@types/co-body": "npm:^6.1.3"
"@types/formidable": "npm:^3.5.1"
"@types/koa": "npm:^3.0.3"
co-body: "npm:^6.2.0"
formidable: "npm:^3.5.4"
type-fest: "npm:^5.9.0"
zod: "npm:^4.5.4"
checksum: 10c0/2382ad65bfbaec550106300d968cd0d2d2dbd64f710bb946edf6029fb0f16e773cfe0a8d4979ec2915d36e4897640916f5373af3416416d62670f314ba27d7e5
languageName: node
linkType: hard
@@ -13507,12 +13507,13 @@ __metadata:
languageName: node
linkType: hard
"koa-helmet@npm:^6.1.0":
version: 6.1.0
resolution: "koa-helmet@npm:6.1.0"
dependencies:
helmet: "npm:^4.4.1"
checksum: 10c0/4ede697b7fb267b9d9eadfca79e590c374212635dea9a3d8c1b079dd2af64f4b9f1152d7dd728cbb6b307bd4d02cdb1d8dccdb7b91301f5b1fe41ad4d2add1a3
"koa-helmet@npm:^9.0.0":
version: 9.0.0
resolution: "koa-helmet@npm:9.0.0"
peerDependencies:
helmet: ^6 || ^7 || ^8
koa: ^2 || ^3
checksum: 10c0/967833dda282ee2b53a99ccd2bb43087d2ed4fa7d36ab698ae884a2159feec5ed0b39b491afb285adc62e4a9f4162e65dcd2a83b2f5c13df09c694cac2c7771c
languageName: node
linkType: hard
@@ -15336,7 +15337,7 @@ __metadata:
"@types/diff": "npm:^5.0.9"
"@types/escape-html": "npm:^1.0.4"
"@types/express-useragent": "npm:^1.0.5"
"@types/formidable": "npm:^2.0.6"
"@types/formidable": "npm:^3.5.1"
"@types/fs-extra": "npm:^11.0.4"
"@types/fuzzy-search": "npm:^2.1.5"
"@types/google.analytics": "npm:^0.0.46"
@@ -15410,6 +15411,7 @@ __metadata:
fast-deep-equal: "npm:^3.1.3"
fetch-retry: "npm:^5.0.6"
form-data: "npm:^4.0.6"
formidable: "npm:^3.5.4"
fractional-index: "npm:^1.0.0"
framer-motion: "npm:^13.1.1"
franc: "npm:^6.2.0"
@@ -15417,6 +15419,7 @@ __metadata:
fuse.js: "npm:^7.5.0"
fuzzy-search: "npm:^3.2.1"
glob: "npm:^11.1.0"
helmet: "npm:^8.3.0"
hot-shots: "npm:^12.1.0"
http-errors: "npm:2.0.1"
https-proxy-agent: "npm:^7.0.6"
@@ -15437,9 +15440,9 @@ __metadata:
katex: "npm:^0.18.2"
kbar: "npm:^1.0.0"
koa: "npm:^3.0.3"
koa-body: "npm:^6.0.1"
koa-body: "npm:^8.0.1"
koa-compress: "npm:^5.2.2"
koa-helmet: "npm:^6.1.0"
koa-helmet: "npm:^9.0.0"
koa-logger: "npm:^3.2.1"
koa-mount: "npm:^4.2.0"
koa-sslify: "npm:5.0.1"
@@ -16889,7 +16892,7 @@ __metadata:
languageName: node
linkType: hard
"qs@npm:^6.11.0, qs@npm:^6.14.0, qs@npm:^6.15.2, qs@npm:^6.5.2":
"qs@npm:^6.14.0, qs@npm:^6.15.2, qs@npm:^6.5.2":
version: 6.16.0
resolution: "qs@npm:6.16.0"
dependencies:
@@ -19604,12 +19607,12 @@ __metadata:
languageName: node
linkType: hard
"type-fest@npm:^5.5.0":
version: 5.6.0
resolution: "type-fest@npm:5.6.0"
"type-fest@npm:^5.5.0, type-fest@npm:^5.9.0":
version: 5.10.0
resolution: "type-fest@npm:5.10.0"
dependencies:
tagged-tag: "npm:^1.0.0"
checksum: 10c0/5468a8ffda7f3904e6f7bbd8069eb8b6dd4bd9156e206df7a01d09a73e28cd1afedf74ead9d0fc12841c8c90074194859feca240511c50800962fde1bd9ddcbc
checksum: 10c0/313c5d0e37a3f1cc82e942f3228f897623c8b54a63a8a95532d0c2c21ab200793caa70bd8904a83fd713eb28d87ba32468b09b345ef6efa25cecb345b467226f
languageName: node
linkType: hard