From 0c8b8daac0d82aef7fe2487d4bf9d5e50bcc6c0d Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Sat, 8 Jun 2024 10:25:34 +1000 Subject: [PATCH] feat: support authority pseudo header for requests Closes #658 --- request.ts | 60 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/request.ts b/request.ts index 2fca284..6ded344 100644 --- a/request.ts +++ b/request.ts @@ -123,39 +123,41 @@ export class Request { get url(): URL { if (!this.#url) { const serverRequest = this.#serverRequest; - if (!this.#proxy) { - // between 1.9.0 and 1.9.1 the request.url of the native HTTP started - // returning the full URL, where previously it only returned the path - // so we will try to use that URL here, but default back to old logic - // if the URL isn't valid. + // between Deno 1.9.0 and 1.9.1 the request.url of the native HTTP started + // returning the full URL, where previously it only returned the path + // so we will try to use that URL here, but default back to old logic + // if the URL isn't valid. + try { + if (serverRequest.rawUrl) { + this.#url = new URL(serverRequest.rawUrl); + } + } catch { + // we don't care about errors here + } + if (this.#proxy || !this.#url) { + let proto: string; + let host: string; + if (this.#proxy) { + proto = serverRequest + .headers.get("x-forwarded-proto")?.split(/\s*,\s*/, 1)[0] ?? + "http"; + host = serverRequest.headers.get("x-forwarded-host") ?? + this.#url?.hostname ?? + serverRequest.headers.get("host") ?? + serverRequest.headers.get(":authority") ?? ""; + } else { + proto = this.#secure ? "https" : "http"; + host = serverRequest.headers.get("host") ?? + serverRequest.headers.get(":authority") ?? ""; + } try { - if (serverRequest.rawUrl) { - this.#url = new URL(serverRequest.rawUrl); - return this.#url; - } + this.#url = new URL(`${proto}://${host}${serverRequest.url}`); } catch { - // we don't care about errors here + throw new TypeError( + `The server request URL of "${proto}://${host}${serverRequest.url}" is invalid.`, + ); } } - let proto: string; - let host: string; - if (this.#proxy) { - proto = serverRequest - .headers.get("x-forwarded-proto")?.split(/\s*,\s*/, 1)[0] ?? - "http"; - host = serverRequest.headers.get("x-forwarded-host") ?? - serverRequest.headers.get("host") ?? ""; - } else { - proto = this.#secure ? "https" : "http"; - host = serverRequest.headers.get("host") ?? ""; - } - try { - this.#url = new URL(`${proto}://${host}${serverRequest.url}`); - } catch { - throw new TypeError( - `The server request URL of "${proto}://${host}${serverRequest.url}" is invalid.`, - ); - } } return this.#url; }