Files
outline/server/utils/redirectOnClient.ts
T
Tom Moor 9bfb1b9930 fix: Preserve custom port in client-side redirects (#13401)
Proxies commonly forward a Host header without the port the installation is
publicly reachable on, so redirects derived from the incoming request pointed at
the wrong address – most visibly breaking the email magic sign-in link.
2026-08-12 21:49:49 -04:00

73 lines
2.0 KiB
TypeScript

import { escape } from "es-toolkit/compat";
import type { Context } from "koa";
import { addMissingUrlPort } from "@shared/utils/urls";
/**
* Performs a redirect on the browser so that the user's auth cookies are
* included in the request. Assigned to the Koa context as `redirectOnClient`.
*
* @param redirectTo the URL to redirect to.
* @param method the HTTP method to use for the redirect. Use POST when
* preventing links in emails from being clicked by bots. Otherwise, use GET.
*/
export function redirectOnClient(
this: Context,
redirectTo: string,
method: "GET" | "POST" = "GET"
) {
const url = addMissingUrlPort(redirectTo);
this.type = "text/html";
if (method === "POST") {
// For POST method, create a form that auto-submits
const urlObj = new URL(url);
const formAction = `${urlObj.origin}${urlObj.pathname}`;
const searchParams = urlObj.searchParams;
let formFields = "";
searchParams.forEach((value, key) => {
formFields += `<input type="hidden" name="${escape(
key
)}" value="${escape(value)}" />`;
});
// Bots are shown a manual submit button instead of auto-submitting, so that
// link scanners in email clients don't follow the redirect.
const isBot = this.userAgent.isBot;
if (isBot) {
formFields += `
<p>If you are not redirected automatically, please click the button below.</p>
<input type="submit" value="Continue" />
`;
}
const script = isBot
? ""
: `<script nonce="${this.state.cspNonce}">
document.getElementById('redirect-form').submit();
</script>`;
this.body = `
<html lang="en">
<head>
<title>Redirecting…</title>
</head>
<body>
<form id="redirect-form" method="POST" action="${formAction}">
${formFields}
</form>
${script}
</body>
</html>`;
} else {
// Default GET method using meta refresh
this.body = `
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL='${escape(url)}'" />
</head>
</html>`;
}
}