chore: reproducible pipeline with dev containers (#10305)

# Which Problems Are Solved

- The previous monorepo in monorepo structure for the login app and its
related packages was fragmented, complicated and buggy.
- The process for building and testing the login container was
inconsistent between local development and CI.
- Lack of clear documentation as well as easy and reliable ways for
non-frontend developers to reproduce and fix failing PR checks locally.

# How the Problems Are Solved

- Consolidated the login app and its related npm packages by moving the
main package to `apps/login/apps/login` and merging
`apps/login/packages/integration` and `apps/login/packages/acceptance`
into the main `apps/login` package.
- Migrated from Docker Compose-based test setups to dev container-based
setups, adding support for multiple dev container configurations:
  - `.devcontainer/base`
  - `.devcontainer/turbo-lint-unit`
  - `.devcontainer/turbo-lint-unit-debug`
  - `.devcontainer/login-integration`
  - `.devcontainer/login-integration-debug`
- Added npm scripts to run the new dev container setups, enabling exact
reproduction of GitHub PR checks locally, and updated the pipeline to
use these containers.
- Cleaned up Dockerfiles and docker-bake.hcl files to only build the
production image for the login app.
- Cleaned up compose files to focus on dev environments in dev
containers.
- Updated `CONTRIBUTING.md` with guidance on running and debugging PR
checks locally using the new dev container approach.
- Introduced separate Dockerfiles for the login app to distinguish
between using published client packages and building clients from local
protos.
- Ensured the login container is always built in the pipeline for use in
integration and acceptance tests.
- Updated Makefile and GitHub Actions workflows to use
`--frozen-lockfile` for installing pnpm packages, ensuring reproducible
installs.
- Disabled GitHub release creation by the changeset action.
- Refactored the `/build` directory structure for clarity and
maintainability.
- Added a `clean` command to `docks/package.json`.
- Experimentally added `knip` to the `zitadel-client` package for
improved linting of dependencies and exports.

# Additional Changes

- Fixed Makefile commands for consistency and reliability.
- Improved the structure and clarity of the `/build` directory to
support seamless integration of the login build.
- Enhanced documentation and developer experience for running and
debugging CI checks locally.

# Additional Context

- See updated `CONTRIBUTING.md` for new local development and debugging
instructions.
- These changes are a prerequisite for further improvements to the CI
pipeline and local development workflow.
- Closes #10276
This commit is contained in:
Elio Bischof
2025-07-24 14:22:32 +02:00
committed by GitHub
parent af66c9844a
commit b10455b51f
430 changed files with 2869 additions and 4108 deletions
+17
View File
@@ -0,0 +1,17 @@
import { newSystemToken } from "@zitadel/client/node";
export async function systemAPIToken() {
const token = {
audience: process.env.AUDIENCE,
userID: process.env.SYSTEM_USER_ID,
token: Buffer.from(process.env.SYSTEM_USER_PRIVATE_KEY, "base64").toString(
"utf-8",
),
};
return newSystemToken({
audience: token.audience,
subject: token.userID,
key: token.token,
});
}
+80
View File
@@ -0,0 +1,80 @@
type FinishFlowCommand =
| {
sessionId: string;
requestId: string;
}
| { loginName: string };
function goToSignedInPage(
props:
| { sessionId: string; organization?: string; requestId?: string }
| { organization?: string; loginName: string; requestId?: string },
) {
const params = new URLSearchParams({});
if ("loginName" in props && props.loginName) {
params.append("loginName", props.loginName);
}
if ("sessionId" in props && props.sessionId) {
params.append("sessionId", props.sessionId);
}
if (props.organization) {
params.append("organization", props.organization);
}
// required to show conditional UI for device flow
if (props.requestId) {
params.append("requestId", props.requestId);
}
return `/signedin?` + params;
}
/**
* for client: redirects user back to an OIDC or SAML application or to a success page when using requestId, check if a default redirect and redirect to it, or just redirect to a success page with the loginName
* @param command
* @returns
*/
export async function getNextUrl(
command: FinishFlowCommand & { organization?: string },
defaultRedirectUri?: string,
): Promise<string> {
// finish Device Authorization Flow
if (
"requestId" in command &&
command.requestId.startsWith("device_") &&
("loginName" in command || "sessionId" in command)
) {
return goToSignedInPage({
...command,
organization: command.organization,
});
}
// finish SAML or OIDC flow
if (
"sessionId" in command &&
"requestId" in command &&
(command.requestId.startsWith("saml_") ||
command.requestId.startsWith("oidc_"))
) {
const params = new URLSearchParams({
sessionId: command.sessionId,
requestId: command.requestId,
});
if (command.organization) {
params.append("organization", command.organization);
}
return `/login?` + params;
}
if (defaultRedirectUri) {
return defaultRedirectUri;
}
return goToSignedInPage(command);
}
+341
View File
@@ -0,0 +1,341 @@
"use server";
import { timestampDate, timestampFromMs } from "@zitadel/client";
import { cookies } from "next/headers";
import { LANGUAGE_COOKIE_NAME } from "./i18n";
// TODO: improve this to handle overflow
const MAX_COOKIE_SIZE = 2048;
export type Cookie = {
id: string;
token: string;
loginName: string;
organization?: string;
creationTs: string;
expirationTs: string;
changeTs: string;
requestId?: string; // if its linked to an OIDC flow
};
type SessionCookie<T> = Cookie & T;
async function setSessionHttpOnlyCookie<T>(
sessions: SessionCookie<T>[],
sameSite: boolean | "lax" | "strict" | "none" = true,
) {
const cookiesList = await cookies();
return cookiesList.set({
name: "sessions",
value: JSON.stringify(sessions),
httpOnly: true,
path: "/",
sameSite: process.env.NODE_ENV === "production" ? sameSite : "lax",
secure: process.env.NODE_ENV === "production",
});
}
export async function setLanguageCookie(language: string) {
const cookiesList = await cookies();
await cookiesList.set({
name: LANGUAGE_COOKIE_NAME,
value: language,
httpOnly: true,
path: "/",
});
}
export async function addSessionToCookie<T>({
session,
cleanup,
sameSite,
}: {
session: SessionCookie<T>;
cleanup?: boolean;
sameSite?: boolean | "lax" | "strict" | "none" | undefined;
}): Promise<any> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
let currentSessions: SessionCookie<T>[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [];
const index = currentSessions.findIndex(
(s) => s.loginName === session.loginName,
);
if (index > -1) {
currentSessions[index] = session;
} else {
const temp = [...currentSessions, session];
if (JSON.stringify(temp).length >= MAX_COOKIE_SIZE) {
console.log("WARNING COOKIE OVERFLOW");
// TODO: improve cookie handling
// this replaces the first session (oldest) with the new one
currentSessions = [session].concat(currentSessions.slice(1));
} else {
currentSessions = [session].concat(currentSessions);
}
}
if (cleanup) {
const now = new Date();
const filteredSessions = currentSessions.filter((session) =>
session.expirationTs
? timestampDate(timestampFromMs(Number(session.expirationTs))) > now
: true,
);
return setSessionHttpOnlyCookie(filteredSessions, sameSite);
} else {
return setSessionHttpOnlyCookie(currentSessions, sameSite);
}
}
export async function updateSessionCookie<T>({
id,
session,
cleanup,
sameSite,
}: {
id: string;
session: SessionCookie<T>;
cleanup?: boolean;
sameSite?: boolean | "lax" | "strict" | "none" | undefined;
}): Promise<any> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
const sessions: SessionCookie<T>[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [session];
const foundIndex = sessions.findIndex((session) => session.id === id);
if (foundIndex > -1) {
sessions[foundIndex] = session;
if (cleanup) {
const now = new Date();
const filteredSessions = sessions.filter((session) =>
session.expirationTs
? timestampDate(timestampFromMs(Number(session.expirationTs))) > now
: true,
);
return setSessionHttpOnlyCookie(filteredSessions, sameSite);
} else {
return setSessionHttpOnlyCookie(sessions, sameSite);
}
} else {
throw "updateSessionCookie<T>: session id now found";
}
}
export async function removeSessionFromCookie<T>({
session,
cleanup,
sameSite,
}: {
session: SessionCookie<T>;
cleanup?: boolean;
sameSite?: boolean | "lax" | "strict" | "none" | undefined;
}) {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
const sessions: SessionCookie<T>[] = stringifiedCookie?.value
? JSON.parse(stringifiedCookie?.value)
: [session];
const reducedSessions = sessions.filter((s) => s.id !== session.id);
if (cleanup) {
const now = new Date();
const filteredSessions = reducedSessions.filter((session) =>
session.expirationTs
? timestampDate(timestampFromMs(Number(session.expirationTs))) > now
: true,
);
return setSessionHttpOnlyCookie(filteredSessions, sameSite);
} else {
return setSessionHttpOnlyCookie(reducedSessions, sameSite);
}
}
export async function getMostRecentSessionCookie<T>(): Promise<Cookie> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const latest = sessions.reduce((prev, current) => {
return prev.changeTs > current.changeTs ? prev : current;
});
return latest;
} else {
return Promise.reject("no session cookie found");
}
}
export async function getSessionCookieById<T>({
sessionId,
organization,
}: {
sessionId: string;
organization?: string;
}): Promise<SessionCookie<T>> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) =>
organization
? s.organization === organization && s.id === sessionId
: s.id === sessionId,
);
if (found) {
return found;
} else {
return Promise.reject();
}
} else {
return Promise.reject();
}
}
export async function getSessionCookieByLoginName<T>({
loginName,
organization,
}: {
loginName?: string;
organization?: string;
}): Promise<SessionCookie<T>> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) =>
organization
? s.organization === organization && s.loginName === loginName
: s.loginName === loginName,
);
if (found) {
return found;
} else {
return Promise.reject("no cookie found with loginName: " + loginName);
}
} else {
return Promise.reject("no session cookie found");
}
}
/**
*
* @param cleanup when true, removes all expired sessions, default true
* @returns Session Cookies
*/
export async function getAllSessionCookieIds<T>(
cleanup: boolean = false,
): Promise<string[]> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
if (cleanup) {
const now = new Date();
return sessions
.filter((session) =>
session.expirationTs
? timestampDate(timestampFromMs(Number(session.expirationTs))) > now
: true,
)
.map((session) => session.id);
} else {
return sessions.map((session) => session.id);
}
} else {
return [];
}
}
/**
*
* @param cleanup when true, removes all expired sessions, default true
* @returns Session Cookies
*/
export async function getAllSessions<T>(
cleanup: boolean = false,
): Promise<SessionCookie<T>[]> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
if (cleanup) {
const now = new Date();
return sessions.filter((session) =>
session.expirationTs
? timestampDate(timestampFromMs(Number(session.expirationTs))) > now
: true,
);
} else {
return sessions;
}
} else {
return [];
}
}
/**
* Returns most recent session filtered by optinal loginName
* @param loginName optional loginName to filter cookies, if non provided, returns most recent session
* @param organization optional organization to filter cookies
* @returns most recent session
*/
export async function getMostRecentCookieWithLoginname<T>({
loginName,
organization,
}: {
loginName?: string;
organization?: string;
}): Promise<any> {
const cookiesList = await cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie<T>[] = JSON.parse(stringifiedCookie?.value);
let filtered = sessions.filter((cookie) => {
return loginName ? cookie.loginName === loginName : true;
});
if (organization) {
filtered = filtered.filter((cookie) => {
return cookie.organization === organization;
});
}
const latest =
filtered && filtered.length
? filtered.reduce((prev, current) => {
return prev.changeTs > current.changeTs ? prev : current;
})
: undefined;
if (latest) {
return latest;
} else {
return Promise.reject("Could not get the context or retrieve a session");
}
} else {
return Promise.reject("Could not read session cookie");
}
}
+38
View File
@@ -0,0 +1,38 @@
export type Item = {
name: string;
slug: string;
description?: string;
};
export const demos: { name: string; items: Item[] }[] = [
{
name: "Login",
items: [
{
name: "Loginname",
slug: "loginname",
description: "Start the loginflow with loginname",
},
{
name: "Accounts",
slug: "accounts",
description: "List active and inactive sessions",
},
],
},
{
name: "Register",
items: [
{
name: "Register",
slug: "register",
description: "Add a user with password or passkey",
},
{
name: "IDP Register",
slug: "idp",
description: "Add a user from an external identity provider",
},
],
},
];
+66
View File
@@ -0,0 +1,66 @@
import { create } from "@zitadel/client";
import {
UserAgent,
UserAgentSchema,
} from "@zitadel/proto/zitadel/session/v2/session_pb";
import { cookies, headers } from "next/headers";
import { userAgent } from "next/server";
import { v4 as uuidv4 } from "uuid";
export async function getFingerprintId() {
return uuidv4();
}
export async function setFingerprintIdCookie(fingerprintId: string) {
const cookiesList = await cookies();
return cookiesList.set({
name: "fingerprintId",
value: fingerprintId,
httpOnly: true,
path: "/",
maxAge: 31536000, // 1 year
});
}
export async function getFingerprintIdCookie() {
const cookiesList = await cookies();
return cookiesList.get("fingerprintId");
}
export async function getOrSetFingerprintId(): Promise<string> {
const cookie = await getFingerprintIdCookie();
if (cookie) {
return cookie.value;
}
const fingerprintId = await getFingerprintId();
await setFingerprintIdCookie(fingerprintId);
return fingerprintId;
}
export async function getUserAgent(): Promise<UserAgent> {
const _headers = await headers();
const fingerprintId = await getOrSetFingerprintId();
const { device, engine, os, browser } = userAgent({ headers: _headers });
const userAgentHeader = _headers.get("user-agent");
const userAgentHeaderValues = userAgentHeader?.split(",");
const deviceDescription = `${device?.type ? `${device.type},` : ""} ${device?.vendor ? `${device.vendor},` : ""} ${device.model ? `${device.model},` : ""} `;
const osDescription = `${os?.name ? `${os.name},` : ""} ${os?.version ? `${os.version},` : ""} `;
const engineDescription = `${engine?.name ? `${engine.name},` : ""} ${engine?.version ? `${engine.version},` : ""} `;
const browserDescription = `${browser?.name ? `${browser.name},` : ""} ${browser.version ? `${browser.version},` : ""} `;
const userAgentData: UserAgent = create(UserAgentSchema, {
ip: _headers.get("x-forwarded-for") ?? _headers.get("remoteAddress") ?? "",
header: { "user-agent": { values: userAgentHeaderValues } },
description: `${browserDescription}, ${deviceDescription}, ${engineDescription}, ${osDescription}`,
fingerprintId: fingerprintId,
});
return userAgentData;
}
+42
View File
@@ -0,0 +1,42 @@
export interface Lang {
name: string;
code: string;
}
export const LANGS: Lang[] = [
{
name: "English",
code: "en",
},
{
name: "Deutsch",
code: "de",
},
{
name: "Italiano",
code: "it",
},
{
name: "Español",
code: "es",
},
{
name: "Polski",
code: "pl",
},
{
name: "简体中文",
code: "zh",
},
{
name: "Русский",
code: "ru",
},
{
name: "Türkçe",
code: "tr",
},
];
export const LANGUAGE_COOKIE_NAME = "NEXT_LOCALE";
export const LANGUAGE_HEADER_NAME = "accept-language";
+77
View File
@@ -0,0 +1,77 @@
import { IDPType } from "@zitadel/proto/zitadel/idp/v2/idp_pb";
import { IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
// This maps the IdentityProviderType to a slug which is used in the /success and /failure routes
export function idpTypeToSlug(idpType: IdentityProviderType) {
switch (idpType) {
case IdentityProviderType.GITHUB:
return "github";
case IdentityProviderType.GITHUB_ES:
return "github_es";
case IdentityProviderType.GITLAB:
return "gitlab";
case IdentityProviderType.GITLAB_SELF_HOSTED:
return "gitlab_es";
case IdentityProviderType.APPLE:
return "apple";
case IdentityProviderType.GOOGLE:
return "google";
case IdentityProviderType.AZURE_AD:
return "azure";
case IdentityProviderType.SAML:
return "saml";
case IdentityProviderType.OAUTH:
return "oauth";
case IdentityProviderType.OIDC:
return "oidc";
case IdentityProviderType.LDAP:
return "ldap";
case IdentityProviderType.JWT:
return "jwt";
default:
throw new Error("Unknown identity provider type");
}
}
// TODO: this is ugly but needed atm as the getIDPByID returns a IDPType and not a IdentityProviderType
export function idpTypeToIdentityProviderType(
idpType: IDPType,
): IdentityProviderType {
switch (idpType) {
case IDPType.IDP_TYPE_GITHUB:
return IdentityProviderType.GITHUB;
case IDPType.IDP_TYPE_GITHUB_ES:
return IdentityProviderType.GITHUB_ES;
case IDPType.IDP_TYPE_GITLAB:
return IdentityProviderType.GITLAB;
case IDPType.IDP_TYPE_GITLAB_SELF_HOSTED:
return IdentityProviderType.GITLAB_SELF_HOSTED;
case IDPType.IDP_TYPE_APPLE:
return IdentityProviderType.APPLE;
case IDPType.IDP_TYPE_GOOGLE:
return IdentityProviderType.GOOGLE;
case IDPType.IDP_TYPE_AZURE_AD:
return IdentityProviderType.AZURE_AD;
case IDPType.IDP_TYPE_SAML:
return IdentityProviderType.SAML;
case IDPType.IDP_TYPE_OAUTH:
return IdentityProviderType.OAUTH;
case IDPType.IDP_TYPE_OIDC:
return IdentityProviderType.OIDC;
case IDPType.IDP_TYPE_JWT:
return IdentityProviderType.JWT;
default:
throw new Error("Unknown identity provider type");
}
}
+132
View File
@@ -0,0 +1,132 @@
import { Cookie } from "@/lib/cookies";
import { sendLoginname, SendLoginnameCommand } from "@/lib/server/loginname";
import { createCallback, getLoginSettings } from "@/lib/zitadel";
import { create } from "@zitadel/client";
import {
CreateCallbackRequestSchema,
SessionSchema,
} from "@zitadel/proto/zitadel/oidc/v2/oidc_service_pb";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { NextRequest, NextResponse } from "next/server";
import { constructUrl } from "./service-url";
import { isSessionValid } from "./session";
type LoginWithOIDCAndSession = {
serviceUrl: string;
authRequest: string;
sessionId: string;
sessions: Session[];
sessionCookies: Cookie[];
request: NextRequest;
};
export async function loginWithOIDCAndSession({
serviceUrl,
authRequest,
sessionId,
sessions,
sessionCookies,
request,
}: LoginWithOIDCAndSession) {
console.log(
`Login with session: ${sessionId} and authRequest: ${authRequest}`,
);
const selectedSession = sessions.find((s) => s.id === sessionId);
if (selectedSession && selectedSession.id) {
console.log(`Found session ${selectedSession.id}`);
const isValid = await isSessionValid({
serviceUrl,
session: selectedSession,
});
console.log("Session is valid:", isValid);
if (!isValid && selectedSession.factors?.user) {
// if the session is not valid anymore, we need to redirect the user to re-authenticate /
// TODO: handle IDP intent direcly if available
const command: SendLoginnameCommand = {
loginName: selectedSession.factors.user?.loginName,
organization: selectedSession.factors?.user?.organizationId,
requestId: `oidc_${authRequest}`,
};
const res = await sendLoginname(command);
if (res && "redirect" in res && res?.redirect) {
const absoluteUrl = constructUrl(request, res.redirect);
return NextResponse.redirect(absoluteUrl.toString());
}
}
const cookie = sessionCookies.find(
(cookie) => cookie.id === selectedSession?.id,
);
if (cookie && cookie.id && cookie.token) {
const session = {
sessionId: cookie?.id,
sessionToken: cookie?.token,
};
// works not with _rsc request
try {
const { callbackUrl } = await createCallback({
serviceUrl,
req: create(CreateCallbackRequestSchema, {
authRequestId: authRequest,
callbackKind: {
case: "session",
value: create(SessionSchema, session),
},
}),
});
if (callbackUrl) {
return NextResponse.redirect(callbackUrl);
} else {
return NextResponse.json(
{ error: "An error occurred!" },
{ status: 500 },
);
}
} catch (error: unknown) {
// handle already handled gracefully as these could come up if old emails with requestId are used (reset password, register emails etc.)
console.error(error);
if (
error &&
typeof error === "object" &&
"code" in error &&
error?.code === 9
) {
const loginSettings = await getLoginSettings({
serviceUrl,
organization: selectedSession.factors?.user?.organizationId,
});
if (loginSettings?.defaultRedirectUri) {
return NextResponse.redirect(loginSettings.defaultRedirectUri);
}
const signedinUrl = constructUrl(request, "/signedin");
if (selectedSession.factors?.user?.loginName) {
signedinUrl.searchParams.set(
"loginName",
selectedSession.factors?.user?.loginName,
);
}
if (selectedSession.factors?.user?.organizationId) {
signedinUrl.searchParams.set(
"organization",
selectedSession.factors?.user?.organizationId,
);
}
return NextResponse.redirect(signedinUrl);
} else {
return NextResponse.json({ error }, { status: 500 });
}
}
}
}
}
+206
View File
@@ -0,0 +1,206 @@
import { Cookie } from "@/lib/cookies";
import { sendLoginname, SendLoginnameCommand } from "@/lib/server/loginname";
import { createResponse, getLoginSettings } from "@/lib/zitadel";
import { create } from "@zitadel/client";
import { CreateResponseRequestSchema } from "@zitadel/proto/zitadel/saml/v2/saml_service_pb";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { v4 as uuidv4 } from "uuid";
import { constructUrl } from "./service-url";
import { isSessionValid } from "./session";
type LoginWithSAMLAndSession = {
serviceUrl: string;
samlRequest: string;
sessionId: string;
sessions: Session[];
sessionCookies: Cookie[];
request: NextRequest;
};
export async function getSAMLFormUID() {
return uuidv4();
}
export async function setSAMLFormCookie(value: string): Promise<string> {
const cookiesList = await cookies();
const uid = await getSAMLFormUID();
try {
// Check cookie size limits (typical limit is 4KB)
if (value.length > 4000) {
console.warn(
`SAML form cookie value is large (${value.length} characters), may exceed browser limits`,
);
}
// Log the attempt
console.log(
`Setting SAML form cookie with uid: ${uid}, value length: ${value.length}`,
);
await cookiesList.set({
name: uid,
value: value,
httpOnly: true,
secure: process.env.NODE_ENV === "production", // Required for HTTPS in production
sameSite: "lax", // Allows cookies with top-level navigation (needed for SAML redirects)
path: "/",
maxAge: 5 * 60, // 5 minutes
});
// Note: We can't reliably verify immediately due to Next.js cookies API behavior
// Instead, we'll rely on the getSAMLFormCookie function to detect failures
console.log(`Successfully set SAML form cookie with uid: ${uid}`);
return uid;
} catch (error) {
console.error(`Failed to set SAML form cookie with uid: ${uid}`, {
error,
valueLength: value.length,
uid,
});
throw new Error(
`Failed to set SAML form cookie: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
export async function getSAMLFormCookie(uid: string): Promise<string | null> {
const cookiesList = await cookies();
try {
const cookie = cookiesList.get(uid);
if (!cookie) {
console.warn(`SAML form cookie not found for uid: ${uid}`);
return null;
}
if (!cookie.value) {
console.warn(`SAML form cookie found but empty value for uid: ${uid}`);
return null;
}
console.log(
`Successfully retrieved SAML form cookie for uid: ${uid}, value length: ${cookie.value.length}`,
);
return cookie.value;
} catch (error) {
console.error(`Error retrieving SAML form cookie for uid: ${uid}`, error);
return null;
}
}
export async function loginWithSAMLAndSession({
serviceUrl,
samlRequest,
sessionId,
sessions,
sessionCookies,
request,
}: LoginWithSAMLAndSession) {
console.log(
`Login with session: ${sessionId} and samlRequest: ${samlRequest}`,
);
const selectedSession = sessions.find((s) => s.id === sessionId);
if (selectedSession && selectedSession.id) {
console.log(`Found session ${selectedSession.id}`);
const isValid = await isSessionValid({
serviceUrl,
session: selectedSession,
});
console.log("Session is valid:", isValid);
if (!isValid && selectedSession.factors?.user) {
// if the session is not valid anymore, we need to redirect the user to re-authenticate /
// TODO: handle IDP intent direcly if available
const command: SendLoginnameCommand = {
loginName: selectedSession.factors.user?.loginName,
organization: selectedSession.factors?.user?.organizationId,
requestId: `saml_${samlRequest}`,
};
const res = await sendLoginname(command);
if (res && "redirect" in res && res?.redirect) {
const absoluteUrl = constructUrl(request, res.redirect);
return NextResponse.redirect(absoluteUrl.toString());
}
}
const cookie = sessionCookies.find(
(cookie) => cookie.id === selectedSession?.id,
);
if (cookie && cookie.id && cookie.token) {
const session = {
sessionId: cookie?.id,
sessionToken: cookie?.token,
};
// works not with _rsc request
try {
const { url } = await createResponse({
serviceUrl,
req: create(CreateResponseRequestSchema, {
samlRequestId: samlRequest,
responseKind: {
case: "session",
value: session,
},
}),
});
if (url) {
return NextResponse.redirect(url);
} else {
return NextResponse.json(
{ error: "An error occurred!" },
{ status: 500 },
);
}
} catch (error: unknown) {
// handle already handled gracefully as these could come up if old emails with requestId are used (reset password, register emails etc.)
console.error(error);
if (
error &&
typeof error === "object" &&
"code" in error &&
error?.code === 9
) {
const loginSettings = await getLoginSettings({
serviceUrl,
organization: selectedSession.factors?.user?.organizationId,
});
if (loginSettings?.defaultRedirectUri) {
return NextResponse.redirect(loginSettings.defaultRedirectUri);
}
const signedinUrl = constructUrl(request, "/signedin");
if (selectedSession.factors?.user?.loginName) {
signedinUrl.searchParams.set(
"loginName",
selectedSession.factors?.user?.loginName,
);
}
if (selectedSession.factors?.user?.organizationId) {
signedinUrl.searchParams.set(
"organization",
selectedSession.factors?.user?.organizationId,
);
}
return NextResponse.redirect(signedinUrl);
} else {
return NextResponse.json({ error }, { status: 500 });
}
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
"use server";
import { createUserServiceClient } from "@zitadel/client/v2";
import { headers } from "next/headers";
import { getSessionCookieById } from "./cookies";
import { getServiceUrlFromHeaders } from "./service-url";
import { createServerTransport, getSession } from "./zitadel";
const myUserService = async (serviceUrl: string, sessionToken: string) => {
const transportPromise = await createServerTransport(
sessionToken,
serviceUrl,
);
return createUserServiceClient(transportPromise);
};
export async function setMyPassword({
sessionId,
password,
}: {
sessionId: string;
password: string;
}) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const sessionCookie = await getSessionCookieById({ sessionId });
const { session } = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
if (!session) {
return { error: "Could not load session" };
}
const service = await myUserService(serviceUrl, `${sessionCookie.token}`);
if (!session?.factors?.user?.id) {
return { error: "No user id found in session" };
}
return service
.setPassword(
{
userId: session.factors.user.id,
newPassword: { password, changeRequired: false },
},
{},
)
.catch((error) => {
console.log(error);
if (error.code === 7) {
return { error: "Session is not valid." };
}
throw error;
});
}
+302
View File
@@ -0,0 +1,302 @@
"use server";
import { addSessionToCookie, updateSessionCookie } from "@/lib/cookies";
import {
createSessionForUserIdAndIdpIntent,
createSessionFromChecks,
getSecuritySettings,
getSession,
setSession,
} from "@/lib/zitadel";
import { ConnectError, Duration, timestampMs } from "@zitadel/client";
import {
CredentialsCheckError,
CredentialsCheckErrorSchema,
ErrorDetail,
} from "@zitadel/proto/zitadel/message_pb";
import {
Challenges,
RequestChallenges,
} from "@zitadel/proto/zitadel/session/v2/challenge_pb";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { headers } from "next/headers";
import { getServiceUrlFromHeaders } from "../service-url";
type CustomCookieData = {
id: string;
token: string;
loginName: string;
organization?: string;
creationTs: string;
expirationTs: string;
changeTs: string;
requestId?: string; // if its linked to an OIDC flow
};
const passwordAttemptsHandler = (error: ConnectError) => {
const details = error.findDetails(CredentialsCheckErrorSchema);
if (details[0] && "failedAttempts" in details[0]) {
const failedAttempts = details[0].failedAttempts;
throw {
error: `Failed to authenticate: You had ${failedAttempts} password attempts.`,
failedAttempts: failedAttempts,
};
}
throw error;
};
export async function createSessionAndUpdateCookie(command: {
checks: Checks;
requestId: string | undefined;
lifetime?: Duration;
}): Promise<Session> {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
let sessionLifetime = command.lifetime;
if (!sessionLifetime) {
console.warn("No session lifetime provided, using default of 24 hours.");
sessionLifetime = {
seconds: BigInt(24 * 60 * 60), // 24 hours
nanos: 0,
} as Duration; // for usecases where the lifetime is not specified (user discovery)
}
const createdSession = await createSessionFromChecks({
serviceUrl,
checks: command.checks,
lifetime: sessionLifetime,
});
if (createdSession) {
return getSession({
serviceUrl,
sessionId: createdSession.sessionId,
sessionToken: createdSession.sessionToken,
}).then(async (response) => {
if (response?.session && response.session?.factors?.user?.loginName) {
const sessionCookie: CustomCookieData = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationTs: response.session.creationDate
? `${timestampMs(response.session.creationDate)}`
: "",
expirationTs: response.session.expirationDate
? `${timestampMs(response.session.expirationDate)}`
: "",
changeTs: response.session.changeDate
? `${timestampMs(response.session.changeDate)}`
: "",
loginName: response.session.factors.user.loginName ?? "",
};
if (command.requestId) {
sessionCookie.requestId = command.requestId;
}
if (response.session.factors.user.organizationId) {
sessionCookie.organization =
response.session.factors.user.organizationId;
}
const securitySettings = await getSecuritySettings({ serviceUrl });
const sameSite = securitySettings?.embeddedIframe?.enabled
? "none"
: true;
await addSessionToCookie({ session: sessionCookie, sameSite });
return response.session as Session;
} else {
throw "could not get session or session does not have loginName";
}
});
} else {
throw "Could not create session";
}
}
export async function createSessionForIdpAndUpdateCookie({
userId,
idpIntent,
requestId,
lifetime,
}: {
userId: string;
idpIntent: {
idpIntentId?: string | undefined;
idpIntentToken?: string | undefined;
};
requestId: string | undefined;
lifetime?: Duration;
}): Promise<Session> {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
let sessionLifetime = lifetime;
if (!sessionLifetime) {
console.warn(
"No IDP session lifetime provided, using default of 24 hours.",
);
sessionLifetime = {
seconds: BigInt(24 * 60 * 60), // 24 hours
nanos: 0,
} as Duration;
}
const createdSession = await createSessionForUserIdAndIdpIntent({
serviceUrl,
userId,
idpIntent,
lifetime: sessionLifetime,
}).catch((error: ErrorDetail | CredentialsCheckError) => {
console.error("Could not set session", error);
if ("failedAttempts" in error && error.failedAttempts) {
throw {
error: `Failed to authenticate: You had ${error.failedAttempts} password attempts.`,
failedAttempts: error.failedAttempts,
};
}
throw error;
});
if (!createdSession) {
throw "Could not create session";
}
const { session } = await getSession({
serviceUrl,
sessionId: createdSession.sessionId,
sessionToken: createdSession.sessionToken,
});
if (!session || !session.factors?.user?.loginName) {
throw "Could not retrieve session";
}
const sessionCookie: CustomCookieData = {
id: createdSession.sessionId,
token: createdSession.sessionToken,
creationTs: session.creationDate
? `${timestampMs(session.creationDate)}`
: "",
expirationTs: session.expirationDate
? `${timestampMs(session.expirationDate)}`
: "",
changeTs: session.changeDate ? `${timestampMs(session.changeDate)}` : "",
loginName: session.factors.user.loginName ?? "",
organization: session.factors.user.organizationId ?? "",
};
if (requestId) {
sessionCookie.requestId = requestId;
}
if (session.factors.user.organizationId) {
sessionCookie.organization = session.factors.user.organizationId;
}
const securitySettings = await getSecuritySettings({ serviceUrl });
const sameSite = securitySettings?.embeddedIframe?.enabled ? "none" : true;
return addSessionToCookie({ session: sessionCookie, sameSite }).then(() => {
return session as Session;
});
}
export type SessionWithChallenges = Session & {
challenges: Challenges | undefined;
};
export async function setSessionAndUpdateCookie(command: {
recentCookie: CustomCookieData;
checks?: Checks;
challenges?: RequestChallenges;
requestId?: string;
lifetime: Duration;
}) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
return setSession({
serviceUrl,
sessionId: command.recentCookie.id,
sessionToken: command.recentCookie.token,
challenges: command.challenges,
checks: command.checks,
lifetime: command.lifetime,
})
.then((updatedSession) => {
if (updatedSession) {
const sessionCookie: CustomCookieData = {
id: command.recentCookie.id,
token: updatedSession.sessionToken,
creationTs: command.recentCookie.creationTs,
expirationTs: command.recentCookie.expirationTs,
// just overwrite the changeDate with the new one
changeTs: updatedSession.details?.changeDate
? `${timestampMs(updatedSession.details.changeDate)}`
: "",
loginName: command.recentCookie.loginName,
organization: command.recentCookie.organization,
};
if (command.requestId) {
sessionCookie.requestId = command.requestId;
}
return getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
}).then(async (response) => {
if (
!response?.session ||
!response.session.factors?.user?.loginName
) {
throw "could not get session or session does not have loginName";
}
const { session } = response;
const newCookie: CustomCookieData = {
id: sessionCookie.id,
token: updatedSession.sessionToken,
creationTs: sessionCookie.creationTs,
expirationTs: sessionCookie.expirationTs,
// just overwrite the changeDate with the new one
changeTs: updatedSession.details?.changeDate
? `${timestampMs(updatedSession.details.changeDate)}`
: "",
loginName: session.factors?.user?.loginName ?? "",
organization: session.factors?.user?.organizationId ?? "",
};
if (sessionCookie.requestId) {
newCookie.requestId = sessionCookie.requestId;
}
const securitySettings = await getSecuritySettings({ serviceUrl });
const sameSite = securitySettings?.embeddedIframe?.enabled
? "none"
: true;
return updateSessionCookie({
id: sessionCookie.id,
session: newCookie,
sameSite,
}).then(() => {
return { challenges: updatedSession.challenges, ...session };
});
});
} else {
throw "Session not be set";
}
})
.catch(passwordAttemptsHandler);
}
+20
View File
@@ -0,0 +1,20 @@
"use server";
import { authorizeOrDenyDeviceAuthorization } from "@/lib/zitadel";
import { headers } from "next/headers";
import { getServiceUrlFromHeaders } from "../service-url";
export async function completeDeviceAuthorization(
deviceAuthorizationId: string,
session?: { sessionId: string; sessionToken: string },
) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
// without the session, device auth request is denied
return authorizeOrDenyDeviceAuthorization({
serviceUrl,
deviceAuthorizationId,
session,
});
}
+241
View File
@@ -0,0 +1,241 @@
"use server";
import {
getLoginSettings,
getUserByID,
startIdentityProviderFlow,
startLDAPIdentityProviderFlow,
} from "@/lib/zitadel";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { getNextUrl } from "../client";
import { getServiceUrlFromHeaders } from "../service-url";
import { checkEmailVerification } from "../verify-helper";
import { createSessionForIdpAndUpdateCookie } from "./cookie";
export type RedirectToIdpState = { error?: string | null } | undefined;
export async function redirectToIdp(
prevState: RedirectToIdpState,
formData: FormData,
): Promise<RedirectToIdpState> {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "Could not get host" };
}
const params = new URLSearchParams();
const linkOnly = formData.get("linkOnly") === "true";
const requestId = formData.get("requestId") as string;
const organization = formData.get("organization") as string;
const idpId = formData.get("id") as string;
const provider = formData.get("provider") as string;
if (linkOnly) params.set("link", "true");
if (requestId) params.set("requestId", requestId);
if (organization) params.set("organization", organization);
// redirect to LDAP page where username and password is requested
if (provider === "ldap") {
params.set("idpId", idpId);
redirect(`/idp/ldap?` + params.toString());
}
const response = await startIDPFlow({
serviceUrl,
host,
idpId,
successUrl: `/idp/${provider}/success?` + params.toString(),
failureUrl: `/idp/${provider}/failure?` + params.toString(),
});
if (!response) {
return { error: "Could not start IDP flow" };
}
if (response && "redirect" in response && response?.redirect) {
redirect(response.redirect);
}
return { error: "Unexpected response from IDP flow" };
}
export type StartIDPFlowCommand = {
serviceUrl: string;
host: string;
idpId: string;
successUrl: string;
failureUrl: string;
};
async function startIDPFlow(command: StartIDPFlowCommand) {
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
const url = await startIdentityProviderFlow({
serviceUrl: command.serviceUrl,
idpId: command.idpId,
urls: {
successUrl: `${command.host.includes("localhost") ? "http://" : "https://"}${command.host}${basePath}${command.successUrl}`,
failureUrl: `${command.host.includes("localhost") ? "http://" : "https://"}${command.host}${basePath}${command.failureUrl}`,
},
});
if (!url) {
return { error: "Could not start IDP flow" };
}
return { redirect: url };
}
type CreateNewSessionCommand = {
userId: string;
idpIntent: {
idpIntentId: string;
idpIntentToken: string;
};
loginName?: string;
password?: string;
organization?: string;
requestId?: string;
};
export async function createNewSessionFromIdpIntent(
command: CreateNewSessionCommand,
) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "Could not get domain" };
}
if (!command.userId || !command.idpIntent) {
throw new Error("No userId or loginName provided");
}
const userResponse = await getUserByID({
serviceUrl,
userId: command.userId,
});
if (!userResponse || !userResponse.user) {
return { error: "User not found in the system" };
}
const loginSettings = await getLoginSettings({
serviceUrl,
organization: userResponse.user.details?.resourceOwner,
});
const session = await createSessionForIdpAndUpdateCookie({
userId: command.userId,
idpIntent: command.idpIntent,
requestId: command.requestId,
lifetime: loginSettings?.externalLoginCheckLifetime,
});
if (!session || !session.factors?.user) {
return { error: "Could not create session" };
}
const humanUser =
userResponse.user.type.case === "human"
? userResponse.user.type.value
: undefined;
// check to see if user was verified
const emailVerificationCheck = checkEmailVerification(
session,
humanUser,
command.organization,
command.requestId,
);
if (emailVerificationCheck?.redirect) {
return emailVerificationCheck;
}
// TODO: check if user has MFA methods
// const mfaFactorCheck = checkMFAFactors(session, loginSettings, authMethods, organization, requestId);
// if (mfaFactorCheck?.redirect) {
// return mfaFactorCheck;
// }
const url = await getNextUrl(
command.requestId && session.id
? {
sessionId: session.id,
requestId: command.requestId,
organization: session.factors.user.organizationId,
}
: {
loginName: session.factors.user.loginName,
organization: session.factors.user.organizationId,
},
loginSettings?.defaultRedirectUri,
);
if (url) {
return { redirect: url };
}
}
type createNewSessionForLDAPCommand = {
username: string;
password: string;
idpId: string;
link: boolean;
};
export async function createNewSessionForLDAP(
command: createNewSessionForLDAPCommand,
) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "Could not get domain" };
}
if (!command.username || !command.password) {
return { error: "No username or password provided" };
}
const response = await startLDAPIdentityProviderFlow({
serviceUrl,
idpId: command.idpId,
username: command.username,
password: command.password,
});
if (
!response ||
response.nextStep.case !== "idpIntent" ||
!response.nextStep.value
) {
return { error: "Could not start LDAP identity provider flow" };
}
const { userId, idpIntentId, idpIntentToken } = response.nextStep.value;
const params = new URLSearchParams({
userId,
id: idpIntentId,
token: idpIntentToken,
});
if (command.link) {
params.set("link", "true");
}
return {
redirect: `/idp/ldap/success?` + params.toString(),
};
}
+466
View File
@@ -0,0 +1,466 @@
"use server";
import { create } from "@zitadel/client";
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { headers } from "next/headers";
import { idpTypeToIdentityProviderType, idpTypeToSlug } from "../idp";
import { PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import { UserState } from "@zitadel/proto/zitadel/user/v2/user_pb";
import { getServiceUrlFromHeaders } from "../service-url";
import {
getActiveIdentityProviders,
getIDPByID,
getLoginSettings,
getOrgsByDomain,
listAuthenticationMethodTypes,
listIDPLinks,
searchUsers,
SearchUsersCommand,
startIdentityProviderFlow,
} from "../zitadel";
import { createSessionAndUpdateCookie } from "./cookie";
export type SendLoginnameCommand = {
loginName: string;
requestId?: string;
organization?: string;
suffix?: string;
};
const ORG_SUFFIX_REGEX = /(?<=@)(.+)/;
export async function sendLoginname(command: SendLoginnameCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
throw new Error("Could not get domain");
}
const loginSettingsByContext = await getLoginSettings({
serviceUrl,
organization: command.organization,
});
if (!loginSettingsByContext) {
return { error: "Could not get login settings" };
}
let searchUsersRequest: SearchUsersCommand = {
serviceUrl,
searchValue: command.loginName,
organizationId: command.organization,
loginSettings: loginSettingsByContext,
suffix: command.suffix,
};
const searchResult = await searchUsers(searchUsersRequest);
if ("error" in searchResult && searchResult.error) {
return searchResult;
}
if (!("result" in searchResult)) {
return { error: "Could not search users" };
}
const { result: potentialUsers } = searchResult;
const redirectUserToSingleIDPIfAvailable = async () => {
const identityProviders = await getActiveIdentityProviders({
serviceUrl,
orgId: command.organization,
}).then((resp) => {
return resp.identityProviders;
});
if (identityProviders.length === 1) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "Could not get host" };
}
const identityProviderType = identityProviders[0].type;
const provider = idpTypeToSlug(identityProviderType);
const params = new URLSearchParams();
if (command.requestId) {
params.set("requestId", command.requestId);
}
if (command.organization) {
params.set("organization", command.organization);
}
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
const url = await startIdentityProviderFlow({
serviceUrl,
idpId: identityProviders[0].id,
urls: {
successUrl:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/success?` +
new URLSearchParams(params),
failureUrl:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` +
new URLSearchParams(params),
},
});
if (!url) {
return { error: "Could not start IDP flow" };
}
return { redirect: url };
}
};
const redirectUserToIDP = async (userId: string) => {
const identityProviders = await listIDPLinks({
serviceUrl,
userId,
}).then((resp) => {
return resp.result;
});
if (identityProviders.length === 1) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "Could not get host" };
}
const identityProviderId = identityProviders[0].idpId;
const idp = await getIDPByID({
serviceUrl,
id: identityProviderId,
});
const idpType = idp?.type;
if (!idp || !idpType) {
throw new Error("Could not find identity provider");
}
const identityProviderType = idpTypeToIdentityProviderType(idpType);
const provider = idpTypeToSlug(identityProviderType);
const params = new URLSearchParams({ userId });
if (command.requestId) {
params.set("requestId", command.requestId);
}
if (command.organization) {
params.set("organization", command.organization);
}
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
const url = await startIdentityProviderFlow({
serviceUrl,
idpId: idp.id,
urls: {
successUrl:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/success?` +
new URLSearchParams(params),
failureUrl:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` +
new URLSearchParams(params),
},
});
if (!url) {
return { error: "Could not start IDP flow" };
}
return { redirect: url };
}
};
if (potentialUsers.length > 1) {
return { error: "More than one user found. Provide a unique identifier." };
} else if (potentialUsers.length == 1 && potentialUsers[0].userId) {
const user = potentialUsers[0];
const userId = potentialUsers[0].userId;
const userLoginSettings = await getLoginSettings({
serviceUrl,
organization: user.details?.resourceOwner,
});
// compare with the concatenated suffix when set
const concatLoginname = command.suffix
? `${command.loginName}@${command.suffix}`
: command.loginName;
const humanUser =
potentialUsers[0].type.case === "human"
? potentialUsers[0].type.value
: undefined;
// recheck login settings after user discovery, as the search might have been done without org scope
if (
userLoginSettings?.disableLoginWithEmail &&
userLoginSettings?.disableLoginWithPhone
) {
if (user.preferredLoginName !== concatLoginname) {
return { error: "User not found in the system!" };
}
} else if (userLoginSettings?.disableLoginWithEmail) {
if (
user.preferredLoginName !== concatLoginname ||
humanUser?.phone?.phone !== command.loginName
) {
return { error: "User not found in the system!" };
}
} else if (userLoginSettings?.disableLoginWithPhone) {
if (
user.preferredLoginName !== concatLoginname ||
humanUser?.email?.email !== command.loginName
) {
return { error: "User not found in the system!" };
}
}
const checks = create(ChecksSchema, {
user: { search: { case: "userId", value: userId } },
});
const session = await createSessionAndUpdateCookie({
checks,
requestId: command.requestId,
});
if (!session.factors?.user?.id) {
return { error: "Could not create session for user" };
}
// TODO: check if handling of userstate INITIAL is needed
if (user.state === UserState.INITIAL) {
return { error: "Initial User not supported" };
}
const methods = await listAuthenticationMethodTypes({
serviceUrl,
userId: session.factors?.user?.id,
});
// always resend invite if user has no auth method set
if (!methods.authMethodTypes || !methods.authMethodTypes.length) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
send: "true", // set this to true to request a new code immediately
invite: "true",
});
if (command.requestId) {
params.append("requestId", command.requestId);
}
if (command.organization || session.factors?.user?.organizationId) {
params.append(
"organization",
command.organization ??
(session.factors?.user?.organizationId as string),
);
}
return { redirect: `/verify?` + params };
}
if (methods.authMethodTypes.length == 1) {
const method = methods.authMethodTypes[0];
switch (method) {
case AuthenticationMethodType.PASSWORD: // user has only password as auth method
if (!userLoginSettings?.allowUsernamePassword) {
return {
error:
"Username Password not allowed! Contact your administrator for more information.",
};
}
const paramsPassword = new URLSearchParams({
loginName: session.factors?.user?.loginName,
});
// TODO: does this have to be checked in loginSettings.allowDomainDiscovery
if (command.organization || session.factors?.user?.organizationId) {
paramsPassword.append(
"organization",
command.organization ?? session.factors?.user?.organizationId,
);
}
if (command.requestId) {
paramsPassword.append("requestId", command.requestId);
}
return {
redirect: "/password?" + paramsPassword,
};
case AuthenticationMethodType.PASSKEY: // AuthenticationMethodType.AUTHENTICATION_METHOD_TYPE_PASSKEY
if (userLoginSettings?.passkeysType === PasskeysType.NOT_ALLOWED) {
return {
error:
"Passkeys not allowed! Contact your administrator for more information.",
};
}
const paramsPasskey = new URLSearchParams({
loginName: session.factors?.user?.loginName,
});
if (command.requestId) {
paramsPasskey.append("requestId", command.requestId);
}
if (command.organization || session.factors?.user?.organizationId) {
paramsPasskey.append(
"organization",
command.organization ?? session.factors?.user?.organizationId,
);
}
return { redirect: "/passkey?" + paramsPasskey };
}
} else {
// prefer passkey in favor of other methods
if (methods.authMethodTypes.includes(AuthenticationMethodType.PASSKEY)) {
const passkeyParams = new URLSearchParams({
loginName: session.factors?.user?.loginName,
altPassword: `${methods.authMethodTypes.includes(1)}`, // show alternative password option
});
if (command.requestId) {
passkeyParams.append("requestId", command.requestId);
}
if (command.organization || session.factors?.user?.organizationId) {
passkeyParams.append(
"organization",
command.organization ?? session.factors?.user?.organizationId,
);
}
return { redirect: "/passkey?" + passkeyParams };
} else if (
methods.authMethodTypes.includes(AuthenticationMethodType.IDP)
) {
return redirectUserToIDP(userId);
} else if (
methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD)
) {
// user has no passkey setup and login settings allow passkeys
const paramsPasswordDefault = new URLSearchParams({
loginName: session.factors?.user?.loginName,
});
if (command.requestId) {
paramsPasswordDefault.append("requestId", command.requestId);
}
if (command.organization || session.factors?.user?.organizationId) {
paramsPasswordDefault.append(
"organization",
command.organization ?? session.factors?.user?.organizationId,
);
}
return {
redirect: "/password?" + paramsPasswordDefault,
};
}
}
}
// user not found, check if register is enabled on instance / organization context
if (
loginSettingsByContext?.allowRegister &&
!loginSettingsByContext?.allowUsernamePassword
) {
const resp = await redirectUserToSingleIDPIfAvailable();
if (resp) {
return resp;
}
return { error: "User not found in the system" };
} else if (
loginSettingsByContext?.allowRegister &&
loginSettingsByContext?.allowUsernamePassword
) {
let orgToRegisterOn: string | undefined = command.organization;
if (
!loginSettingsByContext?.ignoreUnknownUsernames &&
!orgToRegisterOn &&
command.loginName &&
ORG_SUFFIX_REGEX.test(command.loginName)
) {
const matched = ORG_SUFFIX_REGEX.exec(command.loginName);
const suffix = matched?.[1] ?? "";
// this just returns orgs where the suffix is set as primary domain
const orgs = await getOrgsByDomain({
serviceUrl,
domain: suffix,
});
const orgToCheckForDiscovery =
orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined;
const orgLoginSettings = await getLoginSettings({
serviceUrl,
organization: orgToCheckForDiscovery,
});
if (orgLoginSettings?.allowDomainDiscovery) {
orgToRegisterOn = orgToCheckForDiscovery;
}
}
// do not register user if ignoreUnknownUsernames is set
if (orgToRegisterOn && !loginSettingsByContext?.ignoreUnknownUsernames) {
const params = new URLSearchParams({ organization: orgToRegisterOn });
if (command.requestId) {
params.set("requestId", command.requestId);
}
if (command.loginName) {
params.set("email", command.loginName);
}
return { redirect: "/register?" + params };
}
}
if (loginSettingsByContext?.ignoreUnknownUsernames) {
const paramsPasswordDefault = new URLSearchParams({
loginName: command.loginName,
});
if (command.requestId) {
paramsPasswordDefault.append("requestId", command.requestId);
}
if (command.organization) {
paramsPasswordDefault.append("organization", command.organization);
}
return { redirect: "/password?" + paramsPasswordDefault };
}
// fallbackToPassword
return { error: "User not found in the system" };
}
+15
View File
@@ -0,0 +1,15 @@
"use server";
import { getDeviceAuthorizationRequest as zitadelGetDeviceAuthorizationRequest } from "@/lib/zitadel";
import { headers } from "next/headers";
import { getServiceUrlFromHeaders } from "../service-url";
export async function getDeviceAuthorizationRequest(userCode: string) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
return zitadelGetDeviceAuthorizationRequest({
serviceUrl,
userCode,
});
}
+286
View File
@@ -0,0 +1,286 @@
"use server";
import {
createPasskeyRegistrationLink,
getLoginSettings,
getSession,
getUserByID,
listAuthenticationMethodTypes,
registerPasskey,
verifyPasskeyRegistration as zitadelVerifyPasskeyRegistration,
} 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 {
RegisterPasskeyResponse,
VerifyPasskeyRegistrationRequestSchema,
} 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 { getServiceUrlFromHeaders } from "../service-url";
import {
checkEmailVerification,
checkUserVerification,
} from "../verify-helper";
import { setSessionAndUpdateCookie } from "./cookie";
type VerifyPasskeyCommand = {
passkeyId: string;
passkeyName?: string;
publicKeyCredential: any;
sessionId: string;
};
type RegisterPasskeyCommand = {
sessionId: string;
};
function isSessionValid(session: Partial<Session>): {
valid: boolean;
verifiedAt?: Timestamp;
} {
const validPassword = session?.factors?.password?.verifiedAt;
const validPasskey = session?.factors?.webAuthN?.verifiedAt;
const stillValid = session.expirationDate
? timestampDate(session.expirationDate) > new Date()
: true;
const verifiedAt = validPassword || validPasskey;
const valid = !!((validPassword || validPasskey) && stillValid);
return { valid, verifiedAt };
}
export async function registerPasskeyLink(
command: RegisterPasskeyCommand,
): Promise<RegisterPasskeyResponse | { error: string }> {
const { sessionId } = command;
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
throw new Error("Could not get domain");
}
const sessionCookie = await getSessionCookieById({ sessionId });
const session = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
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({
serviceUrl,
userId: session.session.factors.user.id,
});
// 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(
session.session.factors.user.id,
);
if (!hasValidUserVerificationCheck) {
return { error: "User Verification Check has to be done" };
}
}
const [hostname] = host.split(":");
if (!hostname) {
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");
}
return registerPasskey({
serviceUrl,
userId,
code: registerLink.code,
domain: hostname,
});
}
export async function verifyPasskeyRegistration(command: VerifyPasskeyCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
// if no name is provided, try to generate one from the user agent
let passkeyName = command.passkeyName;
if (!passkeyName) {
const headersList = await headers();
const userAgentStructure = { headers: headersList };
const { browser, device, os } = userAgent(userAgentStructure);
passkeyName = `${device.vendor ?? ""} ${device.model ?? ""}${
device.vendor || device.model ? ", " : ""
}${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;
if (!userId) {
throw new Error("Could not get session");
}
return zitadelVerifyPasskeyRegistration({
serviceUrl,
request: create(VerifyPasskeyRegistrationRequestSchema, {
passkeyId: command.passkeyId,
publicKeyCredential: command.publicKeyCredential,
passkeyName,
userId,
}),
});
}
type SendPasskeyCommand = {
loginName?: string;
sessionId?: string;
organization?: string;
checks?: Checks;
requestId?: string;
lifetime?: Duration;
};
export async function sendPasskey(command: SendPasskeyCommand) {
let { loginName, sessionId, organization, checks, requestId } = command;
const recentSession = sessionId
? await getSessionCookieById({ sessionId })
: loginName
? await getSessionCookieByLoginName({ loginName, organization })
: await getMostRecentSessionCookie();
if (!recentSession) {
return {
error: "Could not find session",
};
}
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const loginSettings = await getLoginSettings({
serviceUrl,
organization,
});
let lifetime = checks?.webAuthN
? loginSettings?.multiFactorCheckLifetime // TODO different lifetime for webauthn u2f/passkey
: checks?.otpEmail || checks?.otpSms
? loginSettings?.secondFactorCheckLifetime
: undefined;
if (!lifetime) {
console.warn("No passkey lifetime provided, defaulting to 24 hours");
lifetime = {
seconds: BigInt(60 * 60 * 24), // default to 24 hours
nanos: 0,
} as Duration;
}
const session = await setSessionAndUpdateCookie({
recentCookie: recentSession,
checks,
requestId,
lifetime,
});
if (!session || !session?.factors?.user?.id) {
return { error: "Could not update session" };
}
const userResponse = await getUserByID({
serviceUrl,
userId: session?.factors?.user?.id,
});
if (!userResponse.user) {
return { error: "User not found in the system" };
}
const humanUser =
userResponse.user.type.case === "human"
? userResponse.user.type.value
: undefined;
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 };
}
+478
View File
@@ -0,0 +1,478 @@
"use server";
import {
createSessionAndUpdateCookie,
setSessionAndUpdateCookie,
} from "@/lib/server/cookie";
import {
getLockoutSettings,
getLoginSettings,
getPasswordExpirySettings,
getSession,
getUserByID,
listAuthenticationMethodTypes,
listUsers,
passwordReset,
setPassword,
setUserPassword,
} from "@/lib/zitadel";
import { ConnectError, create, Duration } from "@zitadel/client";
import { createUserServiceClient } from "@zitadel/client/v2";
import {
Checks,
ChecksSchema,
} from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import { User, UserState } from "@zitadel/proto/zitadel/user/v2/user_pb";
import {
AuthenticationMethodType,
SetPasswordRequestSchema,
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { headers } from "next/headers";
import { getNextUrl } from "../client";
import { getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
import { getServiceUrlFromHeaders } from "../service-url";
import {
checkEmailVerification,
checkMFAFactors,
checkPasswordChangeRequired,
checkUserVerification,
} from "../verify-helper";
import { createServerTransport } from "../zitadel";
type ResetPasswordCommand = {
loginName: string;
organization?: string;
requestId?: string;
};
export async function resetPassword(command: ResetPasswordCommand) {
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 users = await listUsers({
serviceUrl,
loginName: command.loginName,
organizationId: command.organization,
});
if (
!users.details ||
users.details.totalResult !== BigInt(1) ||
!users.result[0].userId
) {
return { error: "Could not send Password Reset Link" };
}
const userId = users.result[0].userId;
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
return passwordReset({
serviceUrl,
userId,
urlTemplate:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/password/set?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` +
(command.requestId ? `&requestId=${command.requestId}` : ""),
});
}
export type UpdateSessionCommand = {
loginName: string;
organization?: string;
checks: Checks;
requestId?: string;
};
export async function sendPassword(command: UpdateSessionCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
let sessionCookie = await getSessionCookieByLoginName({
loginName: command.loginName,
organization: command.organization,
}).catch((error) => {
console.warn("Ignored error:", error);
});
let session;
let user: User;
let loginSettings: LoginSettings | undefined;
if (!sessionCookie) {
const users = await listUsers({
serviceUrl,
loginName: command.loginName,
organizationId: command.organization,
});
if (users.details?.totalResult == BigInt(1) && users.result[0].userId) {
user = users.result[0];
const checks = create(ChecksSchema, {
user: { search: { case: "userId", value: users.result[0].userId } },
password: { password: command.checks.password?.password },
});
loginSettings = await getLoginSettings({
serviceUrl,
organization: command.organization,
});
try {
session = await createSessionAndUpdateCookie({
checks,
requestId: command.requestId,
lifetime: loginSettings?.passwordCheckLifetime,
});
} catch (error: any) {
if ("failedAttempts" in error && error.failedAttempts) {
const lockoutSettings = await getLockoutSettings({
serviceUrl,
orgId: command.organization,
});
return {
error:
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
(lockoutSettings?.maxPasswordAttempts &&
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
? "Contact your administrator to unlock your account"
: ""),
};
}
return { error: "Could not create session for user" };
}
}
// this is a fake error message to hide that the user does not even exist
return { error: "Could not verify password" };
} else {
loginSettings = await getLoginSettings({
serviceUrl,
organization: sessionCookie.organization,
});
if (!loginSettings) {
return { error: "Could not load login settings" };
}
let lifetime = loginSettings.passwordCheckLifetime;
if (!lifetime) {
console.warn("No password lifetime provided, defaulting to 24 hours");
lifetime = {
seconds: BigInt(60 * 60 * 24), // default to 24 hours
nanos: 0,
} as Duration;
}
try {
session = await setSessionAndUpdateCookie({
recentCookie: sessionCookie,
checks: command.checks,
requestId: command.requestId,
lifetime,
});
} catch (error: any) {
if ("failedAttempts" in error && error.failedAttempts) {
const lockoutSettings = await getLockoutSettings({
serviceUrl,
orgId: command.organization,
});
return {
error:
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
(lockoutSettings?.maxPasswordAttempts &&
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
? " Contact your administrator to unlock your account"
: ""),
};
}
throw error;
}
if (!session?.factors?.user?.id) {
return { error: "Could not create session for user" };
}
const userResponse = await getUserByID({
serviceUrl,
userId: session?.factors?.user?.id,
});
if (!userResponse.user) {
return { error: "User not found in the system" };
}
user = userResponse.user;
}
if (!loginSettings) {
loginSettings = await getLoginSettings({
serviceUrl,
organization:
command.organization ?? session.factors?.user?.organizationId,
});
}
if (!session?.factors?.user?.id || !sessionCookie) {
return { error: "Could not create session for user" };
}
const humanUser = user.type.case === "human" ? user.type.value : undefined;
const expirySettings = await getPasswordExpirySettings({
serviceUrl,
orgId: command.organization ?? session.factors?.user?.organizationId,
});
// check if the user has to change password first
const passwordChangedCheck = checkPasswordChangeRequired(
expirySettings,
session,
humanUser,
command.organization,
command.requestId,
);
if (passwordChangedCheck?.redirect) {
return passwordChangedCheck;
}
// throw error if user is in initial state here and do not continue
if (user.state === UserState.INITIAL) {
return { error: "Initial User not supported" };
}
// check to see if user was verified
const emailVerificationCheck = checkEmailVerification(
session,
humanUser,
command.organization,
command.requestId,
);
if (emailVerificationCheck?.redirect) {
return emailVerificationCheck;
}
// if password, check if user has MFA methods
let authMethods;
if (command.checks && command.checks.password && session.factors?.user?.id) {
const response = await listAuthenticationMethodTypes({
serviceUrl,
userId: session.factors.user.id,
});
if (response.authMethodTypes && response.authMethodTypes.length) {
authMethods = response.authMethodTypes;
}
}
if (!authMethods) {
return { error: "Could not verify password!" };
}
const mfaFactorCheck = await checkMFAFactors(
serviceUrl,
session,
loginSettings,
authMethods,
command.organization,
command.requestId,
);
if (mfaFactorCheck?.redirect) {
return mfaFactorCheck;
}
if (command.requestId && session.id) {
const nextUrl = await getNextUrl(
{
sessionId: session.id,
requestId: command.requestId,
organization:
command.organization ?? session.factors?.user?.organizationId,
},
loginSettings?.defaultRedirectUri,
);
return { redirect: nextUrl };
}
const url = await getNextUrl(
{
loginName: session.factors.user.loginName,
organization: session.factors?.user?.organizationId,
},
loginSettings?.defaultRedirectUri,
);
return { redirect: url };
}
// this function lets users with code set a password or users with valid User Verification Check
export async function changePassword(command: {
code?: string;
userId: string;
password: string;
}) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
// check for init state
const { user } = await getUserByID({
serviceUrl,
userId: command.userId,
});
if (!user || user.userId !== command.userId) {
return { error: "Could not send Password Reset Link" };
}
const userId = user.userId;
if (user.state === UserState.INITIAL) {
return { error: "User Initial State is not supported" };
}
// check if the user has no password set in order to set a password
if (!command.code) {
const authmethods = await listAuthenticationMethodTypes({
serviceUrl,
userId,
});
// 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 provide a code or have a valid User Verification Check",
};
}
// check if a verification was done earlier
const hasValidUserVerificationCheck = await checkUserVerification(
user.userId,
);
if (!hasValidUserVerificationCheck) {
return { error: "User Verification Check has to be done" };
}
}
return setUserPassword({
serviceUrl,
userId,
password: command.password,
code: command.code,
});
}
type CheckSessionAndSetPasswordCommand = {
sessionId: string;
password: string;
};
export async function checkSessionAndSetPassword({
sessionId,
password,
}: CheckSessionAndSetPasswordCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const sessionCookie = await getSessionCookieById({ sessionId });
const { session } = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
if (!session || !session.factors?.user?.id) {
return { error: "Could not load session" };
}
const payload = create(SetPasswordRequestSchema, {
userId: session.factors.user.id,
newPassword: {
password,
},
});
// check if the user has no password set in order to set a password
const authmethods = await listAuthenticationMethodTypes({
serviceUrl,
userId: session.factors.user.id,
});
if (!authmethods) {
return { error: "Could not load auth methods" };
}
const requiredAuthMethodsForForceMFA = [
AuthenticationMethodType.OTP_EMAIL,
AuthenticationMethodType.OTP_SMS,
AuthenticationMethodType.TOTP,
AuthenticationMethodType.U2F,
];
const hasNoMFAMethods = requiredAuthMethodsForForceMFA.every(
(method) => !authmethods.authMethodTypes.includes(method),
);
const loginSettings = await getLoginSettings({
serviceUrl,
organization: session.factors.user.organizationId,
});
const forceMfa = !!(
loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly
);
// if the user has no MFA but MFA is enforced, we can set a password otherwise we use the token of the user
if (forceMfa && hasNoMFAMethods) {
return setPassword({ serviceUrl, payload }).catch((error) => {
// throw error if failed precondition (ex. User is not yet initialized)
if (error.code === 9 && error.message) {
return { error: "Failed precondition" };
} else {
throw error;
}
});
} else {
const transport = async (serviceUrl: string, token: string) => {
return createServerTransport(token, serviceUrl);
};
const myUserService = async (serviceUrl: string, sessionToken: string) => {
const transportPromise = await transport(serviceUrl, sessionToken);
return createUserServiceClient(transportPromise);
};
const selfService = await myUserService(
serviceUrl,
`${sessionCookie.token}`,
);
return selfService
.setPassword(
{
userId: session.factors.user.id,
newPassword: { password, changeRequired: false },
},
{},
)
.catch((error: ConnectError) => {
console.log(error);
if (error.code === 7) {
return { error: "Session is not valid." };
}
throw error;
});
}
}
+233
View File
@@ -0,0 +1,233 @@
"use server";
import {
createSessionAndUpdateCookie,
createSessionForIdpAndUpdateCookie,
} from "@/lib/server/cookie";
import {
addHumanUser,
addIDPLink,
getLoginSettings,
getUserByID,
} from "@/lib/zitadel";
import { create } from "@zitadel/client";
import { Factors } from "@zitadel/proto/zitadel/session/v2/session_pb";
import {
ChecksJson,
ChecksSchema,
} from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { headers } from "next/headers";
import { getNextUrl } from "../client";
import { getServiceUrlFromHeaders } from "../service-url";
import { checkEmailVerification } from "../verify-helper";
type RegisterUserCommand = {
email: string;
firstName: string;
lastName: string;
password?: string;
organization: string;
requestId?: string;
};
export type RegisterUserResponse = {
userId: string;
sessionId: string;
factors: Factors | undefined;
};
export async function registerUser(command: RegisterUserCommand) {
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 addResponse = await addHumanUser({
serviceUrl,
email: command.email,
firstName: command.firstName,
lastName: command.lastName,
password: command.password ? command.password : undefined,
organization: command.organization,
});
if (!addResponse) {
return { error: "Could not create user" };
}
const loginSettings = await getLoginSettings({
serviceUrl,
organization: command.organization,
});
let checkPayload: any = {
user: { search: { case: "userId", value: addResponse.userId } },
};
if (command.password) {
checkPayload = {
...checkPayload,
password: { password: command.password },
} as ChecksJson;
}
const checks = create(ChecksSchema, checkPayload);
const session = await createSessionAndUpdateCookie({
checks,
requestId: command.requestId,
lifetime: command.password
? loginSettings?.passwordCheckLifetime
: undefined,
});
if (!session || !session.factors?.user) {
return { error: "Could not create session" };
}
if (!command.password) {
const params = new URLSearchParams({
loginName: session.factors.user.loginName,
organization: session.factors.user.organizationId,
});
if (command.requestId) {
params.append("requestId", command.requestId);
}
return { redirect: "/passkey/set?" + params };
} else {
const userResponse = await getUserByID({
serviceUrl,
userId: session?.factors?.user?.id,
});
if (!userResponse.user) {
return { error: "User not found in the system" };
}
const humanUser =
userResponse.user.type.case === "human"
? userResponse.user.type.value
: undefined;
const emailVerificationCheck = checkEmailVerification(
session,
humanUser,
session.factors.user.organizationId,
command.requestId,
);
if (emailVerificationCheck?.redirect) {
return emailVerificationCheck;
}
const url = await getNextUrl(
command.requestId && session.id
? {
sessionId: session.id,
requestId: command.requestId,
organization: session.factors.user.organizationId,
}
: {
loginName: session.factors.user.loginName,
organization: session.factors.user.organizationId,
},
loginSettings?.defaultRedirectUri,
);
return { redirect: url };
}
}
type RegisterUserAndLinkToIDPommand = {
email: string;
firstName: string;
lastName: string;
organization: string;
requestId?: string;
idpIntent: {
idpIntentId: string;
idpIntentToken: string;
};
idpUserId: string;
idpId: string;
idpUserName: string;
};
export type registerUserAndLinkToIDPResponse = {
userId: string;
sessionId: string;
factors: Factors | undefined;
};
export async function registerUserAndLinkToIDP(
command: RegisterUserAndLinkToIDPommand,
) {
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 addResponse = await addHumanUser({
serviceUrl,
email: command.email,
firstName: command.firstName,
lastName: command.lastName,
organization: command.organization,
});
if (!addResponse) {
return { error: "Could not create user" };
}
const loginSettings = await getLoginSettings({
serviceUrl,
organization: command.organization,
});
const idpLink = await addIDPLink({
serviceUrl,
idp: {
id: command.idpId,
userId: command.idpUserId,
userName: command.idpUserName,
},
userId: addResponse.userId,
});
if (!idpLink) {
return { error: "Could not link IDP to user" };
}
const session = await createSessionForIdpAndUpdateCookie({
requestId: command.requestId,
userId: addResponse.userId, // the user we just created
idpIntent: command.idpIntent,
lifetime: loginSettings?.externalLoginCheckLifetime,
});
if (!session || !session.factors?.user) {
return { error: "Could not create session" };
}
const url = await getNextUrl(
command.requestId && session.id
? {
sessionId: session.id,
requestId: command.requestId,
organization: session.factors.user.organizationId,
}
: {
loginName: session.factors.user.loginName,
organization: session.factors.user.organizationId,
},
loginSettings?.defaultRedirectUri,
);
return { redirect: url };
}
+229
View File
@@ -0,0 +1,229 @@
"use server";
import { setSessionAndUpdateCookie } from "@/lib/server/cookie";
import {
deleteSession,
getLoginSettings,
getSecuritySettings,
humanMFAInitSkipped,
listAuthenticationMethodTypes,
} from "@/lib/zitadel";
import { Duration } from "@zitadel/client";
import { RequestChallenges } from "@zitadel/proto/zitadel/session/v2/challenge_pb";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { headers } from "next/headers";
import { getNextUrl } from "../client";
import {
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
removeSessionFromCookie,
} from "../cookies";
import { getServiceUrlFromHeaders } from "../service-url";
export async function skipMFAAndContinueWithNextUrl({
userId,
requestId,
loginName,
sessionId,
organization,
}: {
userId: string;
loginName?: string;
sessionId?: string;
requestId?: string;
organization?: string;
}) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const loginSettings = await getLoginSettings({
serviceUrl,
organization: organization,
});
await humanMFAInitSkipped({ serviceUrl, userId });
const url =
requestId && sessionId
? await getNextUrl(
{
sessionId: sessionId,
requestId: requestId,
organization: organization,
},
loginSettings?.defaultRedirectUri,
)
: loginName
? await getNextUrl(
{
loginName: loginName,
organization: organization,
},
loginSettings?.defaultRedirectUri,
)
: null;
if (url) {
return { redirect: url };
}
}
export async function continueWithSession({
requestId,
...session
}: Session & { requestId?: string }) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const loginSettings = await getLoginSettings({
serviceUrl,
organization: session.factors?.user?.organizationId,
});
const url =
requestId && session.id && session.factors?.user
? await getNextUrl(
{
sessionId: session.id,
requestId: requestId,
organization: session.factors.user.organizationId,
},
loginSettings?.defaultRedirectUri,
)
: session.factors?.user
? await getNextUrl(
{
loginName: session.factors.user.loginName,
organization: session.factors.user.organizationId,
},
loginSettings?.defaultRedirectUri,
)
: null;
if (url) {
return { redirect: url };
}
}
export type UpdateSessionCommand = {
loginName?: string;
sessionId?: string;
organization?: string;
checks?: Checks;
requestId?: string;
challenges?: RequestChallenges;
lifetime?: Duration;
};
export async function updateSession(options: UpdateSessionCommand) {
let { loginName, sessionId, organization, checks, requestId, challenges } =
options;
const recentSession = sessionId
? await getSessionCookieById({ sessionId })
: loginName
? await getSessionCookieByLoginName({ loginName, organization })
: await getMostRecentSessionCookie();
if (!recentSession) {
return {
error: "Could not find session",
};
}
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "Could not get host" };
}
if (
host &&
challenges &&
challenges.webAuthN &&
!challenges.webAuthN.domain
) {
const [hostname] = host.split(":");
challenges.webAuthN.domain = hostname;
}
const loginSettings = await getLoginSettings({
serviceUrl,
organization,
});
let lifetime = checks?.webAuthN
? loginSettings?.multiFactorCheckLifetime // TODO different lifetime for webauthn u2f/passkey
: checks?.otpEmail || checks?.otpSms
? loginSettings?.secondFactorCheckLifetime
: undefined;
if (!lifetime) {
console.warn("No lifetime provided for session, defaulting to 24 hours");
lifetime = {
seconds: BigInt(60 * 60 * 24), // default to 24 hours
nanos: 0,
} as Duration;
}
const session = await setSessionAndUpdateCookie({
recentCookie: recentSession,
checks,
challenges,
requestId,
lifetime,
});
if (!session) {
return { error: "Could not update session" };
}
// if password, check if user has MFA methods
let authMethods;
if (checks && checks.password && session.factors?.user?.id) {
const response = await listAuthenticationMethodTypes({
serviceUrl,
userId: session.factors.user.id,
});
if (response.authMethodTypes && response.authMethodTypes.length) {
authMethods = response.authMethodTypes;
}
}
return {
sessionId: session.id,
factors: session.factors,
challenges: session.challenges,
authMethods,
};
}
type ClearSessionOptions = {
sessionId: string;
};
export async function clearSession(options: ClearSessionOptions) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const { sessionId } = options;
const sessionCookie = await getSessionCookieById({ sessionId });
const deleteResponse = await deleteSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
const securitySettings = await getSecuritySettings({ serviceUrl });
const sameSite = securitySettings?.embeddedIframe?.enabled ? "none" : true;
if (!deleteResponse) {
throw new Error("Could not delete session");
}
return removeSessionFromCookie({ session: sessionCookie, sameSite });
}
+103
View File
@@ -0,0 +1,103 @@
"use server";
import { getSession, registerU2F, verifyU2FRegistration } from "@/lib/zitadel";
import { create } from "@zitadel/client";
import { VerifyU2FRegistrationRequestSchema } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { headers } from "next/headers";
import { userAgent } from "next/server";
import { getSessionCookieById } from "../cookies";
import { getServiceUrlFromHeaders } from "../service-url";
type RegisterU2FCommand = {
sessionId: string;
};
type VerifyU2FCommand = {
u2fId: string;
passkeyName?: string;
publicKeyCredential: any;
sessionId: string;
};
export async function addU2F(command: RegisterU2FCommand) {
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 sessionCookie = await getSessionCookieById({
sessionId: command.sessionId,
});
if (!sessionCookie) {
return { error: "Could not get session" };
}
const session = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
});
const [hostname] = host.split(":");
if (!hostname) {
throw new Error("Could not get hostname");
}
const userId = session?.session?.factors?.user?.id;
if (!session || !userId) {
return { error: "Could not get session" };
}
return registerU2F({ serviceUrl, userId, domain: hostname });
}
export async function verifyU2F(command: VerifyU2FCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host || typeof host !== "string") {
throw new Error("No host found");
}
let passkeyName = command.passkeyName;
if (!passkeyName) {
const headersList = await headers();
const userAgentStructure = { headers: headersList };
const { browser, device, os } = userAgent(userAgentStructure);
passkeyName = `${device.vendor ?? ""} ${device.model ?? ""}${
device.vendor || device.model ? ", " : ""
}${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;
if (!userId) {
return { error: "Could not get session" };
}
const request = create(VerifyU2FRegistrationRequestSchema, {
u2fId: command.u2fId,
publicKeyCredential: command.publicKeyCredential,
tokenName: passkeyName,
userId,
});
return verifyU2FRegistration({ serviceUrl, request });
}
+329
View File
@@ -0,0 +1,329 @@
"use server";
import {
createInviteCode,
getLoginSettings,
getSession,
getUserByID,
listAuthenticationMethodTypes,
verifyEmail,
verifyInviteCode,
verifyTOTPRegistration,
sendEmailCode as zitadelSendEmailCode,
} from "@/lib/zitadel";
import crypto from "crypto";
import { create } from "@zitadel/client";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { cookies, headers } from "next/headers";
import { getNextUrl } from "../client";
import { getSessionCookieByLoginName } from "../cookies";
import { getOrSetFingerprintId } from "../fingerprint";
import { getServiceUrlFromHeaders } from "../service-url";
import { loadMostRecentSession } from "../session";
import { checkMFAFactors } from "../verify-helper";
import { createSessionAndUpdateCookie } from "./cookie";
export async function verifyTOTP(
code: string,
loginName?: string,
organization?: string,
) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
return loadMostRecentSession({
serviceUrl,
sessionParams: {
loginName,
organization,
},
}).then((session) => {
if (session?.factors?.user?.id) {
return verifyTOTPRegistration({
serviceUrl,
code,
userId: session.factors.user.id,
});
} else {
throw Error("No user id found in session.");
}
});
}
type VerifyUserByEmailCommand = {
userId: string;
loginName?: string; // to determine already existing session
organization?: string;
code: string;
isInvite: boolean;
requestId?: string;
};
export async function sendVerification(command: VerifyUserByEmailCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const verifyResponse = command.isInvite
? await verifyInviteCode({
serviceUrl,
userId: command.userId,
verificationCode: command.code,
}).catch((error) => {
console.warn(error);
return { error: "Could not verify invite" };
})
: await verifyEmail({
serviceUrl,
userId: command.userId,
verificationCode: command.code,
}).catch((error) => {
console.warn(error);
return { error: "Could not verify email" };
});
if ("error" in verifyResponse) {
return verifyResponse;
}
if (!verifyResponse) {
return { error: "Could not verify" };
}
let session: Session | undefined;
const userResponse = await getUserByID({
serviceUrl,
userId: command.userId,
});
if (!userResponse || !userResponse.user) {
return { error: "Could not load user" };
}
const user = userResponse.user;
const sessionCookie = await getSessionCookieByLoginName({
loginName:
"loginName" in command ? command.loginName : user.preferredLoginName,
organization: command.organization,
}).catch((error) => {
console.warn("Ignored error:", error); // checked later
});
if (sessionCookie) {
session = await getSession({
serviceUrl,
sessionId: sessionCookie.id,
sessionToken: sessionCookie.token,
}).then((response) => {
if (response?.session) {
return response.session;
}
});
}
// load auth methods for user
const authMethodResponse = await listAuthenticationMethodTypes({
serviceUrl,
userId: user.userId,
});
if (!authMethodResponse || !authMethodResponse.authMethodTypes) {
return { error: "Could not load possible authenticators" };
}
// if no authmethods are found on the user, redirect to set one up
if (
authMethodResponse &&
authMethodResponse.authMethodTypes &&
authMethodResponse.authMethodTypes.length == 0
) {
if (!sessionCookie) {
const checks = create(ChecksSchema, {
user: {
search: {
case: "loginName",
value: userResponse.user.preferredLoginName,
},
},
});
session = await createSessionAndUpdateCookie({
checks,
requestId: command.requestId,
});
}
if (!session) {
return { error: "Could not create session" };
}
const params = new URLSearchParams({
sessionId: session.id,
});
if (session.factors?.user?.loginName) {
params.set("loginName", session.factors?.user?.loginName);
}
// set hash of userId and userAgentId to prevent attacks, checks are done for users with invalid sessions and invalid userAgentId
const cookiesList = await cookies();
const userAgentId = await getOrSetFingerprintId();
const verificationCheck = crypto
.createHash("sha256")
.update(`${user.userId}:${userAgentId}`)
.digest("hex");
await cookiesList.set({
name: "verificationCheck",
value: verificationCheck,
httpOnly: true,
path: "/",
maxAge: 300, // 5 minutes
});
return { redirect: `/authenticator/set?${params}` };
}
// if no session found only show success page,
// if user is invited, recreate invite flow to not depend on session
if (!session?.factors?.user?.id) {
const verifySuccessParams = new URLSearchParams({});
if (command.userId) {
verifySuccessParams.set("userId", command.userId);
}
if (
("loginName" in command && command.loginName) ||
user.preferredLoginName
) {
verifySuccessParams.set(
"loginName",
"loginName" in command && command.loginName
? command.loginName
: user.preferredLoginName,
);
}
if (command.requestId) {
verifySuccessParams.set("requestId", command.requestId);
}
if (command.organization) {
verifySuccessParams.set("organization", command.organization);
}
return { redirect: `/verify/success?${verifySuccessParams}` };
}
const loginSettings = await getLoginSettings({
serviceUrl,
organization: user.details?.resourceOwner,
});
// redirect to mfa factor if user has one, or redirect to set one up
const mfaFactorCheck = await checkMFAFactors(
serviceUrl,
session,
loginSettings,
authMethodResponse.authMethodTypes,
command.organization,
command.requestId,
);
if (mfaFactorCheck?.redirect) {
return mfaFactorCheck;
}
// login user if no additional steps are required
if (command.requestId && session.id) {
const nextUrl = await getNextUrl(
{
sessionId: session.id,
requestId: command.requestId,
organization:
command.organization ?? session.factors?.user?.organizationId,
},
loginSettings?.defaultRedirectUri,
);
return { redirect: nextUrl };
}
const url = await getNextUrl(
{
loginName: session.factors.user.loginName,
organization: session.factors?.user?.organizationId,
},
loginSettings?.defaultRedirectUri,
);
return { redirect: url };
}
type resendVerifyEmailCommand = {
userId: string;
isInvite: boolean;
requestId?: string;
};
export async function resendVerification(command: resendVerifyEmailCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const host = _headers.get("host");
if (!host) {
return { error: "No host found" };
}
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
return command.isInvite
? createInviteCode({
serviceUrl,
userId: command.userId,
urlTemplate:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true` +
(command.requestId ? `&requestId=${command.requestId}` : ""),
}).catch((error) => {
if (error.code === 9) {
return { error: "User is already verified!" };
}
return { error: "Could not resend invite" };
})
: zitadelSendEmailCode({
userId: command.userId,
serviceUrl,
urlTemplate:
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` +
(command.requestId ? `&requestId=${command.requestId}` : ""),
});
}
type SendEmailCommand = {
userId: string;
urlTemplate: string;
};
export async function sendEmailCode(command: SendEmailCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
return zitadelSendEmailCode({
serviceUrl,
userId: command.userId,
urlTemplate: command.urlTemplate,
});
}
export async function sendInviteEmailCode(command: SendEmailCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
return createInviteCode({
serviceUrl,
userId: command.userId,
urlTemplate: command.urlTemplate,
});
}
+58
View File
@@ -0,0 +1,58 @@
import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
import { NextRequest } from "next/server";
/**
* Extracts the service url and region from the headers if used in a multitenant context (host, x-zitadel-forward-host header)
* or falls back to the ZITADEL_API_URL for a self hosting deployment
* or falls back to the host header for a self hosting deployment using custom domains
* @param headers
* @returns the service url and region from the headers
* @throws if the service url could not be determined
*
*/
export function getServiceUrlFromHeaders(headers: ReadonlyHeaders): {
serviceUrl: string;
} {
let instanceUrl;
const forwardedHost = headers.get("x-zitadel-forward-host");
// use the forwarded host if available (multitenant), otherwise fall back to the host of the deployment itself
if (forwardedHost) {
instanceUrl = forwardedHost;
instanceUrl = instanceUrl.startsWith("http://")
? instanceUrl
: `https://${instanceUrl}`;
} else if (process.env.ZITADEL_API_URL) {
instanceUrl = process.env.ZITADEL_API_URL;
} else {
const host = headers.get("host");
if (host) {
const [hostname] = host.split(":");
if (hostname !== "localhost") {
instanceUrl = host.startsWith("http") ? host : `https://${host}`;
}
}
}
if (!instanceUrl) {
throw new Error("Service URL could not be determined");
}
return {
serviceUrl: instanceUrl,
};
}
export function constructUrl(request: NextRequest, path: string) {
const forwardedProto = request.headers.get("x-forwarded-proto")
? `${request.headers.get("x-forwarded-proto")}:`
: request.nextUrl.protocol;
const forwardedHost =
request.headers.get("x-zitadel-forward-host") ??
request.headers.get("x-forwarded-host") ??
request.headers.get("host");
const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";
return new URL(`${basePath}${path}`, `${forwardedProto}//${forwardedHost}`);
}
+49
View File
@@ -0,0 +1,49 @@
import { createClientFor } from "@zitadel/client";
import { IdentityProviderService } from "@zitadel/proto/zitadel/idp/v2/idp_service_pb";
import { OIDCService } from "@zitadel/proto/zitadel/oidc/v2/oidc_service_pb";
import { OrganizationService } from "@zitadel/proto/zitadel/org/v2/org_service_pb";
import { SAMLService } from "@zitadel/proto/zitadel/saml/v2/saml_service_pb";
import { SessionService } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { SettingsService } from "@zitadel/proto/zitadel/settings/v2/settings_service_pb";
import { UserService } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { systemAPIToken } from "./api";
import { createServerTransport } from "./zitadel";
type ServiceClass =
| typeof IdentityProviderService
| typeof UserService
| typeof OrganizationService
| typeof SessionService
| typeof OIDCService
| typeof SettingsService
| typeof SAMLService;
export async function createServiceForHost<T extends ServiceClass>(
service: T,
serviceUrl: string,
) {
let token;
// if we are running in a multitenancy context, use the system user token
if (
process.env.AUDIENCE &&
process.env.SYSTEM_USER_ID &&
process.env.SYSTEM_USER_PRIVATE_KEY
) {
token = await systemAPIToken();
} else if (process.env.ZITADEL_SERVICE_USER_TOKEN) {
token = process.env.ZITADEL_SERVICE_USER_TOKEN;
}
if (!serviceUrl) {
throw new Error("No instance url found");
}
if (!token) {
throw new Error("No token found");
}
const transport = createServerTransport(token, serviceUrl);
return createClientFor<T>(service)(transport);
}
+193
View File
@@ -0,0 +1,193 @@
import { timestampDate } from "@zitadel/client";
import { AuthRequest } from "@zitadel/proto/zitadel/oidc/v2/authorization_pb";
import { SAMLRequest } from "@zitadel/proto/zitadel/saml/v2/authorization_pb";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { GetSessionResponse } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { getMostRecentCookieWithLoginname } from "./cookies";
import {
getLoginSettings,
getSession,
listAuthenticationMethodTypes,
} from "./zitadel";
type LoadMostRecentSessionParams = {
serviceUrl: string;
sessionParams: {
loginName?: string;
organization?: string;
};
};
export async function loadMostRecentSession({
serviceUrl,
sessionParams,
}: LoadMostRecentSessionParams): Promise<Session | undefined> {
const recent = await getMostRecentCookieWithLoginname({
loginName: sessionParams.loginName,
organization: sessionParams.organization,
});
return getSession({
serviceUrl,
sessionId: recent.id,
sessionToken: recent.token,
}).then((resp: GetSessionResponse) => resp.session);
}
/**
* mfa is required, session is not valid anymore (e.g. session expired, user logged out, etc.)
* to check for mfa for automatically selected session -> const response = await listAuthenticationMethodTypes(userId);
**/
export async function isSessionValid({
serviceUrl,
session,
}: {
serviceUrl: string;
session: Session;
}): Promise<boolean> {
// session can't be checked without user
if (!session.factors?.user) {
console.warn("Session has no user");
return false;
}
let mfaValid = true;
const authMethodTypes = await listAuthenticationMethodTypes({
serviceUrl,
userId: session.factors.user.id,
});
const authMethods = authMethodTypes.authMethodTypes;
if (authMethods && authMethods.includes(AuthenticationMethodType.TOTP)) {
mfaValid = !!session.factors.totp?.verifiedAt;
if (!mfaValid) {
console.warn(
"Session has no valid totpEmail factor",
session.factors.totp?.verifiedAt,
);
}
} else if (
authMethods &&
authMethods.includes(AuthenticationMethodType.OTP_EMAIL)
) {
mfaValid = !!session.factors.otpEmail?.verifiedAt;
if (!mfaValid) {
console.warn(
"Session has no valid otpEmail factor",
session.factors.otpEmail?.verifiedAt,
);
}
} else if (
authMethods &&
authMethods.includes(AuthenticationMethodType.OTP_SMS)
) {
mfaValid = !!session.factors.otpSms?.verifiedAt;
if (!mfaValid) {
console.warn(
"Session has no valid otpSms factor",
session.factors.otpSms?.verifiedAt,
);
}
} else if (
authMethods &&
authMethods.includes(AuthenticationMethodType.U2F)
) {
mfaValid = !!session.factors.webAuthN?.verifiedAt;
if (!mfaValid) {
console.warn(
"Session has no valid u2f factor",
session.factors.webAuthN?.verifiedAt,
);
}
} else {
// only check settings if no auth methods are available, as this would require a setup
const loginSettings = await getLoginSettings({
serviceUrl,
organization: session.factors?.user?.organizationId,
});
if (loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly) {
const otpEmail = session.factors.otpEmail?.verifiedAt;
const otpSms = session.factors.otpSms?.verifiedAt;
const totp = session.factors.totp?.verifiedAt;
const webAuthN = session.factors.webAuthN?.verifiedAt;
const idp = session.factors.intent?.verifiedAt; // TODO: forceMFA should not consider this as valid factor
// must have one single check
mfaValid = !!(otpEmail || otpSms || totp || webAuthN || idp);
if (!mfaValid) {
console.warn("Session has no valid multifactor", session.factors);
}
} else {
mfaValid = true;
}
}
const validPassword = session?.factors?.password?.verifiedAt;
const validPasskey = session?.factors?.webAuthN?.verifiedAt;
const validIDP = session?.factors?.intent?.verifiedAt;
const stillValid = session.expirationDate
? timestampDate(session.expirationDate).getTime() > new Date().getTime()
: true;
if (!stillValid) {
console.warn(
"Session is expired",
session.expirationDate
? timestampDate(session.expirationDate).toDateString()
: "no expiration date",
);
}
const validChecks = !!(validPassword || validPasskey || validIDP);
return stillValid && validChecks && mfaValid;
}
export async function findValidSession({
serviceUrl,
sessions,
authRequest,
samlRequest,
}: {
serviceUrl: string;
sessions: Session[];
authRequest?: AuthRequest;
samlRequest?: SAMLRequest;
}): Promise<Session | undefined> {
const sessionsWithHint = sessions.filter((s) => {
if (authRequest && authRequest.hintUserId) {
return s.factors?.user?.id === authRequest.hintUserId;
}
if (authRequest && authRequest.loginHint) {
return s.factors?.user?.loginName === authRequest.loginHint;
}
if (samlRequest) {
// TODO: do whatever
return true;
}
return true;
});
if (sessionsWithHint.length === 0) {
return undefined;
}
// sort by change date descending
sessionsWithHint.sort((a, b) => {
const dateA = a.changeDate ? timestampDate(a.changeDate).getTime() : 0;
const dateB = b.changeDate ? timestampDate(b.changeDate).getTime() : 0;
return dateB - dateA;
});
// return the first valid session according to settings
for (const session of sessionsWithHint) {
if (await isSessionValid({ serviceUrl, session })) {
return session;
}
}
return undefined;
}
+289
View File
@@ -0,0 +1,289 @@
import { timestampDate } from "@zitadel/client";
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import { PasswordExpirySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb";
import { HumanUser } from "@zitadel/proto/zitadel/user/v2/user_pb";
import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import crypto from "crypto";
import moment from "moment";
import { cookies } from "next/headers";
import { getFingerprintIdCookie } from "./fingerprint";
import { getUserByID } from "./zitadel";
export function checkPasswordChangeRequired(
expirySettings: PasswordExpirySettings | undefined,
session: Session,
humanUser: HumanUser | undefined,
organization?: string,
requestId?: string,
) {
let isOutdated = false;
if (expirySettings?.maxAgeDays && humanUser?.passwordChanged) {
const maxAgeDays = Number(expirySettings.maxAgeDays); // Convert bigint to number
const passwordChangedDate = moment(
timestampDate(humanUser.passwordChanged),
);
const outdatedPassword = passwordChangedDate.add(maxAgeDays, "days");
isOutdated = moment().isAfter(outdatedPassword);
}
if (humanUser?.passwordChangeRequired || isOutdated) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
});
if (organization || session.factors?.user?.organizationId) {
params.append(
"organization",
session.factors?.user?.organizationId as string,
);
}
if (requestId) {
params.append("requestId", requestId);
}
return { redirect: "/password/change?" + params };
}
}
export function checkEmailVerified(
session: Session,
humanUser?: HumanUser,
organization?: string,
requestId?: string,
) {
if (!humanUser?.email?.isVerified) {
const paramsVerify = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
userId: session.factors?.user?.id as string, // verify needs user id
send: "true", // we request a new email code once the page is loaded
});
if (organization || session.factors?.user?.organizationId) {
paramsVerify.append(
"organization",
organization ?? (session.factors?.user?.organizationId as string),
);
}
if (requestId) {
paramsVerify.append("requestId", requestId);
}
return { redirect: "/verify?" + paramsVerify };
}
}
export function checkEmailVerification(
session: Session,
humanUser?: HumanUser,
organization?: string,
requestId?: string,
) {
if (
!humanUser?.email?.isVerified &&
process.env.EMAIL_VERIFICATION === "true"
) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
send: "true", // set this to true as we dont expect old email codes to be valid anymore
});
if (requestId) {
params.append("requestId", requestId);
}
if (organization || session.factors?.user?.organizationId) {
params.append(
"organization",
organization ?? (session.factors?.user?.organizationId as string),
);
}
return { redirect: `/verify?` + params };
}
}
export async function checkMFAFactors(
serviceUrl: string,
session: Session,
loginSettings: LoginSettings | undefined,
authMethods: AuthenticationMethodType[],
organization?: string,
requestId?: string,
) {
const availableMultiFactors = authMethods?.filter(
(m: AuthenticationMethodType) =>
m !== AuthenticationMethodType.PASSWORD &&
m !== AuthenticationMethodType.PASSKEY,
);
const hasAuthenticatedWithPasskey =
session.factors?.webAuthN?.verifiedAt &&
session.factors?.webAuthN?.userVerified;
// escape further checks if user has authenticated with passkey
if (hasAuthenticatedWithPasskey) {
return;
}
// if user has not authenticated with passkey and has only one additional mfa factor, redirect to that
if (availableMultiFactors?.length == 1) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
});
if (requestId) {
params.append("requestId", requestId);
}
if (organization || session.factors?.user?.organizationId) {
params.append(
"organization",
organization ?? (session.factors?.user?.organizationId as string),
);
}
const factor = availableMultiFactors[0];
// if passwordless is other method, but user selected password as alternative, perform a login
if (factor === AuthenticationMethodType.TOTP) {
return { redirect: `/otp/time-based?` + params };
} else if (factor === AuthenticationMethodType.OTP_SMS) {
return { redirect: `/otp/sms?` + params };
} else if (factor === AuthenticationMethodType.OTP_EMAIL) {
return { redirect: `/otp/email?` + params };
} else if (factor === AuthenticationMethodType.U2F) {
return { redirect: `/u2f?` + params };
}
} else if (availableMultiFactors?.length > 1) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
});
if (requestId) {
params.append("requestId", requestId);
}
if (organization || session.factors?.user?.organizationId) {
params.append(
"organization",
organization ?? (session.factors?.user?.organizationId as string),
);
}
return { redirect: `/mfa?` + params };
} else if (
(loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly) &&
!availableMultiFactors.length
) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
force: "true", // this defines if the mfa is forced in the settings
checkAfter: "true", // this defines if the check is directly made after the setup
});
if (requestId) {
params.append("requestId", requestId);
}
if (organization || session.factors?.user?.organizationId) {
params.append(
"organization",
organization ?? (session.factors?.user?.organizationId as string),
);
}
// TODO: provide a way to setup passkeys on mfa page?
return { redirect: `/mfa/set?` + params };
} else if (
loginSettings?.mfaInitSkipLifetime &&
(loginSettings.mfaInitSkipLifetime.nanos > 0 ||
loginSettings.mfaInitSkipLifetime.seconds > 0) &&
!availableMultiFactors.length &&
session?.factors?.user?.id
) {
const userResponse = await getUserByID({
serviceUrl,
userId: session.factors?.user?.id,
});
const humanUser =
userResponse?.user?.type.case === "human"
? userResponse?.user.type.value
: undefined;
if (humanUser?.mfaInitSkipped) {
const mfaInitSkippedTimestamp = timestampDate(humanUser.mfaInitSkipped);
const mfaInitSkipLifetimeMillis =
Number(loginSettings.mfaInitSkipLifetime.seconds) * 1000 +
loginSettings.mfaInitSkipLifetime.nanos / 1000000;
const currentTime = Date.now();
const mfaInitSkippedTime = mfaInitSkippedTimestamp.getTime();
const timeDifference = currentTime - mfaInitSkippedTime;
if (!(timeDifference > mfaInitSkipLifetimeMillis)) {
// if the time difference is smaller than the lifetime, skip the mfa setup
return;
}
}
// the user has never skipped the mfa init but we have a setting so we redirect
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
force: "false", // this defines if the mfa is not forced in the settings and can be skipped
checkAfter: "true", // this defines if the check is directly made after the setup
});
if (requestId) {
params.append("requestId", requestId);
}
if (organization || session.factors?.user?.organizationId) {
params.append(
"organization",
organization ?? (session.factors?.user?.organizationId as string),
);
}
// TODO: provide a way to setup passkeys on mfa page?
return { redirect: `/mfa/set?` + params };
}
}
export async function checkUserVerification(userId: string): Promise<boolean> {
// check if a verification was done earlier
const cookiesList = await cookies();
// only read cookie to prevent issues on page.tsx
const fingerPrintCookie = await getFingerprintIdCookie();
if (!fingerPrintCookie || !fingerPrintCookie.value) {
return false;
}
const verificationCheck = crypto
.createHash("sha256")
.update(`${userId}:${fingerPrintCookie.value}`)
.digest("hex");
const cookieValue = await cookiesList.get("verificationCheck")?.value;
if (!cookieValue) {
console.warn(
"User verification check cookie not found. User verification check failed.",
);
return false;
}
if (cookieValue !== verificationCheck) {
console.warn(
`User verification check failed. Expected ${verificationCheck} but got ${cookieValue}`,
);
return false;
}
return true;
}
File diff suppressed because it is too large Load Diff