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 <ashersaupingomez@gmail.com>
This commit is contained in:
Luca Casonato
2023-05-25 18:40:40 +10:00
committed by GitHub
co-authored by Asher Gomez
parent 1a456444e4
commit f95f7586f5
2 changed files with 12 additions and 20 deletions
+9 -17
View File
@@ -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;
}
+3 -3
View File
@@ -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",
);
});