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 <tom@getoutline.com>
This commit is contained in:
codegen-sh[bot]andTom Moor authored and GitHub committed 2025-05-17 09:06:32 -04:00
1 parent 052924d816
commit d2aba1de96
6 files changed
+170 -120

No files matched your search

+50 -52
View File
@@ -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<T.EmailCallbackReq>) => {
const { token, client, follow } = ctx.input.query;
const emailCallback = async (ctx: APIContext<T.EmailCallbackReq>) => {
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;
+6 -1
View File
@@ -13,7 +13,12 @@ export type EmailReq = z.infer<typeof EmailSchema>;
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(""),
}),
+46 -5
View File
@@ -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 += `<input type="hidden" name="${escape(
key
)}" value="${escape(value)}" />`;
});
this.body = `
<html>
<head>
<meta http-equiv="refresh" content="0;URL='${url}'"/>
</head>`;
<title>Redirecting…</title>
</head>
<body>
<form id="redirect-form" method="POST" action="${formAction}">
${formFields}
</form>
<script nonce="${this.state.cspNonce}">
document.getElementById('redirect-form').submit();
</script>
</body>
</html>`;
} else {
// Default GET method using meta refresh
this.body = `
<html>
<head>
<meta http-equiv="refresh" content="0;URL='${escape(url)}'" />
</head>
</html>`;
}
};
// 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);
}
+61
View File
@@ -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);
};
}
-2
View File
@@ -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");
}
+7 -60
View File
@@ -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;