diff --git a/apps/login/src/app/(login)/idp/[provider]/success/page.tsx b/apps/login/src/app/(login)/idp/[provider]/success/page.tsx index ae9feff6b..1acf2a39c 100644 --- a/apps/login/src/app/(login)/idp/[provider]/success/page.tsx +++ b/apps/login/src/app/(login)/idp/[provider]/success/page.tsx @@ -51,8 +51,7 @@ async function resolveOrganizationForUser({ serviceUrl, domain: suffix, }); - const orgToCheckForDiscovery = - orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined; + const orgToCheckForDiscovery = orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined; if (orgToCheckForDiscovery) { const orgLoginSettings = await getLoginSettings({ @@ -141,12 +140,7 @@ export default async function Page(props: { } } - return loginSuccess( - userId, - { idpIntentId: id, idpIntentToken: token }, - requestId, - branding, - ); + return loginSuccess(userId, { idpIntentId: id, idpIntentToken: token }, requestId, branding); } if (link) { @@ -174,12 +168,7 @@ export default async function Page(props: { if (!idpLink) { return linkingFailed(branding); } else { - return linkingSuccess( - userId, - { idpIntentId: id, idpIntentToken: token }, - requestId, - branding, - ); + return linkingSuccess(userId, { idpIntentId: id, idpIntentToken: token }, requestId, branding); } } @@ -230,12 +219,7 @@ export default async function Page(props: { if (!idpLink) { return linkingFailed(branding); } else { - return linkingSuccess( - foundUser.userId, - { idpIntentId: id, idpIntentToken: token }, - requestId, - branding, - ); + return linkingSuccess(foundUser.userId, { idpIntentId: id, idpIntentToken: token }, requestId, branding); } } } @@ -260,10 +244,7 @@ export default async function Page(props: { organization: organizationSchema, }); } else { - addHumanUserWithOrganization = create( - AddHumanUserRequestSchema, - addHumanUser, - ); + addHumanUserWithOrganization = create(AddHumanUserRequestSchema, addHumanUser); } try { @@ -272,16 +253,10 @@ export default async function Page(props: { request: addHumanUserWithOrganization, }); } catch (error: unknown) { - console.error( - "An error occurred while creating the user:", - error, - addHumanUser, - ); + console.error("An error occurred while creating the user:", error, addHumanUser); return loginFailed( branding, - (error as ConnectError).message - ? (error as ConnectError).message - : "Could not create user", + (error as ConnectError).message ? (error as ConnectError).message : "Could not create user", ); } } else if (options?.isCreationAllowed) { @@ -325,11 +300,7 @@ export default async function Page(props: {

- + ); diff --git a/apps/login/src/app/(login)/mfa/set/page.tsx b/apps/login/src/app/(login)/mfa/set/page.tsx index 0203ba341..c966a4d88 100644 --- a/apps/login/src/app/(login)/mfa/set/page.tsx +++ b/apps/login/src/app/(login)/mfa/set/page.tsx @@ -22,7 +22,7 @@ import { headers } from "next/headers"; export async function generateMetadata(): Promise { const t = await getTranslations("mfa"); - return { title: t('set.title')}; + return { title: t("set.title") }; } function isSessionValid(session: Partial): { @@ -31,23 +31,19 @@ function isSessionValid(session: Partial): { } { const validPassword = session?.factors?.password?.verifiedAt; const validPasskey = session?.factors?.webAuthN?.verifiedAt; - const stillValid = session.expirationDate - ? timestampDate(session.expirationDate) > new Date() - : true; + const validIDP = session?.factors?.intent?.verifiedAt; + const stillValid = session.expirationDate ? timestampDate(session.expirationDate) > new Date() : true; - const verifiedAt = validPassword || validPasskey; - const valid = !!((validPassword || validPasskey) && stillValid); + const verifiedAt = validPassword || validPasskey || validIDP; + const valid = !!((validPassword || validPasskey || validIDP) && stillValid); return { valid, verifiedAt }; } -export default async function Page(props: { - searchParams: Promise>; -}) { +export default async function Page(props: { searchParams: Promise> }) { const searchParams = await props.searchParams; - const { loginName, checkAfter, force, requestId, organization, sessionId } = - searchParams; + const { loginName, checkAfter, force, requestId, organization, sessionId } = searchParams; const _headers = await headers(); const { serviceUrl } = getServiceUrlFromHeaders(_headers); @@ -68,8 +64,7 @@ export default async function Page(props: { userId, }).then((methods) => { return getUserByID({ serviceUrl, userId }).then((user) => { - const humanUser = - user.user?.type.case === "human" ? user.user?.type.value : undefined; + const humanUser = user.user?.type.case === "human" ? user.user?.type.value : undefined; return { id: session.id, @@ -83,10 +78,7 @@ export default async function Page(props: { }); } - async function loadSessionByLoginname( - loginName?: string, - organization?: string, - ) { + async function loadSessionByLoginname(loginName?: string, organization?: string) { return loadMostRecentSession({ serviceUrl, sessionParams: { @@ -152,24 +144,21 @@ export default async function Page(props: { )} - {isSessionValid(sessionWithData).valid && - loginSettings && - sessionWithData && - sessionWithData.factors?.user?.id && ( - - )} + {valid && loginSettings && sessionWithData && sessionWithData.factors?.user?.id && ( + + )}
diff --git a/apps/login/src/app/(login)/otp/[method]/page.tsx b/apps/login/src/app/(login)/otp/[method]/page.tsx index d39c9ffda..4e8bfe860 100644 --- a/apps/login/src/app/(login)/otp/[method]/page.tsx +++ b/apps/login/src/app/(login)/otp/[method]/page.tsx @@ -4,20 +4,17 @@ import { LoginOTP } from "@/components/login-otp"; import { Translated } from "@/components/translated"; import { UserAvatar } from "@/components/user-avatar"; import { getSessionCookieById } from "@/lib/cookies"; +import { getOriginalHost } from "@/lib/server/host"; import { getServiceUrlFromHeaders } from "@/lib/service-url"; import { loadMostRecentSession } from "@/lib/session"; -import { - getBrandingSettings, - getLoginSettings, - getSession, -} from "@/lib/zitadel"; +import { getBrandingSettings, getLoginSettings, getSession } from "@/lib/zitadel"; import { Metadata } from "next"; import { getTranslations } from "next-intl/server"; import { headers } from "next/headers"; export async function generateMetadata(): Promise { const t = await getTranslations("otp"); - return { title: t('verify.title')}; + return { title: t("verify.title") }; } export default async function Page(props: { @@ -29,11 +26,7 @@ export default async function Page(props: { const _headers = await headers(); const { serviceUrl } = getServiceUrlFromHeaders(_headers); - const host = _headers.get("host"); - - if (!host || typeof host !== "string") { - throw new Error("No host found"); - } + const host = await getOriginalHost(); const { loginName, // send from password page @@ -120,9 +113,7 @@ export default async function Page(props: { loginName={loginName ?? session.factors?.user?.loginName} sessionId={sessionId} requestId={requestId} - organization={ - organization ?? session?.factors?.user?.organizationId - } + organization={organization ?? session?.factors?.user?.organizationId} method={method} loginSettings={loginSettings} host={host} diff --git a/apps/login/src/app/(login)/u2f/page.tsx b/apps/login/src/app/(login)/u2f/page.tsx index 5bf892846..558314e5b 100644 --- a/apps/login/src/app/(login)/u2f/page.tsx +++ b/apps/login/src/app/(login)/u2f/page.tsx @@ -13,23 +13,16 @@ import { headers } from "next/headers"; export async function generateMetadata(): Promise { const t = await getTranslations("u2f"); - return { title: t('verify.title')}; + return { title: t("verify.title") }; } -export default async function Page(props: { - searchParams: Promise>; -}) { +export default async function Page(props: { searchParams: Promise> }) { const searchParams = await props.searchParams; const { loginName, requestId, sessionId, organization } = searchParams; const _headers = await headers(); const { serviceUrl } = getServiceUrlFromHeaders(_headers); - const host = _headers.get("host"); - - if (!host || typeof host !== "string") { - throw new Error("No host found"); - } const branding = await getBrandingSettings({ serviceUrl, @@ -37,17 +30,13 @@ export default async function Page(props: { }); const sessionFactors = sessionId - ? await loadSessionById(serviceUrl, sessionId, organization) + ? await loadSessionById(sessionId, organization) : await loadMostRecentSession({ serviceUrl, sessionParams: { loginName, organization }, }); - async function loadSessionById( - host: string, - sessionId: string, - organization?: string, - ) { + async function loadSessionById(sessionId: string, organization?: string) { const recent = await getSessionCookieById({ sessionId, organization }); return getSession({ serviceUrl, diff --git a/apps/login/src/app/(login)/verify/page.tsx b/apps/login/src/app/(login)/verify/page.tsx index 67166ed37..e1aa91698 100644 --- a/apps/login/src/app/(login)/verify/page.tsx +++ b/apps/login/src/app/(login)/verify/page.tsx @@ -4,6 +4,7 @@ import { Translated } from "@/components/translated"; import { UserAvatar } from "@/components/user-avatar"; import { VerifyForm } from "@/components/verify-form"; import { sendEmailCode, sendInviteEmailCode } from "@/lib/server/verify"; +import { getOriginalHostWithProtocol } from "@/lib/server/host"; import { getServiceUrlFromHeaders } from "@/lib/service-url"; import { loadMostRecentSession } from "@/lib/session"; import { getBrandingSettings, getUserByID } from "@/lib/zitadel"; @@ -14,14 +15,13 @@ import { headers } from "next/headers"; export async function generateMetadata(): Promise { const t = await getTranslations("verify"); - return { title: t('verify.title')}; + return { title: t("verify.title") }; } export default async function Page(props: { searchParams: Promise }) { const searchParams = await props.searchParams; - const { userId, loginName, code, organization, requestId, invite, send } = - searchParams; + const { userId, loginName, code, organization, requestId, invite, send } = searchParams; const _headers = await headers(); const { serviceUrl } = getServiceUrlFromHeaders(_headers); @@ -41,17 +41,13 @@ export default async function Page(props: { searchParams: Promise }) { const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ""; async function sendEmail(userId: string) { - const host = _headers.get("host"); - - if (!host || typeof host !== "string") { - throw new Error("No host found"); - } + const hostWithProtocol = await getOriginalHostWithProtocol(); if (invite === "true") { await sendInviteEmailCode({ userId, urlTemplate: - `${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true` + + `${hostWithProtocol}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true` + (requestId ? `&requestId=${requestId}` : ""), }).catch((error) => { console.error("Could not send invitation email", error); @@ -61,7 +57,7 @@ export default async function Page(props: { searchParams: Promise }) { await sendEmailCode({ userId, urlTemplate: - `${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` + + `${hostWithProtocol}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` + (requestId ? `&requestId=${requestId}` : ""), }).catch((error) => { console.error("Could not send verification email", error); @@ -157,11 +153,7 @@ export default async function Page(props: { searchParams: Promise }) { > ) : ( user && ( - + ) )} diff --git a/apps/login/src/app/login/route.ts b/apps/login/src/app/login/route.ts index 2c1d94746..ed61c43c3 100644 --- a/apps/login/src/app/login/route.ts +++ b/apps/login/src/app/login/route.ts @@ -1,14 +1,7 @@ import { getAllSessions } from "@/lib/cookies"; import { getServiceUrlFromHeaders } from "@/lib/service-url"; -import { - validateAuthRequest, - isRSCRequest -} from "@/lib/auth-utils"; -import { - handleOIDCFlowInitiation, - handleSAMLFlowInitiation, - FlowInitiationParams -} from "@/lib/server/flow-initiation"; +import { validateAuthRequest, isRSCRequest } from "@/lib/auth-utils"; +import { handleOIDCFlowInitiation, handleSAMLFlowInitiation, FlowInitiationParams } from "@/lib/server/flow-initiation"; import { listSessions } from "@/lib/zitadel"; import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb"; import { headers } from "next/headers"; @@ -17,6 +10,8 @@ import { NextRequest, NextResponse } from "next/server"; export const dynamic = "force-dynamic"; export const revalidate = false; export const fetchCache = "default-no-store"; +// Add this to prevent RSC requests +export const runtime = "nodejs"; async function loadSessions({ serviceUrl, ids }: { serviceUrl: string; ids: string[] }): Promise { const response = await listSessions({ @@ -41,10 +36,7 @@ export async function GET(request: NextRequest) { // Early validation: if no valid request parameters, return error immediately const requestId = validateAuthRequest(searchParams); if (!requestId) { - return NextResponse.json( - { error: "No valid authentication request found" }, - { status: 400 }, - ); + return NextResponse.json({ error: "No valid authentication request found" }, { status: 400 }); } const sessionCookies = await getAllSessions(); @@ -69,14 +61,8 @@ export async function GET(request: NextRequest) { return handleSAMLFlowInitiation(flowParams); } else if (requestId.startsWith("device_")) { // Device Authorization does not need to start here as it is handled on the /device endpoint - return NextResponse.json( - { error: "Device authorization should use /device endpoint" }, - { status: 400 } - ); + return NextResponse.json({ error: "Device authorization should use /device endpoint" }, { status: 400 }); } else { - return NextResponse.json( - { error: "Invalid request ID format" }, - { status: 400 } - ); + return NextResponse.json({ error: "Invalid request ID format" }, { status: 400 }); } } diff --git a/apps/login/src/components/idp-signin.tsx b/apps/login/src/components/idp-signin.tsx index a7c938e90..ec7da3fc8 100644 --- a/apps/login/src/components/idp-signin.tsx +++ b/apps/login/src/components/idp-signin.tsx @@ -1,8 +1,8 @@ "use client"; -import { createNewSessionFromIdpIntent } from "@/lib/server/idp"; +import { CreateNewSessionCommand, createNewSessionFromIdpIntent } from "@/lib/server/idp"; import { useRouter } from "next/navigation"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { Alert } from "./alert"; import { Spinner } from "./spinner"; @@ -16,25 +16,33 @@ type Props = { requestId?: string; }; -export function IdpSignin({ - userId, - idpIntent: { idpIntentId, idpIntentToken }, - requestId, -}: Props) { +export function IdpSignin({ userId, idpIntent: { idpIntentId, idpIntentToken }, requestId }: Props) { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const executedRef = useRef(false); const router = useRouter(); useEffect(() => { - createNewSessionFromIdpIntent({ + // Prevent double execution in React Strict Mode + if (executedRef.current) { + return; + } + + executedRef.current = true; + let request: CreateNewSessionCommand = { userId, idpIntent: { idpIntentId, idpIntentToken, }, - requestId, - }) + }; + + if (requestId) { + request = { ...request, requestId: requestId }; + } + + createNewSessionFromIdpIntent(request) .then((response) => { if (response && "error" in response && response?.error) { setError(response?.error); diff --git a/apps/login/src/components/session-item.tsx b/apps/login/src/components/session-item.tsx index 3ae425d0b..c74f52ff1 100644 --- a/apps/login/src/components/session-item.tsx +++ b/apps/login/src/components/session-item.tsx @@ -1,7 +1,7 @@ "use client"; import { sendLoginname } from "@/lib/server/loginname"; -import { clearSession, continueWithSession } from "@/lib/server/session"; +import { clearSession, continueWithSession, ContinueWithSessionCommand } from "@/lib/server/session"; import { XCircleIcon } from "@heroicons/react/24/outline"; import * as Tooltip from "@radix-ui/react-tooltip"; import { Timestamp, timestampDate } from "@zitadel/client"; @@ -21,9 +21,7 @@ export function isSessionValid(session: Partial): { const validPasskey = session?.factors?.webAuthN?.verifiedAt; const validIDP = session?.factors?.intent?.verifiedAt; - const stillValid = session.expirationDate - ? timestampDate(session.expirationDate) > new Date() - : true; + const stillValid = session.expirationDate ? timestampDate(session.expirationDate) > new Date() : true; const verifiedAt = validPassword || validPasskey || validIDP; const valid = !!((validPassword || validPasskey || validIDP) && stillValid); @@ -31,15 +29,7 @@ export function isSessionValid(session: Partial): { return { valid, verifiedAt }; } -export function SessionItem({ - session, - reload, - requestId, -}: { - session: Session; - reload: () => void; - requestId?: string; -}) { +export function SessionItem({ session, reload, requestId }: { session: Session; reload: () => void; requestId?: string }) { const currentLocale = useLocale(); moment.locale(currentLocale === "zh" ? "zh-cn" : currentLocale); @@ -73,10 +63,21 @@ export function SessionItem({