Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/utils/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ export function sanitizeStatusCode(
if (typeof statusCode === "string") {
statusCode = Number.parseInt(statusCode, 10);
}
if (statusCode < 100 || statusCode > 999) {
// `Number.parseInt` returns `NaN` for non-numeric strings, and `NaN` passes
// the range check below (every comparison with `NaN` is `false`), so an
// invalid status code would leak through unchanged. Guard against it.
if (Number.isNaN(statusCode) || statusCode < 100 || statusCode > 999) {
return defaultStatusCode;
}
return statusCode;
Expand Down
26 changes: 26 additions & 0 deletions test/sanitize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, it, expect } from "vitest";
import { sanitizeStatusCode } from "../src/utils/sanitize";

describe("sanitizeStatusCode", () => {
it("returns valid status codes unchanged", () => {
expect(sanitizeStatusCode(200)).toBe(200);
expect(sanitizeStatusCode(404)).toBe(404);
expect(sanitizeStatusCode("301")).toBe(301);
});

it("returns the default for missing or out-of-range input", () => {
expect(sanitizeStatusCode(undefined)).toBe(200);
expect(sanitizeStatusCode(0)).toBe(200);
expect(sanitizeStatusCode(99)).toBe(200);
expect(sanitizeStatusCode(1000)).toBe(200);
expect(sanitizeStatusCode(99, 500)).toBe(500);
});

it("returns the default for non-numeric strings instead of NaN", () => {
// `Number.parseInt("abc", 10)` is NaN and NaN passes the range check, so
// the function used to return NaN here, which breaks downstream consumers
// (e.g. setting `res.statusCode` or building a `Response`).
expect(sanitizeStatusCode("abc")).toBe(200);
expect(sanitizeStatusCode("abc", 500)).toBe(500);
});
});