From f95f7586f54194b17015939876888d8661cc0879 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Thu, 25 May 2023 10:40:40 +0200 Subject: [PATCH] fix: don't change scheme on redirect (#1024) Fixes #1015 This scenario can happen when a user has a proxy sitting in front of Fresh, that does TLS termination, while Fresh is running on plain text HTTP. --------- Co-authored-by: Asher Gomez --- src/server/context.ts | 26 +++++++++----------------- tests/main_test.ts | 6 +++--- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/server/context.ts b/src/server/context.ts index ba443d17..78301886 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -320,9 +320,16 @@ export class ServerContext { return async function handler(req: Request, connInfo: ConnInfo) { // Redirect requests that end with a trailing slash to their non-trailing // slash counterpart. + // Ex: /about/ -> /about const url = new URL(req.url); - if (cleanPathname(url)) { - return Response.redirect(url.href, Status.TemporaryRedirect); + if (url.pathname.length > 1 && url.pathname.endsWith("/")) { + // Remove trailing slashes + const path = url.pathname.replace(/\/+$/, ""); + const location = `${path}${url.search}`; + return new Response(null, { + status: Status.TemporaryRedirect, + headers: { location }, + }); } const res = await withMiddlewares(req, connInfo, inner); @@ -828,18 +835,3 @@ es.addEventListener("message", function listener(e) { } });`; } - -/** - * Clean the pathname in the given URL by removing all trailing slashes. - * - * Returns true if the pathname was changed. - */ -export function cleanPathname(url: URL): boolean { - const pathname = url.pathname.replace(/\/+$/, ""); - if (pathname === "") return false; - if (pathname !== url.pathname) { - url.pathname = pathname; - return true; - } - return false; -} diff --git a/tests/main_test.ts b/tests/main_test.ts index 00e34617..da1385e7 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -199,7 +199,7 @@ Deno.test("redirect /pages/fresh/ to /pages/fresh", async () => { assertEquals(resp.status, Status.TemporaryRedirect); assertEquals( resp.headers.get("location"), - "https://fresh.deno.dev/pages/fresh", + "/pages/fresh", ); }); @@ -211,7 +211,7 @@ Deno.test("redirect /pages/////fresh///// to /pages/////fresh", async () => { assertEquals(resp.status, Status.TemporaryRedirect); assertEquals( resp.headers.get("location"), - "https://fresh.deno.dev/pages/////fresh", + "/pages/////fresh", ); }); @@ -223,7 +223,7 @@ Deno.test("redirect /pages/////fresh/ to /pages/////fresh", async () => { assertEquals(resp.status, Status.TemporaryRedirect); assertEquals( resp.headers.get("location"), - "https://fresh.deno.dev/pages/////fresh", + "/pages/////fresh", ); });