Skip to content

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

feat: implemented verify domain required and respective other bugs has been fixed

=9ba3910b2c6c
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index 11c37dce5c..6a8d468b50 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -75,24 +75,24 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
},
schema: {
querystring: z.object({
- orgSlug: z.string().trim(),
+ domain: z.string().trim(),
callbackPort: z.string().trim().optional()
})
},
preValidation: [
async (req, res) => {
- const { orgSlug, callbackPort } = req.query;
+ const { domain, callbackPort } = req.query;
// ensure fresh session state per login attempt
await req.session.regenerate();
- req.session.set<any>("oidcOrgSlug", orgSlug);
+ req.session.set<any>("oidcDomain", domain);
if (callbackPort) {
req.session.set<any>("callbackPort", callbackPort);
}
- const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(orgSlug, callbackPort);
+ const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(domain, callbackPort);
return (
passport.authenticate(oidcStrategy as Strategy, {
scope: "profile email openid"
@@ -109,9 +109,9 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
method: "GET",
preValidation: [
async (req, res) => {
- const oidcOrgSlug = req.session.get<any>("oidcOrgSlug");
+ const oidcDomain = req.session.get<any>("oidcDomain");
const callbackPort = req.session.get<any>("callbackPort");
- const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(oidcOrgSlug, callbackPort);
+ const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(oidcDomain, callbackPort);
return (
passport.authenticate(oidcStrategy as Strategy, {
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 43d9cdbbee..31a4d86dfa 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -52,14 +52,14 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
// eslint-disable-next-line
getSamlOptions: async (req, done) => {
try {
- const { samlConfigId, orgSlug } = req.params;
+ const { samlConfigId, domain } = req.params;
let ssoLookupDetails: TGetSamlCfgDTO;
- if (orgSlug) {
+ if (domain) {
ssoLookupDetails = {
- type: "orgSlug",
- orgSlug
+ type: "domain",
+ domain
};
} else if (samlConfigId) {
ssoLookupDetails = {
@@ -200,14 +200,14 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
);
server.route({
- url: "/redirect/saml2/organizations/:orgSlug",
+ url: "/redirect/saml2/organizations/:domain",
method: "GET",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- orgSlug: z.string().trim()
+ domain: z.string().trim()
}),
querystring: z.object({
callback_port: z.string().optional()
diff --git a/backend/src/ee/services/email-domain/email-domain-fns.ts b/backend/src/ee/services/email-domain/email-domain-fns.ts
index b81916404a..7e5c5c1258 100644
--- a/backend/src/ee/services/email-domain/email-domain-fns.ts
+++ b/backend/src/ee/services/email-domain/email-domain-fns.ts
@@ -1,6 +1,6 @@
import { getHostname } from "tldts";
-import { AccessScope, TableName } from "@app/db/schemas";
+// import { AccessScope, TableName } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -18,9 +18,9 @@ import { EmailDomainStatus } from "./email-domain-types";
export const verifyEmailDomainOwnership = async ({
email,
orgId,
- emailDomainDAL,
- orgDAL,
- userId
+ emailDomainDAL
+ // orgDAL,
+ // userId
}: {
email: string;
orgId: string;
@@ -37,27 +37,15 @@ export const verifyEmailDomainOwnership = async ({
status: EmailDomainStatus.Verified
});
- if (verifiedDomain) {
- if (verifiedDomain.orgId !== orgId) {
- throw new BadRequestError({
- message: `The email domain "${emailDomain}" is verified by another organization. This operation is not allowed.`
- });
- }
- return;
+ if (!verifiedDomain) {
+ throw new BadRequestError({
+ message: `Invalid email domain`
+ });
}
- // Tier 2: No verified domain — check if user exists in other orgs
- if (!userId) return;
-
- const existingMemberships = await orgDAL.findMembership({
- [`${TableName.Membership}.actorUserId` as "actorUserId"]: userId,
- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
- });
-
- const belongsToOtherOrg = existingMemberships.some((m) => m.scopeOrgId !== orgId);
- if (belongsToOtherOrg) {
+ if (verifiedDomain.orgId !== orgId) {
throw new BadRequestError({
- message: `This user belongs to another organization. To manage users with this email domain, please verify "${emailDomain}" in your organization's email domain settings first.`
+ message: `Invalid email domain`
});
}
};
diff --git a/backend/src/ee/services/group/user-group-membership-dal.ts b/backend/src/ee/services/group/user-group-membership-dal.ts
index 7598fe9bfb..e0fdcb11fc 100644
--- a/backend/src/ee/services/group/user-group-membership-dal.ts
+++ b/backend/src/ee/services/group/user-group-membership-dal.ts
@@ -94,7 +94,7 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
db.ref("username").withSchema(TableName.Users),
db.ref("firstName").withSchema(TableName.Users),
db.ref("lastName").withSchema(TableName.Users),
- db.ref("id").withSchema(TableName.Users).as("userId"),
+ db.ref("id").withSchema(TableName.Users).as("userId")
)
.where({ isGhost: false }) // MAKE SURE USER IS NOT A GHOST USER
.whereNotIn(`${TableName.UserGroupMembership}.userId`, (bd) => {
@@ -104,7 +104,7 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
.whereIn(`${TableName.UserGroupMembership}.groupId`, groups);
});
- return members.map(({ email, username, firstName, lastName, userId, publicKey: "", ...data }) => ({
+ return members.map(({ email, username, firstName, lastName, userId, ...data }) => ({
...data,
user: { email, username, firstName, lastName, id: userId, publicKey: "" }
}));
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 36e48e466a..8f3e5e46d4 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -52,6 +52,7 @@ import {
} from "./ldap-config-types";
import { searchGroups, testLDAPConfig } from "./ldap-fns";
import { TLdapGroupMapDALFactory } from "./ldap-group-map-dal";
+import { validateEmail } from "@app/lib/validator/validate-email";
type TLdapConfigServiceFactoryDep = {
ldapConfigDAL: Pick<TLdapConfigDALFactory, "create" | "update" | "findOne" | "transaction">;
@@ -409,6 +410,8 @@ export const ldapConfigServiceFactory = ({
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });
+ const sanitizedEmail = email.toLowerCase();
+ validateEmail(sanitizedEmail);
let userAlias = await userAliasDAL.findOne({
externalId,
@@ -449,7 +452,7 @@ export const ldapConfigServiceFactory = ({
actorUserId: userAlias.userId,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: OrgMembershipStatus.Accepted,
+ status: OrgMembershipStatus.Invited,
isActive: true
},
tx
@@ -462,27 +465,19 @@ export const ldapConfigServiceFactory = ({
},
tx
);
- } else if (orgMembership.status === OrgMembershipStatus.Invited) {
- await orgDAL.updateMembershipById(
- orgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
}
});
} else {
userAlias = await userDAL.transaction(async (tx) => {
let newUser: TUsers | undefined;
- newUser = await userDAL.findOne({ username: email.toLowerCase() }, tx);
+ newUser = await userDAL.findOne({ username: sanitizedEmail }, tx);
if (!newUser) {
newUser = await userDAL.create(
{
- username: email.toLowerCase(),
- email: email.toLowerCase(),
+ username: sanitizedEmail,
+ email: sanitizedEmail,
firstName,
lastName,
authMethods: [],
@@ -495,10 +490,10 @@ export const ldapConfigServiceFactory = ({
const newUserAlias = await userAliasDAL.create(
{
userId: newUser.id,
- username: email.toLowerCase(),
+ username: sanitizedEmail,
aliasType: UserAliasType.LDAP,
externalId,
- emails: [email],
+ emails: [sanitizedEmail],
orgId
},
tx
@@ -522,9 +517,9 @@ export const ldapConfigServiceFactory = ({
actorUserId: newUser.id,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
+ status: OrgMembershipStatus.Invited,
isActive: true,
- inviteEmail: email.toLowerCase()
+ inviteEmail: sanitizedEmail
},
tx
);
@@ -537,14 +532,6 @@ export const ldapConfigServiceFactory = ({
tx
);
// Only update the membership to Accepted if the user account is already completed.
- } else if (orgMembership.status === OrgMembershipStatus.Invited && newUser.isAccepted) {
- await orgDAL.updateMembershipById(
- orgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
}
return newUserAlias;
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index bb68bd2cc8..fc72474584 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -101,7 +101,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
pkiEst: false,
pkiAcme: false,
pkiScep: false,
- enforceMfa: false,
+ enforceMfa: true,
projectTemplates: false,
kmip: false,
gateway: false,
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 76b3669e17..674df060c9 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -17,7 +17,7 @@ import { getConfig } from "@app/lib/config/env";
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 { blockLocalAndPrivateIpAddresses, matchesAllowedEmailDomain, validateEmail } from "@app/lib/validator";
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";
@@ -39,7 +39,7 @@ import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";
-import { verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
+import { findOrgIdByVerifiedDomain, verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
import { TOidcConfigDALFactory } from "./oidc-config-dal";
import {
OIDCConfigurationType,
@@ -193,6 +193,8 @@ export const oidcConfigServiceFactory = ({
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });
+ const sanitizedEmail = email.toLowerCase();
+ validateEmail(sanitizedEmail);
let userAlias = await userAliasDAL.findOne({
externalId,
@@ -231,7 +233,7 @@ export const oidcConfigServiceFactory = ({
actorUserId: userAlias.userId,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: OrgMembershipStatus.Accepted,
+ status: OrgMembershipStatus.Invited,
isActive: true
},
tx
@@ -244,15 +246,6 @@ export const oidcConfigServiceFactory = ({
},
tx
);
- // Only update the membership to Accepted if the user account is already completed.
- } else if (orgMembership.status === OrgMembershipStatus.Invited && foundUser.isAccepted) {
- await orgDAL.updateMembershipById(
- orgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
}
return foundUser;
@@ -262,7 +255,7 @@ export const oidcConfigServiceFactory = ({
let newUser: TUsers | undefined;
// we prioritize getting the most complete user to create the new alias under
newUser = await userDAL.findOne({
- username: email.toLowerCase()
+ username: sanitizedEmail
});
if (!newUser) {
@@ -270,7 +263,7 @@ export const oidcConfigServiceFactory = ({
{
email,
firstName,
- username: email.toLowerCase(),
+ username: sanitizedEmail,
lastName,
authMethods: [],
isGhost: false
@@ -309,9 +302,9 @@ export const oidcConfigServiceFactory = ({
actorUserId: newUser.id,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
+ status: OrgMembershipStatus.Invited,
isActive: true,
- inviteEmail: email.toLowerCase()
+ inviteEmail: sanitizedEmail
},
tx
);
@@ -323,15 +316,6 @@ export const oidcConfigServiceFactory = ({
},
tx
);
- // Only update the membership to Accepted if the user account is already completed.
- } else if (orgMembership.status === OrgMembershipStatus.Invited && newUser.isAccepted) {
- await orgDAL.updateMembershipById(
- orgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
}
return newUser;
@@ -654,22 +638,23 @@ export const oidcConfigServiceFactory = ({
return oidcCfg;
};
- const getOrgAuthStrategy = async (orgSlug: string, callbackPort?: string) => {
+ const getOrgAuthStrategy = async (domain: string, callbackPort?: string) => {
const appCfg = getConfig();
+ const verifiedDomain = await findOrgIdByVerifiedDomain({ domain, emailDomainDAL });
- const org = await orgDAL.findOne({
- slug: orgSlug
- });
-
- if (!org) {
- throw new NotFoundError({
- message: `Organization with slug '${orgSlug}' not found`
+ if (!verifiedDomain) {
+ throw new ForbiddenRequestError({
+ message: "Failed to authenticate with OIDC SSO"
});
}
+ const org = await orgDAL.findOne({
+ id: verifiedDomain.orgId
+ });
+
const oidcCfg = await getOidc({
type: "internal",
- organizationId: org.id
+ organizationId: verifiedDomain.orgId
});
if (!oidcCfg || !oidcCfg.isActive) {
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 cc429c1e9a..f988566364 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -16,6 +16,7 @@ import {
} from "@app/db/schemas";
import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { validateEmail } from "@app/lib/validator/validate-email";
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";
@@ -425,31 +426,24 @@ export const samlConfigServiceFactory = ({
message: `SAML configuration for organization with ID '${dto.orgId}' not found`
});
}
- } else if (dto.type === "orgSlug") {
+ } else if (dto.type === "domain") {
let resolvedOrgId: string | undefined;
// If orgSlug starts with @, treat the rest as a domain name and resolve via verified email domains
- if (dto.orgSlug.startsWith("@")) {
- const domain = dto.orgSlug.slice(1);
- const verifiedDomain = await findOrgIdByVerifiedDomain({ domain, emailDomainDAL });
- if (verifiedDomain) {
- resolvedOrgId = verifiedDomain.orgId;
- }
+ const verifiedDomain = await findOrgIdByVerifiedDomain({ domain: dto.domain, emailDomainDAL });
+ if (verifiedDomain) {
+ resolvedOrgId = verifiedDomain.orgId;
}
- if (dto.orgSlug.startsWith("@") && !resolvedOrgId) {
- throw new NotFoundError({ message: `No verified domain found for '${dto.orgSlug.slice(1)}'` });
- }
-
- if (!resolvedOrgId) {
- const org = await orgDAL.findOne({ slug: dto.orgSlug, rootOrgId: null });
- if (!org) {
- throw new NotFoundError({
- message: `Organization with slug '${dto.orgSlug}' not found`
- });
- }
- resolvedOrgId = org.id;
- }
+ // if (!resolvedOrgId) {
+ // const org = await orgDAL.findOne({ slug: dto.orgSlug, rootOrgId: null });
+ // if (!org) {
+ // throw new NotFoundError({
+ // message: `Organization with slug '${dto.orgSlug}' not found`
+ // });
+ // }
+ // resolvedOrgId = org.id;
+ // }
samlConfig = await samlConfigDAL.findOne({ orgId: resolvedOrgId });
} else if (dto.type === "ssoId") {
@@ -548,6 +542,8 @@ export const samlConfigServiceFactory = ({
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });
+ const sanitizedEmail = email.toLowerCase();
+ validateEmail(sanitizedEmail);
const organization = await orgDAL.findOrgById(orgId);
if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
@@ -588,7 +584,7 @@ export const samlConfigServiceFactory = ({
inviteEmail: email,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: OrgMembershipStatus.Accepted,
+ status: OrgMembershipStatus.Invited,
isActive: true
},
tx
@@ -601,15 +597,6 @@ export const samlConfigServiceFactory = ({
},
tx
);
- // Only update the membership to Accepted if the user account is already completed.
- } else if (orgMembership.status === OrgMembershipStatus.Invited && foundUser.isAccepted) {
- await orgDAL.updateMembershipById(
- orgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
}
if (metadata && foundUser.id) {
@@ -644,12 +631,12 @@ export const samlConfigServiceFactory = ({
user = await userDAL.transaction(async (tx) => {
let newUser: TUsers | undefined;
- newUser = await userDAL.findOne({ username: email.toLowerCase() }, tx);
+ newUser = await userDAL.findOne({ username: sanitizedEmail }, tx);
if (!newUser) {
newUser = await userDAL.create(
{
- username: email.toLowerCase(),
+ username: sanitizedEmail,
email,
isEmailVerified: false,
firstName,
@@ -666,7 +653,7 @@ export const samlConfigServiceFactory = ({
userId: newUser.id,
aliasType: UserAliasType.SAML,
externalId,
- emails: email ? [email.toLowerCase()] : [],
+ emails: email ? [sanitizedEmail] : [],
orgId,
isEmailVerified: false
},
@@ -692,9 +679,9 @@ export const samlConfigServiceFactory = ({
actorUserId: newUser.id,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
+ status: OrgMembershipStatus.Invited,
isActive: true,
- inviteEmail: email.toLowerCase()
+ inviteEmail: sanitizedEmail
},
tx
);
@@ -706,15 +693,6 @@ export const samlConfigServiceFactory = ({
},
tx
);
- // Only update the membership to Accepted if the user account is already completed.
- } else if (orgMembership.status === OrgMembershipStatus.Invited && newUser.isAccepted) {
- await orgDAL.updateMembershipById(
- orgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
}
if (metadata && newUser.id) {
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 747f1f10dc..36f6ba63dc 100644
--- a/backend/src/ee/services/saml-config/saml-config-types.ts
+++ b/backend/src/ee/services/saml-config/saml-config-types.ts
@@ -41,8 +41,8 @@ export type TGetSamlCfgDTO =
actorOrgId: string;
}
| {
- type: "orgSlug";
- orgSlug: string;
+ type: "domain";
+ domain: string;
}
| {
type: "ssoId";
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index 92492cb517..7903ee1b67 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -22,6 +22,7 @@ import { BadRequestError, NotFoundError, ScimRequestError, UnauthorizedError } f
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { validateEmail } from "@app/lib/validator/validate-email";
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { AuthTokenType } from "@app/services/auth/auth-type";
import { TExternalGroupOrgRoleMappingDALFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-dal";
@@ -373,6 +374,9 @@ export const scimServiceFactory = ({
}) => {
if (!email) throw new ScimRequestError({ detail: "Invalid request. Missing email.", status: 400 });
+ const sanitizedEmail = email.toLowerCase();
+ validateEmail(sanitizedEmail);
+
const org = await orgDAL.findOrgById(orgId);
if (!org)
throw new ScimRequestError({
@@ -403,7 +407,7 @@ export const scimServiceFactory = ({
});
// Resolve the user ID: either from the existing alias, or by looking up the email
- const existingUserId = userAlias?.userId ?? (await userDAL.findOne({ username: email.toLowerCase() }))?.id;
+ const existingUserId = userAlias?.userId ?? (await userDAL.findOne({ username: sanitizedEmail }))?.id;
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL, userId: existingUserId });
@@ -428,10 +432,10 @@ export const scimServiceFactory = ({
orgMembership = await membershipUserDAL.create(
{
actorUserId: userAlias.userId,
- inviteEmail: email.toLowerCase(),
+ inviteEmail: sanitizedEmail,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: user.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
+ status: OrgMembershipStatus.Invited,
isActive: true
},
tx
@@ -448,12 +452,12 @@ export const scimServiceFactory = ({
orgMembership = effectiveMembership;
}
} else {
- user = await userDAL.findOne({ username: email.toLowerCase() }, tx);
+ user = await userDAL.findOne({ username: sanitizedEmail }, tx);
if (!user) {
user = await userDAL.create(
{
- username: email.toLowerCase(),
- email: email.toLowerCase(),
+ username: sanitizedEmail,
+ email: sanitizedEmail,
isEmailVerified: false,
firstName,
lastName,
@@ -469,7 +473,7 @@ export const scimServiceFactory = ({
userId: user.id,
aliasType,
externalId,
- emails: email ? [email.toLowerCase()] : [],
+ emails: email ? [sanitizedEmail] : [],
orgId,
isEmailVerified: false
},
@@ -491,10 +495,10 @@ export const scimServiceFactory = ({
orgMembership = await membershipUserDAL.create(
{
actorUserId: user.id,
- inviteEmail: email.toLowerCase(),
+ inviteEmail: sanitizedEmail,
scopeOrgId: orgId,
scope: AccessScope.Organization,
- status: user.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
+ status: OrgMembershipStatus.Invited,
isActive: true
},
tx
@@ -601,6 +605,11 @@ export const scimServiceFactory = ({
});
const user = await userDAL.findOne({ id: membership.actorUserId });
+ if (!user)
+ throw new ScimRequestError({
+ detail: "User not found",
+ status: 404
+ });
const scimUser = buildScimUser({
orgMembershipId: membership.id,
@@ -608,12 +617,21 @@ export const scimServiceFactory = ({
lastName: user.lastName,
firstName: user.firstName,
active: membership.isActive,
- username: user.username,
+ username: userAliases?.[0]?.externalId ?? user.username,
createdAt: membership.createdAt,
updatedAt: membership.updatedAt
});
scimPatch(scimUser, operations);
+ // email is our identifier - changing that user must delete this user and provision a new one
+ if (scimUser.emails?.[0]?.value !== user?.email) {
+ throw new ScimRequestError({
+ detail: "Email cannot be changed",
+ status: 404,
+ mutability: "immutable"
+ });
+ }
+
await verifyEmailDomainOwnership({
email: user.username,
orgId,
@@ -621,18 +639,6 @@ export const scimServiceFactory = ({
orgDAL,
userId: membership.actorUserId
});
- // TODO(auth-revamp): validate username is email
- const hasEmailChanged = scimUser.userName !== user.username;
- if (hasEmailChanged) {
- await verifyEmailDomainOwnership({
- email: scimUser.userName,
- orgId,
- emailDomainDAL,
- orgDAL,
- userId: user.id
- });
- }
-
await userDAL.transaction(async (tx) => {
await membershipUserDAL.updateById(
membership.id,
@@ -645,27 +651,11 @@ export const scimServiceFactory = ({
membership.actorUserId as string,
{
firstName: scimUser.name.givenName,
- ...(hasEmailChanged ? { username: scimUser.userName, email: scimUser.userName } : {}),
- lastName: scimUser.name.familyName,
- isEmailVerified: hasEmailChanged ? false : undefined
+ lastName: scimUser.name.familyName
},
tx
);
- if (hasEmailChanged) {
- // clean up previous alias of same auth type and set the new one
- await userAliasDAL.delete({ $in: { id: userAliasesIds } }, tx);
- await userAliasDAL.create(
- {
- userId: user.id,
- aliasType: org.orgAuthMethod === OrgAuthMethod.OIDC ? UserAliasType.OIDC : UserAliasType.SAML,
- emails: [scimUser.userName],
- orgId,
- externalId: userAliases[0].externalId
- },
- tx
- );
- }
await scimEventsDAL.create(
{
orgId,
@@ -700,6 +690,9 @@ export const scimServiceFactory = ({
status: 400
});
}
+ if (email) {
+ validateEmail(email.toLowerCase());
+ }
const [membership] = await orgDAL
.findMembership({
@@ -741,7 +734,14 @@ export const scimServiceFactory = ({
const user = await userDAL.findOne({ id: membership.actorUserId });
- const hasEmailChanged = email?.toLowerCase() !== user.username;
+ // email is our identifier - changing that user must delete this user and provision a new one
+ if (email && (user.email !== email || user.username !== email)) {
+ throw new ScimRequestError({
+ detail: "Email cannot be changed",
+ status: 404,
+ mutability: "immutable"
+ });
+ }
await verifyEmailDomainOwnership({
email: user.username,
@@ -751,16 +751,6 @@ export const scimServiceFactory = ({
userId: membership.actorUserId
});
- if (hasEmailChanged && email) {
- await verifyEmailDomainOwnership({
- email,
- orgId,
- emailDomainDAL,
- orgDAL,
- userId: membership.actorUserId
- });
- }
-
await userDAL.transaction(async (tx) => {
await membershipUserDAL.updateById(
membership.id,
@@ -773,30 +763,13 @@ export const scimServiceFactory = ({
membership.actorUserId!,
{
firstName,
- ...(hasEmailChanged && email ? { username: email.toLowerCase(), email: email.toLowerCase() } : {}),
- lastName,
- isEmailVerified: hasEmailChanged ? false : undefined
+ lastName
},
tx
);
- if (hasEmailChanged && email) {
- const userAliasesIds = userAliases.map((el) => el.id);
- await userAliasDAL.delete({ $in: { id: userAliasesIds } }, tx);
- await userAliasDAL.create(
- {
- userId: user.id,
- aliasType,
- emails: [email.toLowerCase()],
- orgId,
- externalId: externalId || userAliases[0].externalId
- },
- tx
- );
- } else {
- // Update externalId on existing alias if provided and changed
- await userAliasDAL.update({ orgId, aliasType, userId: membership.actorUserId as string }, { externalId }, tx);
- }
+ // Update externalId on existing alias if provided and changed
+ await userAliasDAL.update({ orgId, aliasType, userId: membership.actorUserId as string }, { externalId }, tx);
await scimEventsDAL.create(
{
@@ -816,8 +789,8 @@ export const scimServiceFactory = ({
return buildScimUser({
orgMembershipId: membership.id,
- username: user.username,
- email: hasEmailChanged && email ? email.toLowerCase() : user.email,
+ username: externalId || user.username,
+ email: user.email,
firstName: firstName || user.firstName,
lastName: lastName || user.lastName,
active,
@@ -1064,6 +1037,7 @@ export const scimServiceFactory = ({
if (members && members.length) {
const orgMemberships = await membershipUserDAL.find({
scope: AccessScope.Organization,
+ scopeOrgId: orgId,
$in: {
id: members.map((member) => member.value)
}
diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.ts
index 7cc4063fe5..c7577fe7bf 100644
--- a/backend/src/lib/errors/index.ts
+++ b/backend/src/lib/errors/index.ts
@@ -160,14 +160,18 @@ export class ScimRequestError extends Error {
error: unknown;
+ mutability?: string;
+
constructor({
name,
error,
detail,
- status
+ status,
+ mutability
}: {
message?: string;
name?: string;
+ mutability?: string;
error?: unknown;
detail: string;
status: number;
@@ -178,6 +182,7 @@ export class ScimRequestError extends Error {
this.error = error;
this.detail = detail;
this.status = status;
+ this.mutability = mutability;
}
}
diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.ts
index bb49429120..3edd025e05 100644
--- a/backend/src/lib/validator/index.ts
+++ b/backend/src/lib/validator/index.ts
@@ -1,5 +1,5 @@
export { matchesAllowedEmailDomain } from "./email-domain-matcher";
-export { isDisposableEmail } from "./validate-email";
+export { isDisposableEmail, validateEmail } from "./validate-email";
export { isValidFolderName, isValidSecretPath } from "./validate-folder-name";
export {
containsDangerousSmbChars,
diff --git a/backend/src/lib/validator/validate-email.ts b/backend/src/lib/validator/validate-email.ts
index c0c50155bc..9cef57cf2b 100644
--- a/backend/src/lib/validator/validate-email.ts
+++ b/backend/src/lib/validator/validate-email.ts
@@ -1,5 +1,7 @@
import fs from "fs/promises";
import path from "path";
+import { getDomain } from "tldts";
+import { BadRequestError } from "../errors";
export const isDisposableEmail = async (emails: string | string[]) => {
const disposableEmails = await fs.readFile(path.join(__dirname, "disposable_emails.txt"), "utf8");
@@ -14,3 +16,16 @@ export const isDisposableEmail = async (emails: string | string[]) => {
if (disposableEmails.split("\n").includes(emailDomain)) return true;
return false;
};
+
+export const validateEmail = (email: string) => {
+ const domain = getDomain(email);
+ if (!domain) throw new BadRequestError({ message: "Missing email domain" });
+
+ const userIdentifier = email.split("@")[0];
+ if (!userIdentifier) throw new BadRequestError({ message: "Missing user identifier in email" });
+
+ if (userIdentifier.includes("+"))
+ throw new BadRequestError({ message: "Email user identifier contains a plus sign" });
+
+ if (email.toLowerCase() !== email) throw new BadRequestError({ message: "Email contains uppercase characters" });
+};
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index 9c245923f3..b5ac7caa94 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -213,7 +213,8 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
reqId: req.id,
schemas: error.schemas,
status: error.status,
- detail: error.detail
+ detail: error.detail,
+ mutatability: error.mutatability
});
} else if (error instanceof OidcAuthError) {
void res.status(HttpStatusCodes.InternalServerError).send({
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts
index ea352eed8a..c32bc068cf 100644
--- a/backend/src/server/routes/v1/project-router.ts
+++ b/backend/src/server/routes/v1/project-router.ts
@@ -94,11 +94,10 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
firstName: true,
lastName: true,
id: true
- })
- .merge(UserEncryptionKeysSchema.pick({ publicKey: true }))
- .extend({
- isOrgMembershipActive: z.boolean()
- }),
+ }).extend({
+ publicKey: z.string().optional().nullable(),
+ isOrgMembershipActive: z.boolean()
+ }),
project: SanitizedProjectSchema.pick({ name: true, id: true }),
roles: z.array(
z.object({
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 0f7b927a25..5de3c8f1ad 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -375,6 +375,19 @@ export const authLoginServiceFactory = ({
organizationId
});
+ // Step 4: Promote any Invited memberships to Accepted now that the user has authenticated
+ if (organizationId) {
+ await membershipUserDAL.update(
+ {
+ actorUserId: user.id,
+ scopeOrgId: organizationId,
+ scope: AccessScope.Organization,
+ status: OrgMembershipStatus.Invited
+ },
+ { status: OrgMembershipStatus.Accepted }
+ );
+ }
+
return { result: ProviderAuthResult.SESSION, tokens } as const;
};
@@ -1147,12 +1160,12 @@ export const authLoginServiceFactory = ({
if (!user || !user.isAccepted)
throw new BadRequestError({ message: "User not found", name: "Find user from token" });
- // Check user membership in the sub-organization (direct or via group)
+ // Check user membership in the organization (accept any status — promotion happens after auth)
const orgMembership = await orgDAL.findEffectiveOrgMembership({
actorType: ActorType.USER,
actorId: user.id,
orgId: organizationId,
- status: OrgMembershipStatus.Accepted
+ acceptAnyStatus: true
});
if (!orgMembership) {
@@ -1184,12 +1197,11 @@ export const authLoginServiceFactory = ({
});
}
- // Check user membership in the root organization
+ // Check user membership in the root organization (accept any status — promotion happens after auth)
const rootOrgMembership = await membershipUserDAL.findOne({
actorUserId: user.id,
scopeOrgId: selectedOrg.rootOrgId,
- scope: AccessScope.Organization,
- status: OrgMembershipStatus.Accepted
+ scope: AccessScope.Organization
});
if (!rootOrgMembership) {
@@ -1253,7 +1265,8 @@ export const authLoginServiceFactory = ({
userId: user.id,
email: user.email,
authMethod: decodedToken.authMethod,
- requiredMfaMethod
+ requiredMfaMethod,
+ organizationId: rootOrg.id
});
return { isMfaEnabled: true, mfa: mfaToken, mfaMethod: requiredMfaMethod } as const;
@@ -1272,6 +1285,17 @@ export const authLoginServiceFactory = ({
mfaMethod: decodedToken.mfaMethod
});
+ // Promote any Invited memberships to Accepted now that the user has authenticated into this org
+ await membershipUserDAL.update(
+ {
+ actorUserId: user.id,
+ scopeOrgId: organizationId,
+ scope: AccessScope.Organization,
+ status: OrgMembershipStatus.Invited
+ },
+ { status: OrgMembershipStatus.Accepted }
+ );
+
// In the event of this being a break-glass request (non-saml / non-oidc / non-google, when any is enforced)
const isAuthEnforcedBypass =
rootOrg.authEnforced &&
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 16d8ba048b..47046526ae 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -992,14 +992,9 @@ export const orgServiceFactory = ({
isEmailVerified: true
});
+ // If user already completed signup, they'll be promoted to Accepted
+ // when they authenticate via selectOrganization or processProviderCallback
if (user.isAccepted) {
- // this means user has already completed signup process
- // isAccepted is set true when keys are exchanged
- await orgDAL.updateMembershipById(orgMembership.id, {
- scopeOrgId: orgId,
- status: OrgMembershipStatus.Accepted
- });
- await licenseService.updateSubscriptionOrgMemberCount(orgId);
return { user };
}
diff --git a/frontend/src/config/request.ts b/frontend/src/config/request.ts
index a1bfbd42a2..bbe3430425 100644
--- a/frontend/src/config/request.ts
+++ b/frontend/src/config/request.ts
@@ -26,15 +26,15 @@ apiRequest.interceptors.request.use((config) => {
const providerAuthToken = SecurityClient.getProviderAuthToken();
if (config.headers) {
- if (token) {
+ if (mfaTempToken) {
+ // eslint-disable-next-line no-param-reassign
+ config.headers.Authorization = `Bearer ${mfaTempToken}`;
+ } else if (token) {
// eslint-disable-next-line no-param-reassign
config.headers.Authorization = `Bearer ${token}`;
} else if (signupTempToken) {
// eslint-disable-next-line no-param-reassign
config.headers.Authorization = `Bearer ${signupTempToken}`;
- } else if (mfaTempToken) {
- // eslint-disable-next-line no-param-reassign
- config.headers.Authorization = `Bearer ${mfaTempToken}`;
} else if (providerAuthToken) {
// eslint-disable-next-line no-param-reassign
config.headers.Authorization = `Bearer ${providerAuthToken}`;
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
index 74c75c2f31..38b0c99f07 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
@@ -317,7 +317,7 @@ export const Navbar = () => {
await logout.mutateAsync();
if (org.orgAuthMethod === AuthMethod.OIDC) {
- window.open(`/api/v1/sso/oidc/login?orgSlug=${org.slug}`);
+ window.open(`/api/v1/sso/oidc/login?domain=${org.slug}`);
} else {
window.open(`/api/v1/sso/redirect/saml2/organizations/${org.slug}`);
}
diff --git a/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx b/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx
index e951fc7b3a..7803062c19 100644
--- a/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx
+++ b/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx
@@ -88,7 +88,7 @@ export const InitialStep = ({ setSection, isAdmin }: Props) => {
};
const redirectToOidc = (orgSlug: string) => {
- const redirectUrl = `/api/v1/sso/oidc/login?orgSlug=${orgSlug}${
+ const redirectUrl = `/api/v1/sso/oidc/login?domain=${orgSlug}${
callbackPort ? `&callbackPort=${callbackPort}` : ""
}`;
window.location.assign(redirectUrl);
diff --git a/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx b/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx
index 64a4601201..164775f019 100644
--- a/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx
+++ b/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx
@@ -24,33 +24,34 @@ export const SSOStep = ({ setSection, type }: Props) => {
const { t } = useTranslation();
const matchingMethod = type === "SAML" ? LoginMethod.SAML : LoginMethod.OIDC;
- const initialSlug =
+ const initialEmail =
lastLogin?.method === matchingMethod && lastLogin.orgSlug ? lastLogin.orgSlug : "";
- const [ssoIdentifier, setSSOIdentifier] = useState(initialSlug);
+ const [ssoEmail, setSSOEmail] = useState(initialEmail);
const queryParams = new URLSearchParams(window.location.search);
const handleSubmission = (e: React.FormEvent) => {
e.preventDefault();
+
+ // Extract domain from email (or use raw input if no @ present)
+ const domain = ssoEmail.includes("@") ? ssoEmail.split("@")[1]?.trim() : ssoEmail.trim();
+ if (!domain) return;
+
+ const identifier = encodeURIComponent(domain);
const callbackPort = queryParams.get("callback_port");
+
+ saveLastLogin({ method: matchingMethod, orgSlug: ssoEmail });
+
if (type === "SAML") {
- saveLastLogin({ method: LoginMethod.SAML, orgSlug: ssoIdentifier });
- window.open(
- `/api/v1/sso/redirect/saml2/organizations/${ssoIdentifier}${
- callbackPort ? `?callback_port=${callbackPort}` : ""
- }`
- );
+ window.location.href = `/api/v1/sso/redirect/saml2/organizations/${identifier}${
+ callbackPort ? `?callback_port=${callbackPort}` : ""
+ }`;
} else {
- saveLastLogin({ method: LoginMethod.OIDC, orgSlug: ssoIdentifier });
- window.open(
- `/api/v1/sso/oidc/login?orgSlug=${ssoIdentifier}${
- callbackPort ? `&callbackPort=${callbackPort}` : ""
- }`
- );
+ window.location.href = `/api/v1/sso/oidc/login?domain=${identifier}${
+ callbackPort ? `&callbackPort=${callbackPort}` : ""
+ }`;
}
-
- window.close();
};
return (
@@ -58,16 +59,16 @@ export const SSOStep = ({ setSection, type }: Props) => {
<UnstableCard className="w-full items-stretch gap-0 p-6">
<UnstableCardHeader className="mb-4 gap-4">
<UnstableCardTitle className="ml-0.5 bg-linear-to-b from-white to-bunker-200 bg-clip-text text-[1.35rem] font-medium text-transparent">
- What&apos;s your organization slug?
+ What&apos;s your work email?
</UnstableCardTitle>
</UnstableCardHeader>
<UnstableCardContent>
<div className="w-full">
<UnstableInput
- value={ssoIdentifier}
- onChange={(e) => setSSOIdentifier(e.target.value)}
- type="text"
- placeholder="acme-123"
+ value={ssoEmail}
+ onChange={(e) => setSSOEmail(e.target.value)}
+ type="email"
+ placeholder="[email protected]"
required
className="h-10"
/>
diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
index 672f99640d..83580a9a8a 100644
--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
+++ b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
@@ -8,10 +8,15 @@ import { MfaMethod } from "@app/hooks/api/auth/types";
import { navigateUserToOrg } from "../LoginPage/Login.utils";
import { SelectOrganizationSection } from "./SelectOrgSection";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { useUser } from "@app/context";
export const SelectOrganizationPage = () => {
const search = useSearch({ from: ROUTE_PATHS.Auth.SelectOrgPage.id });
const navigate = useNavigate();
+ const { t } = useTranslation();
+ const { user } = useUser();
// IdP MFA redirect: backend sends mfaToken + mfaMethod when org-scoped SSO requires MFA
const { mfaToken, mfaMethod } = search;
@@ -23,18 +28,27 @@ export const SelectOrganizationPage = () => {
const decoded = jwtDecode(mfaToken) as { organizationId?: string };
return (
- <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 });
- }
- }}
- />
+ <div className="flex max-h-screen min-h-screen flex-col justify-center overflow-y-auto bg-linear-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">
+ <Helmet>
+ <title>MFA | Infisical</title>
+ <link rel="icon" href="/infisical.ico" />
+ <meta property="og:image" content="/images/message.png" />
+ <meta property="og:title" content={t("login.og-title") ?? ""} />
+ <meta name="og:description" content={t("login.og-description") ?? ""} />
+ </Helmet>
+ <Mfa
+ email={user?.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 });
+ }
+ }}
+ />
+ </div>
);
}
diff --git a/frontend/src/pages/auth/SelectOrgPage/route.tsx b/frontend/src/pages/auth/SelectOrgPage/route.tsx
index 804ac82556..55476f27be 100644
--- a/frontend/src/pages/auth/SelectOrgPage/route.tsx
+++ b/frontend/src/pages/auth/SelectOrgPage/route.tsx
@@ -63,8 +63,15 @@ export const Route = createFileRoute("/_restrict-login-signup/login/select-organ
const result = await selectOrganization({ organizationId: orgId });
if (result.isMfaEnabled) {
- // MFA required — let the page handle it
- return;
+ // MFA required — redirect back to this page with MFA params so the component renders MFA immediately
+ throw redirect({
+ to: "/login/select-organization",
+ search: {
+ mfaToken: result.token,
+ mfaMethod: result.mfaMethod,
+ org_id: orgId
+ }
+ });
}
setAuthToken(result.token);
diff --git a/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx b/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx
index 098a97883c..e5fab7d00f 100644
--- a/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx
+++ b/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx
@@ -1,10 +1,45 @@
-import { useSearch } from "@tanstack/react-router";
+import { Helmet } from "react-helmet";
+import { Link, useNavigate, useRouteContext } from "@tanstack/react-router";
+
+import { Button } from "@app/components/v2";
import { SignUpPage } from "../SignUpPage/SignUpPage";
export const SignupInvitePage = () => {
- const search = useSearch({ from: "/_restrict-login-signup/signupinvite" });
- const email = (search.to as string)?.replace(" ", "+").trim();
+ const navigate = useNavigate();
+ const { inviteEmail, error } = useRouteContext({
+ from: "/_restrict-login-signup/signupinvite"
+ }) as { inviteEmail?: string; error?: string };
+
+ if (error) {
+ return (
+ <div className="flex min-h-screen flex-col items-center justify-center bg-linear-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">
+ <Helmet>
+ <title>Invalid Invitation</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Helmet>
+ <Link to="/">
+ <div className="mb-8 flex justify-center">
+ <img
+ src="/images/gradientLogo.svg"
+ style={{ height: "90px", width: "120px" }}
+ alt="Infisical logo"
+ />
+ </div>
+ </Link>
+ <div className="mx-auto w-full max-w-md rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-8 text-center">
+ <h1 className="mb-2 text-xl font-medium text-gray-200">Invitation Invalid</h1>
+ <p className="mb-6 text-sm text-gray-400">{error}</p>
+ <p className="mb-4 text-sm text-gray-500">
+ Please ask your organization admin to send a new invitation.
+ </p>
+ <Button onClick={() => navigate({ to: "/login" })} size="sm" colorSchema="primary">
+ Go to Login
+ </Button>
+ </div>
+ </div>
+ );
+ }
- return <SignUpPage invite={{ email }} />;
+ return <SignUpPage invite={{ email: inviteEmail ?? "" }} />;
};
diff --git a/frontend/src/pages/auth/SignUpInvitePage/route.tsx b/frontend/src/pages/auth/SignUpInvitePage/route.tsx
index 0e31645fcc..4b33de781f 100644
--- a/frontend/src/pages/auth/SignUpInvitePage/route.tsx
+++ b/frontend/src/pages/auth/SignUpInvitePage/route.tsx
@@ -1,7 +1,11 @@
-import { createFileRoute } from "@tanstack/react-router";
+import { createFileRoute, redirect } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
+import SecurityClient from "@app/components/utilities/SecurityClient";
+import { authKeys, fetchAuthToken, verifySignupInvite } from "@app/hooks/api/auth/queries";
+import { setAuthToken } from "@app/hooks/api/reactQuery";
+
import { SignupInvitePage } from "./SignUpInvitePage";
const SignupInvitePageQueryParamsSchema = z.object({
@@ -12,5 +16,71 @@ const SignupInvitePageQueryParamsSchema = z.object({
export const Route = createFileRoute("/_restrict-login-signup/signupinvite")({
component: SignupInvitePage,
- validateSearch: zodValidator(SignupInvitePageQueryParamsSchema)
+ validateSearch: zodValidator(SignupInvitePageQueryParamsSchema),
+ beforeLoad: async ({ context, search }) => {
+ const email = decodeURIComponent(search.to).trim();
+ const { token, organization_id: organizationId } = search;
+
+ // Check if user is already logged in
+ const authData = await context.queryClient
+ .ensureQueryData({
+ queryKey: authKeys.getAuthToken,
+ queryFn: fetchAuthToken
+ })
+ .catch(() => null);
+
+ if (authData) {
+ setAuthToken(authData.token);
+ }
+
+ try {
+ const result = await verifySignupInvite({
+ email,
+ code: token,
+ organizationId
+ });
+
+ if (authData) {
+ // Logged-in user — invitation accepted, go to the org
+ throw redirect({
+ to: "/login/select-organization",
+ search: { org_id: organizationId }
+ });
+ }
+
+ if (result.token) {
+ // New user — store signup token, render the signup form
+ SecurityClient.setSignupToken(result.token);
+ return { inviteEmail: email };
+ }
+
+ // Existing user, not logged in, membership accepted — send to login
+ throw redirect({ to: "/login" });
+ } catch (error: unknown) {
+ // Re-throw redirects
+ if (typeof error === "object" && error !== null && "to" in error) throw error;
+
+ // "Already a member" — redirect appropriately
+ const message =
+ (error as { response?: { data?: { message?: string } } })?.response?.data?.message ||
+ (error as Error)?.message ||
+ "";
+
+ if (message.includes("already a member")) {
+ if (authData) {
+ throw redirect({
+ to: "/login/select-organization",
+ search: { org_id: organizationId }
+ });
+ }
+ throw redirect({ to: "/login" });
+ }
+
+ // Verification failed — pass error to the page
+ return {
+ inviteEmail: email,
+ error: message || "This invitation link is invalid or has expired."
+ };
+ }
+ }
});