Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: added reusable logic for the verify alias

=32815c01f105
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 2a7dc22076..4cd5325416 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -226,12 +226,9 @@ declare module "fastify" {
rootOrgId: string;
};
rateLimits: RateLimitConfiguration;
- // passport data
- passportUser: {
- isUserCompleted: boolean;
- providerAuthToken: string;
- externalProviderAccessToken?: string;
- };
+ // passport data — result from processProviderCallback
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ passportUser: any;
passportMachineIdentity: {
identityId: string;
user: {
diff --git a/backend/src/ee/routes/v1/ldap-router.ts b/backend/src/ee/routes/v1/ldap-router.ts
index c6d9f89648..8e17af35fb 100644
--- a/backend/src/ee/routes/v1/ldap-router.ts
+++ b/backend/src/ee/routes/v1/ldap-router.ts
@@ -9,6 +9,7 @@
import { IncomingMessage } from "node:http";
import { Authenticator } from "@fastify/passport";
+import { requestContext } from "@fastify/request-context";
import fastifySession from "@fastify/session";
import { FastifyRequest } from "fastify";
import LdapStrategy from "passport-ldapauth";
@@ -25,7 +26,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { SanitizedLdapConfigSchema } from "@app/server/routes/sanitizedSchema/directory-config";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { AuthMode, ProviderAuthResult } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
export const registerLdapRouter = async (server: FastifyZodProvider) => {
@@ -77,7 +78,7 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
const externalId = ldapConfig.uniqueUserAttribute ? user[ldapConfig.uniqueUserAttribute] : user.uidNumber;
const username = ldapConfig.uniqueUserAttribute ? externalId : user.uid;
- const { isUserCompleted, providerAuthToken } = await server.services.ldap.ldapLogin({
+ const loginResult = await server.services.ldap.ldapLogin({
externalId,
username,
ldapConfigId: ldapConfig.id,
@@ -85,11 +86,13 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
lastName: user.sn ?? "",
email: user.mail,
groups,
+ ip: requestContext.get("ip") || "",
+ userAgent: requestContext.get("userAgent") || "",
relayState: ((req as unknown as FastifyRequest).body as { RelayState?: string }).RelayState,
orgId: (req as unknown as FastifyRequest).ldapConfig.organization
});
- return cb(null, { isUserCompleted, providerAuthToken });
+ return cb(null, loginResult);
} catch (error) {
logger.error(error);
return cb(error, false);
@@ -116,16 +119,26 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
// this is due to zod type difference
}) as any,
handler: (req, res) => {
+ const passportResult = req.passportUser;
let nextUrl;
- if (req.passportUser.isUserCompleted) {
- nextUrl = `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`;
+
+ if (passportResult.result === ProviderAuthResult.SESSION) {
+ void res.setCookie("jid", passportResult.tokens.refresh, {
+ httpOnly: true,
+ path: "/",
+ sameSite: "strict",
+ secure: appCfg.HTTPS_ENABLED
+ });
+ nextUrl = `${appCfg.SITE_URL}/login/select-organization`;
+ } else if (passportResult.result === ProviderAuthResult.MFA_REQUIRED) {
+ nextUrl = `${appCfg.SITE_URL}/login/select-organization?mfaToken=${encodeURIComponent(passportResult.mfaToken)}&mfaMethod=${passportResult.mfaMethod}`;
+ } else if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
+ nextUrl = `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`;
} else {
- nextUrl = `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`;
+ throw new BadRequestError({ message: "Unexpected auth result" });
}
- return res.status(200).send({
- nextUrl
- });
+ return res.status(200).send({ nextUrl });
}
});
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index 95ad7c08f7..11c37dce5c 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -17,9 +17,10 @@ import { ApiDocsTags, OidcSSo } from "@app/lib/api-docs";
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { AuthMode, ProviderAuthResult } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
const SanitizedOidcConfigSchema = OidcConfigsSchema.pick({
@@ -123,17 +124,30 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
],
handler: async (req, res) => {
await req.session.destroy();
+ const passportResult = req.passportUser;
- if (req.passportUser.isUserCompleted) {
+ if (passportResult.result === ProviderAuthResult.SESSION) {
+ void res.setCookie("jid", passportResult.tokens.refresh, {
+ httpOnly: true,
+ path: "/",
+ sameSite: "strict",
+ secure: appCfg.HTTPS_ENABLED
+ });
+ addAuthOriginDomainCookie(res);
+ return res.redirect(`${appCfg.SITE_URL}/login/select-organization`);
+ }
+
+ if (passportResult.result === ProviderAuthResult.MFA_REQUIRED) {
return res.redirect(
- `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`
+ `${appCfg.SITE_URL}/login/select-organization?mfaToken=${encodeURIComponent(passportResult.mfaToken)}&mfaMethod=${passportResult.mfaMethod}`
);
}
- // signup
- return res.redirect(
- `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`
- );
+ if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
+ return res.redirect(`${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`);
+ }
+
+ throw new Error("Unexpected auth result");
}
});
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 54fd740ead..43d9cdbbee 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -20,10 +20,11 @@ import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { SanitizedSamlConfigSchema } from "@app/server/routes/sanitizedSchema/directory-config";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { AuthMode, ProviderAuthResult } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
type TSAMLConfig = {
@@ -152,7 +153,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
})
.filter((el) => el.key && !["email", "firstName", "lastName"].includes(el.key));
- const { isUserCompleted, providerAuthToken, user, organization } = await server.services.saml.samlLogin({
+ const loginResult = await server.services.saml.samlLogin({
externalId: profile.nameID,
email: email.toLowerCase(),
firstName,
@@ -160,15 +161,17 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
relayState: (req.body as { RelayState?: string }).RelayState,
authProvider: (req as unknown as FastifyRequest).ssoConfig?.authProvider,
orgId: (req as unknown as FastifyRequest).ssoConfig?.orgId,
+ ip: requestContext.get("ip") || "",
+ userAgent: requestContext.get("userAgent") || "",
metadata: userMetadata
});
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": email.toLowerCase(),
- "infisical.user.id": user.id,
- "infisical.organization.id": organization.id,
- "infisical.organization.name": organization.name,
+ "infisical.user.id": loginResult.user.id,
+ "infisical.organization.id": loginResult.organization.id,
+ "infisical.organization.name": loginResult.organization.name,
"infisical.auth.method": AuthAttemptAuthMethod.SAML,
"infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
"client.address": requestContext.get("ip"),
@@ -176,7 +179,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
});
}
- cb(null, { isUserCompleted, providerAuthToken });
+ cb(null, loginResult);
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
@@ -274,18 +277,34 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
if (err) {
throw new BadRequestError({ message: `Saml authentication failed. ${err?.message}`, error: err });
}
- req.passportUser = user as { isUserCompleted: boolean; providerAuthToken: string };
+ req.passportUser = user;
}
) as any, // this is due to zod type difference
handler: (req, res) => {
- if (req.passportUser.isUserCompleted) {
+ const passportResult = req.passportUser;
+
+ if (passportResult.result === ProviderAuthResult.SESSION) {
+ void res.setCookie("jid", passportResult.tokens.refresh, {
+ httpOnly: true,
+ path: "/",
+ sameSite: "strict",
+ secure: appCfg.HTTPS_ENABLED
+ });
+ addAuthOriginDomainCookie(res);
+ return res.redirect(`${appCfg.SITE_URL}/login/select-organization`);
+ }
+
+ if (passportResult.result === ProviderAuthResult.MFA_REQUIRED) {
return res.redirect(
- `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`
+ `${appCfg.SITE_URL}/login/select-organization?mfaToken=${encodeURIComponent(passportResult.mfaToken)}&mfaMethod=${passportResult.mfaMethod}`
);
}
- return res.redirect(
- `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`
- );
+
+ if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
+ return res.redirect(`${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`);
+ }
+
+ throw new BadRequestError({ message: "Unexpected auth result" });
}
});
diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.ts
index ae287bb39e..231df210e7 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -13,10 +13,9 @@ import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
-import { getConfig } from "@app/lib/config/env";
-import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
+import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
+import { AuthMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -86,6 +85,7 @@ type TLdapConfigServiceFactoryDep = {
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
smtpService: Pick<TSmtpService, "sendMail">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ loginService: Pick<TAuthLoginFactory, "processProviderCallback">;
};
export type TLdapConfigServiceFactory = ReturnType<typeof ldapConfigServiceFactory>;
@@ -107,7 +107,8 @@ export const ldapConfigServiceFactory = ({
licenseService,
tokenService,
smtpService,
- kmsService
+ kmsService,
+ loginService
}: TLdapConfigServiceFactoryDep) => {
const createLdapCfg = async ({
actor,
@@ -392,9 +393,10 @@ export const ldapConfigServiceFactory = ({
email,
groups,
orgId,
+ ip,
+ userAgent,
relayState
}: TLdapLoginDTO) => {
- const appCfg = getConfig();
const serverCfg = await getServerCfg();
if (serverCfg.enabledLoginMethods && !serverCfg.enabledLoginMethods.includes(LoginMethod.LDAP)) {
@@ -649,35 +651,6 @@ export const ldapConfigServiceFactory = ({
return newUser;
});
- const isUserCompleted = Boolean(user.isAccepted) && userAlias.isEmailVerified;
- const providerAuthToken = crypto.jwt().sign(
- {
- authTokenType: AuthTokenType.PROVIDER_TOKEN,
- userId: user.id,
- username: user.username,
- hasExchangedPrivateKey: true,
- ...(user.email && { email: user.email, isEmailVerified: userAlias.isEmailVerified }),
- firstName,
- lastName,
- organizationName: organization.name,
- organizationId: organization.id,
- organizationSlug: organization.slug,
- authMethod: AuthMethod.LDAP,
- authType: UserAliasType.LDAP,
- aliasId: userAlias.id,
- isUserCompleted,
- ...(relayState
- ? {
- callbackPort: (JSON.parse(relayState) as { callbackPort: string }).callbackPort
- }
- : {})
- },
- appCfg.AUTH_SECRET,
- {
- expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME
- }
- );
-
if (user.email && !userAlias.isEmailVerified) {
const token = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_VERIFICATION,
@@ -695,7 +668,21 @@ export const ldapConfigServiceFactory = ({
});
}
- return { isUserCompleted, providerAuthToken };
+ const callbackPort = relayState ? (JSON.parse(relayState) as { callbackPort: string }).callbackPort : undefined;
+
+ const callbackResult = await loginService.processProviderCallback({
+ user,
+ authMethod: AuthMethod.LDAP,
+ isAliasVerified: Boolean(userAlias.isEmailVerified),
+ isEmailVerified: Boolean(userAlias.isEmailVerified),
+ aliasId: userAlias.id,
+ ip,
+ userAgent,
+ organizationId: organization.id,
+ callbackPort
+ });
+
+ return callbackResult;
};
const getLdapGroupMaps = async ({
diff --git a/backend/src/ee/services/ldap-config/ldap-config-types.ts b/backend/src/ee/services/ldap-config/ldap-config-types.ts
index effee5dac4..78052bba05 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-types.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-types.ts
@@ -61,6 +61,8 @@ export type TLdapLoginDTO = {
lastName: string;
email: string;
orgId: string;
+ ip: string;
+ userAgent: string;
groups?: {
dn: string;
cn: string;
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 974bf4b9e4..36684379c4 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -14,12 +14,12 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-service
import { OrgPermissionSsoActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { getConfig } from "@app/lib/config/env";
-import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError, OidcAuthError } from "@app/lib/errors";
import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
import { OrgServiceActor } from "@app/lib/types";
import { blockLocalAndPrivateIpAddresses, matchesAllowedEmailDomain } from "@app/lib/validator";
-import { ActorType, AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
+import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -87,6 +87,7 @@ type TOidcConfigServiceFactoryDep = {
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ loginService: Pick<TAuthLoginFactory, "processProviderCallback">;
};
export type TOidcConfigServiceFactory = ReturnType<typeof oidcConfigServiceFactory>;
@@ -108,7 +109,8 @@ export const oidcConfigServiceFactory = ({
projectDAL,
projectBotDAL,
auditLogService,
- kmsService
+ kmsService,
+ loginService
}: TOidcConfigServiceFactoryDep) => {
const getOidc = async (dto: TGetOidcCfgDTO) => {
const oidcCfg = await oidcConfigDAL.findOne({
@@ -172,6 +174,8 @@ export const oidcConfigServiceFactory = ({
firstName,
lastName,
orgId,
+ ip,
+ userAgent,
callbackPort,
groups = [],
manageGroupMemberships
@@ -184,7 +188,6 @@ export const oidcConfigServiceFactory = ({
});
}
- const appCfg = getConfig();
let userAlias = await userAliasDAL.findOne({
externalId,
orgId,
@@ -454,31 +457,6 @@ export const oidcConfigServiceFactory = ({
await licenseService.updateSubscriptionOrgMemberCount(organization.id);
- const isUserCompleted = Boolean(user.isAccepted) && userAlias.isEmailVerified;
- const providerAuthToken = crypto.jwt().sign(
- {
- authTokenType: AuthTokenType.PROVIDER_TOKEN,
- userId: user.id,
- username: user.username,
- ...(user.email && { email: user.email, isEmailVerified: userAlias.isEmailVerified }),
- firstName,
- lastName,
- organizationName: organization.name,
- organizationId: organization.id,
- organizationSlug: organization.slug,
- hasExchangedPrivateKey: true,
- aliasId: userAlias.id,
- authMethod: AuthMethod.OIDC,
- authType: UserAliasType.OIDC,
- isUserCompleted,
- ...(callbackPort && { callbackPort })
- },
- appCfg.AUTH_SECRET,
- {
- expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME
- }
- );
-
await oidcConfigDAL.update({ orgId }, { lastUsed: new Date() });
if (user.email && !userAlias.isEmailVerified) {
@@ -504,7 +482,19 @@ export const oidcConfigServiceFactory = ({
});
}
- return { isUserCompleted, providerAuthToken, user };
+ const callbackResult = await loginService.processProviderCallback({
+ user,
+ authMethod: AuthMethod.OIDC,
+ isAliasVerified: Boolean(userAlias.isEmailVerified),
+ isEmailVerified: Boolean(userAlias.isEmailVerified),
+ aliasId: userAlias.id,
+ ip,
+ userAgent,
+ organizationId: organization.id,
+ callbackPort
+ });
+
+ return { ...callbackResult, user };
};
const updateOidcCfg = async ({
@@ -810,15 +800,17 @@ export const oidcConfigServiceFactory = ({
firstName: name,
lastName: claims.family_name ?? "",
orgId: org.id,
+ ip: requestContext.get("ip") || "",
+ userAgent: requestContext.get("userAgent") || "",
groups,
callbackPort,
manageGroupMemberships: oidcCfg.manageGroupMemberships
})
- .then(({ isUserCompleted, providerAuthToken, user }) => {
+ .then((loginResult) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": claims?.email?.toLowerCase(),
- "infisical.user.id": user.id,
+ "infisical.user.id": loginResult.user?.id,
"infisical.organization.id": org.id,
"infisical.organization.name": org.name,
"infisical.auth.method": AuthAttemptAuthMethod.OIDC,
@@ -828,7 +820,7 @@ export const oidcConfigServiceFactory = ({
});
}
- cb(null, { isUserCompleted, providerAuthToken });
+ cb(null, loginResult);
})
.catch((error) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
diff --git a/backend/src/ee/services/oidc/oidc-config-types.ts b/backend/src/ee/services/oidc/oidc-config-types.ts
index f38f2172f1..fb1bdd57fa 100644
--- a/backend/src/ee/services/oidc/oidc-config-types.ts
+++ b/backend/src/ee/services/oidc/oidc-config-types.ts
@@ -18,6 +18,8 @@ export type TOidcLoginDTO = {
firstName: string;
lastName?: string;
orgId: string;
+ ip: string;
+ userAgent: string;
callbackPort?: string;
groups?: string[];
manageGroupMemberships?: boolean | null;
diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.ts
index 85fddab620..5291631e57 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -15,10 +15,9 @@ import {
TUsers
} from "@app/db/schemas";
import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
-import { getConfig } from "@app/lib/config/env";
-import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { AuthTokenType } from "@app/services/auth/auth-type";
+import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
+import { AuthMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TIdentityMetadataDALFactory } from "@app/services/identity/identity-metadata-dal";
@@ -85,6 +84,7 @@ type TSamlConfigServiceFactoryDep = {
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete" | "findLatestProjectKey" | "insertMany">;
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find" | "create">;
+ loginService: Pick<TAuthLoginFactory, "processProviderCallback">;
};
export const samlConfigServiceFactory = ({
@@ -104,7 +104,8 @@ export const samlConfigServiceFactory = ({
identityMetadataDAL,
kmsService,
membershipRoleDAL,
- membershipGroupDAL
+ membershipGroupDAL,
+ loginService
}: TSamlConfigServiceFactoryDep): TSamlConfigServiceFactory => {
const parseSamlGroups = (groupsValue: string): string[] => {
let samlGroups: string[] = [];
@@ -504,10 +505,11 @@ export const samlConfigServiceFactory = ({
lastName,
authProvider,
orgId,
+ ip,
+ userAgent,
relayState,
metadata
}) => {
- const appCfg = getConfig();
const serverCfg = await getServerCfg();
if (serverCfg.enabledLoginMethods && !serverCfg.enabledLoginMethods.includes(LoginMethod.SAML)) {
@@ -748,35 +750,6 @@ export const samlConfigServiceFactory = ({
}
await licenseService.updateSubscriptionOrgMemberCount(organization.id);
- const isUserCompleted = Boolean(user.isAccepted && userAlias.isEmailVerified);
- const providerAuthToken = crypto.jwt().sign(
- {
- authTokenType: AuthTokenType.PROVIDER_TOKEN,
- userId: user.id,
- username: user.username,
- ...(user.email && { email: user.email, isEmailVerified: userAlias.isEmailVerified }),
- firstName,
- lastName,
- organizationName: organization.name,
- organizationId: organization.id,
- organizationSlug: organization.slug,
- authMethod: authProvider,
- hasExchangedPrivateKey: true,
- aliasId: userAlias.id,
- authType: UserAliasType.SAML,
- isUserCompleted,
- ...(relayState
- ? {
- callbackPort: (JSON.parse(relayState) as { callbackPort: string }).callbackPort
- }
- : {})
- },
- appCfg.AUTH_SECRET,
- {
- expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME
- }
- );
-
await samlConfigDAL.update({ orgId }, { lastUsed: new Date() });
if (user.email && !userAlias.isEmailVerified) {
@@ -796,7 +769,21 @@ export const samlConfigServiceFactory = ({
});
}
- return { isUserCompleted, providerAuthToken, user, organization };
+ const callbackPort = relayState ? (JSON.parse(relayState) as { callbackPort: string }).callbackPort : undefined;
+
+ const callbackResult = await loginService.processProviderCallback({
+ user,
+ authMethod: authProvider as AuthMethod,
+ isAliasVerified: Boolean(userAlias.isEmailVerified),
+ isEmailVerified: Boolean(userAlias.isEmailVerified),
+ aliasId: userAlias.id,
+ ip,
+ userAgent,
+ organizationId: organization.id,
+ callbackPort
+ });
+
+ return { ...callbackResult, user, organization };
};
return {
diff --git a/backend/src/ee/services/saml-config/saml-config-types.ts b/backend/src/ee/services/saml-config/saml-config-types.ts
index 5ca3e09fb6..747f1f10dc 100644
--- a/backend/src/ee/services/saml-config/saml-config-types.ts
+++ b/backend/src/ee/services/saml-config/saml-config-types.ts
@@ -1,5 +1,6 @@
import { TOrganizations, TSamlConfigs, TUsers } from "@app/db/schemas";
import { TOrgPermission } from "@app/lib/types";
+import { TProviderAuthResult } from "@app/services/auth/auth-login-type";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
export enum SamlProviders {
@@ -55,6 +56,8 @@ export type TSamlLoginDTO = {
lastName?: string;
authProvider: string;
orgId: string;
+ ip: string;
+ userAgent: string;
// saml thingy
relayState?: string;
metadata?: { key: string; value: string }[];
@@ -75,10 +78,10 @@ export type TSamlConfigServiceFactory = {
lastUsed: Date | null | undefined;
enableGroupSync?: boolean;
}>;
- samlLogin: (arg: TSamlLoginDTO) => Promise<{
- isUserCompleted: boolean;
- providerAuthToken: string;
- user: TUsers;
- organization: TOrganizations;
- }>;
+ samlLogin: (arg: TSamlLoginDTO) => Promise<
+ TProviderAuthResult & {
+ user: TUsers;
+ organization: TOrganizations;
+ }
+ >;
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7df02dc95c..bd07dcb0aa 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -848,25 +848,7 @@ export const registerRoutes = async (
secretApprovalRequestDAL
});
- const samlService = samlConfigServiceFactory({
- identityMetadataDAL,
- permissionService,
- orgDAL,
- userDAL,
- userAliasDAL,
- samlConfigDAL,
- groupDAL,
- userGroupMembershipDAL,
- projectDAL,
- projectBotDAL,
- projectKeyDAL,
- licenseService,
- tokenService,
- smtpService,
- kmsService,
- membershipRoleDAL,
- membershipGroupDAL
- });
+ // samlService is created after loginService (below) due to dependency on processProviderCallback
const groupService = groupServiceFactory({
identityDAL,
membershipDAL,
@@ -958,25 +940,7 @@ export const registerRoutes = async (
membershipGroupDAL
});
- const ldapService = ldapConfigServiceFactory({
- ldapConfigDAL,
- ldapGroupMapDAL,
- orgDAL,
- groupDAL,
- projectKeyDAL,
- projectDAL,
- projectBotDAL,
- userGroupMembershipDAL,
- userDAL,
- userAliasDAL,
- permissionService,
- licenseService,
- tokenService,
- smtpService,
- kmsService,
- membershipGroupDAL,
- membershipRoleDAL
- });
+ // ldapService is created after loginService (below) due to dependency on processProviderCallback
const telemetryService = telemetryServiceFactory({
keyStore,
@@ -1035,6 +999,48 @@ export const registerRoutes = async (
keyStore,
permissionService
});
+
+ const samlService = samlConfigServiceFactory({
+ identityMetadataDAL,
+ permissionService,
+ orgDAL,
+ userDAL,
+ userAliasDAL,
+ samlConfigDAL,
+ groupDAL,
+ userGroupMembershipDAL,
+ projectDAL,
+ projectBotDAL,
+ projectKeyDAL,
+ licenseService,
+ tokenService,
+ smtpService,
+ kmsService,
+ membershipRoleDAL,
+ membershipGroupDAL,
+ loginService
+ });
+
+ const ldapService = ldapConfigServiceFactory({
+ ldapConfigDAL,
+ ldapGroupMapDAL,
+ orgDAL,
+ groupDAL,
+ projectKeyDAL,
+ projectDAL,
+ projectBotDAL,
+ userGroupMembershipDAL,
+ userDAL,
+ userAliasDAL,
+ permissionService,
+ licenseService,
+ tokenService,
+ smtpService,
+ kmsService,
+ membershipGroupDAL,
+ membershipRoleDAL,
+ loginService
+ });
const passwordService = authPaswordServiceFactory({
tokenService,
smtpService,
@@ -1105,8 +1111,10 @@ export const registerRoutes = async (
smtpService,
authDAL,
userDAL,
+ userAliasDAL,
orgDAL,
- orgService
+ orgService,
+ loginService
});
const microsoftTeamsService = microsoftTeamsServiceFactory({
@@ -2201,7 +2209,8 @@ export const registerRoutes = async (
groupDAL,
auditLogService,
membershipGroupDAL,
- membershipRoleDAL
+ membershipRoleDAL,
+ loginService
});
const userEngagementService = userEngagementServiceFactory({
diff --git a/backend/src/server/routes/v1/password-router.ts b/backend/src/server/routes/v1/password-router.ts
index 53c70ca51d..1e5cd681bc 100644
--- a/backend/src/server/routes/v1/password-router.ts
+++ b/backend/src/server/routes/v1/password-router.ts
@@ -24,7 +24,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const token = validateSignUpAuthorization(req.headers.authorization as string, "", false)!;
+ const token = validateSignUpAuthorization(req.headers.authorization as string, "", false);
const backupPrivateKey = await server.services.password.getBackupPrivateKeyOfUser(token.userId);
if (!backupPrivateKey) throw new Error("Failed to find backup key");
@@ -58,7 +58,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const token = validateSignUpAuthorization(req.headers.authorization as string, "", false)!;
+ const token = validateSignUpAuthorization(req.headers.authorization as string, "", false);
await server.services.password.resetPasswordByBackupKey({
...req.body,
userId: token.userId
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index edd2eb9503..fe39379a4d 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -25,7 +25,7 @@ import { fetchGithubEmails, fetchGithubUser } from "@app/lib/requests/github";
import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
import { authRateLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
-import { AuthMethod } from "@app/services/auth/auth-type";
+import { AuthMethod, ProviderAuthResult } from "@app/services/auth/auth-type";
import { OrgAuthMethod } from "@app/services/org/org-types";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
@@ -66,27 +66,28 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
try {
- const { isUserCompleted, providerAuthToken, user, orgId, orgName } =
- await server.services.login.oauth2Login({
- email,
- firstName: profile?.name?.givenName || "",
- lastName: profile?.name?.familyName || "",
- authMethod: AuthMethod.GOOGLE,
- callbackPort,
- orgSlug,
- providerUserId: profile.id
- });
+ const loginResult = await server.services.login.oauth2Login({
+ email,
+ firstName: profile?.name?.givenName || "",
+ lastName: profile?.name?.familyName || "",
+ authMethod: AuthMethod.GOOGLE,
+ callbackPort,
+ orgSlug,
+ providerUserId: profile.id,
+ ip: requestContext.get("ip") || "",
+ userAgent: requestContext.get("userAgent") || ""
+ });
- const googleDistinctId = user.username ?? user.email ?? "";
+ const googleDistinctId = loginResult.user.username ?? loginResult.user.email ?? "";
if (googleDistinctId) {
void server.services.telemetry.identifyUser(
googleDistinctId,
{
- email: user.email ?? undefined,
- username: user.username,
- userId: user.id,
- firstName: user.firstName ?? undefined,
- lastName: user.lastName ?? undefined
+ email: loginResult.user.email ?? undefined,
+ username: loginResult.user.username,
+ userId: loginResult.user.id,
+ firstName: loginResult.user.firstName ?? undefined,
+ lastName: loginResult.user.lastName ?? undefined
},
{ skipDedup: true }
);
@@ -95,9 +96,9 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": email,
- "infisical.user.id": user.id,
- "infisical.organization.id": orgId,
- "infisical.organization.name": orgName,
+ "infisical.user.id": loginResult.user.id,
+ "infisical.organization.id": loginResult.orgId,
+ "infisical.organization.name": loginResult.orgName,
"infisical.auth.method": AuthAttemptAuthMethod.GOOGLE,
"infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
"client.address": requestContext.get("ip"),
@@ -105,7 +106,7 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
- cb(null, { isUserCompleted, providerAuthToken });
+ cb(null, loginResult);
} catch (error) {
logger.error(error);
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -154,26 +155,27 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
const callbackPort = req.session.get("callbackPort");
- const { isUserCompleted, providerAuthToken, user, orgId, orgName } =
- await server.services.login.oauth2Login({
- email,
- firstName: githubUser.name || githubUser.login,
- lastName: "",
- authMethod: AuthMethod.GITHUB,
- callbackPort,
- providerUserId: String(githubUser.id)
- });
+ const loginResult = await server.services.login.oauth2Login({
+ email,
+ firstName: githubUser.name || githubUser.login,
+ lastName: "",
+ authMethod: AuthMethod.GITHUB,
+ callbackPort,
+ providerUserId: String(githubUser.id),
+ ip: requestContext.get("ip") || "",
+ userAgent: requestContext.get("userAgent") || ""
+ });
- const githubDistinctId = user.username ?? user.email ?? "";
+ const githubDistinctId = loginResult.user.username ?? loginResult.user.email ?? "";
if (githubDistinctId) {
void server.services.telemetry.identifyUser(
githubDistinctId,
{
- email: user.email ?? undefined,
- username: user.username,
- userId: user.id,
- firstName: user.firstName ?? undefined,
- lastName: user.lastName ?? undefined
+ email: loginResult.user.email ?? undefined,
+ username: loginResult.user.username,
+ userId: loginResult.user.id,
+ firstName: loginResult.user.firstName ?? undefined,
+ lastName: loginResult.user.lastName ?? undefined
},
{ skipDedup: true }
);
@@ -182,9 +184,9 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": email,
- "infisical.user.id": user.id,
- "infisical.organization.id": orgId,
- "infisical.organization.name": orgName,
+ "infisical.user.id": loginResult.user.id,
+ "infisical.organization.id": loginResult.orgId,
+ "infisical.organization.name": loginResult.orgName,
"infisical.auth.method": AuthAttemptAuthMethod.GITHUB,
"infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
"client.address": requestContext.get("ip"),
@@ -192,7 +194,7 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
- done(null, { isUserCompleted, providerAuthToken, externalProviderAccessToken: accessToken });
+ done(null, { ...loginResult, externalProviderAccessToken: accessToken });
} catch (err) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
@@ -233,26 +235,27 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
try {
const callbackPort = req.session.get("callbackPort");
- const { isUserCompleted, providerAuthToken, user, orgId, orgName } =
- await server.services.login.oauth2Login({
- email,
- firstName: profile.displayName || profile.username || "",
- lastName: "",
- authMethod: AuthMethod.GITLAB,
- callbackPort,
- providerUserId: String(profile.id)
- });
+ const loginResult = await server.services.login.oauth2Login({
+ email,
+ firstName: profile.displayName || profile.username || "",
+ lastName: "",
+ authMethod: AuthMethod.GITLAB,
+ callbackPort,
+ providerUserId: String(profile.id),
+ ip: requestContext.get("ip") || "",
+ userAgent: requestContext.get("userAgent") || ""
+ });
- const gitlabDistinctId = user.username ?? user.email ?? "";
+ const gitlabDistinctId = loginResult.user.username ?? loginResult.user.email ?? "";
if (gitlabDistinctId) {
void server.services.telemetry.identifyUser(
gitlabDistinctId,
{
- email: user.email ?? undefined,
- username: user.username,
- userId: user.id,
- firstName: user.firstName ?? undefined,
- lastName: user.lastName ?? undefined
+ email: loginResult.user.email ?? undefined,
+ username: loginResult.user.username,
+ userId: loginResult.user.id,
+ firstName: loginResult.user.firstName ?? undefined,
+ lastName: loginResult.user.lastName ?? undefined
},
{ skipDedup: true }
);
@@ -261,9 +264,9 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": email,
- "infisical.user.id": user.id,
- "infisical.organization.id": orgId,
- "infisical.organization.name": orgName,
+ "infisical.user.id": loginResult.user.id,
+ "infisical.organization.id": loginResult.orgId,
+ "infisical.organization.name": loginResult.orgName,
"infisical.auth.method": AuthAttemptAuthMethod.GITLAB,
"infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
"client.address": requestContext.get("ip"),
@@ -271,7 +274,7 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
- return cb(null, { isUserCompleted, providerAuthToken });
+ return cb(null, loginResult);
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
@@ -375,6 +378,43 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
handler: () => {}
});
+ // Shared redirect logic for all OAuth provider callbacks
+ const handleOAuthCallbackRedirect = async (req: any, res: any) => {
+ const isAdminLogin = req.session.get("isAdminLogin");
+ await req.session.destroy();
+ const passportResult = req.passportUser;
+
+ if (passportResult.result === ProviderAuthResult.SESSION) {
+ void res.setCookie("jid", passportResult.tokens.refresh, {
+ httpOnly: true,
+ path: "/",
+ sameSite: "strict",
+ secure: appCfg.HTTPS_ENABLED
+ });
+ addAuthOriginDomainCookie(res);
+ return res.redirect(
+ `${appCfg.SITE_URL}/login/select-organization${isAdminLogin ? `?isAdminLogin=${isAdminLogin}` : ""}`
+ );
+ }
+
+ if (passportResult.result === ProviderAuthResult.MFA_REQUIRED) {
+ return res.redirect(
+ `${appCfg.SITE_URL}/login/select-organization?mfaToken=${encodeURIComponent(passportResult.mfaToken)}&mfaMethod=${passportResult.mfaMethod}`
+ );
+ }
+
+ if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
+ const serverCfg = await getServerCfg();
+ return res.redirect(
+ `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}${
+ serverCfg.defaultAuthOrgId && !appCfg.isCloud ? `&defaultOrgAllowed=true` : ""
+ }`
+ );
+ }
+
+ throw new BadRequestError({ message: "Unexpected auth result" });
+ };
+
server.route({
url: "/google",
method: "GET",
@@ -384,20 +424,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
authInfo: false
// this is due to zod type difference
}) as never,
- handler: async (req, res) => {
- const isAdminLogin = req.session.get("isAdminLogin");
- await req.session.destroy();
- if (req.passportUser.isUserCompleted) {
- return res.redirect(
- `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}${
- isAdminLogin ? `&isAdminLogin=${isAdminLogin}` : ""
- }`
- );
- }
- return res.redirect(
- `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`
- );
- }
+ handler: handleOAuthCallbackRedirect
});
server.route({
@@ -486,34 +513,17 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
authInfo: false
// this is due to zod type difference
}) as any,
- handler: async (req, res) => {
- const isAdminLogin = req.session.get("isAdminLogin");
- await req.session.destroy();
-
+ handler: async (req: any, res: any) => {
if (req.passportUser.externalProviderAccessToken) {
void res.cookie(INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN, req.passportUser.externalProviderAccessToken, {
httpOnly: true,
path: "/",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
- expires: new Date(Date.now() + ms(appCfg.JWT_PROVIDER_AUTH_LIFETIME))
+ expires: new Date(Date.now() + ms("15m"))
});
}
-
- if (req.passportUser.isUserCompleted) {
- return res.redirect(
- `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}${
- isAdminLogin ? `&isAdminLogin=${isAdminLogin}` : ""
- }`
- );
- }
-
- const serverCfg = await getServerCfg();
- return res.redirect(
- `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}${
- serverCfg.defaultAuthOrgId && !appCfg.isCloud ? `&defaultOrgAllowed=true` : ""
- }`
- );
+ return handleOAuthCallbackRedirect(req, res);
}
});
@@ -566,22 +576,11 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
// this is due to zod type difference
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any,
- handler: async (req, res) => {
- const isAdminLogin = req.session.get("isAdminLogin");
- await req.session.destroy();
- if (req.passportUser.isUserCompleted) {
- return res.redirect(
- `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}${
- isAdminLogin ? `&isAdminLogin=${isAdminLogin}` : ""
- }`
- );
- }
- return res.redirect(
- `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(req.passportUser.providerAuthToken)}`
- );
- }
+ handler: handleOAuthCallbackRedirect
});
+ // Deprecated: token-exchange is no longer needed — sessions are issued directly from callbacks.
+ // Kept for backward compatibility with old clients.
server.route({
url: "/token-exchange",
method: "POST",
@@ -592,53 +591,10 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
email: z.string()
})
},
- handler: async (req, res) => {
- const userAgent = req.headers["user-agent"];
- if (!userAgent) throw new Error("user agent header is required");
-
- const data = await server.services.login.oauth2TokenExchange({
- email: req.body.email,
- ip: req.realIp,
- userAgent,
- providerAuthToken: req.body.providerAuthToken
+ handler: async () => {
+ throw new BadRequestError({
+ message: "Token exchange is no longer supported. Please update your client."
});
-
- const tokenExchangeDistinctId = data.user.username ?? data.user.email ?? "";
- if (tokenExchangeDistinctId) {
- void server.services.telemetry.identifyUser(
- tokenExchangeDistinctId,
- {
- email: data.user.email ?? undefined,
- username: data.user.username,
- userId: data.user.userId
- },
- { skipDedup: true }
- );
- }
- if ([AuthMethod.GOOGLE, AuthMethod.GITHUB, AuthMethod.GITLAB].includes(data.decodedProviderToken.authMethod)) {
- void res.setCookie("jid", data.token.refresh, {
- httpOnly: true,
- path: "/",
- sameSite: "strict",
- secure: appCfg.HTTPS_ENABLED
- });
- }
-
- addAuthOriginDomainCookie(res);
-
- return {
- encryptionVersion: data.user.encryptionVersion,
- token: data.token.access,
- isMfaEnabled: data.isMfaEnabled,
- mfaMethod: data?.mfaMethod,
- publicKey: data.user.publicKey,
- encryptedPrivateKey: data.user.encryptedPrivateKey,
- iv: data.user.iv,
- tag: data.user.tag,
- protectedKey: data.user.protectedKey || null,
- protectedKeyIV: data.user.protectedKeyIV || null,
- protectedKeyTag: data.user.protectedKeyTag || null
- } as const;
}
});
};
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index 890c7728c2..e759fc3148 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -363,23 +363,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
description: "Retrieve the current user on the request",
response: {
200: z.object({
- user: UsersSchema.merge(
- UserEncryptionKeysSchema.pick({
- clientPublicKey: true,
- serverPrivateKey: true,
- encryptionVersion: true,
- protectedKey: true,
- protectedKeyIV: true,
- protectedKeyTag: true,
- publicKey: true,
- encryptedPrivateKey: true,
- iv: true,
- tag: true,
- salt: true,
- verifier: true,
- userId: true
- })
- )
+ user: UsersSchema.omit({ hashedPassword: true })
})
}
},
diff --git a/backend/src/server/routes/v3/signup-router.ts b/backend/src/server/routes/v3/signup-router.ts
index 22f21870c7..df73f3dfb8 100644
--- a/backend/src/server/routes/v3/signup-router.ts
+++ b/backend/src/server/routes/v3/signup-router.ts
@@ -6,6 +6,7 @@ import { ForbiddenRequestError } from "@app/lib/errors";
import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { GenericResourceNameSchema } from "@app/server/lib/schemas";
+import { ProviderAuthResult } from "@app/services/auth/auth-type";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -176,4 +177,52 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
return { message: "Successfully set up account", user, token: accessToken };
}
});
+
+ server.route({
+ url: "/verify-alias",
+ method: "POST",
+ config: {
+ rateLimit: authRateLimit
+ },
+ schema: {
+ operationId: "verifyAliasSignupV3",
+ body: z.object({
+ code: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ accessToken: z.string(),
+ refreshToken: z.string()
+ })
+ }
+ },
+ handler: async (req, res) => {
+ const userAgent = req.headers["user-agent"];
+ if (!userAgent) throw new Error("user agent header is required");
+ const appCfg = getConfig();
+
+ const { tokens } = await server.services.signup.verifyAlias({
+ code: req.body.code,
+ authorization: req.headers.authorization as string,
+ ip: req.realIp,
+ userAgent
+ });
+
+ void res.setCookie("jid", tokens.refresh, {
+ httpOnly: true,
+ path: "/",
+ sameSite: "strict",
+ secure: appCfg.HTTPS_ENABLED
+ });
+
+ addAuthOriginDomainCookie(res);
+
+ return {
+ message: "Successfully verified alias",
+ accessToken: tokens.access,
+ refreshToken: tokens.refresh
+ };
+ }
+ });
};
diff --git a/backend/src/services/auth/auth-fns.ts b/backend/src/services/auth/auth-fns.ts
index 28572e7fd8..c5d3039c14 100644
--- a/backend/src/services/auth/auth-fns.ts
+++ b/backend/src/services/auth/auth-fns.ts
@@ -1,76 +1,49 @@
-import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
-import {
- AuthMethod,
- AuthModeProviderJwtTokenPayload,
- AuthModeProviderSignUpTokenPayload,
- AuthTokenType
-} from "./auth-type";
+import { AuthModeSignUpTokenPayload, AuthTokenType } from "./auth-type";
-export const validateProviderAuthToken = (providerToken: string, username?: string) => {
- if (!providerToken) throw new UnauthorizedError();
- const appCfg = getConfig();
- const decodedToken = crypto.jwt().verify(providerToken, appCfg.AUTH_SECRET) as AuthModeProviderJwtTokenPayload;
-
- if (decodedToken.authTokenType !== AuthTokenType.PROVIDER_TOKEN) throw new UnauthorizedError();
-
- if (decodedToken.username !== username) throw new Error("Invalid auth credentials");
-
- if (decodedToken.organizationId) {
- return { orgId: decodedToken.organizationId, authMethod: decodedToken.authMethod, userName: decodedToken.username };
+const extractBearerToken = (token?: string): string => {
+ if (!token) {
+ throw new UnauthorizedError({ message: "Missing Authorization Header in the request header." });
}
-
- return { authMethod: decodedToken.authMethod, orgId: null, userName: decodedToken.username };
-};
-
-export const validateSignUpAuthorization = (token: string, userId: string, validate = true) => {
- const appCfg = getConfig();
- const [AUTH_TOKEN_TYPE, AUTH_TOKEN_VALUE] = <[string, string]>token?.split(" ", 2) ?? [null, null];
- if (AUTH_TOKEN_TYPE === null) {
+ const [authTokenType, authTokenValue] = token.split(" ", 2) as [string, string];
+ if (!authTokenType) {
throw new UnauthorizedError({ message: "Missing Authorization Header in the request header." });
}
- if (AUTH_TOKEN_TYPE.toLowerCase() !== "bearer") {
+ if (authTokenType.toLowerCase() !== "bearer") {
throw new UnauthorizedError({
- message: `The provided authentication type '${AUTH_TOKEN_TYPE}' is not supported.`
+ message: `The provided authentication type '${authTokenType}' is not supported.`
});
}
- if (AUTH_TOKEN_VALUE === null) {
+ if (!authTokenValue) {
throw new UnauthorizedError({
message: "Missing Authorization Body in the request header"
});
}
+ return authTokenValue;
+};
+
+export const validateSignUpAuthorization = (token: string, userId: string, validate = true) => {
+ const appCfg = getConfig();
+ const authTokenValue = extractBearerToken(token);
- const decodedToken = crypto.jwt().verify(AUTH_TOKEN_VALUE, appCfg.AUTH_SECRET) as AuthModeProviderSignUpTokenPayload;
+ const decodedToken = crypto.jwt().verify(authTokenValue, appCfg.AUTH_SECRET) as AuthModeSignUpTokenPayload;
if (!validate) return decodedToken;
if (decodedToken.authTokenType !== AuthTokenType.SIGNUP_TOKEN) throw new UnauthorizedError();
if (decodedToken.userId !== userId) throw new UnauthorizedError();
+
+ return decodedToken;
};
export const validatePasswordResetAuthorization = (token?: string) => {
- if (!token) throw new UnauthorizedError();
-
const appCfg = getConfig();
- const [AUTH_TOKEN_TYPE, AUTH_TOKEN_VALUE] = <[string, string]>token?.split(" ", 2) ?? [null, null];
- if (AUTH_TOKEN_TYPE === null) {
- throw new UnauthorizedError({ message: "Missing Authorization Header in the request header." });
- }
- if (AUTH_TOKEN_TYPE.toLowerCase() !== "bearer") {
- throw new UnauthorizedError({
- message: `The provided authentication type '${AUTH_TOKEN_TYPE}' is not supported.`
- });
- }
- if (AUTH_TOKEN_VALUE === null) {
- throw new UnauthorizedError({
- message: "Missing Authorization Body in the request header"
- });
- }
+ const authTokenValue = extractBearerToken(token);
- const decodedToken = crypto.jwt().verify(AUTH_TOKEN_VALUE, appCfg.AUTH_SECRET) as AuthModeProviderSignUpTokenPayload;
+ const decodedToken = crypto.jwt().verify(authTokenValue, appCfg.AUTH_SECRET) as AuthModeSignUpTokenPayload;
if (decodedToken.authTokenType !== AuthTokenType.SIGNUP_TOKEN) {
throw new UnauthorizedError({
@@ -128,22 +101,3 @@ export const verifyCaptcha = async (consecutiveFailedPasswordAttempts?: number |
}
}
};
-
-export const getAuthMethodAndOrgId = (email: string, providerAuthToken?: string) => {
- let authMethod = AuthMethod.EMAIL;
- let organizationId: string | undefined;
-
- if (providerAuthToken) {
- const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email);
-
- authMethod = decodedProviderToken.authMethod;
- if (
- (isAuthMethodSaml(authMethod) || [AuthMethod.LDAP, AuthMethod.OIDC].includes(authMethod)) &&
- decodedProviderToken.orgId
- ) {
- organizationId = decodedProviderToken.orgId;
- }
- }
-
- return { authMethod, organizationId };
-};
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 81dd9dd48f..c97e1109a5 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -43,11 +43,12 @@ import { TTotpServiceFactory } from "../totp/totp-service";
import { TUserDALFactory } from "../user/user-dal";
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
import { UserAliasType } from "../user-alias/user-alias-types";
-import { enforceUserLockStatus, getAuthMethodAndOrgId, validateProviderAuthToken, verifyCaptcha } from "./auth-fns";
+import { enforceUserLockStatus, verifyCaptcha } from "./auth-fns";
import {
TLoginClientProofDTO,
TLoginGenServerPublicKeyDTO,
TOauthLoginDTO,
+ TProcessProviderCallbackDTO,
TVerifyMfaTokenDTO
} from "./auth-login-type";
import {
@@ -56,7 +57,8 @@ import {
AuthModeJwtTokenPayload,
AuthModeMfaJwtTokenPayload,
AuthTokenType,
- MfaMethod
+ MfaMethod,
+ ProviderAuthResult
} from "./auth-type";
type TAuthLoginServiceFactoryDep = {
@@ -238,6 +240,101 @@ export const authLoginServiceFactory = ({
return { access: accessToken, refresh: refreshToken };
};
+ /*
+ * Shared pipeline called by all provider callbacks (OAuth, SAML, OIDC, LDAP).
+ * Decides whether to:
+ * - Issue a session (refresh + access tokens)
+ * - Require MFA (for org-scoped IdP flows where org is already known)
+ * - Require signup/alias verification
+ *
+ * For OAuth (no organizationId): MFA is deferred to selectOrganization.
+ * For IdP (SAML/OIDC/LDAP with organizationId): MFA is checked here.
+ */
+ const processProviderCallback = async ({
+ user,
+ authMethod,
+ isAliasVerified,
+ isEmailVerified,
+ aliasId,
+ ip,
+ userAgent,
+ organizationId,
+ callbackPort
+ }: TProcessProviderCallbackDTO) => {
+ const appCfg = getConfig();
+
+ // Step 1: If user is not fully set up or alias needs verification, issue a signup token
+ if (!user.isAccepted || !isAliasVerified) {
+ const signupToken = crypto.jwt().sign(
+ {
+ authTokenType: AuthTokenType.SIGNUP_TOKEN,
+ userId: user.id,
+ authMethod,
+ isEmailVerified,
+ isAliasVerified,
+ aliasId,
+ organizationId,
+ callbackPort,
+ email: user.email,
+ firstName: user.firstName,
+ lastName: user.lastName
+ },
+ appCfg.AUTH_SECRET,
+ { expiresIn: appCfg.JWT_SIGNUP_LIFETIME }
+ );
+
+ return { result: ProviderAuthResult.SIGNUP_REQUIRED, signupToken } as const;
+ }
+
+ // Step 2: For org-scoped IdP flows, check MFA before issuing tokens
+ if (organizationId) {
+ const org = await orgDAL.findById(organizationId);
+ if (org) {
+ const isOrgMfaEnforced = org.enforceMfa;
+ const isUserMfaEnabled = user.isMfaEnabled;
+ const isMfaRequired = isOrgMfaEnforced || isUserMfaEnabled;
+
+ if (isMfaRequired) {
+ enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
+
+ const requiredMfaMethod = isOrgMfaEnforced
+ ? (org.selectedMfaMethod ?? MfaMethod.EMAIL)
+ : ((user.selectedMfaMethod as MfaMethod) ?? MfaMethod.EMAIL);
+
+ const mfaToken = crypto.jwt().sign(
+ {
+ authMethod,
+ authTokenType: AuthTokenType.MFA_TOKEN,
+ userId: user.id,
+ organizationId
+ },
+ appCfg.AUTH_SECRET,
+ { expiresIn: appCfg.JWT_MFA_LIFETIME }
+ );
+
+ if (requiredMfaMethod === MfaMethod.EMAIL && user.email) {
+ await sendUserMfaCode({ userId: user.id, email: user.email });
+ }
+
+ return { result: ProviderAuthResult.MFA_REQUIRED, mfaToken, mfaMethod: requiredMfaMethod } as const;
+ }
+ }
+ }
+
+ // Step 3: All clear — issue session tokens
+ // For OAuth (no org): tokens without org context, MFA deferred to selectOrganization
+ // For IdP (with org): tokens with org context, MFA already passed above
+ const tokens = await generateUserTokens({
+ userId: user.id,
+ ip,
+ userAgent,
+ authMethod,
+ organizationId
+ });
+
+ return { result: ProviderAuthResult.SESSION, tokens } as const;
+ };
+
/*
* Step 1 of login. To get server public key in exchange of client public key
*/
@@ -278,7 +375,8 @@ export const authLoginServiceFactory = ({
}
if (!userEnc.authMethods?.includes(AuthMethod.EMAIL)) {
- validateProviderAuthToken(providerAuthToken as string, email);
+ // Deprecated: provider token validation removed. This path is only reachable from legacy SRP clients.
+ if (!providerAuthToken) throw new UnauthorizedError();
}
const serverSrpKey = await generateSrpServerKey(userEnc.salt, userEnc.verifier);
@@ -298,7 +396,6 @@ export const authLoginServiceFactory = ({
clientProof,
ip,
userAgent,
- providerAuthToken,
captchaToken,
password
}: TLoginClientProofDTO) => {
@@ -312,7 +409,9 @@ export const authLoginServiceFactory = ({
const user = await userDAL.findById(userEnc.userId);
const cfg = getConfig();
- const { authMethod, organizationId } = getAuthMethodAndOrgId(email, providerAuthToken);
+ // Deprecated SRP path: default to email auth. Provider token exchange is no longer supported.
+ const authMethod = AuthMethod.EMAIL;
+ const organizationId: string | undefined = undefined;
await verifyCaptcha(user.consecutiveFailedPasswordAttempts, captchaToken);
if (!userEnc.salt || !userEnc.verifier) {
@@ -681,7 +780,9 @@ export const authLoginServiceFactory = ({
authMethod,
callbackPort,
orgSlug,
- providerUserId
+ providerUserId,
+ ip,
+ userAgent
}: TOauthLoginDTO) => {
const aliasType = authMethodToAliasType(authMethod);
@@ -928,41 +1029,21 @@ export const authLoginServiceFactory = ({
}
}
- const isUserCompleted = user.isAccepted;
- const providerAuthToken = crypto.jwt().sign(
- {
- authTokenType: AuthTokenType.PROVIDER_TOKEN,
- userId: user.id,
-
- ...(orgId && orgSlug && orgName !== undefined
- ? {
- organizationId: orgId,
- organizationName: orgName,
- organizationSlug: orgSlug
- }
- : {}),
-
- username: user.username,
- email: user.email,
- isEmailVerified: user.isEmailVerified,
- firstName: user.firstName,
- lastName: user.lastName,
- hasExchangedPrivateKey: true,
- authMethod,
- isUserCompleted,
- ...(callbackPort
- ? {
- callbackPort
- }
- : {})
- },
- appCfg.AUTH_SECRET,
- {
- expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME
- }
- );
+ // TODO(auth-revamp): check this out later
+ const callbackResult = await processProviderCallback({
+ user,
+ authMethod,
+ // For OAuth, new users get alias created with the user, so alias is always verified.
+ // For existing users found by email fallback (isNewAlias), the alias was just backfilled above.
+ isAliasVerified: true,
+ isEmailVerified: Boolean(user.isEmailVerified),
+ ip,
+ userAgent,
+ organizationId: orgId || undefined,
+ callbackPort
+ });
- return { isUserCompleted, providerAuthToken, user, orgId, orgName };
+ return { ...callbackResult, user: { ...user, hashedPassword: null }, orgId, orgName };
};
/*
@@ -1273,6 +1354,7 @@ export const authLoginServiceFactory = ({
verifyMfaToken,
selectOrganization,
generateUserTokens,
+ processProviderCallback,
// deprecated completely
loginGenServerPublicKey,
diff --git a/backend/src/services/auth/auth-login-type.ts b/backend/src/services/auth/auth-login-type.ts
index d11d2ddf39..d7737da29b 100644
--- a/backend/src/services/auth/auth-login-type.ts
+++ b/backend/src/services/auth/auth-login-type.ts
@@ -1,4 +1,4 @@
-import { AuthMethod, MfaMethod } from "./auth-type";
+import { AuthMethod, MfaMethod, ProviderAuthResult } from "./auth-type";
export type TLoginGenServerPublicKeyDTO = {
email: string;
@@ -35,11 +35,34 @@ export type TOauthLoginDTO = {
callbackPort?: string;
orgSlug?: string;
providerUserId: string;
+ ip: string;
+ userAgent: string;
};
-export type TOauthTokenExchangeDTO = {
- providerAuthToken: string;
+export type TProcessProviderCallbackDTO = {
+ user: {
+ id: string;
+ isAccepted?: boolean | null;
+ email?: string | null;
+ firstName?: string | null;
+ lastName?: string | null;
+ isEmailVerified?: boolean | null;
+ isMfaEnabled?: boolean | null;
+ selectedMfaMethod?: string | null;
+ isLocked?: boolean | null;
+ temporaryLockDateEnd?: Date | null;
+ };
+ authMethod: AuthMethod;
+ isAliasVerified: boolean;
+ isEmailVerified: boolean;
+ aliasId?: string;
ip: string;
userAgent: string;
- email: string;
+ organizationId?: string;
+ callbackPort?: string;
};
+
+export type TProviderAuthResult =
+ | { result: ProviderAuthResult.SESSION; tokens: { access: string; refresh: string } }
+ | { result: ProviderAuthResult.MFA_REQUIRED; mfaToken: string; mfaMethod: MfaMethod }
+ | { result: ProviderAuthResult.SIGNUP_REQUIRED; signupToken: string };
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index eef6e94668..72a080201d 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -1,7 +1,7 @@
import { AccessScope } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
import { isDisposableEmail } from "@app/lib/validator";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
@@ -11,29 +11,34 @@ import { TOrgServiceFactory } from "../org/org-service";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { getServerCfg } from "../super-admin/super-admin-service";
import { TUserDALFactory } from "../user/user-dal";
-import { UserEncryption } from "../user/user-types";
+import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
import { TAuthDALFactory } from "./auth-dal";
import { validateSignUpAuthorization } from "./auth-fns";
+import { TAuthLoginFactory } from "./auth-login-service";
import { TCompleteAccountSignupDTO } from "./auth-signup-type";
-import { AuthMethod, AuthTokenType } from "./auth-type";
+import { AuthMethod, AuthModeSignUpTokenPayload, AuthTokenType } from "./auth-type";
type TAuthSignupDep = {
authDAL: TAuthDALFactory;
userDAL: TUserDALFactory;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "updateById">;
orgService: Pick<TOrgServiceFactory, "createOrganization" | "findOrganizationById">;
orgDAL: TOrgDALFactory;
tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService;
+ loginService: Pick<TAuthLoginFactory, "generateUserTokens">;
};
export type TAuthSignupFactory = ReturnType<typeof authSignupServiceFactory>;
export const authSignupServiceFactory = ({
authDAL,
userDAL,
+ userAliasDAL,
tokenService,
smtpService,
orgService,
- orgDAL
+ orgDAL,
+ loginService
}: TAuthSignupDep) => {
// first step of signup. create user and send email
const beginEmailSignupProcess = async (email: string) => {
@@ -229,9 +234,87 @@ export const authSignupServiceFactory = ({
};
};
+ /*
+ * Verify an SSO/OAuth alias via email confirmation code.
+ * Called from /signup/verify-alias with the signup token in the Authorization header.
+ *
+ * For org IdP (SAML/OIDC/LDAP): organizationId is in the signup token → tokens issued with org context
+ * For OAuth (Google/GitHub/GitLab): no organizationId → tokens issued without org, user goes to select-org
+ *
+ * If the user is not yet accepted, they are automatically accepted (SSO users don't need password setup).
+ */
+ const verifyAlias = async ({
+ code,
+ authorization,
+ ip,
+ userAgent
+ }: {
+ code: string;
+ authorization: string;
+ ip: string;
+ userAgent: string;
+ }) => {
+ const appCfg = getConfig();
+
+ // Extract and validate the signup token
+ const [, tokenValue] = authorization.split(" ", 2);
+ if (!tokenValue) throw new UnauthorizedError({ message: "Missing authorization token" });
+
+ const decodedToken = crypto.jwt().verify(tokenValue, appCfg.AUTH_SECRET) as AuthModeSignUpTokenPayload;
+
+ if (decodedToken.authTokenType !== AuthTokenType.SIGNUP_TOKEN) {
+ throw new UnauthorizedError({ message: "Invalid token type" });
+ }
+
+ const user = await userDAL.findById(decodedToken.userId);
+ if (!user) throw new BadRequestError({ message: "User not found" });
+
+ if (!decodedToken.aliasId) {
+ throw new BadRequestError({ message: "Missing alias ID in signup token" });
+ }
+
+ // Verify the alias belongs to this user
+ const userAlias = await userAliasDAL.findOne({
+ id: decodedToken.aliasId,
+ userId: user.id
+ });
+
+ if (!userAlias) {
+ throw new BadRequestError({ message: "Alias not found for this user" });
+ }
+
+ // Validate the email verification code — the code was created with this specific aliasId
+ // by the EE service (saml/oidc/ldap) when the alias was first created
+ await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_EMAIL_VERIFICATION,
+ userId: user.id,
+ code
+ });
+
+ // Mark this specific alias as email-verified
+ await userAliasDAL.updateById(userAlias.id, { isEmailVerified: true });
+
+ // If user is not yet accepted, accept them (SSO users don't need password/account setup)
+ if (!user.isAccepted) {
+ await userDAL.updateById(user.id, { isAccepted: true });
+ }
+
+ // Issue session tokens
+ const tokens = await loginService.generateUserTokens({
+ userId: user.id,
+ ip,
+ userAgent,
+ authMethod: decodedToken.authMethod,
+ organizationId: decodedToken.organizationId
+ });
+
+ return { tokens, user };
+ };
+
return {
beginEmailSignupProcess,
verifyEmailSignup,
- completeAccountSignup
+ completeAccountSignup,
+ verifyAlias
};
};
diff --git a/backend/src/services/auth/auth-signup-type.ts b/backend/src/services/auth/auth-signup-type.ts
index a9b5d57802..97f691c9fa 100644
--- a/backend/src/services/auth/auth-signup-type.ts
+++ b/backend/src/services/auth/auth-signup-type.ts
@@ -4,7 +4,6 @@ export type TCompleteAccountSignupDTO = {
firstName: string;
lastName?: string;
organizationName?: string;
- providerAuthToken?: string | null;
attributionSource?: string | undefined;
ip: string;
userAgent: string;
diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.ts
index 280433ffa4..1bf8861cf0 100644
--- a/backend/src/services/auth/auth-type.ts
+++ b/backend/src/services/auth/auth-type.ts
@@ -15,9 +15,8 @@ export enum AuthMethod {
export enum AuthTokenType {
ACCESS_TOKEN = "accessToken",
REFRESH_TOKEN = "refreshToken",
- SIGNUP_TOKEN = "signupToken", // TODO: remove in favor of claim
- MFA_TOKEN = "mfaToken", // TODO: remove in favor of claim
- PROVIDER_TOKEN = "providerToken", // TODO: remove in favor of claim
+ SIGNUP_TOKEN = "signupToken",
+ MFA_TOKEN = "mfaToken",
API_KEY = "apiKey",
SERVICE_ACCESS_TOKEN = "serviceAccessToken",
SERVICE_REFRESH_TOKEN = "serviceRefreshToken",
@@ -25,6 +24,16 @@ export enum AuthTokenType {
SCIM_TOKEN = "scimToken"
}
+// Result state from processProviderCallback — determines what the route handler should do
+export enum ProviderAuthResult {
+ // User is fully authenticated — set refresh cookie and redirect to app
+ SESSION = "session",
+ // User needs MFA verification (org-scoped IdP flows: SAML/OIDC/LDAP)
+ MFA_REQUIRED = "mfa_required",
+ // User account is incomplete (new user or unverified alias) — issue signup token
+ SIGNUP_REQUIRED = "signup_required"
+}
+
export enum AuthMode {
JWT = "jwt",
SERVICE_TOKEN = "serviceToken",
@@ -86,17 +95,19 @@ export type AuthModeRefreshJwtTokenPayload = {
mfaMethod?: MfaMethod;
};
-export type AuthModeProviderJwtTokenPayload = {
- authTokenType: AuthTokenType.PROVIDER_TOKEN;
- username: string;
- authMethod: AuthMethod;
- email: string;
- organizationId?: string;
-};
-
-export type AuthModeProviderSignUpTokenPayload = {
+export type AuthModeSignUpTokenPayload = {
authTokenType: AuthTokenType.SIGNUP_TOKEN;
userId: string;
+ authMethod: AuthMethod;
+ isEmailVerified: boolean;
+ isAliasVerified: boolean;
+ aliasId?: string;
+ organizationId?: string;
+ callbackPort?: string;
+ // User profile fields for the frontend signup page
+ email?: string;
+ firstName?: string;
+ lastName?: string;
};
export enum MfaMethod {
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 7dd0519bcc..16d8ba048b 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -753,7 +753,7 @@ export const orgServiceFactory = ({
const user = await userDAL.findById(userId, tx);
const { access: accessToken, refresh: refreshToken } = await loginService.generateUserTokens(
{
- user,
+ userId: user.id,
authMethod: decodedToken.authMethod,
ip: ipAddress,
userAgent: userAgentHeader,
diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts
index e6f600cf29..2ac7ffb426 100644
--- a/backend/src/services/super-admin/super-admin-service.ts
+++ b/backend/src/services/super-admin/super-admin-service.ts
@@ -536,7 +536,7 @@ export const superAdminServiceFactory = ({
await updateServerCfg({ initialized: true }, userInfo.user.id);
const token = await authService.generateUserTokens({
- user: userInfo.user,
+ userId: userInfo.user.id,
authMethod: AuthMethod.EMAIL,
ip,
userAgent,
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index c0ce2c6e4f..c0603b33de 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -63,7 +63,7 @@ export const userServiceFactory = ({
username: string;
authTokenType: AuthTokenType;
};
- if (authTokenType !== AuthTokenType.PROVIDER_TOKEN) throw new BadRequestError({ name: "Invalid auth token type" });
+ if (authTokenType !== AuthTokenType.SIGNUP_TOKEN) throw new BadRequestError({ name: "Invalid auth token type" });
// akhilmhdh: case sensitive email resolution
const users = await userDAL.findUserByUsername(username);
diff --git a/frontend/src/components/auth/CodeInputStep.tsx b/frontend/src/components/auth/CodeInputStep.tsx
index d551340b4b..ef9531cc76 100644
--- a/frontend/src/components/auth/CodeInputStep.tsx
+++ b/frontend/src/components/auth/CodeInputStep.tsx
@@ -123,11 +123,7 @@ export default function CodeInputStep({ email, onComplete }: CodeInputStepProps)
</div>
<div className="mt-6 flex flex-col items-center gap-2 text-xs text-label">
<div className="flex flex-row items-baseline gap-1">
- <button
- disabled={isResending}
- onClick={() => resendEmail({ email })}
- type="button"
- >
+ <button disabled={isResending} onClick={() => resendEmail({ email })} type="button">
<span className="cursor-pointer duration-200 hover:text-foreground hover:underline hover:decoration-project/45 hover:underline-offset-2">
{t("signup.step2-resend-alert")}{" "}
{isResending
diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts
index 062ca67c25..97934d127e 100644
--- a/frontend/src/const/routes.ts
+++ b/frontend/src/const/routes.ts
@@ -7,7 +7,10 @@ const setRoute = <TFull extends FileRouteTypes["fullPaths"], TId extends FileRou
export const ROUTE_PATHS = Object.freeze({
Auth: {
- LoginSSO: setRoute("/login/sso", "/_restrict-login-signup/login/sso"),
+ SelectOrgPage: setRoute(
+ "/login/select-organization",
+ "/_restrict-login-signup/login/select-organization"
+ ),
ProviderSuccessPage: setRoute(
"/login/provider/success",
"/_restrict-login-signup/login/provider/success"
diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsx
index 2700bf15fd..cd0828465e 100644
--- a/frontend/src/hooks/api/auth/queries.tsx
+++ b/frontend/src/hooks/api/auth/queries.tsx
@@ -7,6 +7,9 @@ import { SessionStorageKeys } from "@app/const";
import { organizationKeys } from "../organization/queries";
import { projectKeys } from "../projects";
import { TGenerateAuthenticationOptionsResponse, TVerifyAuthenticationDTO } from "../webauthn";
+// Re-export from refresh.ts to maintain backwards compatibility
+// The actual implementation lives in refresh.ts to avoid circular imports with request.ts
+import { fetchAuthToken } from "./refresh";
import {
CompleteAccountSignupDTO,
GetBackupEncryptedPrivateKeyDTO,
@@ -148,6 +151,20 @@ export const useCompleteAccountSignup = () => {
});
};
+export const verifyAlias = async (details: { code: string }) => {
+ const { data } = await apiRequest.post<{ accessToken: string; refreshToken: string }>(
+ "/api/v3/signup/verify-alias",
+ details
+ );
+ return data;
+};
+
+export const useVerifyAlias = () => {
+ return useMutation({
+ mutationFn: verifyAlias
+ });
+};
+
export const useSendMfaToken = () => {
return useMutation<object, object, SendMfaTokenDTO>({
mutationFn: async ({ email }) => {
@@ -284,10 +301,6 @@ export const useResetUserPasswordV2 = () => {
});
};
-// Re-export from refresh.ts to maintain backwards compatibility
-// The actual implementation lives in refresh.ts to avoid circular imports with request.ts
-import { fetchAuthToken } from "./refresh";
-
export { fetchAuthToken };
export const useGetAuthToken = () =>
diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
index b22f0f0fae..672f99640d 100644
--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
+++ b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
@@ -1,26 +1,40 @@
-import { useState } from "react";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import { jwtDecode } from "jwt-decode";
-import { ContentLoader } from "@app/components/v2";
-import { useGetMyDuplicateAccount } from "@app/hooks/api";
+import { Mfa } from "@app/components/auth/Mfa";
+import SecurityClient from "@app/components/utilities/SecurityClient";
+import { ROUTE_PATHS } from "@app/const/routes";
+import { MfaMethod } from "@app/hooks/api/auth/types";
-import { EmailDuplicationConfirmation } from "./EmailDuplicationConfirmation";
+import { navigateUserToOrg } from "../LoginPage/Login.utils";
import { SelectOrganizationSection } from "./SelectOrgSection";
export const SelectOrganizationPage = () => {
- const duplicateAccounts = useGetMyDuplicateAccount();
- const [removeDuplicateLater, setRemoveDuplicateLater] = useState(false);
+ const search = useSearch({ from: ROUTE_PATHS.Auth.SelectOrgPage.id });
+ const navigate = useNavigate();
- if (duplicateAccounts.isPending) {
- return (
- <div className="h-screen w-screen bg-bunker-800">
- <ContentLoader />
- </div>
- );
- }
+ // IdP MFA redirect: backend sends mfaToken + mfaMethod when org-scoped SSO requires MFA
+ const { mfaToken, mfaMethod } = search;
+
+ if (mfaToken && mfaMethod) {
+ SecurityClient.setMfaToken(mfaToken);
+
+ // Decode the MFA token to get the organizationId for post-MFA navigation
+ const decoded = jwtDecode(mfaToken) as { organizationId?: string };
- if (duplicateAccounts.data?.duplicateAccounts?.length && !removeDuplicateLater) {
return (
- <EmailDuplicationConfirmation onRemoveDuplicateLater={() => setRemoveDuplicateLater(true)} />
+ <Mfa
+ email=""
+ method={mfaMethod as MfaMethod}
+ successCallback={async () => {
+ if (decoded.organizationId) {
+ localStorage.setItem("orgData.id", decoded.organizationId);
+ navigateUserToOrg({ navigate, organizationId: decoded.organizationId });
+ } else {
+ navigate({ to: "/login/select-organization", search: {}, replace: true });
+ }
+ }}
+ />
);
}
diff --git a/frontend/src/pages/auth/SelectOrgPage/route.tsx b/frontend/src/pages/auth/SelectOrgPage/route.tsx
index f20fda1f3b..805c1643eb 100644
--- a/frontend/src/pages/auth/SelectOrgPage/route.tsx
+++ b/frontend/src/pages/auth/SelectOrgPage/route.tsx
@@ -9,7 +9,9 @@ export const SelectOrganizationPageQueryParams = z.object({
callback_port: z.coerce.number().optional().catch(undefined),
is_admin_login: z.boolean().optional().catch(false),
force: z.boolean().optional(),
- mfa_pending: z.boolean().optional().catch(false)
+ mfa_pending: z.boolean().optional().catch(false),
+ mfaToken: z.string().optional().catch(undefined),
+ mfaMethod: z.string().optional().catch(undefined)
});
export const Route = createFileRoute("/_restrict-login-signup/login/select-organization")({
@@ -21,7 +23,9 @@ export const Route = createFileRoute("/_restrict-login-signup/login/select-organ
org_id: "",
callback_port: undefined,
is_admin_login: false,
- mfa_pending: false
+ mfa_pending: false,
+ mfaToken: undefined,
+ mfaMethod: undefined
})
]
}
diff --git a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
index c1fdbec83e..12176ffc01 100644
--- a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
+++ b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
@@ -10,12 +10,12 @@ import CodeInputStep from "@app/components/auth/CodeInputStep";
import InitialSignupStep from "@app/components/auth/InitialSignupStep";
import TeamInviteStep from "@app/components/auth/TeamInviteStep";
import UserInfoStep from "@app/components/auth/UserInfoStep";
+import { createNotification } from "@app/components/notifications";
import { Button } from "@app/components/v3";
import { useServerConfig } from "@app/context";
import { useSelectOrganization } from "@app/hooks/api/auth/queries";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
import { useFetchServerStatus } from "@app/hooks/api/serverDetails";
-import { createNotification } from "@app/components/notifications";
enum SignupSection {
Email = "email",
diff --git a/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx b/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx
index 7ddc0ab497..99a07a61d2 100644
--- a/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx
+++ b/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx
@@ -1,70 +1,119 @@
-import { useEffect, useState } from "react";
+import { useState } from "react";
+import ReactCodeInput from "react-code-input";
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
-import { Link, useSearch } from "@tanstack/react-router";
+import { Link, useNavigate, useSearch } from "@tanstack/react-router";
import { jwtDecode } from "jwt-decode";
+import Error from "@app/components/basic/Error";
import { AuthPageBackground } from "@app/components/auth/AuthPageBackground";
import { AuthPageFooter } from "@app/components/auth/AuthPageFooter";
+import { createNotification } from "@app/components/notifications";
+import SecurityClient from "@app/components/utilities/SecurityClient";
+import { Button } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
+import { useSendEmailVerificationCode } from "@app/hooks/api";
+import { verifyAlias } from "@app/hooks/api/auth/queries";
-import { EmailConfirmationStep } from "./components/EmailConfirmationStep";
-import { UserInfoSSOStep } from "./components/UserInfoSSOStep";
+const codeInputProps = {
+ inputStyle: {
+ fontFamily: "monospace",
+ margin: "4px",
+ MozAppearance: "textfield",
+ width: "55px",
+ borderRadius: "5px",
+ fontSize: "24px",
+ height: "55px",
+ paddingLeft: "7",
+ backgroundColor: "#0d1117",
+ color: "white",
+ border: "1px solid #2d2f33",
+ textAlign: "center",
+ outlineColor: "#8ca542",
+ borderColor: "#2d2f33"
+ }
+} as const;
+
+const codeInputPropsPhone = {
+ inputStyle: {
+ fontFamily: "monospace",
+ margin: "4px",
+ MozAppearance: "textfield",
+ width: "40px",
+ borderRadius: "5px",
+ fontSize: "24px",
+ height: "40px",
+ paddingLeft: "7",
+ backgroundColor: "#0d1117",
+ color: "white",
+ border: "1px solid #2d2f33",
+ textAlign: "center",
+ outlineColor: "#8ca542",
+ borderColor: "#2d2f33"
+ }
+} as const;
export const SignupSsoPage = () => {
const { t } = useTranslation();
+ const navigate = useNavigate();
const search = useSearch({ from: ROUTE_PATHS.Auth.SignUpSsoPage.id });
const token = search.token as string;
- const defaultOrgAllowed = search.defaultOrgAllowed as boolean | undefined;
- const [step, setStep] = useState(0);
- const [password, setPassword] = useState("");
+ const [code, setCode] = useState("");
+ const [codeError, setCodeError] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const decoded = jwtDecode(token) as {
+ email?: string;
+ firstName?: string;
+ lastName?: string;
+ authMethod?: string;
+ isEmailVerified?: boolean;
+ isAliasVerified?: boolean;
+ organizationId?: string;
+ };
+
+ // Store the signup token so the Axios interceptor uses it for Authorization headers
+ SecurityClient.setSignupToken(token);
+
+ const { mutateAsync: sendEmailVerificationCode } = useSendEmailVerificationCode();
+
+ const handleVerify = async () => {
+ setIsLoading(true);
+ try {
+ const { accessToken, refreshToken } = await verifyAlias({ code });
+
+ setCodeError(false);
+ SecurityClient.setSignupToken("");
+ SecurityClient.setToken(accessToken);
- const {
- username,
- email,
- organizationName,
- organizationSlug,
- firstName,
- lastName,
- authType,
- isEmailVerified
- } = jwtDecode(token) as any;
+ createNotification({
+ text: "Successfully verified",
+ type: "success"
+ });
- useEffect(() => {
- if (!isEmailVerified) {
- setStep(0);
- } else {
- setStep(1);
+ // refreshToken is set as jid cookie by the backend response
+ // Navigate to org selection
+ void refreshToken; // used by backend cookie, not needed here
+ navigate({ to: "/login/select-organization" });
+ } catch {
+ setCodeError(true);
+ setIsLoading(false);
}
- }, []);
+ };
- const renderView = () => {
- switch (step) {
- case 0:
- return (
- <EmailConfirmationStep
- authType={authType}
- username={username}
- email={email}
- organizationSlug={organizationSlug}
- setStep={setStep}
- />
- );
- case 1:
- return (
- <UserInfoSSOStep
- username={username}
- name={`${firstName} ${lastName}`}
- providerOrganizationName={organizationName}
- password={password}
- setPassword={setPassword}
- providerAuthToken={token}
- forceDefaultOrg={defaultOrgAllowed}
- />
- );
- default:
- return <div />;
+ const handleResendCode = async () => {
+ try {
+ await sendEmailVerificationCode(token);
+ createNotification({
+ text: "Successfully resent code",
+ type: "success"
+ });
+ } catch {
+ createNotification({
+ text: "Failed to resend code",
+ type: "error"
+ });
}
};
@@ -88,7 +137,63 @@ export const SignupSsoPage = () => {
/>
</div>
</Link>
- {renderView()}
+ <div className="mx-auto h-full w-full pb-4 md:px-8">
+ <p className="text-md flex justify-center text-bunker-200">
+ We&apos;ve sent a verification code to {decoded.email}
+ </p>
+ <div className="mx-auto hidden w-max min-w-[20rem] md:block">
+ <ReactCodeInput
+ name=""
+ inputMode="tel"
+ type="text"
+ fields={6}
+ onChange={setCode}
+ {...codeInputProps}
+ className="mt-6 mb-2"
+ />
+ </div>
+ <div className="mx-auto mt-4 block w-max md:hidden">
+ <ReactCodeInput
+ name=""
+ inputMode="tel"
+ type="text"
+ fields={6}
+ onChange={setCode}
+ {...codeInputPropsPhone}
+ className="mt-2 mb-2"
+ />
+ </div>
+ {codeError && <Error text="Oops. Your code is wrong. Please try again." />}
+ <div className="mx-auto mt-2 flex w-1/4 max-w-xs min-w-[20rem] flex-col items-center justify-center text-center text-sm md:max-w-md md:text-left lg:w-[19%]">
+ <div className="text-l w-full py-1 text-lg">
+ <Button
+ type="submit"
+ onClick={handleVerify}
+ size="sm"
+ isFullWidth
+ className="h-14"
+ colorSchema="primary"
+ variant="outline_bg"
+ isLoading={isLoading}
+ >
+ Verify
+ </Button>
+ </div>
+ </div>
+ <div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2">
+ <div className="flex flex-row items-baseline gap-1 text-sm">
+ <span className="text-bunker-400">Don&apos;t see the code?</span>
+ <div className="text-md mt-2 flex flex-row text-bunker-400">
+ <button disabled={isLoading} onClick={handleResendCode} type="button">
+ <span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">
+ Resend
+ </span>
+ </button>
+ </div>
+ </div>
+ <p className="pb-2 text-sm text-bunker-400">Make sure to check your spam inbox.</p>
+ </div>
+ </div>
</div>
<AuthPageFooter />
</div>
diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx
index f490c3efa2..71843de811 100644
--- a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx
+++ b/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx
@@ -29,7 +29,6 @@ type Props = {
setPassword: (value: string) => void;
name: string;
providerOrganizationName: string;
- providerAuthToken?: string;
forceDefaultOrg?: boolean;
};