From d2aba1de968e758325337de423b4dc4d0c353c65 Mon Sep 17 00:00:00 2001 From: "codegen-sh[bot]" <131295404+codegen-sh[bot]@users.noreply.github.com> Date: Sat, 17 May 2025 09:06:32 -0400 Subject: [PATCH] feat: Add POST method option to `redirectOnClient` (#9228) * feat: Add POST method option to redirectOnClient helper * Applied automatic fixes * fix: Add missing closing HTML tag in redirectOnClient GET method * fix: Use lodash escape for form field values to prevent XSS * Applied automatic fixes * fix: Add missing lodash/escape import * Applied automatic fixes * fix: Escape all URLs in redirectOnClient function * Update index.ts * fix: CSP * Refactor CSP middleware * docs, only use for email signin --------- Co-authored-by: codegen-sh[bot] <131295404+codegen-sh[bot]@users.noreply.github.com> Co-authored-by: Tom Moor --- plugins/email/server/auth/email.ts | 102 ++++++++++++++-------------- plugins/email/server/auth/schema.ts | 7 +- server/index.ts | 51 ++++++++++++-- server/middlewares/csp.ts | 61 +++++++++++++++++ server/routes/api/users/users.ts | 2 - server/services/web.ts | 67 ++---------------- 6 files changed, 170 insertions(+), 120 deletions(-) create mode 100644 server/middlewares/csp.ts diff --git a/plugins/email/server/auth/email.ts b/plugins/email/server/auth/email.ts index 612396d802..59528b035d 100644 --- a/plugins/email/server/auth/email.ts +++ b/plugins/email/server/auth/email.ts @@ -1,5 +1,5 @@ import Router from "koa-router"; -import { NotificationEventType } from "@shared/types"; +import { Client, NotificationEventType } from "@shared/types"; import { parseDomain } from "@shared/utils/domains"; import InviteAcceptedEmail from "@server/emails/templates/InviteAcceptedEmail"; import SigninEmail from "@server/emails/templates/SigninEmail"; @@ -86,66 +86,64 @@ router.post( } ); -router.get( - "email.callback", - validate(T.EmailCallbackSchema), - async (ctx: APIContext) => { - const { token, client, follow } = ctx.input.query; +const emailCallback = async (ctx: APIContext) => { + const token = ctx.input.query?.token || ctx.input.body?.token; + const client = ctx.input.query?.client || ctx.input.body?.client; + const follow = ctx.input.query?.follow || ctx.input.body?.follow; - // The link in the email does not include the follow query param, this - // is to help prevent anti-virus, and email clients from pre-fetching the link - // and spending the token before the user clicks on it. Instead we redirect - // to the same URL with the follow query param added from the client side. - if (!follow) { - return ctx.redirectOnClient(ctx.request.href + "&follow=true"); - } + // The link in the email does not include the follow query param, this + // is to help prevent anti-virus, and email clients from pre-fetching the link + // and spending the token before the user clicks on it. Instead we redirect + // to the same URL with the follow query param added from the client side. + if (!follow) { + return ctx.redirectOnClient(ctx.request.href + "&follow=true", "POST"); + } - let user!: User; + let user!: User; - try { - user = await getUserForEmailSigninToken(token as string); - } catch (err) { - ctx.redirect(`/?notice=expired-token`); - return; - } + try { + user = await getUserForEmailSigninToken(token as string); + } catch (err) { + ctx.redirect(`/?notice=expired-token`); + return; + } - if (!user.team.emailSigninEnabled) { - return ctx.redirect("/?notice=auth-error"); - } + if (!user.team.emailSigninEnabled) { + return ctx.redirect("/?notice=auth-error"); + } - if (user.isSuspended) { - return ctx.redirect("/?notice=user-suspended"); - } + if (user.isSuspended) { + return ctx.redirect("/?notice=user-suspended"); + } - if (user.isInvited) { - await new WelcomeEmail({ - to: user.email, - role: user.role, + if (user.isInvited) { + await new WelcomeEmail({ + to: user.email, + role: user.role, + teamUrl: user.team.url, + }).schedule(); + + const inviter = await user.$get("invitedBy"); + if (inviter?.subscribedToEventType(NotificationEventType.InviteAccepted)) { + await new InviteAcceptedEmail({ + to: inviter.email, + inviterId: inviter.id, + invitedName: user.name, teamUrl: user.team.url, }).schedule(); - - const inviter = await user.$get("invitedBy"); - if ( - inviter?.subscribedToEventType(NotificationEventType.InviteAccepted) - ) { - await new InviteAcceptedEmail({ - to: inviter.email, - inviterId: inviter.id, - invitedName: user.name, - teamUrl: user.team.url, - }).schedule(); - } } - - // set cookies on response and redirect to team subdomain - await signIn(ctx, "email", { - user, - team: user.team, - isNewTeam: false, - isNewUser: false, - client, - }); } -); + + // set cookies on response and redirect to team subdomain + await signIn(ctx, "email", { + user, + team: user.team, + isNewTeam: false, + isNewUser: false, + client: client ?? Client.Web, + }); +}; +router.get("email.callback", validate(T.EmailCallbackSchema), emailCallback); +router.post("email.callback", validate(T.EmailCallbackSchema), emailCallback); export default router; diff --git a/plugins/email/server/auth/schema.ts b/plugins/email/server/auth/schema.ts index 9412f7dd97..e20ccc88f2 100644 --- a/plugins/email/server/auth/schema.ts +++ b/plugins/email/server/auth/schema.ts @@ -13,7 +13,12 @@ export type EmailReq = z.infer; export const EmailCallbackSchema = BaseSchema.extend({ query: z.object({ - token: z.string(), + token: z.string().optional(), + client: z.nativeEnum(Client).default(Client.Web), + follow: z.string().default(""), + }), + body: z.object({ + token: z.string().optional(), client: z.nativeEnum(Client).default(Client.Web), follow: z.string().default(""), }), diff --git a/server/index.ts b/server/index.ts index 3b8ba88967..45e435322c 100644 --- a/server/index.ts +++ b/server/index.ts @@ -13,6 +13,7 @@ import Router from "koa-router"; import { AddressInfo } from "net"; import stoppable from "stoppable"; import throng from "throng"; +import escape from "lodash/escape"; import Logger from "./logging/Logger"; import services from "./services"; import { getArg } from "./utils/args"; @@ -88,13 +89,53 @@ async function start(_id: number, disconnect: () => void) { app.use(defaultRateLimiter()); /** Perform a redirect on the browser so that the user's auth cookies are included in the request. */ - app.context.redirectOnClient = function (url: string) { + app.context.redirectOnClient = function ( + /** The URL to redirect to */ + url: string, + /** + * The HTTP method to use for the redirect. Use POST when preventing links in emails from being + * clicked by bots. Otherwise, use GET. + */ + method: "GET" | "POST" = "GET" + ) { this.type = "text/html"; - this.body = ` + + 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 += ``; + }); + + this.body = ` - -`; + Redirecting… + + +
+ ${formFields} +
+ + +`; + } else { + // Default GET method using meta refresh + this.body = ` + + + + +`; + } }; // Add a health check endpoint to all services @@ -133,7 +174,7 @@ async function start(_id: number, disconnect: () => void) { server.on("error", (err) => { if ("code" in err && err.code === "EADDRINUSE") { - Logger.error(`Port ${normalizedPort} is already in use. Exiting…`, err); + Logger.error(`Port ${normalizedPort} is already in use. Exiting…`, err); process.exit(0); } diff --git a/server/middlewares/csp.ts b/server/middlewares/csp.ts new file mode 100644 index 0000000000..410e6fa719 --- /dev/null +++ b/server/middlewares/csp.ts @@ -0,0 +1,61 @@ +import crypto from "crypto"; +import { Context, Next } from "koa"; +import { contentSecurityPolicy } from "koa-helmet"; +import uniq from "lodash/uniq"; +import env from "@server/env"; + +/** + * Create a Content Security Policy middleware for the application. + */ +export default function createCSPMiddleware() { + // Construct scripts CSP based on options in use + const defaultSrc = ["'self'"]; + const scriptSrc = ["'self'"]; + const styleSrc = ["'self'", "'unsafe-inline'"]; + + if (env.isCloudHosted) { + scriptSrc.push("www.googletagmanager.com"); + scriptSrc.push("cdn.zapier.com"); + styleSrc.push("cdn.zapier.com"); + } + + // Allow to load assets from Vite + if (!env.isProduction) { + scriptSrc.push(env.URL.replace(`:${env.PORT}`, ":3001")); + scriptSrc.push("localhost:3001"); + } + + if (env.GOOGLE_ANALYTICS_ID) { + scriptSrc.push("www.googletagmanager.com"); + scriptSrc.push("www.google-analytics.com"); + } + + if (env.CDN_URL) { + scriptSrc.push(env.CDN_URL); + styleSrc.push(env.CDN_URL); + defaultSrc.push(env.CDN_URL); + } + + return function cspMiddleware(ctx: Context, next: Next) { + ctx.state.cspNonce = crypto.randomBytes(16).toString("hex"); + + return contentSecurityPolicy({ + directives: { + defaultSrc, + styleSrc, + scriptSrc: [ + ...uniq(scriptSrc), + env.DEVELOPMENT_UNSAFE_INLINE_CSP + ? "'unsafe-inline'" + : `'nonce-${ctx.state.cspNonce}'`, + ], + mediaSrc: ["*", "data:", "blob:"], + imgSrc: ["*", "data:", "blob:"], + frameSrc: ["*", "data:"], + // Do not use connect-src: because self + websockets does not work in + // Safari, ref: https://bugs.webkit.org/show_bug.cgi?id=201591 + connectSrc: ["*"], + }, + })(ctx, next); + }; +} diff --git a/server/routes/api/users/users.ts b/server/routes/api/users/users.ts index e6ca3ff4ee..07fdb33e16 100644 --- a/server/routes/api/users/users.ts +++ b/server/routes/api/users/users.ts @@ -260,8 +260,6 @@ router.get( // The link in the email does not include the follow query param, this // is to help prevent anti-virus, and email clients from pre-fetching the link - // and spending the token before the user clicks on it. Instead we redirect - // to the same URL with the follow query param added from the client side. if (!follow) { return ctx.redirectOnClient(ctx.request.href + "&follow=true"); } diff --git a/server/services/web.ts b/server/services/web.ts index f75eeb5700..f978652d48 100644 --- a/server/services/web.ts +++ b/server/services/web.ts @@ -1,13 +1,8 @@ /* eslint-disable @typescript-eslint/no-var-requires */ -import crypto from "crypto"; import { Server } from "https"; import Koa from "koa"; import compress from "koa-compress"; -import { - contentSecurityPolicy, - dnsPrefetchControl, - referrerPolicy, -} from "koa-helmet"; +import { dnsPrefetchControl, referrerPolicy } from "koa-helmet"; import mount from "koa-mount"; import enforceHttps, { httpsResolver, @@ -17,6 +12,7 @@ import { Second } from "@shared/utils/time"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; +import csp from "@server/middlewares/csp"; import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; import { initI18n } from "@server/utils/i18n"; import routes from "../routes"; @@ -24,32 +20,6 @@ import api from "../routes/api"; import auth from "../routes/auth"; import oauth from "../routes/oauth"; -// Construct scripts CSP based on services in use by this installation -const defaultSrc = ["'self'"]; -const scriptSrc = ["'self'", "www.googletagmanager.com"]; -const styleSrc = ["'self'", "'unsafe-inline'"]; - -if (env.isCloudHosted) { - scriptSrc.push("cdn.zapier.com"); - styleSrc.push("cdn.zapier.com"); -} - -// Allow to load assets from Vite -if (!env.isProduction) { - scriptSrc.push(env.URL.replace(`:${env.PORT}`, ":3001")); - scriptSrc.push("localhost:3001"); -} - -if (env.GOOGLE_ANALYTICS_ID) { - scriptSrc.push("www.google-analytics.com"); -} - -if (env.CDN_URL) { - scriptSrc.push(env.CDN_URL); - styleSrc.push(env.CDN_URL); - defaultSrc.push(env.CDN_URL); -} - export default function init(app: Koa = new Koa(), server?: Server) { void initI18n(); @@ -76,10 +46,6 @@ export default function init(app: Koa = new Koa(), server?: Server) { app.use(compress()); - app.use(mount("/oauth", oauth)); - app.use(mount("/auth", auth)); - app.use(mount("/api", api)); - // Monitor server connections if (server) { setInterval(() => { @@ -96,31 +62,10 @@ export default function init(app: Koa = new Koa(), server?: Server) { Metrics.gaugePerInstance("connections.count", 0); }); - // Sets common security headers by default, such as no-sniff, hsts, hide powered - // by etc, these are applied after auth and api so they are only returned on - // standard non-XHR accessed routes - app.use((ctx, next) => { - ctx.state.cspNonce = crypto.randomBytes(16).toString("hex"); + app.use(mount("/api", api)); - return contentSecurityPolicy({ - directives: { - defaultSrc, - styleSrc, - scriptSrc: [ - ...scriptSrc, - env.DEVELOPMENT_UNSAFE_INLINE_CSP - ? "'unsafe-inline'" - : `'nonce-${ctx.state.cspNonce}'`, - ], - mediaSrc: ["*", "data:", "blob:"], - imgSrc: ["*", "data:", "blob:"], - frameSrc: ["*", "data:"], - // Do not use connect-src: because self + websockets does not work in - // Safari, ref: https://bugs.webkit.org/show_bug.cgi?id=201591 - connectSrc: ["*"], - }, - })(ctx, next); - }); + // Apply CSP middleware after API as these responses are rendered in the browser + app.use(csp()); // Allow DNS prefetching for performance, we do not care about leaking requests // to our own CDN's @@ -135,6 +80,8 @@ export default function init(app: Koa = new Koa(), server?: Server) { }) ); + app.use(mount("/oauth", oauth)); + app.use(mount("/auth", auth)); app.use(mount(routes)); return app;