Skip to content

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

feat: added lint and ts check

=7d7afd026ad7
diff --git a/backend/src/db/seeds/3-project.ts b/backend/src/db/seeds/3-project.ts
index 99083ab943..303ee5bad3 100644
--- a/backend/src/db/seeds/3-project.ts
+++ b/backend/src/db/seeds/3-project.ts
@@ -141,7 +141,7 @@ const createUserWithGhostUser = async (
const user = await userDAL.findUserEncKeyByUserId(userId, knex);
- if (!user || !user.publicKey) {
+ if (!user) {
throw new Error("User not found");
}
@@ -150,7 +150,7 @@ const createUserWithGhostUser = async (
userPrivateKey: encKeys.plainPrivateKey,
members: [
{
- userPublicKey: user.publicKey,
+ userPublicKey: "",
orgMembershipId: userOrgMembershipId
}
]
diff --git a/backend/src/ee/routes/v1/ldap-router.ts b/backend/src/ee/routes/v1/ldap-router.ts
index 8e17af35fb..d20f726f2c 100644
--- a/backend/src/ee/routes/v1/ldap-router.ts
+++ b/backend/src/ee/routes/v1/ldap-router.ts
@@ -130,8 +130,6 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
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 {
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index 6a8d468b50..1e050d091a 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -137,12 +137,6 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
return res.redirect(`${appCfg.SITE_URL}/login/select-organization`);
}
- 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) {
return res.redirect(`${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`);
}
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 31a4d86dfa..9304aff4d0 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -294,12 +294,6 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
return res.redirect(`${appCfg.SITE_URL}/login/select-organization`);
}
- 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) {
return res.redirect(`${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`);
}
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 7e5c5c1258..7ab3b7315f 100644
--- a/backend/src/ee/services/email-domain/email-domain-fns.ts
+++ b/backend/src/ee/services/email-domain/email-domain-fns.ts
@@ -39,13 +39,13 @@ export const verifyEmailDomainOwnership = async ({
if (!verifiedDomain) {
throw new BadRequestError({
- message: `Invalid email domain`
+ message: "You organization does not have a verified domain for this email address"
});
}
if (verifiedDomain.orgId !== orgId) {
throw new BadRequestError({
- message: `Invalid email domain`
+ message: "Your organization does not have a verified domain for this email address"
});
}
};
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 8f3e5e46d4..ccd9992426 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -14,6 +14,7 @@ import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
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";
@@ -52,7 +53,6 @@ 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">;
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index fc72474584..19e3ad6f23 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -78,7 +78,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
auditLogsRetentionDays: 0,
auditLogStreams: false,
auditLogStreamLimit: 3,
- samlSSO: false,
+ samlSSO: true,
enforceGoogleSSO: false,
hsm: false,
oidcSSO: false,
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 f988566364..fa19d7a140 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 { logger } from "@app/lib/logger";
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";
@@ -420,19 +421,20 @@ export const samlConfigServiceFactory = ({
const getSaml: TSamlConfigServiceFactory["getSaml"] = async (dto) => {
let samlConfig: TSamlConfigs | undefined;
if (dto.type === "org") {
- samlConfig = await samlConfigDAL.findOne({ orgId: dto.orgId });
+ samlConfig = await samlConfigDAL.findOne({ orgId: dto.orgId, isActive: true });
if (!samlConfig) {
throw new NotFoundError({
message: `SAML configuration for organization with ID '${dto.orgId}' not found`
});
}
} 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
const verifiedDomain = await findOrgIdByVerifiedDomain({ domain: dto.domain, emailDomainDAL });
if (verifiedDomain) {
- resolvedOrgId = verifiedDomain.orgId;
+ const resolvedOrgId = verifiedDomain.orgId;
+ samlConfig = await samlConfigDAL.findOne({ orgId: resolvedOrgId, isActive: true });
+ } else {
+ logger.error(`No verified domain found for domain '${dto.domain}'`);
}
// if (!resolvedOrgId) {
@@ -444,8 +446,6 @@ export const samlConfigServiceFactory = ({
// }
// resolvedOrgId = org.id;
// }
-
- samlConfig = await samlConfigDAL.findOne({ orgId: resolvedOrgId });
} else if (dto.type === "ssoId") {
// TODO:
// We made this change because saml config ids were not moved over during the migration
@@ -745,7 +745,12 @@ export const samlConfigServiceFactory = ({
});
}
- const callbackPort = relayState ? (JSON.parse(relayState) as { callbackPort: string }).callbackPort : undefined;
+ let callbackPort;
+ try {
+ callbackPort = relayState ? (JSON.parse(relayState) as { callbackPort: string }).callbackPort : undefined;
+ } catch {
+ // relayState is invalid JSON, ignore and proceed without a callback port
+ }
const callbackResult = await loginService.processProviderCallback({
user,
diff --git a/backend/src/lib/validator/validate-email.ts b/backend/src/lib/validator/validate-email.ts
index 9cef57cf2b..edd645a8ee 100644
--- a/backend/src/lib/validator/validate-email.ts
+++ b/backend/src/lib/validator/validate-email.ts
@@ -1,6 +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[]) => {
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index b5ac7caa94..a68b355e0d 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -214,7 +214,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
schemas: error.schemas,
status: error.status,
detail: error.detail,
- mutatability: error.mutatability
+ mutability: error.mutability
});
} else if (error instanceof OidcAuthError) {
void res.status(HttpStatusCodes.InternalServerError).send({
diff --git a/backend/src/server/routes/sanitizedSchemas.ts b/backend/src/server/routes/sanitizedSchemas.ts
index 7bd4c3c316..226f17fff1 100644
--- a/backend/src/server/routes/sanitizedSchemas.ts
+++ b/backend/src/server/routes/sanitizedSchemas.ts
@@ -107,6 +107,17 @@ export const sapPubSchema = SecretApprovalPoliciesSchema.merge(
})
);
+export const SanitizedUserSchema = UsersSchema.pick({
+ username: true,
+ email: true,
+ isEmailVerified: true,
+ firstName: true,
+ lastName: true,
+ id: true
+}).extend({
+ publicKey: z.string().nullable().optional()
+});
+
export const sanitizedServiceTokenUserSchema = UsersSchema.pick({
authMethods: true,
id: true,
diff --git a/backend/src/server/routes/v1/project-membership-router.ts b/backend/src/server/routes/v1/project-membership-router.ts
index 42d248f60c..dcd58abec1 100644
--- a/backend/src/server/routes/v1/project-membership-router.ts
+++ b/backend/src/server/routes/v1/project-membership-router.ts
@@ -6,7 +6,6 @@ import {
ProjectMembershipsSchema,
ProjectUserMembershipRolesSchema,
TemporaryPermissionMode,
- UserEncryptionKeysSchema,
UsersSchema
} from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index fe39379a4d..25530bc3b6 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -397,12 +397,6 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
);
}
- 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(
diff --git a/backend/src/server/routes/v2/organization-router.ts b/backend/src/server/routes/v2/organization-router.ts
index 14ff7a2c59..78a2fe4e98 100644
--- a/backend/src/server/routes/v2/organization-router.ts
+++ b/backend/src/server/routes/v2/organization-router.ts
@@ -1,13 +1,6 @@
import { z } from "zod";
-import {
- OrgMembershipsSchema,
- OrgMembershipStatus,
- ProjectMembershipsSchema,
- ProjectsSchema,
- UserEncryptionKeysSchema,
- UsersSchema
-} from "@app/db/schemas";
+import { OrgMembershipsSchema, OrgMembershipStatus, ProjectMembershipsSchema, ProjectsSchema } from "@app/db/schemas";
import { ApiDocsTags, ORGANIZATIONS } from "@app/lib/api-docs";
import { getConfig } from "@app/lib/config/env";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -17,6 +10,8 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { sanitizedOrganizationSchema } from "@app/services/org/org-schema";
+import { SanitizedUserSchema } from "../sanitizedSchemas";
+
export const registerOrgRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
@@ -41,14 +36,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
200: z.object({
users: OrgMembershipsSchema.merge(
z.object({
- user: UsersSchema.pick({
- username: true,
- email: true,
- isEmailVerified: true,
- firstName: true,
- lastName: true,
- id: true
- }).merge(UserEncryptionKeysSchema.pick({ publicKey: true }))
+ user: SanitizedUserSchema
})
)
.omit({ createdAt: true, updatedAt: true })
@@ -152,14 +140,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
})
.array()
.optional(),
- user: UsersSchema.pick({
- username: true,
- email: true,
- isEmailVerified: true,
- firstName: true,
- lastName: true,
- id: true
- }).extend({ publicKey: z.string().nullish() })
+ user: SanitizedUserSchema
}).omit({ createdAt: true, updatedAt: true })
})
}
@@ -358,13 +339,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
memberships: ProjectMembershipsSchema.extend({
- user: UsersSchema.pick({
- email: true,
- username: true,
- firstName: true,
- lastName: true,
- id: true
- }).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
+ user: SanitizedUserSchema,
project: ProjectsSchema.pick({ name: true, id: true, type: true }),
roles: z.array(
z.object({
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index 79154ea808..56e04b113e 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -363,7 +363,31 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
description: "Retrieve the current user on the request",
response: {
200: z.object({
- user: UsersSchema.omit({ hashedPassword: true })
+ user: z.object({
+ id: z.string().uuid(),
+ email: z.string().nullable().optional(),
+ authMethods: z.string().array().nullable().optional(),
+ superAdmin: z.boolean().default(false).nullable().optional(),
+ firstName: z.string().nullable().optional(),
+ lastName: z.string().nullable().optional(),
+ isAccepted: z.boolean().default(false).nullable().optional(),
+ isMfaEnabled: z.boolean().default(false).nullable().optional(),
+ mfaMethods: z.string().array().nullable().optional(),
+ devices: z.unknown().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ isGhost: z.boolean().default(false),
+ username: z.string(),
+ isEmailVerified: z.boolean().default(false).nullable().optional(),
+ consecutiveFailedMfaAttempts: z.number().default(0).nullable().optional(),
+ isLocked: z.boolean().default(false).nullable().optional(),
+ temporaryLockDateEnd: z.date().nullable().optional(),
+ consecutiveFailedPasswordAttempts: z.number().default(0).nullable().optional(),
+ selectedMfaMethod: z.string().nullable().optional(),
+ isGitHubVerified: z.boolean().nullable().optional(),
+ isGitLabVerified: z.boolean().nullable().optional(),
+ isGoogleVerified: z.boolean().nullable().optional()
+ })
})
}
},
diff --git a/backend/src/services/account-recovery/account-recovery-service.ts b/backend/src/services/account-recovery/account-recovery-service.ts
index 296adefda8..859593c82a 100644
--- a/backend/src/services/account-recovery/account-recovery-service.ts
+++ b/backend/src/services/account-recovery/account-recovery-service.ts
@@ -9,7 +9,6 @@ import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TMembershipUserDALFactory } from "@app/services/membership-user/membership-user-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TUserDALFactory } from "@app/services/user/user-dal";
-import { UserEncryption } from "@app/services/user/user-types";
import { validatePasswordResetAuthorization } from "../auth/auth-fns";
@@ -114,7 +113,7 @@ export const accountRecoveryServiceFactory = ({
{ expiresIn: cfg.JWT_SIGNUP_LIFETIME }
);
- return { token, user, userEncryptionVersion: userEnc.encryptionVersion as UserEncryption };
+ return { token, user, userEncryptionVersion: 2 };
};
const enableEmailAuthForUser = async (token: string) => {
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 5de3c8f1ad..6f67caed7a 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -192,7 +192,8 @@ export const authLoginServiceFactory = ({
authMethod,
authTokenType: AuthTokenType.MFA_TOKEN,
userId,
- organizationId
+ organizationId,
+ email
},
appCfg.AUTH_SECRET,
{ expiresIn: appCfg.JWT_MFA_LIFETIME }
@@ -342,31 +343,28 @@ export const authLoginServiceFactory = ({
return { result: ProviderAuthResult.SIGNUP_REQUIRED, signupToken } as const;
}
- // Step 2: For org-scoped IdP flows, check MFA before issuing tokens
+ // Step 2: For org-scoped IdP flows with MFA, issue tokens without org scope
+ // so the user gets a session (for TOTP setup) but must go through selectOrganization
+ // which handles MFA before granting org access.
if (organizationId) {
const org = await orgDAL.findById(organizationId);
if (org) {
- const { isMfaRequired, requiredMfaMethod } = getRequiredMfaMethod(org, user);
+ const { isMfaRequired } = getRequiredMfaMethod(org, user);
if (isMfaRequired) {
- enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
-
- const mfaToken = await issueMfaChallenge({
+ const tokens = await generateUserTokens({
userId: user.id,
- email: user.email,
- authMethod,
- organizationId,
- requiredMfaMethod
+ ip,
+ userAgent,
+ authMethod
});
- return { result: ProviderAuthResult.MFA_REQUIRED, mfaToken, mfaMethod: requiredMfaMethod } as const;
+ return { result: ProviderAuthResult.SESSION, tokens } 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
+ // Step 3: No MFA — issue org-scoped session tokens
const tokens = await generateUserTokens({
userId: user.id,
ip,
diff --git a/backend/src/services/auth/auth-password-service.ts b/backend/src/services/auth/auth-password-service.ts
index 38b74cfab0..3545a98b26 100644
--- a/backend/src/services/auth/auth-password-service.ts
+++ b/backend/src/services/auth/auth-password-service.ts
@@ -12,7 +12,6 @@ import { TUserDALFactory } from "../user/user-dal";
import { UserEncryption } from "../user/user-types";
import { TAuthDALFactory } from "./auth-dal";
import {
- ResetPasswordV2Type,
TResetPasswordV2DTO,
TResetPasswordViaBackupKeyDTO,
TSetupPasswordViaBackupKeyDTO
@@ -35,7 +34,7 @@ export const authPaswordServiceFactory = ({
smtpService,
totpConfigDAL
}: TAuthPasswordServiceFactoryDep) => {
- const resetPasswordV2 = async ({ userId, newPassword, type, oldPassword }: TResetPasswordV2DTO) => {
+ const resetPasswordV2 = async ({ userId, newPassword, oldPassword }: TResetPasswordV2DTO) => {
const cfg = getConfig();
const user = await userDAL.findUserEncKeyByUserId(userId);
@@ -51,26 +50,17 @@ export const authPaswordServiceFactory = ({
throw new BadRequestError({ message: "Unable to reset password, no email authentication method is configured" });
}
- // we check the old password if the user is resetting their password while logged in
- if (type === ResetPasswordV2Type.LoggedInReset) {
- if (!user.hashedPassword) {
- throw new BadRequestError({ message: "Unable to change password, no password is set" });
- }
- if (!oldPassword) {
- throw new BadRequestError({ message: "Current password is required." });
- }
+ if (!user.hashedPassword) {
+ throw new BadRequestError({ message: "Unable to change password, no password is set" });
+ }
- const isValid = await crypto.hashing().compareHash(oldPassword, user.hashedPassword);
- if (!isValid) {
- throw new BadRequestError({ message: "Incorrect current password." });
- }
+ if (!oldPassword) {
+ throw new BadRequestError({ message: "Current password is required." });
}
- if (user.encryptionVersion !== UserEncryption.V2) {
- throw new BadRequestError({
- message: "Cannot reset password without current credentials or recovery method",
- name: "Reset password"
- });
+ const isValid = await crypto.hashing().compareHash(oldPassword, user.hashedPassword);
+ if (!isValid) {
+ throw new BadRequestError({ message: "Incorrect current password." });
}
const newHashedPassword = await crypto.hashing().createHash(newPassword, cfg.SALT_ROUNDS);
diff --git a/backend/src/services/user/user-dal.ts b/backend/src/services/user/user-dal.ts
index 10f0fb793a..f703b0963e 100644
--- a/backend/src/services/user/user-dal.ts
+++ b/backend/src/services/user/user-dal.ts
@@ -112,7 +112,7 @@ export const userDALFactory = (db: TDbClient) => {
const findUserEncKeyByUserId = async (userId: string, tx?: Knex) => {
try {
const user = await (tx || db.replicaNode())(TableName.Users).where(`${TableName.Users}.id`, userId).first();
- return user;
+ return { ...user, publicKey: "" };
} catch (error) {
throw new DatabaseError({ error, name: "Find user enc by user id" });
}
diff --git a/frontend/src/config/request.ts b/frontend/src/config/request.ts
index bbe3430425..53815c7d09 100644
--- a/frontend/src/config/request.ts
+++ b/frontend/src/config/request.ts
@@ -62,41 +62,33 @@ apiRequest.interceptors.response.use(
async (error) => {
const { response, config } = error;
- if (response && (response.status === 401 || response.status === 403)) {
- const currentToken = getAuthToken();
- const isAuthenticatedRequest = Boolean(currentToken);
-
- if (isAuthenticatedRequest) {
- const errorMessage = response.data?.message || "";
-
- // Attempt transparent token refresh on expiration
- if (
- isTokenExpiredError(errorMessage) &&
- !(config as AxiosRequestConfig & { _retry?: boolean })._retry
- ) {
- (config as AxiosRequestConfig & { _retry?: boolean })._retry = true;
-
- try {
- // Deduplicate concurrent refresh attempts
- if (!refreshPromise) {
- refreshPromise = fetchAuthToken()
- .then((data) => data.token)
- .finally(() => {
- refreshPromise = null;
- });
- }
-
- const newToken = await refreshPromise;
-
- // Retry the original request with the new token
- // eslint-disable-next-line no-param-reassign
- config.headers.Authorization = `Bearer ${newToken}`;
- return apiRequest(config);
- } catch {
- // Refresh failed — fall through to redirect logic below
- }
+ if (
+ response &&
+ response.status === 401 &&
+ isTokenExpiredError(response.data?.message || "") &&
+ getAuthToken() &&
+ !(config as AxiosRequestConfig & { infisicalRetry?: boolean }).infisicalRetry
+ ) {
+ (config as AxiosRequestConfig & { infisicalRetry?: boolean }).infisicalRetry = true;
+
+ try {
+ // Deduplicate concurrent refresh attempts
+ if (!refreshPromise) {
+ refreshPromise = fetchAuthToken()
+ .then((data) => data.token)
+ .finally(() => {
+ refreshPromise = null;
+ });
}
+ const newToken = await refreshPromise;
+
+ // Retry the original request with the new token
+ // eslint-disable-next-line no-param-reassign
+ config.headers.Authorization = `Bearer ${newToken}`;
+ return await apiRequest(config);
+ } catch {
+ // Refresh failed — clear session and redirect to login
if (!isRedirecting) {
isRedirecting = true;
@@ -117,7 +109,7 @@ apiRequest.interceptors.response.use(
sessionStorage.setItem(
SessionStorageKeys.ORG_LOGIN_SUCCESS_REDIRECT_URL,
JSON.stringify({
- expiry: formatISO(addSeconds(new Date(), 300)), // 5 minutes
+ expiry: formatISO(addSeconds(new Date(), 300)),
data: window.location.href
})
);
@@ -127,7 +119,7 @@ apiRequest.interceptors.response.use(
setTimeout(() => {
window.location.href = "/login";
- }, 2000); // 2 seconds to read the notification
+ }, 2000);
setTimeout(resetRedirectingFlag, 3000);
diff --git a/frontend/src/hooks/api/organization/index.ts b/frontend/src/hooks/api/organization/index.ts
index 0e591aa50d..1506a5777f 100644
--- a/frontend/src/hooks/api/organization/index.ts
+++ b/frontend/src/hooks/api/organization/index.ts
@@ -1,5 +1,7 @@
export type { TOrgWithSubOrgs } from "./queries";
export {
+ fetchOrganizationsWithSubOrgs,
+ organizationKeys,
useAddOrgPmtMethod,
useAddOrgTaxId,
useCreateCustomerPortalSession,
@@ -10,8 +12,6 @@ export {
useGetIdentityMembershipOrgs,
useGetOrganizationGroups,
useGetOrganizations,
- fetchOrganizationsWithSubOrgs,
- organizationKeys,
useGetOrganizationsWithSubOrgs,
useGetOrgBillingDetails,
useGetOrgIntegrationAuths,
diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
index 83580a9a8a..5ac6a38c91 100644
--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
+++ b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx
@@ -1,56 +1,529 @@
-import { useNavigate, useSearch } from "@tanstack/react-router";
+import { useCallback, useMemo, useState } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { Link, useNavigate, useRouter, useSearch } from "@tanstack/react-router";
+import axios from "axios";
+import { addSeconds, format, formatISO } from "date-fns";
import { jwtDecode } from "jwt-decode";
+import { ChevronRight, LogIn, Search } from "lucide-react";
import { Mfa } from "@app/components/auth/Mfa";
+import { createNotification } from "@app/components/notifications";
+import { IsCliLoginSuccessful } from "@app/components/utilities/attemptCliLogin";
import SecurityClient from "@app/components/utilities/SecurityClient";
+import { Button, ContentLoader, Input, Spinner } from "@app/components/v2";
+import { SessionStorageKeys } from "@app/const";
import { ROUTE_PATHS } from "@app/const/routes";
-import { MfaMethod } from "@app/hooks/api/auth/types";
+import { useToggle } from "@app/hooks";
+import {
+ TOrgWithSubOrgs,
+ useGetOrganizations,
+ useGetOrganizationsWithSubOrgs,
+ useGetUser,
+ useLogoutUser,
+ useSelectOrganization
+} from "@app/hooks/api";
+import { MfaMethod, UserAgentType } from "@app/hooks/api/auth/types";
+import { getAuthToken, isLoggedIn, setAuthToken } from "@app/hooks/api/reactQuery";
+import { Organization } from "@app/hooks/api/types";
+import { AuthMethod, SAML_AUTH_METHODS } from "@app/hooks/api/users/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 });
+// Shared org row component to avoid repeating the same layout + userJoinedAt logic
+const OrgRow = ({
+ name,
+ label,
+ joinedAt,
+ onClick,
+ variant = "default"
+}: {
+ name: string;
+ label?: string;
+ joinedAt?: string | null;
+ onClick: () => void;
+ variant?: "default" | "sub" | "root";
+}) => {
+ const bgClass =
+ variant === "sub"
+ ? "bg-mineshaft-800 text-gray-300 hover:bg-mineshaft-700"
+ : "bg-mineshaft-700 text-gray-200 hover:bg-mineshaft-600";
+
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={`Login to ${name}`}
+ className={`group flex h-14 w-full cursor-pointer items-center justify-between rounded-md border border-mineshaft-600 px-4 shadow-md transition-colors ${bgClass}`}
+ >
+ <div className="flex flex-col items-start">
+ <p className="truncate">{name}</p>
+ {(label || joinedAt) && (
+ <p className="text-xs text-mineshaft-400">
+ {label}
+ {label && joinedAt && " · "}
+ {joinedAt && <>Member since {format(new Date(joinedAt), "MMM d yyyy")}</>}
+ </p>
+ )}
+ </div>
+ <LogIn className="size-4 text-gray-400 transition-all group-hover:text-primary-400" />
+ </button>
+ );
+};
+
+export const SelectOrgPage = () => {
const navigate = useNavigate();
const { t } = useTranslation();
- const { user } = useUser();
+ const router = useRouter();
+ const search = useSearch({ from: ROUTE_PATHS.Auth.SelectOrgPage.id });
- // IdP MFA redirect: backend sends mfaToken + mfaMethod when org-scoped SSO requires MFA
- const { mfaToken, mfaMethod } = search;
+ const {
+ org_id: orgId,
+ callback_port: callbackPort,
+ is_admin_login: isBreakglassRoute,
+ mfa_pending: mfaPending
+ } = search;
- if (mfaToken && mfaMethod) {
- SecurityClient.setMfaToken(mfaToken);
+ const organizations = useGetOrganizations();
+ const orgsWithSubOrgs = useGetOrganizationsWithSubOrgs();
+ const selectOrg = useSelectOrganization();
+ const { data: user, isPending: userLoading } = useGetUser();
+ const logout = useLogoutUser();
- // Decode the MFA token to get the organizationId for post-MFA navigation
- const decoded = jwtDecode(mfaToken) as { organizationId?: string };
+ const [shouldShowMfa, toggleShowMfa] = useToggle(false);
+ const [requiredMfaMethod, setRequiredMfaMethod] = useState(MfaMethod.EMAIL);
+ const [selectedRootOrg, setSelectedRootOrg] = useState<TOrgWithSubOrgs | null>(null);
+ const [searchTerm, setSearchTerm] = useState("");
+ const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
- return (
- <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 });
+ const defaultSelectedOrg = organizations.data?.find((org) => org.id === orgId);
+
+ // Build a flat lookup map: orgId → { org (full Organization), rootOrg? (for sub-orgs) }
+ const orgLookup = useMemo(() => {
+ const map = new Map<string, { org: Organization; rootOrg?: Organization }>();
+ if (!organizations.data || !orgsWithSubOrgs.data) return map;
+
+ organizations.data.forEach((fullOrg) => {
+ map.set(fullOrg.id, { org: fullOrg });
+ });
+
+ orgsWithSubOrgs.data.forEach((entry) => {
+ const rootOrg = organizations.data.find((o) => o.id === entry.id);
+ if (!rootOrg) return;
+
+ entry.subOrganizations.forEach((sub) => {
+ if (!map.has(sub.id)) {
+ map.set(sub.id, { org: { ...rootOrg, id: sub.id }, rootOrg });
+ }
+ });
+ });
+
+ return map;
+ }, [organizations.data, orgsWithSubOrgs.data]);
+
+ const handleLogout = useCallback(async () => {
+ try {
+ await logout.mutateAsync();
+ navigate({ to: "/login" });
+ } catch (error) {
+ console.error(error);
+ }
+ }, [logout, navigate]);
+
+ const filteredOrgs = useMemo(() => {
+ if (!orgsWithSubOrgs.data) return [];
+ if (!searchTerm.trim()) return orgsWithSubOrgs.data;
+
+ const term = searchTerm.toLowerCase();
+ return orgsWithSubOrgs.data
+ .filter(
+ (org) =>
+ org.name.toLowerCase().includes(term) ||
+ org.subOrganizations.some((sub) => sub.name.toLowerCase().includes(term))
+ )
+ .map((org) => ({
+ ...org,
+ subOrganizations: org.name.toLowerCase().includes(term)
+ ? org.subOrganizations
+ : org.subOrganizations.filter((sub) => sub.name.toLowerCase().includes(term))
+ }));
+ }, [orgsWithSubOrgs.data, searchTerm]);
+
+ const totalOrgCount = useMemo(() => {
+ if (!orgsWithSubOrgs.data) return 0;
+ return orgsWithSubOrgs.data.reduce((sum, org) => sum + 1 + org.subOrganizations.length, 0);
+ }, [orgsWithSubOrgs.data]);
+
+ const filteredSubOrgs = useMemo(() => {
+ if (!selectedRootOrg) return [];
+ if (!searchTerm.trim()) return selectedRootOrg.subOrganizations;
+ const term = searchTerm.toLowerCase();
+ return selectedRootOrg.subOrganizations.filter((sub) => sub.name.toLowerCase().includes(term));
+ }, [selectedRootOrg, searchTerm]);
+
+ const handleSelectOrganization = useCallback(
+ async (organization: Organization) => {
+ const canBypassOrgAuth = organization.bypassOrgAuthEnabled && isBreakglassRoute;
+
+ if (isBreakglassRoute && !organization.bypassOrgAuthEnabled) {
+ createNotification({
+ text: "This organization does not have bypass org auth enabled",
+ type: "error"
+ });
+ return;
+ }
+
+ // SSO enforcement: block and notify instead of logging out
+ if ((organization.authEnforced || organization.googleSsoAuthEnforced) && !canBypassOrgAuth) {
+ const authToken = jwtDecode(getAuthToken()) as { authMethod: AuthMethod };
+
+ let ssoRequired = false;
+ let ssoType = "";
+
+ if (organization.googleSsoAuthEnforced && authToken.authMethod !== AuthMethod.GOOGLE) {
+ ssoRequired = true;
+ ssoType = "Google SSO";
+ } else if (
+ organization.orgAuthMethod === AuthMethod.OIDC &&
+ authToken.authMethod !== AuthMethod.OIDC
+ ) {
+ ssoRequired = true;
+ ssoType = "OIDC SSO";
+ } else if (
+ organization.orgAuthMethod === AuthMethod.SAML &&
+ !SAML_AUTH_METHODS.includes(authToken.authMethod as (typeof SAML_AUTH_METHODS)[number])
+ ) {
+ ssoRequired = true;
+ ssoType = "SAML SSO";
+ }
+
+ if (ssoRequired) {
+ createNotification({
+ text: `This organization requires ${ssoType}. Please log out and re-login via your identity provider.`,
+ type: "error"
+ });
+ return;
+ }
+ }
+
+ let token;
+ let isMfaEnabled;
+ let mfaMethod;
+
+ try {
+ const result = await selectOrg.mutateAsync({
+ organizationId: organization.id,
+ userAgent: callbackPort ? UserAgentType.CLI : undefined
+ });
+ token = result.token;
+ isMfaEnabled = result.isMfaEnabled;
+ mfaMethod = result.mfaMethod;
+ } catch (error: any) {
+ const message = error?.response?.data?.message || "Failed to select organization.";
+ createNotification({ text: message, type: "error" });
+ return;
+ }
+
+ await router.invalidate();
+
+ if (isMfaEnabled) {
+ SecurityClient.setMfaToken(token);
+ if (mfaMethod) {
+ setRequiredMfaMethod(mfaMethod);
+ }
+ toggleShowMfa.on();
+ setMfaSuccessCallback(() => () => handleSelectOrganization(organization));
+ return;
+ }
+
+ if (callbackPort) {
+ let error: string | null = null;
+
+ if (!user?.email) error = "User email not found";
+ if (!token) error = "No token found";
+
+ if (error) {
+ createNotification({ text: error, type: "error" });
+ return;
+ }
+
+ const payload = {
+ JTWToken: token,
+ email: user?.email,
+ privateKey: ""
+ } as IsCliLoginSuccessful["loginResponse"];
+
+ const instance = axios.create();
+ await instance.post(`http://127.0.0.1:${callbackPort}/`, payload).catch(() => {
+ sessionStorage.setItem(
+ SessionStorageKeys.CLI_TERMINAL_TOKEN,
+ JSON.stringify({
+ expiry: formatISO(addSeconds(new Date(), 30)),
+ data: window.btoa(JSON.stringify(payload))
+ })
+ );
+ });
+ navigate({ to: "/cli-redirect" });
+ } else {
+ setAuthToken(token);
+ navigateUserToOrg({ navigate, organizationId: organization.id });
+ }
+ },
+ [selectOrg, callbackPort, isBreakglassRoute, user, router, toggleShowMfa, navigate]
+ );
+
+ const handleLoginById = useCallback(
+ (id: string) => {
+ const entry = orgLookup.get(id);
+ if (entry) {
+ handleSelectOrganization(entry.org);
+ return;
+ }
+ createNotification({ text: "Organization not found", type: "error" });
+ },
+ [orgLookup, handleSelectOrganization]
+ );
+
+ const handleCliRedirect = useCallback(() => {
+ const authToken = getAuthToken();
+
+ if (authToken && !callbackPort) {
+ const decodedJwt = jwtDecode(authToken) as any;
+ if (decodedJwt?.organizationId) {
+ navigateUserToOrg({ navigate, organizationId: decodedJwt.organizationId });
+ }
+ }
+
+ if (!isLoggedIn()) {
+ navigate({ to: "/login" });
+ }
+ }, [callbackPort, navigate]);
+
+ // CLI redirect on mount
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useMemo(() => {
+ if (callbackPort) handleCliRedirect();
+ }, []);
+
+ // MFA pending from IdP redirect
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useMemo(() => {
+ if (mfaPending && defaultSelectedOrg) {
+ const storedMfaToken = sessionStorage.getItem(SessionStorageKeys.MFA_TEMP_TOKEN);
+ if (storedMfaToken) {
+ sessionStorage.removeItem(SessionStorageKeys.MFA_TEMP_TOKEN);
+ SecurityClient.setMfaToken(storedMfaToken);
+ toggleShowMfa.on();
+ setMfaSuccessCallback(() => () => handleSelectOrganization(defaultSelectedOrg));
+ }
+ }
+ }, [mfaPending, defaultSelectedOrg]);
+
+ const renderListContent = () => {
+ if (orgsWithSubOrgs.isPending) {
+ return (
+ <div className="flex justify-center py-6">
+ <Spinner size="sm" />
+ </div>
+ );
+ }
+
+ if (selectedRootOrg) {
+ return (
+ <div className="space-y-2">
+ <OrgRow
+ name={selectedRootOrg.name}
+ label="Root organization"
+ joinedAt={
+ selectedRootOrg.userJoinedAt ??
+ organizations.data?.find((o) => o.id === selectedRootOrg.id)?.userJoinedAt
}
- }}
- />
+ onClick={() => handleLoginById(selectedRootOrg.id)}
+ variant="root"
+ />
+ <p className="px-1 pt-1 text-xs font-medium tracking-wider text-mineshaft-400 uppercase">
+ Sub-organizations
+ </p>
+ {filteredSubOrgs.length === 0 ? (
+ <p className="py-4 text-center text-sm text-mineshaft-400">
+ No sub-organizations found
+ </p>
+ ) : (
+ filteredSubOrgs.map((sub) => (
+ <OrgRow
+ key={sub.id}
+ name={sub.name}
+ joinedAt={sub.userJoinedAt}
+ onClick={() => handleLoginById(sub.id)}
+ variant="sub"
+ />
+ ))
+ )}
+ </div>
+ );
+ }
+
+ if (filteredOrgs.length === 0) {
+ return <p className="py-4 text-center text-sm text-mineshaft-400">No organizations found</p>;
+ }
+
+ const isSearching = !!searchTerm.trim();
+ return (
+ <div className="space-y-2">
+ {filteredOrgs.map((org) => {
+ const hasSubOrgs = org.subOrganizations.length > 0;
+ const joinedAt =
+ org.userJoinedAt ?? organizations.data?.find((o) => o.id === org.id)?.userJoinedAt;
+
+ return (
+ <div key={org.id}>
+ {hasSubOrgs && !isSearching ? (
+ <div className="relative overflow-clip rounded-md border border-mineshaft-600 text-gray-200 shadow-md">
+ <button
+ type="button"
+ onClick={() => handleLoginById(org.id)}
+ aria-label={`Login to ${org.name}`}
+ className="group relative z-10 flex w-full cursor-pointer items-center justify-between bg-mineshaft-700 px-4 py-3 transition-colors hover:bg-mineshaft-600"
+ >
+ <div className="flex flex-col items-start gap-1.5">
+ <p className="truncate transition-colors">{org.name}</p>
+ {joinedAt && (
+ <p className="text-xs text-mineshaft-400">
+ Member since {format(new Date(joinedAt), "MMM d yyyy")}
+ </p>
+ )}
+ </div>
+ <LogIn className="size-4.5 text-gray-400 transition-all group-hover:text-primary-400" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setSelectedRootOrg(org)}
+ aria-label={`View sub-organizations of ${org.name}`}
+ className="pointer-events-auto flex w-full cursor-pointer items-center gap-1 bg-mineshaft-500 px-2 py-2 text-xs text-mineshaft-300 transition-colors hover:bg-mineshaft-500 hover:text-gray-200"
+ >
+ <ChevronRight className="size-4" />
+ View {org.subOrganizations.length} sub-organization
+ {org.subOrganizations.length !== 1 ? "s" : ""}
+ </button>
+ </div>
+ ) : (
+ <OrgRow
+ name={org.name}
+ joinedAt={joinedAt}
+ onClick={() => handleLoginById(org.id)}
+ />
+ )}
+
+ {isSearching && hasSubOrgs && (
+ <div className="mt-2 ml-1 space-y-1 border-l border-primary pl-2">
+ {org.subOrganizations.map((sub) => (
+ <OrgRow
+ key={sub.id}
+ name={sub.name}
+ label="Sub-organization"
+ joinedAt={sub.userJoinedAt}
+ onClick={() => handleLoginById(sub.id)}
+ variant="sub"
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+ };
+
+ if (userLoading || !user) {
+ return (
+ <div className="h-screen w-screen bg-bunker-800">
+ <ContentLoader />
</div>
);
}
- return <SelectOrganizationSection />;
+ return (
+ <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>{t("common.head-title", { title: t("login.title") })}</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>
+ {shouldShowMfa ? (
+ <Mfa
+ email={user.email as string}
+ successCallback={mfaSuccessCallback}
+ method={requiredMfaMethod}
+ />
+ ) : (
+ <div className="mx-auto mt-20 w-full max-w-md pb-28">
+ <Link to="/">
+ <div className="mb-4 flex justify-center">
+ <img
+ src="/images/gradientLogo.svg"
+ style={{ height: "90px", width: "120px" }}
+ alt="Infisical logo"
+ />
+ </div>
+ </Link>
+ <div className="mb-8 space-y-2">
+ <h1 className="bg-linear-to-b from-white to-bunker-200 bg-clip-text text-center text-2xl font-medium text-transparent">
+ Choose your organization
+ </h1>
+ <div className="space-y-1">
+ <p className="text-md text-center text-gray-500">
+ You&apos;re currently logged in as <strong>{user.username}</strong>
+ </p>
+ <p className="text-md text-center text-gray-500">
+ Not you?{" "}
+ <Button variant="link" onClick={handleLogout} className="font-medium">
+ Change account
+ </Button>
+ </p>
+ </div>
+ </div>
+
+ <div className="rounded-lg border-2 border-mineshaft-500 shadow-lg">
+ {totalOrgCount >= 5 && (
+ <div className="border-b border-mineshaft-600 px-4 py-3">
+ <Input
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ placeholder={
+ selectedRootOrg ? "Search sub-organizations..." : "Search organizations..."
+ }
+ leftIcon={<Search className="size-4" />}
+ className="h-10"
+ />
+ </div>
+ )}
+
+ {selectedRootOrg && (
+ <div className="border-b border-mineshaft-600 px-4 py-2">
+ <nav className="flex items-center gap-1.5 text-sm">
+ <button
+ type="button"
+ onClick={() => {
+ setSelectedRootOrg(null);
+ setSearchTerm("");
+ }}
+ className="text-mineshaft-400 transition-colors hover:text-gray-200"
+ >
+ All organizations
+ </button>
+ <span className="text-white">›</span>
+ <span className="font-medium text-gray-300">{selectedRootOrg.name}</span>
+ </nav>
+ </div>
+ )}
+
+ <div className="max-h-96 thin-scrollbar overflow-y-auto p-2">{renderListContent()}</div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
};
diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsx b/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsx
deleted file mode 100644
index 1f1d4d262c..0000000000
--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsx
+++ /dev/null
@@ -1,527 +0,0 @@
-import { useCallback, useMemo, useState } from "react";
-import { Helmet } from "react-helmet";
-import { useTranslation } from "react-i18next";
-import { Link, useNavigate, useRouter, useSearch } from "@tanstack/react-router";
-import axios from "axios";
-import { addSeconds, format, formatISO } from "date-fns";
-import { jwtDecode } from "jwt-decode";
-import { ChevronRight, LogIn, Search } from "lucide-react";
-
-import { Mfa } from "@app/components/auth/Mfa";
-import { createNotification } from "@app/components/notifications";
-import { IsCliLoginSuccessful } from "@app/components/utilities/attemptCliLogin";
-import SecurityClient from "@app/components/utilities/SecurityClient";
-import { Button, ContentLoader, Input, Spinner } from "@app/components/v2";
-import { SessionStorageKeys } from "@app/const";
-import { ROUTE_PATHS } from "@app/const/routes";
-import { useToggle } from "@app/hooks";
-import {
- TOrgWithSubOrgs,
- useGetOrganizations,
- useGetOrganizationsWithSubOrgs,
- useGetUser,
- useLogoutUser,
- useSelectOrganization
-} from "@app/hooks/api";
-import { MfaMethod, UserAgentType } from "@app/hooks/api/auth/types";
-import { getAuthToken, isLoggedIn, setAuthToken } from "@app/hooks/api/reactQuery";
-import { Organization } from "@app/hooks/api/types";
-import { AuthMethod, SAML_AUTH_METHODS } from "@app/hooks/api/users/types";
-
-import { navigateUserToOrg } from "../LoginPage/Login.utils";
-
-// Shared org row component to avoid repeating the same layout + userJoinedAt logic
-const OrgRow = ({
- name,
- label,
- joinedAt,
- onClick,
- variant = "default"
-}: {
- name: string;
- label?: string;
- joinedAt?: string | null;
- onClick: () => void;
- variant?: "default" | "sub" | "root";
-}) => {
- const bgClass =
- variant === "sub"
- ? "bg-mineshaft-800 text-gray-300 hover:bg-mineshaft-700"
- : "bg-mineshaft-700 text-gray-200 hover:bg-mineshaft-600";
-
- return (
- <button
- type="button"
- onClick={onClick}
- aria-label={`Login to ${name}`}
- className={`group flex h-14 w-full cursor-pointer items-center justify-between rounded-md border border-mineshaft-600 px-4 shadow-md transition-colors ${bgClass}`}
- >
- <div className="flex flex-col items-start">
- <p className="truncate">{name}</p>
- {(label || joinedAt) && (
- <p className="text-xs text-mineshaft-400">
- {label}
- {label && joinedAt && " · "}
- {joinedAt && <>Member since {format(new Date(joinedAt), "MMM d yyyy")}</>}
- </p>
- )}
- </div>
- <LogIn className="size-4 text-gray-400 transition-all group-hover:text-primary-400" />
- </button>
- );
-};
-
-export const SelectOrganizationSection = () => {
- const navigate = useNavigate();
- const { t } = useTranslation();
- const router = useRouter();
- const search = useSearch({ from: ROUTE_PATHS.Auth.SelectOrgPage.id });
-
- const { org_id: orgId, callback_port: callbackPort, is_admin_login: isBreakglassRoute, mfa_pending: mfaPending } = search;
-
- const organizations = useGetOrganizations();
- const orgsWithSubOrgs = useGetOrganizationsWithSubOrgs();
- const selectOrg = useSelectOrganization();
- const { data: user, isPending: userLoading } = useGetUser();
- const logout = useLogoutUser();
-
- const [shouldShowMfa, toggleShowMfa] = useToggle(false);
- const [requiredMfaMethod, setRequiredMfaMethod] = useState(MfaMethod.EMAIL);
- const [selectedRootOrg, setSelectedRootOrg] = useState<TOrgWithSubOrgs | null>(null);
- const [searchTerm, setSearchTerm] = useState("");
- const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
-
- const defaultSelectedOrg = organizations.data?.find((org) => org.id === orgId);
-
- // Build a flat lookup map: orgId → { org (full Organization), rootOrg? (for sub-orgs) }
- const orgLookup = useMemo(() => {
- const map = new Map<string, { org: Organization; rootOrg?: Organization }>();
- if (!organizations.data || !orgsWithSubOrgs.data) return map;
-
- for (const fullOrg of organizations.data) {
- map.set(fullOrg.id, { org: fullOrg });
- }
-
- for (const entry of orgsWithSubOrgs.data) {
- const rootOrg = organizations.data.find((o) => o.id === entry.id);
- if (!rootOrg) continue;
- for (const sub of entry.subOrganizations) {
- if (!map.has(sub.id)) {
- map.set(sub.id, { org: { ...rootOrg, id: sub.id }, rootOrg });
- }
- }
- }
- return map;
- }, [organizations.data, orgsWithSubOrgs.data]);
-
- const handleLogout = useCallback(async () => {
- try {
- await logout.mutateAsync();
- navigate({ to: "/login" });
- } catch (error) {
- console.error(error);
- }
- }, [logout, navigate]);
-
- const filteredOrgs = useMemo(() => {
- if (!orgsWithSubOrgs.data) return [];
- if (!searchTerm.trim()) return orgsWithSubOrgs.data;
-
- const term = searchTerm.toLowerCase();
- return orgsWithSubOrgs.data
- .filter(
- (org) =>
- org.name.toLowerCase().includes(term) ||
- org.subOrganizations.some((sub) => sub.name.toLowerCase().includes(term))
- )
- .map((org) => ({
- ...org,
- subOrganizations: org.name.toLowerCase().includes(term)
- ? org.subOrganizations
- : org.subOrganizations.filter((sub) => sub.name.toLowerCase().includes(term))
- }));
- }, [orgsWithSubOrgs.data, searchTerm]);
-
- const totalOrgCount = useMemo(() => {
- if (!orgsWithSubOrgs.data) return 0;
- return orgsWithSubOrgs.data.reduce((sum, org) => sum + 1 + org.subOrganizations.length, 0);
- }, [orgsWithSubOrgs.data]);
-
- const filteredSubOrgs = useMemo(() => {
- if (!selectedRootOrg) return [];
- if (!searchTerm.trim()) return selectedRootOrg.subOrganizations;
- const term = searchTerm.toLowerCase();
- return selectedRootOrg.subOrganizations.filter((sub) => sub.name.toLowerCase().includes(term));
- }, [selectedRootOrg, searchTerm]);
-
- const handleSelectOrganization = useCallback(
- async (organization: Organization) => {
- const canBypassOrgAuth = organization.bypassOrgAuthEnabled && isBreakglassRoute;
-
- if (isBreakglassRoute && !organization.bypassOrgAuthEnabled) {
- createNotification({
- text: "This organization does not have bypass org auth enabled",
- type: "error"
- });
- return;
- }
-
- // SSO enforcement: block and notify instead of logging out
- if ((organization.authEnforced || organization.googleSsoAuthEnforced) && !canBypassOrgAuth) {
- const authToken = jwtDecode(getAuthToken()) as { authMethod: AuthMethod };
-
- let ssoRequired = false;
- let ssoType = "";
-
- if (organization.googleSsoAuthEnforced && authToken.authMethod !== AuthMethod.GOOGLE) {
- ssoRequired = true;
- ssoType = "Google SSO";
- } else if (
- organization.orgAuthMethod === AuthMethod.OIDC &&
- authToken.authMethod !== AuthMethod.OIDC
- ) {
- ssoRequired = true;
- ssoType = "OIDC SSO";
- } else if (
- organization.orgAuthMethod === AuthMethod.SAML &&
- !SAML_AUTH_METHODS.includes(authToken.authMethod as (typeof SAML_AUTH_METHODS)[number])
- ) {
- ssoRequired = true;
- ssoType = "SAML SSO";
- }
-
- if (ssoRequired) {
- createNotification({
- text: `This organization requires ${ssoType}. Please log out and re-login via your identity provider.`,
- type: "error"
- });
- return;
- }
- }
-
- let token;
- let isMfaEnabled;
- let mfaMethod;
-
- try {
- const result = await selectOrg.mutateAsync({
- organizationId: organization.id,
- userAgent: callbackPort ? UserAgentType.CLI : undefined
- });
- token = result.token;
- isMfaEnabled = result.isMfaEnabled;
- mfaMethod = result.mfaMethod;
- } catch (error: any) {
- if (error?.response?.status === 403) {
- createNotification({
- text: "You do not have access to this organization.",
- type: "error"
- });
- return;
- }
- throw error;
- }
-
- await router.invalidate();
-
- if (isMfaEnabled) {
- SecurityClient.setMfaToken(token);
- if (mfaMethod) {
- setRequiredMfaMethod(mfaMethod);
- }
- toggleShowMfa.on();
- setMfaSuccessCallback(() => () => handleSelectOrganization(organization));
- return;
- }
-
- if (callbackPort) {
- let error: string | null = null;
-
- if (!user?.email) error = "User email not found";
- if (!token) error = "No token found";
-
- if (error) {
- createNotification({ text: error, type: "error" });
- return;
- }
-
- const payload = {
- JTWToken: token,
- email: user?.email,
- privateKey: ""
- } as IsCliLoginSuccessful["loginResponse"];
-
- const instance = axios.create();
- await instance.post(`http://127.0.0.1:${callbackPort}/`, payload).catch(() => {
- sessionStorage.setItem(
- SessionStorageKeys.CLI_TERMINAL_TOKEN,
- JSON.stringify({
- expiry: formatISO(addSeconds(new Date(), 30)),
- data: window.btoa(JSON.stringify(payload))
- })
- );
- });
- navigate({ to: "/cli-redirect" });
- } else {
- setAuthToken(token);
- navigateUserToOrg({ navigate, organizationId: organization.id });
- }
- },
- [selectOrg, callbackPort, isBreakglassRoute, user, router, toggleShowMfa, navigate]
- );
-
- const handleLoginById = useCallback(
- (id: string) => {
- const entry = orgLookup.get(id);
- if (entry) {
- handleSelectOrganization(entry.org);
- return;
- }
- createNotification({ text: "Organization not found", type: "error" });
- },
- [orgLookup, handleSelectOrganization]
- );
-
- const handleCliRedirect = useCallback(() => {
- const authToken = getAuthToken();
-
- if (authToken && !callbackPort) {
- const decodedJwt = jwtDecode(authToken) as any;
- if (decodedJwt?.organizationId) {
- navigateUserToOrg({ navigate, organizationId: decodedJwt.organizationId });
- }
- }
-
- if (!isLoggedIn()) {
- navigate({ to: "/login" });
- }
- }, [callbackPort, navigate]);
-
- // CLI redirect on mount
- // eslint-disable-next-line react-hooks/exhaustive-deps
- useMemo(() => {
- if (callbackPort) handleCliRedirect();
- }, []);
-
- // MFA pending from IdP redirect
- // eslint-disable-next-line react-hooks/exhaustive-deps
- useMemo(() => {
- if (mfaPending && defaultSelectedOrg) {
- const storedMfaToken = sessionStorage.getItem(SessionStorageKeys.MFA_TEMP_TOKEN);
- if (storedMfaToken) {
- sessionStorage.removeItem(SessionStorageKeys.MFA_TEMP_TOKEN);
- SecurityClient.setMfaToken(storedMfaToken);
- toggleShowMfa.on();
- setMfaSuccessCallback(() => () => handleSelectOrganization(defaultSelectedOrg));
- }
- }
- }, [mfaPending, defaultSelectedOrg]);
-
- const renderListContent = () => {
- if (orgsWithSubOrgs.isPending) {
- return (
- <div className="flex justify-center py-6">
- <Spinner size="sm" />
- </div>
- );
- }
-
- if (selectedRootOrg) {
- return (
- <div className="space-y-2">
- <OrgRow
- name={selectedRootOrg.name}
- label="Root organization"
- joinedAt={
- selectedRootOrg.userJoinedAt ??
- organizations.data?.find((o) => o.id === selectedRootOrg.id)?.userJoinedAt
- }
- onClick={() => handleLoginById(selectedRootOrg.id)}
- variant="root"
- />
- <p className="px-1 pt-1 text-xs font-medium tracking-wider text-mineshaft-400 uppercase">
- Sub-organizations
- </p>
- {filteredSubOrgs.length === 0 ? (
- <p className="py-4 text-center text-sm text-mineshaft-400">
- No sub-organizations found
- </p>
- ) : (
- filteredSubOrgs.map((sub) => (
- <OrgRow
- key={sub.id}
- name={sub.name}
- joinedAt={sub.userJoinedAt}
- onClick={() => handleLoginById(sub.id)}
- variant="sub"
- />
- ))
- )}
- </div>
- );
- }
-
- if (filteredOrgs.length === 0) {
- return <p className="py-4 text-center text-sm text-mineshaft-400">No organizations found</p>;
- }
-
- const isSearching = !!searchTerm.trim();
- return (
- <div className="space-y-2">
- {filteredOrgs.map((org) => {
- const hasSubOrgs = org.subOrganizations.length > 0;
- const joinedAt =
- org.userJoinedAt ?? organizations.data?.find((o) => o.id === org.id)?.userJoinedAt;
-
- return (
- <div key={org.id}>
- {hasSubOrgs && !isSearching ? (
- <div className="relative overflow-clip rounded-md border border-mineshaft-600 text-gray-200 shadow-md">
- <button
- type="button"
- onClick={() => handleLoginById(org.id)}
- aria-label={`Login to ${org.name}`}
- className="group relative z-10 flex w-full cursor-pointer items-center justify-between bg-mineshaft-700 px-4 py-3 transition-colors hover:bg-mineshaft-600"
- >
- <div className="flex flex-col items-start gap-1.5">
- <p className="truncate transition-colors">{org.name}</p>
- {joinedAt && (
- <p className="text-xs text-mineshaft-400">
- Member since {format(new Date(joinedAt), "MMM d yyyy")}
- </p>
- )}
- </div>
- <LogIn className="size-4.5 text-gray-400 transition-all group-hover:text-primary-400" />
- </button>
- <button
- type="button"
- onClick={() => setSelectedRootOrg(org)}
- aria-label={`View sub-organizations of ${org.name}`}
- className="pointer-events-auto flex w-full cursor-pointer items-center gap-1 bg-mineshaft-500 px-2 py-2 text-xs text-mineshaft-300 transition-colors hover:bg-mineshaft-500 hover:text-gray-200"
- >
- <ChevronRight className="size-4" />
- View {org.subOrganizations.length} sub-organization
- {org.subOrganizations.length !== 1 ? "s" : ""}
- </button>
- </div>
- ) : (
- <OrgRow
- name={org.name}
- joinedAt={joinedAt}
- onClick={() => handleLoginById(org.id)}
- />
- )}
-
- {isSearching && hasSubOrgs && (
- <div className="mt-2 ml-1 space-y-1 border-l border-primary pl-2">
- {org.subOrganizations.map((sub) => (
- <OrgRow
- key={sub.id}
- name={sub.name}
- label="Sub-organization"
- joinedAt={sub.userJoinedAt}
- onClick={() => handleLoginById(sub.id)}
- variant="sub"
- />
- ))}
- </div>
- )}
- </div>
- );
- })}
- </div>
- );
- };
-
- if (userLoading || !user) {
- return (
- <div className="h-screen w-screen bg-bunker-800">
- <ContentLoader />
- </div>
- );
- }
-
- return (
- <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>{t("common.head-title", { title: t("login.title") })}</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>
- {shouldShowMfa ? (
- <Mfa
- email={user.email as string}
- successCallback={mfaSuccessCallback}
- method={requiredMfaMethod}
- />
- ) : (
- <div className="mx-auto mt-20 w-full max-w-md pb-28">
- <Link to="/">
- <div className="mb-4 flex justify-center">
- <img
- src="/images/gradientLogo.svg"
- style={{ height: "90px", width: "120px" }}
- alt="Infisical logo"
- />
- </div>
- </Link>
- <div className="mb-8 space-y-2">
- <h1 className="bg-linear-to-b from-white to-bunker-200 bg-clip-text text-center text-2xl font-medium text-transparent">
- Choose your organization
- </h1>
- <div className="space-y-1">
- <p className="text-md text-center text-gray-500">
- You&apos;re currently logged in as <strong>{user.username}</strong>
- </p>
- <p className="text-md text-center text-gray-500">
- Not you?{" "}
- <Button variant="link" onClick={handleLogout} className="font-medium">
- Change account
- </Button>
- </p>
- </div>
- </div>
-
- <div className="rounded-lg border-2 border-mineshaft-500 shadow-lg">
- {totalOrgCount >= 5 && (
- <div className="border-b border-mineshaft-600 px-4 py-3">
- <Input
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
- placeholder={
- selectedRootOrg ? "Search sub-organizations..." : "Search organizations..."
- }
- leftIcon={<Search className="size-4" />}
- className="h-10"
- />
- </div>
- )}
-
- {selectedRootOrg && (
- <div className="border-b border-mineshaft-600 px-4 py-2">
- <nav className="flex items-center gap-1.5 text-sm">
- <button
- type="button"
- onClick={() => {
- setSelectedRootOrg(null);
- setSearchTerm("");
- }}
- className="text-mineshaft-400 transition-colors hover:text-gray-200"
- >
- All organizations
- </button>
- <span className="text-white">›</span>
- <span className="font-medium text-gray-300">{selectedRootOrg.name}</span>
- </nav>
- </div>
- )}
-
- <div className="max-h-96 thin-scrollbar overflow-y-auto p-2">{renderListContent()}</div>
- </div>
- </div>
- )}
- </div>
- );
-};
diff --git a/frontend/src/pages/auth/SelectOrgPage/route.tsx b/frontend/src/pages/auth/SelectOrgPage/route.tsx
index 55476f27be..0fe405fb90 100644
--- a/frontend/src/pages/auth/SelectOrgPage/route.tsx
+++ b/frontend/src/pages/auth/SelectOrgPage/route.tsx
@@ -2,14 +2,14 @@ import { createFileRoute, redirect, stripSearchParams } from "@tanstack/react-ro
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
+import { selectOrganization } from "@app/hooks/api/auth/queries";
import {
fetchOrganizationsWithSubOrgs,
organizationKeys
} from "@app/hooks/api/organization/queries";
-import { selectOrganization } from "@app/hooks/api/auth/queries";
import { setAuthToken } from "@app/hooks/api/reactQuery";
-import { SelectOrganizationPage } from "./SelectOrgPage";
+import { SelectOrgPage } from "./SelectOrgPage";
export const SelectOrganizationPageQueryParams = z.object({
org_id: z.string().optional().catch(""),
@@ -22,7 +22,7 @@ export const SelectOrganizationPageQueryParams = z.object({
});
export const Route = createFileRoute("/_restrict-login-signup/login/select-organization")({
- component: SelectOrganizationPage,
+ component: SelectOrgPage,
validateSearch: zodValidator(SelectOrganizationPageQueryParams),
search: {
middlewares: [
@@ -81,6 +81,7 @@ export const Route = createFileRoute("/_restrict-login-signup/login/select-organ
});
}
} catch (error) {
+ console.error(error);
// If it's a redirect, re-throw it
if (error instanceof Error && error.message === "REDIRECT") throw error;
// For redirect objects from TanStack Router