Skip to content

Commit f9b5f04

Browse files
cursoragentkitsonk
andcommitted
Improve proxy header parsing with safety and validation checks
Co-authored-by: me <[email protected]>
1 parent 9ba33ed commit f9b5f04

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

request.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,14 @@ export class Request {
8383
* `X-Forwarded-For`. When `false` an empty array is returned. */
8484
get ips(): string[] {
8585
return this.#proxy
86-
? (this.#serverRequest.headers.get("x-forwarded-for") ??
87-
this.#getRemoteAddr()).split(/\s*,\s*/)
86+
? (() => {
87+
const raw = this.#serverRequest.headers.get("x-forwarded-for") ?? this.#getRemoteAddr();
88+
const bounded = raw.length > 4096 ? raw.slice(0, 4096) : raw;
89+
return bounded
90+
.split(",", 100)
91+
.map((part) => part.trim())
92+
.filter((part) => part.length > 0);
93+
})()
8894
: [];
8995
}
9096

@@ -138,9 +144,14 @@ export class Request {
138144
let proto: string;
139145
let host: string;
140146
if (this.#proxy) {
141-
proto = serverRequest
142-
.headers.get("x-forwarded-proto")?.split(/\s*,\s*/, 1)[0] ??
143-
"http";
147+
const xForwardedProto = serverRequest.headers.get("x-forwarded-proto");
148+
let maybeProto = xForwardedProto
149+
? xForwardedProto.split(",", 1)[0].trim().toLowerCase()
150+
: undefined;
151+
if (maybeProto !== "http" && maybeProto !== "https") {
152+
maybeProto = undefined;
153+
}
154+
proto = maybeProto ?? "http";
144155
host = serverRequest.headers.get("x-forwarded-host") ??
145156
this.#url?.hostname ??
146157
serverRequest.headers.get("host") ??

0 commit comments

Comments
 (0)