Skip to content

Commit

Permalink
fix(getRequestURL): make x-forwarded-host support opt-in
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed May 15, 2023
1 parent b5d2972 commit 2fce169
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
34 changes: 26 additions & 8 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,31 @@ export function getRequestHeader(

export const getHeader = getRequestHeader;

export function getRequestHost(event: H3Event) {
const xForwardedHost = event.node.req.headers["x-forwarded-host"] as string;
if (xForwardedHost) {
return xForwardedHost;
interface XForwaredOptions {

Check warning on line 88 in src/utils/request.ts

View workflow job for this annotation

GitHub Actions / ci

'XForwaredOptions' is defined but never used
respectXForwarded?: boolean;
}

export function getRequestHost(
event: H3Event,
opts: { xForwardedHost?: boolean } = {}
) {
if (opts.xForwardedHost) {
const xForwardedHost = event.node.req.headers["x-forwarded-host"] as string;
if (xForwardedHost) {
return xForwardedHost;
}
}
return event.node.req.headers.host || "localhost";
}

export function getRequestProtocol(event: H3Event) {
if (event.node.req.headers["x-forwarded-proto"] === "https") {
export function getRequestProtocol(
event: H3Event,
opts: { xForwardedProto?: boolean } = {}
) {
if (
opts.xForwardedProto !== false &&
event.node.req.headers["x-forwarded-proto"] === "https"
) {
return "https";
}
return (event.node.req.connection as any).encrypted ? "https" : "http";
Expand All @@ -107,8 +122,11 @@ export function getRequestPath(event: H3Event) {
return path;
}

export function getRequestURL(event: H3Event) {
const host = getRequestHost(event);
export function getRequestURL(
event: H3Event,
opts: { xForwardedHost?: boolean; xForwardedProto?: boolean } = {}
) {
const host = getRequestHost(event, opts);
const protocol = getRequestProtocol(event);
const path = getRequestPath(event);
return new URL(path, `${protocol}://${host}`);
Expand Down
5 changes: 4 additions & 1 deletion test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ describe("", () => {
app.use(
"/",
eventHandler((event) => {
const url = getRequestURL(event);
const url = getRequestURL(event, {
xForwardedProto: true,
xForwardedHost: true,
});
// @ts-ignore
url.port = 80;
return url;
Expand Down

0 comments on commit 2fce169

Please sign in to comment.