chore(login): Extract auth flow utilities and eliminate RSC request interference (#10644)

The /login route was experiencing issues with React Server Component
(RSC) requests interfering with one-time authentication callbacks. When
users navigated to /login via client-side routing (router.push()),
Next.js automatically triggered _rsc requests that could consume
single-use createCallback tokens, breaking OIDC and SAML authentication
flows.

# Which Problems Are Solved

When users attempt to log in, Next.js automatically makes requests with
the `_rsc=1` query parameter for React Server Components. The current
implementation treats these as server errors:

```typescript
// Before
if (_rsc) {
  return NextResponse.json({ error: "No _rsc supported" }, { status: 500 });
}
```

This results in:
- Spurious 500 error logs polluting monitoring systems
- False alerts for server failures 
- Difficulty distinguishing real issues from benign RSC requests

# How the Problems Are Solved

This PR implements a comprehensive refactoring that:

- Eliminates RSC interference by providing server actions for internal
auth flow completion
- Separates concerns between external flow initiation and internal flow
completion
- Extracts shared utilities to improve code maintainability and
reusability
- Maintains full backward compatibility for external applications

# Additional Context

## New Architecture
- auth-flow.ts: Shared utilities for auth flow completion with RSC
protection
- flow-initiation.ts: Extracted OIDC/SAML flow initiation logic (~400
lines)
- auth.ts: Server actions for internal components

## Route Handler Simplification
- route.ts: Reduced from ~350 lines to ~75 lines
- External-only focus: Now handles only flow initiation for external
applications
- Removed completion logic: External apps use their own callback URLs
- Enhanced validation: Early RSC blocking and parameter validation

## Flow Logic Improvements
- Early return patterns: Guard clauses eliminate deep nesting
- Better error handling: Specific error messages for different failure
modes
- Fixed SAML flow: Addressed incomplete logic
- Consistent session handling: Unified approach across OIDC and SAML
This commit is contained in:
Max Peintner
2025-09-22 16:09:20 +00:00
committed by GitHub
parent 0a31f4ba2b
commit 637b370c17
23 changed files with 1334 additions and 1146 deletions
+26 -49
View File
@@ -18,17 +18,10 @@ import {
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { headers } from "next/headers";
import { userAgent } from "next/server";
import { getNextUrl } from "../client";
import {
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
} from "../cookies";
import { completeFlowOrGetUrl } from "../client";
import { getMostRecentSessionCookie, getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
import { getServiceUrlFromHeaders } from "../service-url";
import {
checkEmailVerification,
checkUserVerification,
} from "../verify-helper";
import { checkEmailVerification, checkUserVerification } from "../verify-helper";
import { setSessionAndUpdateCookie } from "./cookie";
type VerifyPasskeyCommand = {
@@ -48,9 +41,7 @@ function isSessionValid(session: Partial<Session>): {
} {
const validPassword = session?.factors?.password?.verifiedAt;
const validPasskey = session?.factors?.webAuthN?.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;
const valid = !!((validPassword || validPasskey) && stillValid);
@@ -93,15 +84,12 @@ export async function registerPasskeyLink(
// if the user has no authmethods set, we need to check if the user was verified
if (authmethods.authMethodTypes.length !== 0) {
return {
error:
"You have to authenticate or have a valid User Verification Check",
error: "You have to authenticate or have a valid User Verification Check",
};
}
// check if a verification was done earlier
const hasValidUserVerificationCheck = await checkUserVerification(
session.session.factors.user.id,
);
const hasValidUserVerificationCheck = await checkUserVerification(session.session.factors.user.id);
if (!hasValidUserVerificationCheck) {
return { error: "User Verification Check has to be done" };
@@ -246,41 +234,30 @@ export async function sendPasskey(command: SendPasskeyCommand) {
return { error: "User not found in the system" };
}
const humanUser =
userResponse.user.type.case === "human"
? userResponse.user.type.value
: undefined;
const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined;
const emailVerificationCheck = checkEmailVerification(
session,
humanUser,
organization,
requestId,
);
const emailVerificationCheck = checkEmailVerification(session, humanUser, organization, requestId);
if (emailVerificationCheck?.redirect) {
return emailVerificationCheck;
}
const url =
requestId && session.id
? await getNextUrl(
{
sessionId: session.id,
requestId: requestId,
organization: organization,
},
loginSettings?.defaultRedirectUri,
)
: session?.factors?.user?.loginName
? await getNextUrl(
{
loginName: session.factors.user.loginName,
organization: organization,
},
loginSettings?.defaultRedirectUri,
)
: null;
return { redirect: url };
if (requestId && session.id) {
return completeFlowOrGetUrl(
{
sessionId: session.id,
requestId: requestId,
organization: organization,
},
loginSettings?.defaultRedirectUri,
);
} else if (session?.factors?.user?.loginName) {
return completeFlowOrGetUrl(
{
loginName: session.factors.user.loginName,
organization: organization,
},
loginSettings?.defaultRedirectUri,
);
}
}