Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(auth): notification email links land on the home page (#1815)

Naveen Kashyap5a0fb8ffc397
diff --git a/.ai/lessons.md b/.ai/lessons.md
index ba0eb2c5d4..873dd16d4c 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2867,3 +2867,14 @@ tag until proven otherwise.
**Rule:** When a slot frees and a call is queued, pass the slot to it directly and leave the count unchanged; decrement only when the queue is empty. A queued call never increments. Test it by starting a new call in the same tick a running one finishes and asserting the queued one runs first.
**Applies to:** `packages/utils/src/async.ts` (`limit`), any hand-written semaphore.
+
+
+## "Come back here" must carry the query string
+
+**Context:** Notification emails link to `/api/link?event=…&documentId=…&companyId=…`, and `requireAuthSession` sends a request away and back for a token refresh, login, MFA or idle unlock.
+
+**Problem:** `getCurrentPath` returned `pathname` only, so every one of those round trips came back to a bare `/api/link`, which has nothing to resolve and redirects to the home page. The link itself was correct, and it worked on a second click (the token was fresh by then), so it read as an email bug. The token-refresh branch hit anyone idle for longer than the refresh threshold, which is the normal state of someone arriving from an email.
+
+**Rule:** A "return to where you were" target is `pathname + search`, never `pathname`. When it is passed on inside another URL, encode it (`encodeURIComponent` / `URLSearchParams`), or its own `&` splits it. Test the round trip with a URL that has a query string. Drop React Router's `_routes` param from it, and only when present: middleware sees that param (loaders do not), a page URL that carries it limits which loaders later data requests run, and `searchParams.delete` re-encodes the whole query even when it removes nothing. Whatever sends the target on must be matched by something that reads it: three of the four callbacks ignored the `redirectTo` their login page sent.
+
+**Applies to:** `packages/auth/src/utils/http.ts` (`getCurrentPath`, `makeRedirectToFromHere`), `requireAuthSession` / `refreshAuthSession`, every app's `login.tsx` callback URL and the `callback.tsx` that consumes it.
diff --git a/apps/academy/app/routes/_auth+/callback.tsx b/apps/academy/app/routes/_auth+/callback.tsx
index 9d78714b69..8a5353ec64 100644
--- a/apps/academy/app/routes/_auth+/callback.tsx
+++ b/apps/academy/app/routes/_auth+/callback.tsx
@@ -6,7 +6,8 @@ import {
assertIsPost,
callbackValidator,
carbonClient,
- error
+ error,
+ safeRedirect
} from "@carbon/auth";
import { refreshAccessToken } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
@@ -30,7 +31,14 @@ import {
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, Link, redirect, useFetcher, useLocation } from "react-router";
+import {
+ data,
+ Link,
+ redirect,
+ useFetcher,
+ useLocation,
+ useSearchParams
+} from "react-router";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
@@ -54,7 +62,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
- const { refreshToken, userId } = validation.data;
+ const { refreshToken, userId, redirectTo } = validation.data;
const serviceRole = getCarbonServiceRole();
const companies = await serviceRole
.from("userToCompany")
@@ -87,7 +95,7 @@ export async function action({ request }: ActionFunctionArgs) {
authSession
});
const companyIdCookie = setCompanyId(authSession.companyId);
- return redirect(path.to.root, {
+ return redirect(safeRedirect(redirectTo, path.to.root), {
headers: [
["Set-Cookie", sessionCookie],
["Set-Cookie", companyIdCookie]
@@ -107,6 +115,8 @@ export default function AuthCallback() {
const [error, setError] = useState<string | null>(null);
const { hash } = useLocation();
+ const [searchParams] = useSearchParams();
+ const redirectTo = searchParams.get("redirectTo") ?? undefined;
useEffect(() => {
const hashParams = new URLSearchParams(hash.slice(1));
@@ -134,6 +144,7 @@ export default function AuthCallback() {
const formData = new FormData();
formData.append("refreshToken", refreshToken);
formData.append("userId", userId);
+ if (redirectTo) formData.append("redirectTo", redirectTo);
fetcher.submit(formData, { method: "post" });
}
@@ -142,7 +153,7 @@ export default function AuthCallback() {
return () => {
subscription.unsubscribe();
};
- }, [fetcher]);
+ }, [fetcher, redirectTo]);
return (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-background">
diff --git a/apps/academy/app/routes/_auth+/login.tsx b/apps/academy/app/routes/_auth+/login.tsx
index 66c2b40623..10e428ef03 100644
--- a/apps/academy/app/routes/_auth+/login.tsx
+++ b/apps/academy/app/routes/_auth+/login.tsx
@@ -144,7 +144,7 @@ export default function LoginRoute() {
provider: "google",
options: {
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
@@ -160,7 +160,7 @@ export default function LoginRoute() {
options: {
scopes: "email",
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index 5bdc465420..06aa68411e 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -454,7 +454,7 @@ export default function LoginRoute() {
provider: "google",
options: {
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
@@ -470,7 +470,7 @@ export default function LoginRoute() {
options: {
scopes: "email",
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
@@ -522,7 +522,7 @@ export default function LoginRoute() {
domain,
options: {
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
diff --git a/apps/mes/app/routes/_public+/callback.tsx b/apps/mes/app/routes/_public+/callback.tsx
index 1a702d607b..dc368141c4 100644
--- a/apps/mes/app/routes/_public+/callback.tsx
+++ b/apps/mes/app/routes/_public+/callback.tsx
@@ -6,7 +6,8 @@ import {
assertIsPost,
callbackValidator,
carbonClient,
- error
+ error,
+ safeRedirect
} from "@carbon/auth";
import { refreshAccessToken } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
@@ -45,7 +46,14 @@ import { Trans } from "@lingui/react/macro";
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, Link, redirect, useFetcher, useLocation } from "react-router";
+import {
+ data,
+ Link,
+ redirect,
+ useFetcher,
+ useLocation,
+ useSearchParams
+} from "react-router";
import { path } from "~/utils/path";
const logger = getLogger("mes", "callback");
@@ -71,7 +79,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
- const { refreshToken, userId } = validation.data;
+ const { refreshToken, userId, redirectTo } = validation.data;
const serviceRole = getCarbonServiceRole();
const companies = await serviceRole
.from("userToCompany")
@@ -190,7 +198,7 @@ export async function action({ request }: ActionFunctionArgs) {
authSession.mfaVerified = true;
const ssoSessionCookie = await setAuthSession(request, { authSession });
- return redirect(path.to.authenticatedRoot, {
+ return redirect(safeRedirect(redirectTo, path.to.authenticatedRoot), {
headers: [
["Set-Cookie", ssoSessionCookie],
["Set-Cookie", setCompanyId(ssoCompanyId)]
@@ -260,7 +268,8 @@ export async function action({ request }: ActionFunctionArgs) {
// any full session cookie exists. The /mfa action mints the real session.
if (await userHasVerifiedTotpFactor(authSession.userId)) {
const pendingCookie = await setPendingMfaSession(request, {
- authSession
+ authSession,
+ redirectTo
});
return redirect(path.to.mfa, {
headers: [["Set-Cookie", pendingCookie]]
@@ -271,7 +280,7 @@ export async function action({ request }: ActionFunctionArgs) {
authSession
});
const companyIdCookie = setCompanyId(authSession.companyId);
- return redirect(path.to.authenticatedRoot, {
+ return redirect(safeRedirect(redirectTo, path.to.authenticatedRoot), {
headers: [
["Set-Cookie", sessionCookie],
["Set-Cookie", companyIdCookie]
@@ -291,6 +300,8 @@ export default function AuthCallback() {
const [error, setError] = useState<string | null>(null);
const { hash } = useLocation();
+ const [searchParams] = useSearchParams();
+ const redirectTo = searchParams.get("redirectTo") ?? undefined;
useEffect(() => {
const hashParams = new URLSearchParams(hash.slice(1));
@@ -318,6 +329,7 @@ export default function AuthCallback() {
const formData = new FormData();
formData.append("refreshToken", refreshToken);
formData.append("userId", userId);
+ if (redirectTo) formData.append("redirectTo", redirectTo);
fetcher.submit(formData, { method: "post" });
}
@@ -326,7 +338,7 @@ export default function AuthCallback() {
return () => {
subscription.unsubscribe();
};
- }, [fetcher]);
+ }, [fetcher, redirectTo]);
return (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-background">
diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsx
index 34c79f36da..d6cf34893e 100644
--- a/apps/mes/app/routes/_public+/login.tsx
+++ b/apps/mes/app/routes/_public+/login.tsx
@@ -371,7 +371,7 @@ export default function LoginRoute() {
provider: "google",
options: {
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
@@ -387,7 +387,7 @@ export default function LoginRoute() {
options: {
scopes: "email",
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
@@ -439,7 +439,7 @@ export default function LoginRoute() {
domain,
options: {
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
diff --git a/apps/starter/app/routes/_public+/callback.tsx b/apps/starter/app/routes/_public+/callback.tsx
index b1b043c3ae..1d26708428 100644
--- a/apps/starter/app/routes/_public+/callback.tsx
+++ b/apps/starter/app/routes/_public+/callback.tsx
@@ -6,7 +6,8 @@ import {
assertIsPost,
callbackValidator,
carbonClient,
- error
+ error,
+ safeRedirect
} from "@carbon/auth";
import { refreshAccessToken } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
@@ -30,7 +31,14 @@ import {
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, Link, redirect, useFetcher, useLocation } from "react-router";
+import {
+ data,
+ Link,
+ redirect,
+ useFetcher,
+ useLocation,
+ useSearchParams
+} from "react-router";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
@@ -54,7 +62,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
- const { refreshToken, userId } = validation.data;
+ const { refreshToken, userId, redirectTo } = validation.data;
const serviceRole = getCarbonServiceRole();
const companies = await serviceRole
.from("userToCompany")
@@ -87,7 +95,7 @@ export async function action({ request }: ActionFunctionArgs) {
authSession
});
const companyIdCookie = setCompanyId(authSession.companyId);
- return redirect(path.to.authenticatedRoot, {
+ return redirect(safeRedirect(redirectTo, path.to.authenticatedRoot), {
headers: [
["Set-Cookie", sessionCookie],
["Set-Cookie", companyIdCookie]
@@ -107,6 +115,8 @@ export default function AuthCallback() {
const [error, setError] = useState<string | null>(null);
const { hash } = useLocation();
+ const [searchParams] = useSearchParams();
+ const redirectTo = searchParams.get("redirectTo") ?? undefined;
useEffect(() => {
const hashParams = new URLSearchParams(hash.slice(1));
@@ -134,6 +144,7 @@ export default function AuthCallback() {
const formData = new FormData();
formData.append("refreshToken", refreshToken);
formData.append("userId", userId);
+ if (redirectTo) formData.append("redirectTo", redirectTo);
fetcher.submit(formData, { method: "post" });
}
@@ -142,7 +153,7 @@ export default function AuthCallback() {
return () => {
subscription.unsubscribe();
};
- }, [fetcher]);
+ }, [fetcher, redirectTo]);
return (
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-background">
diff --git a/apps/starter/app/routes/_public+/login.tsx b/apps/starter/app/routes/_public+/login.tsx
index 1a8c51f266..b9eff2e3b4 100644
--- a/apps/starter/app/routes/_public+/login.tsx
+++ b/apps/starter/app/routes/_public+/login.tsx
@@ -144,7 +144,7 @@ export default function LoginRoute() {
provider: "google",
options: {
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
@@ -160,7 +160,7 @@ export default function LoginRoute() {
options: {
scopes: "email",
redirectTo: `${window.location.origin}/callback${
- redirectTo ? `?redirectTo=${redirectTo}` : ""
+ redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""
}`
}
});
diff --git a/packages/auth/src/services/session-timeout.test.ts b/packages/auth/src/services/session-timeout.test.ts
index f59939e637..2312a47494 100644
--- a/packages/auth/src/services/session-timeout.test.ts
+++ b/packages/auth/src/services/session-timeout.test.ts
@@ -54,10 +54,12 @@ vi.mock("./users", () => ({
import type { AuthSession } from "../types";
import { refreshAccessToken } from "./auth.server";
+import { userHasVerifiedTotpFactor } from "./mfa.server";
import {
isSessionExpiredAbsolute,
isSessionIdleLocked,
refreshAuthSession,
+ requireAuthSession,
setAuthSession
} from "./session.server";
@@ -174,3 +176,83 @@ describe("refreshAuthSession preserves session-age clocks", () => {
expect(isSessionIdleLocked(refreshed)).toBe(false);
});
});
+
+// A request that has to leave for a token refresh, login or MFA challenge must
+// come back to the URL it asked for, query string included. A notification
+// email links to `/api/link?event=…&documentId=…`, and returning to the bare
+// path lands on the home page.
+describe("requireAuthSession returns to the requested URL", () => {
+ const EMAIL_LINK =
+ "/api/link?event=approval-requested&documentId=po_1&companyId=co_1&documentType=purchaseOrder";
+ const ORIGIN = "http://localhost:3000";
+
+ const redirectOf = async (request: Request) => {
+ try {
+ await requireAuthSession(request);
+ } catch (thrown) {
+ return thrown as Response;
+ }
+ throw new Error("requireAuthSession did not redirect");
+ };
+
+ const redirectToOf = (response: Response) =>
+ new URL(response.headers.get("Location") ?? "", ORIGIN).searchParams.get(
+ "redirectTo"
+ );
+
+ const sessionCookie = async (overrides: Partial<AuthSession> = {}) =>
+ setAuthSession(new Request(`${ORIGIN}/x`), {
+ authSession: makeSession(overrides)
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-17T12:00:00Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ vi.mocked(userHasVerifiedTotpFactor).mockResolvedValue(false);
+ });
+
+ it("after a token refresh", async () => {
+ // Thirty seconds left, inside the refresh threshold.
+ const cookie = await sessionCookie({
+ expiresAt: Math.floor(Date.now() / 1000) + 30
+ });
+ vi.mocked(refreshAccessToken).mockResolvedValue(makeSession());
+
+ const response = await redirectOf(
+ requestWithCookie(cookie, {
+ method: "GET",
+ url: `${ORIGIN}${EMAIL_LINK}`
+ })
+ );
+
+ expect(response.headers.get("Location")).toBe(EMAIL_LINK);
+ expect(response.headers.get("Set-Cookie")).toContain("carbon=");
+ });
+
+ it("after a login, when there is no session", async () => {
+ const response = await redirectOf(new Request(`${ORIGIN}${EMAIL_LINK}`));
+
+ expect(response.headers.get("Location")).toMatch(/^\/login\?/);
+ expect(redirectToOf(response)).toBe(EMAIL_LINK);
+ });
+
+ it("after an MFA challenge", async () => {
+ const cookie = await sessionCookie();
+ vi.mocked(userHasVerifiedTotpFactor).mockResolvedValue(true);
+
+ const response = await redirectOf(
+ requestWithCookie(cookie, {
+ method: "GET",
+ url: `${ORIGIN}${EMAIL_LINK}`
+ })
+ );
+
+ expect(response.headers.get("Location")).toMatch(/^\/mfa\?/);
+ expect(redirectToOf(response)).toBe(EMAIL_LINK);
+ });
+});
diff --git a/packages/auth/src/utils/http.test.ts b/packages/auth/src/utils/http.test.ts
index 27834ef146..1a271931e5 100644
--- a/packages/auth/src/utils/http.test.ts
+++ b/packages/auth/src/utils/http.test.ts
@@ -3,7 +3,54 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { describe, expect, it } from "vitest";
-import { safeRedirect } from "./http";
+import { getCurrentPath, makeRedirectToFromHere, safeRedirect } from "./http";
+
+// The link a notification email carries (see buildNotificationLink).
+const emailLink =
+ "/api/link?event=approval-requested&documentId=po_1&companyId=co_1&documentType=purchaseOrder";
+
+describe("getCurrentPath", () => {
+ it("keeps the query string", () => {
+ expect(
+ getCurrentPath(new Request(`https://app.carbon.ms${emailLink}`))
+ ).toBe(emailLink);
+ });
+
+ it("returns a bare path unchanged", () => {
+ expect(getCurrentPath(new Request("https://app.carbon.ms/x/parts"))).toBe(
+ "/x/parts"
+ );
+ });
+
+ it("leaves a query without the single-fetch param byte for byte", () => {
+ const filtered = "/x/parts?filter=status:in:[open,late]&index";
+
+ expect(
+ getCurrentPath(new Request(`https://app.carbon.ms${filtered}`))
+ ).toBe(filtered);
+ });
+
+ it("drops React Router's single-fetch param", () => {
+ expect(
+ getCurrentPath(
+ new Request("https://app.carbon.ms/x/parts?tab=open&_routes=root")
+ )
+ ).toBe("/x/parts?tab=open");
+ });
+});
+
+describe("makeRedirectToFromHere", () => {
+ it("round-trips a URL with a query string through redirectTo", () => {
+ const params = makeRedirectToFromHere(
+ new Request(`https://app.carbon.ms${emailLink}`)
+ );
+ const login = new URL(`https://app.carbon.ms/login?${params}`);
+
+ expect(safeRedirect(login.searchParams.get("redirectTo"), "/x")).toBe(
+ emailLink
+ );
+ });
+});
describe("safeRedirect", () => {
it("keeps a same-origin path", () => {
diff --git a/packages/auth/src/utils/http.ts b/packages/auth/src/utils/http.ts
index 4dcf8435bc..1f51002feb 100644
--- a/packages/auth/src/utils/http.ts
+++ b/packages/auth/src/utils/http.ts
@@ -8,7 +8,14 @@ import { path } from "./path";
const log = getLogger("auth");
export function getCurrentPath(request: Request) {
- return new URL(request.url).pathname;
+ const url = new URL(request.url);
+ // `_routes` is React Router's single-fetch transport param. Loaders never
+ // see it, but middleware does (MES runs auth there), and a page URL that
+ // carries it limits which loaders later data requests run. Only when it is
+ // present: `delete` re-encodes the whole query (`a:b` to `a%3Ab`, `?index`
+ // to `?index=`), and every other URL should come back exactly as it was.
+ if (url.searchParams.has("_routes")) url.searchParams.delete("_routes");
+ return `${url.pathname}${url.search}`;
}
export function makeRedirectToFromHere(request: Request) {