import { escape } from "es-toolkit/compat"; import { isbot } from "isbot"; import { addMissingUrlPort } from "@shared/utils/urls"; import type { AppContext } from "@server/types"; /** * 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: AppContext, 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 += ``; }); // 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 += `

If you are not redirected automatically, please click the button below.

`; } const script = isBot ? "" : ``; this.body = ` Redirecting…
${formFields}
${script} `; } else { // Default GET method using meta refresh this.body = ` `; } }