Files
outline/server/utils/redirectOnClient.ts
Tom Moor 25eac11a6c perf: Render share page content without the export lock and cache it (#14284)
* perf: Render share page content without the export lock and cache it

* perf: Render share page content only for bots, detect bots with isbot

Browsers never read the server-rendered share content, so skip the render
for them. Replace the koa-useragent isBot check with the isbot package,
which also detects AI crawlers, and add a lint rule against isBot.
2026-11-01 08:05:55 -05:00

74 lines
2.0 KiB
TypeScript

import { escape } from "es-toolkit/compat";
import { isbot } from "isbot";
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 = isbot(this.get("user-agent"));
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>`;
}
}