fix(login): Organization domain scope, Support for External Passkey Registration (#10729)

Closes #10727
Closes #10577

# Which Problems Are Solved

This PR fixes the organization domain scope when provided and introduces
a deep-link feature for external applications, that sends users directly
into passkey registration flow using either session-based or sessionless
flows. Previously, the `/passkey/set` page only supported session-based
registration, limiting external application integration scenarios.

The `/passkey/set` page now supports:
- `code` search parameter for automatic passkey registration
- `userId` parameter for sessionless flows (similar to `/verify` and
`/password/set` pages)
- Auto-submit functionality when verification codes are provided

# How the Problems Are Solved

The organization scope is fixed by the backend handler for OIDC flows,
now correctly submitting a `suffix` queryparam to the /loginname url
which is used to show in the input field.

The passkey code support is implemented by support multiple integration
patterns:
- **Session-based**: `/passkey/set?sessionId=123&code=abc123` (existing
flow)
- **Sessionless**: `/passkey/set?userId=123456&code=abc123` (new flow)

External Application Integration Flow
1. External app triggers passkey register and obtains code
2. User verification link containing `userId`, `code` and `id`
parameters
3. User clicks link → `/passkey/set?userId=123&code=abc&id=123`
4. Page loads user information using `userId` parameter
5. Auto-submit triggers passkey registration when `code` and `id` is
present
6. User completes WebAuthn request
7. Passkey is registered and user continues authentication flow

This enables external applications to seamlessly integrate passkey
registration into their user onboarding
This commit is contained in:
Max Peintner
2025-09-30 17:58:32 +02:00
committed by GitHub
parent efdeaaf39d
commit 28db24fa67
9 changed files with 319 additions and 9310 deletions
+140 -59
View File
@@ -11,29 +11,33 @@ import {
} from "@/lib/zitadel";
import { create, Duration, Timestamp, timestampDate } from "@zitadel/client";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { Checks, ChecksSchema, GetSessionResponse } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import {
RegisterPasskeyResponse,
VerifyPasskeyRegistrationRequestSchema,
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { headers } from "next/headers";
import { userAgent } from "next/server";
import { completeFlowOrGetUrl } from "../client";
import { getMostRecentSessionCookie, getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
import { getServiceUrlFromHeaders } from "../service-url";
import { checkEmailVerification, checkUserVerification } from "../verify-helper";
import { setSessionAndUpdateCookie } from "./cookie";
import { createSessionAndUpdateCookie, setSessionAndUpdateCookie } from "./cookie";
import { getOriginalHost } from "./host";
import { completeFlowOrGetUrl } from "../client";
type VerifyPasskeyCommand = {
passkeyId: string;
passkeyName?: string;
publicKeyCredential: any;
sessionId: string;
sessionId?: string;
userId?: string;
};
type RegisterPasskeyCommand = {
sessionId: string;
sessionId?: string;
userId?: string;
code?: string;
codeId?: string;
};
function isSessionValid(session: Partial<Session>): {
@@ -53,44 +57,110 @@ function isSessionValid(session: Partial<Session>): {
export async function registerPasskeyLink(
command: RegisterPasskeyCommand,
): Promise<RegisterPasskeyResponse | { error: string }> {
const { sessionId } = command;
if (!command.sessionId && !command.userId) {
return { error: "Either sessionId or userId must be provided" };
}
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = await getOriginalHost();
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
let session: GetSessionResponse | undefined;
let createdSession: Session | undefined;
let currentUserId: string | undefined = undefined;
let registerCode: { id: string; code: string } | undefined = undefined;
if (!session?.session?.factors?.user?.id) {
return { error: "Could not determine user from session" };
}
const sessionValid = isSessionValid(session.session);
if (!sessionValid) {
const authmethods = await listAuthenticationMethodTypes({
if (command.sessionId) {
// Session-based flow (existing logic)
const sessionCookie = await getSessionCookieById({ sessionId: command.sessionId });
session = await getSession({
serviceUrl,
userId: session.session.factors.user.id,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
// 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",
};
if (!session?.session?.factors?.user?.id) {
return { error: "Could not determine user from session" };
}
// check if a verification was done earlier
const hasValidUserVerificationCheck = await checkUserVerification(session.session.factors.user.id);
currentUserId = session.session.factors.user.id;
if (!hasValidUserVerificationCheck) {
return { error: "User Verification Check has to be done" };
const sessionValid = isSessionValid(session.session);
if (!sessionValid.valid) {
const authmethods = await listAuthenticationMethodTypes({
serviceUrl,
userId: currentUserId,
});
// 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",
};
}
// check if a verification was done earlier
const hasValidUserVerificationCheck = await checkUserVerification(currentUserId);
console.log("hasValidUserVerificationCheck", hasValidUserVerificationCheck);
if (!hasValidUserVerificationCheck) {
return { error: "User Verification Check has to be done" };
}
if (!command.code) {
// request a new code if no code is provided
const codeResponse = await createPasskeyRegistrationLink({
serviceUrl,
userId: currentUserId,
});
if (!codeResponse?.code?.code) {
return { error: "Could not create registration link" };
}
registerCode = codeResponse.code;
}
}
} else if (command.userId && command.code && command.codeId) {
currentUserId = command.userId;
registerCode = {
id: command.codeId,
code: command.code,
};
// Check if user exists
const userResponse = await getUserByID({
serviceUrl,
userId: currentUserId,
});
if (!userResponse || !userResponse.user) {
return { error: "User not found" };
}
// Create a session for the user to continue the flow after passkey registration
const checks = create(ChecksSchema, {
user: {
search: {
case: "loginName",
value: userResponse.user.preferredLoginName,
},
},
});
createdSession = await createSessionAndUpdateCookie({
checks,
requestId: undefined, // No requestId in passkey registration context, TODO: consider if needed
});
if (!createdSession) {
return { error: "Could not create session" };
}
}
if (!registerCode) {
throw new Error("Missing code in response");
}
const [hostname] = host.split(":");
@@ -99,27 +169,14 @@ export async function registerPasskeyLink(
throw new Error("Could not get hostname");
}
const userId = session?.session?.factors?.user?.id;
if (!userId) {
throw new Error("Could not get session");
}
// TODO: add org context
// use session token to add the passkey
const registerLink = await createPasskeyRegistrationLink({
serviceUrl,
userId,
});
if (!registerLink.code) {
throw new Error("Missing code in response");
if (!currentUserId) {
throw new Error("Could not determine user");
}
return registerPasskey({
serviceUrl,
userId,
code: registerLink.code,
userId: currentUserId,
code: registerCode,
domain: hostname,
});
}
@@ -128,6 +185,10 @@ export async function verifyPasskeyRegistration(command: VerifyPasskeyCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
if (!command.sessionId && !command.userId) {
throw new Error("Either sessionId or userId must be provided");
}
// if no name is provided, try to generate one from the user agent
let passkeyName = command.passkeyName;
if (!passkeyName) {
@@ -140,18 +201,38 @@ export async function verifyPasskeyRegistration(command: VerifyPasskeyCommand) {
}${os.name}${os.name ? ", " : ""}${browser.name}`;
}
const sessionCookie = await getSessionCookieById({
sessionId: command.sessionId,
});
const session = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
const userId = session?.session?.factors?.user?.id;
let currentUserId: string;
if (!userId) {
throw new Error("Could not get session");
if (command.sessionId) {
// Session-based flow
const sessionCookie = await getSessionCookieById({
sessionId: command.sessionId,
});
const session = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
const userId = session?.session?.factors?.user?.id;
if (!userId) {
throw new Error("Could not get session");
}
currentUserId = userId;
} else {
// UserId-based flow
currentUserId = command.userId!;
// Verify user exists
const userResponse = await getUserByID({
serviceUrl,
userId: currentUserId,
});
if (!userResponse || !userResponse.user) {
throw new Error("User not found");
}
}
return zitadelVerifyPasskeyRegistration({
@@ -160,7 +241,7 @@ export async function verifyPasskeyRegistration(command: VerifyPasskeyCommand) {
passkeyId: command.passkeyId,
publicKeyCredential: command.publicKeyCredential,
passkeyName,
userId,
userId: currentUserId,
}),
});
}