Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: implemented new email verification flow for oauth and sso
=849a972fb61e
diff --git a/backend/src/db/migrations/20260330072924_auth-revamp.ts b/backend/src/db/migrations/20260330072924_auth-revamp.tsindex a08bed996e..c433fcad3d 100644--- a/backend/src/db/migrations/20260330072924_auth-revamp.ts+++ b/backend/src/db/migrations/20260330072924_auth-revamp.ts@@ -6,6 +6,7 @@ import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";export async function up(knex: Knex): Promise<void> {const hasUserTable = await knex.schema.hasTable(TableName.Users);const hasHashedPasswordColumn = await knex.schema.hasColumn(TableName.Users, "hashedPassword");+ const hasIsGoogleVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGoogleVerified");const hasIsGitHubVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitHubVerified");const hasIsGitlabVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitLabVerified");if (hasUserTable) {@@ -13,6 +14,9 @@ export async function up(knex: Knex): Promise<void> {if (!hasHashedPasswordColumn) {table.string("hashedPassword").nullable();}+ if (!hasIsGoogleVerifiedColumn) {+ table.boolean("isGoogleVerified").nullable();+ }if (!hasIsGitHubVerifiedColumn) {table.boolean("isGitHubVerified").nullable();}@@ -72,11 +76,15 @@ export async function down(knex: Knex): Promise<void> {const hasHashedPasswordColumn = await knex.schema.hasColumn(TableName.Users, "hashedPassword");const hasIsGitHubVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitHubVerified");const hasIsGitlabVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitLabVerified");+ const hasIsGoogleVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGoogleVerified");if (hasUserTable) {await knex.schema.alterTable(TableName.Users, (table) => {if (hasHashedPasswordColumn) {table.dropColumn("hashedPassword");}+ if (hasIsGoogleVerifiedColumn) {+ table.dropColumn("isGoogleVerified");+ }if (hasIsGitHubVerifiedColumn) {table.dropColumn("isGitHubVerified");}diff --git a/backend/src/db/schemas/users.ts b/backend/src/db/schemas/users.tsindex 4b30880cf4..62fe38b1e7 100644--- a/backend/src/db/schemas/users.ts+++ b/backend/src/db/schemas/users.ts@@ -30,7 +30,8 @@ export const UsersSchema = z.object({selectedMfaMethod: z.string().nullable().optional(),hashedPassword: z.string().nullable().optional(),isGitHubVerified: z.boolean().nullable().optional(),- isGitLabVerified: z.boolean().nullable().optional()+ isGitLabVerified: z.boolean().nullable().optional(),+ isGoogleVerified: z.boolean().nullable().optional()});export type TUsers = z.infer<typeof UsersSchema>;diff --git a/backend/src/server/routes/v3/signup-router.ts b/backend/src/server/routes/v3/signup-router.tsindex df73f3dfb8..772a0dd32b 100644--- a/backend/src/server/routes/v3/signup-router.ts+++ b/backend/src/server/routes/v3/signup-router.ts@@ -6,7 +6,6 @@ import { ForbiddenRequestError } from "@app/lib/errors";import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";import { GenericResourceNameSchema } from "@app/server/lib/schemas";-import { ProviderAuthResult } from "@app/services/auth/auth-type";import { getServerCfg } from "@app/services/super-admin/super-admin-service";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";@@ -97,15 +96,22 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {},schema: {operationId: "completeAccountSignupV3",- body: z.object({- email: z.string().trim(),- firstName: z.string().trim(),- lastName: z.string().trim().optional(),- providerAuthToken: z.string().trim().optional().nullish(),- attributionSource: z.string().trim().optional(),- password: z.string(),- organizationName: GenericResourceNameSchema.optional()- }),+ body: z.discriminatedUnion("type", [+ z.object({+ type: z.literal("email"),+ email: z.string().trim(),+ firstName: z.string().trim(),+ lastName: z.string().trim().optional(),+ attributionSource: z.string().trim().optional(),+ password: z.string(),+ organizationName: GenericResourceNameSchema.optional()+ }),+ z.object({+ type: z.literal("alias"),+ code: z.string().trim(),+ organizationName: GenericResourceNameSchema.optional()+ })+ ]),response: {200: z.object({message: z.string(),@@ -119,7 +125,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {if (!userAgent) throw new Error("user agent header is required");const appCfg = getConfig();- const { user, accessToken, refreshToken, authMethod } = await server.services.signup.completeAccountSignup({+ const { user, accessToken, refreshToken, authMethod } = await server.services.signup.completeAccount({...req.body,ip: req.realIp,userAgent,@@ -143,7 +149,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {properties: {username: user.username,email: user.email ?? "",- attributionSource: req.body.attributionSource+ attributionSource: "attributionSource" in req.body ? req.body.attributionSource : undefined}});@@ -178,51 +184,4 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {}});- server.route({- url: "/verify-alias",- method: "POST",- config: {- rateLimit: authRateLimit- },- schema: {- operationId: "verifyAliasSignupV3",- body: z.object({- code: z.string().trim()- }),- response: {- 200: z.object({- message: z.string(),- accessToken: z.string(),- refreshToken: z.string()- })- }- },- handler: async (req, res) => {- const userAgent = req.headers["user-agent"];- if (!userAgent) throw new Error("user agent header is required");- const appCfg = getConfig();-- const { tokens } = await server.services.signup.verifyAlias({- code: req.body.code,- authorization: req.headers.authorization as string,- ip: req.realIp,- userAgent- });-- void res.setCookie("jid", tokens.refresh, {- httpOnly: true,- path: "/",- sameSite: "strict",- secure: appCfg.HTTPS_ENABLED- });-- addAuthOriginDomainCookie(res);-- return {- message: "Successfully verified alias",- accessToken: tokens.access,- refreshToken: tokens.refresh- };- }- });};diff --git a/backend/src/services/auth/auth-fns.ts b/backend/src/services/auth/auth-fns.tsindex c5d3039c14..54bbc8a414 100644--- a/backend/src/services/auth/auth-fns.ts+++ b/backend/src/services/auth/auth-fns.ts@@ -5,7 +5,7 @@ import { BadRequestError, ForbiddenRequestError, UnauthorizedError } from "@app/import { AuthModeSignUpTokenPayload, AuthTokenType } from "./auth-type";-const extractBearerToken = (token?: string): string => {+export const extractBearerToken = (token?: string): string => {if (!token) {throw new UnauthorizedError({ message: "Missing Authorization Header in the request header." });}diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex c97e1109a5..943adcf1d5 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -789,7 +789,7 @@ export const authLoginServiceFactory = ({// Step 1: Look up user by provider alias (stable, immutable ID)let user: TUsers | undefined;let isNewAlias = false;- const existingAlias = await userAliasDAL.findOne({ externalId: providerUserId, aliasType });+ let existingAlias = await userAliasDAL.findOne({ externalId: providerUserId, aliasType });if (existingAlias) {user = await userDAL.findById(existingAlias.userId);}@@ -874,7 +874,8 @@ export const authLoginServiceFactory = ({{username: email.trim().toLowerCase(),email: email.trim().toLowerCase(),- isEmailVerified: true,+ isEmailVerified: false,+ isAccepted: false,firstName,lastName,authMethods: [authMethod],@@ -923,14 +924,14 @@ export const authLoginServiceFactory = ({}}- await userAliasDAL.create(+ existingAlias = await userAliasDAL.create({userId: newUser.id,aliasType,externalId: providerUserId,emails: [email],orgId: orgId || null,- isEmailVerified: true+ isEmailVerified: false},tx);@@ -1008,17 +1009,28 @@ export const authLoginServiceFactory = ({}}+ // Use user-level provider verification flags+ let isAliasVerified = false;+ if (authMethod === AuthMethod.GOOGLE) {+ isAliasVerified = Boolean(user.isGoogleVerified);+ } else if (authMethod === AuthMethod.GITHUB) {+ isAliasVerified = Boolean(user.isGitHubVerified);+ } else if (authMethod === AuthMethod.GITLAB) {+ isAliasVerified = Boolean(user.isGitLabVerified);+ }// Self-healing backfill: create alias for existing users found by email fallback+ let aliasId = existingAlias?.id;if (isNewAlias) {try {- await userAliasDAL.create({+ const newAlias = await userAliasDAL.create({userId: user.id,aliasType,externalId: providerUserId,emails: [email],orgId: orgId || null,- isEmailVerified: true+ isEmailVerified: isAliasVerified});+ aliasId = newAlias.id;} catch (err) {// Swallow duplicate key errors from the unique index (race condition: concurrent login already created the alias)if (err instanceof DatabaseError && (err.error as { code: string })?.code === "23505") {@@ -1029,14 +1041,30 @@ export const authLoginServiceFactory = ({}}- // TODO(auth-revamp): check this out later+ // Send verification email for OAuth providers that haven't verified the user's email+ if (!isAliasVerified && user.email && aliasId) {+ const verificationCode = await tokenService.createTokenForUser({+ type: TokenType.TOKEN_EMAIL_VERIFICATION,+ userId: user.id,+ aliasId+ });++ await smtpService.sendMail({+ template: SmtpTemplates.EmailVerification,+ subjectLine: "Infisical confirmation code",+ recipients: [user.email],+ substitutions: {+ code: verificationCode+ }+ });+ }+const callbackResult = await processProviderCallback({user,authMethod,- // For OAuth, new users get alias created with the user, so alias is always verified.- // For existing users found by email fallback (isNewAlias), the alias was just backfilled above.- isAliasVerified: true,- isEmailVerified: Boolean(user.isEmailVerified),+ isAliasVerified,+ isEmailVerified: isAliasVerified,+ aliasId,ip,userAgent,organizationId: orgId || undefined,diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.tsindex 72a080201d..ff9e86cf3a 100644--- a/backend/src/services/auth/auth-signup-service.ts+++ b/backend/src/services/auth/auth-signup-service.ts@@ -13,9 +13,9 @@ import { getServerCfg } from "../super-admin/super-admin-service";import { TUserDALFactory } from "../user/user-dal";import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";import { TAuthDALFactory } from "./auth-dal";-import { validateSignUpAuthorization } from "./auth-fns";+import { extractBearerToken } from "./auth-fns";import { TAuthLoginFactory } from "./auth-login-service";-import { TCompleteAccountSignupDTO } from "./auth-signup-type";+import { CompleteAccountType, TCompleteAccountDTO } from "./auth-signup-type";import { AuthMethod, AuthModeSignUpTokenPayload, AuthTokenType } from "./auth-type";type TAuthSignupDep = {@@ -134,187 +134,153 @@ export const authSignupServiceFactory = ({return { user, token: jwtToken };};- const completeAccountSignup = async ({- email,- password,- firstName,- lastName,- organizationName,- ip,- userAgent,- authorization- }: TCompleteAccountSignupDTO) => {- const sanitizedEmail = email.trim().toLowerCase();- const appCfg = getConfig();-- const user = await userDAL.findOne({ username: sanitizedEmail });-- // Always validate the authorization token to prevent timing attacks- // that could reveal whether an email is registered.- // Use a dummy userId when user is missing so the JWT work is still performed.- const dummyUserId = "00000000-0000-0000-0000-000000000000";- validateSignUpAuthorization(authorization, user?.id ?? dummyUserId);-- if (!user || (user && user.isAccepted)) {- throw new BadRequestError({ message: "Failed to complete account for complete user" });- }-- // Check if user has existing org memberships (i.e., they were invited)- const existingMemberships = await orgDAL.findMembership({- actorUserId: user.id,- scope: AccessScope.Organization- });- const isInvitedUser = existingMemberships.length > 0;-- // Self-signup requires allowSignUp to be enabled- if (!isInvitedUser) {- const serverCfg = await getServerCfg();- if (!serverCfg.allowSignUp) {- throw new ForbiddenRequestError({- message: "Signup's are disabled"- });- }- }-- const hashedPassword = await crypto.hashing().createHash(password, appCfg.SALT_ROUNDS);- const updatedUser = await authDAL.transaction(async (tx) => {- const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true, hashedPassword }, tx);- return { ...us, hashedPassword: null };- });-- // If self-signup, create a default organization- if (!isInvitedUser && organizationName) {- await orgService.createOrganization({- userId: user.id,- userEmail: user.email ?? user.username,- orgName: organizationName- });- }-- // TODO(auth-revamp): check for license count- const tokenSessionExpiresIn = appCfg.JWT_AUTH_LIFETIME;- const refreshTokenExpiresIn = appCfg.JWT_REFRESH_LIFETIME;-- const tokenSession = await tokenService.getUserTokenSession({- userAgent,- ip,- userId: updatedUser.id- });- if (!tokenSession) throw new Error("Failed to create token");-- const accessToken = crypto.jwt().sign(- {- authMethod: AuthMethod.EMAIL,- authTokenType: AuthTokenType.ACCESS_TOKEN,- userId: updatedUser.id,- tokenVersionId: tokenSession.id,- accessVersion: tokenSession.accessVersion- },- appCfg.AUTH_SECRET,- { expiresIn: tokenSessionExpiresIn }- );-- const refreshToken = crypto.jwt().sign(- {- authTokenType: AuthTokenType.REFRESH_TOKEN,- userId: updatedUser.id,- tokenVersionId: tokenSession.id,- refreshVersion: tokenSession.refreshVersion- },- appCfg.AUTH_SECRET,- { expiresIn: refreshTokenExpiresIn }- );-- return {- user: updatedUser,- isInvitedUser,- accessToken,- refreshToken,- authMethod: AuthMethod.EMAIL- };- };-/*- * Verify an SSO/OAuth alias via email confirmation code.- * Called from /signup/verify-alias with the signup token in the Authorization header.+ * Unified account completion for both email signup and SSO/OAuth alias verification.*- * For org IdP (SAML/OIDC/LDAP): organizationId is in the signup token → tokens issued with org context- * For OAuth (Google/GitHub/GitLab): no organizationId → tokens issued without org, user goes to select-org+ * Shared: signup token validation, user lookup, org creation if no membership, session token issuance.*- * If the user is not yet accepted, they are automatically accepted (SSO users don't need password setup).+ * Email: sets password + user profile, creates user account.+ * Alias: verifies email code against alias, marks alias + user flags as verified.*/- const verifyAlias = async ({- code,- authorization,- ip,- userAgent- }: {- code: string;- authorization: string;- ip: string;- userAgent: string;- }) => {+ const completeAccount = async (dto: TCompleteAccountDTO) => {const appCfg = getConfig();+ const DUMMY_USER_ID = "00000000-0000-0000-0000-000000000000";- // Extract and validate the signup token- const [, tokenValue] = authorization.split(" ", 2);- if (!tokenValue) throw new UnauthorizedError({ message: "Missing authorization token" });-+ // Step 1: Extract and validate the signup token+ const tokenValue = extractBearerToken(dto.authorization);const decodedToken = crypto.jwt().verify(tokenValue, appCfg.AUTH_SECRET) as AuthModeSignUpTokenPayload;if (decodedToken.authTokenType !== AuthTokenType.SIGNUP_TOKEN) {throw new UnauthorizedError({ message: "Invalid token type" });}- const user = await userDAL.findById(decodedToken.userId);- if (!user) throw new BadRequestError({ message: "User not found" });+ // Step 2: Find the user+ let user = await userDAL.findById(decodedToken.userId);- if (!decodedToken.aliasId) {- throw new BadRequestError({ message: "Missing alias ID in signup token" });- }+ // Step 3: Type-specific validation and user updates+ // All branches perform their expensive work (bcrypt hash / token validation) before+ // checking rejection conditions, so the response time is constant regardless of+ // whether the request is valid. This prevents timing-based user/alias enumeration.+ let authMethod: AuthMethod;- // Verify the alias belongs to this user- const userAlias = await userAliasDAL.findOne({- id: decodedToken.aliasId,- userId: user.id- });+ if (dto.type === CompleteAccountType.Email) {+ const sanitizedEmail = dto.email.trim().toLowerCase();+ const userByEmail = await userDAL.findOne({ username: sanitizedEmail });++ // Determine rejection before hashing, but don't throw yet+ const shouldReject = !user || user.isAccepted || !userByEmail || userByEmail.id !== user?.id;++ // Always hash the password so bcrypt cost is incurred regardless of validity+ const hashedPassword = await crypto.hashing().createHash(dto.password, appCfg.SALT_ROUNDS);++ if (shouldReject) {+ throw new BadRequestError({ message: "Failed to complete account for complete user" });+ }++ const updatedUser = await authDAL.transaction(async (tx) => {+ const us = await userDAL.updateById(+ user.id,+ { firstName: dto.firstName, lastName: dto.lastName, isAccepted: true, hashedPassword },+ tx+ );+ return { ...us, hashedPassword: null };+ });+ user = updatedUser;+ authMethod = AuthMethod.EMAIL;+ } else {+ // Alias verification+ const userAlias = decodedToken.aliasId+ ? await userAliasDAL.findOne({+ id: decodedToken.aliasId,+ userId: user?.id ?? DUMMY_USER_ID+ })+ : null;++ // Determine rejection before token validation, but don't throw yet+ const shouldReject = !user || !decodedToken.aliasId || !userAlias;++ // Always validate the verification code so the bcrypt cost is incurred+ // Use dummy userId when rejecting so the work is still performed+ try {+ await tokenService.validateTokenForUser({+ type: TokenType.TOKEN_EMAIL_VERIFICATION,+ userId: shouldReject ? DUMMY_USER_ID : user.id,+ code: dto.code+ });+ } catch {+ throw new BadRequestError({ message: "Invalid or expired verification code" });+ }++ if (shouldReject) {+ throw new BadRequestError({ message: "Invalid or expired verification code" });+ }- if (!userAlias) {- throw new BadRequestError({ message: "Alias not found for this user" });+ // Mark alias as verified+ await userAliasDAL.updateById(userAlias.id, { isEmailVerified: true });++ // Update user-level verification flags based on auth method+ const userUpdates: Record<string, boolean> = { isEmailVerified: true };+ if (decodedToken.authMethod === AuthMethod.GOOGLE) {+ userUpdates.isGoogleVerified = true;+ } else if (decodedToken.authMethod === AuthMethod.GITHUB) {+ userUpdates.isGitHubVerified = true;+ } else if (decodedToken.authMethod === AuthMethod.GITLAB) {+ userUpdates.isGitLabVerified = true;+ }+ if (!user.isAccepted) {+ userUpdates.isAccepted = true;+ }++ user = await userDAL.updateById(user.id, userUpdates);+ authMethod = decodedToken.authMethod;}- // Validate the email verification code — the code was created with this specific aliasId- // by the EE service (saml/oidc/ldap) when the alias was first created- await tokenService.validateTokenForUser({- type: TokenType.TOKEN_EMAIL_VERIFICATION,- userId: user.id,- code+ // Step 4: Check org membership — create org if self-signup with no existing membership+ const existingMemberships = await orgDAL.findMembership({+ actorUserId: user.id,+ scope: AccessScope.Organization});+ const isInvitedUser = existingMemberships.length > 0;- // Mark this specific alias as email-verified- await userAliasDAL.updateById(userAlias.id, { isEmailVerified: true });+ let { organizationId } = decodedToken;+ if (!isInvitedUser) {+ const serverCfg = await getServerCfg();+ if (!serverCfg.allowSignUp) {+ throw new ForbiddenRequestError({ message: "Signups are disabled" });+ }++ if (dto.organizationName) {+ const org = await orgService.createOrganization({+ userId: user.id,+ userEmail: user.email ?? user.username,+ orgName: dto.organizationName+ });- // If user is not yet accepted, accept them (SSO users don't need password/account setup)- if (!user.isAccepted) {- await userDAL.updateById(user.id, { isAccepted: true });+ organizationId = org.id;+ }}- // Issue session tokens+ // Step 5: Issue session tokensconst tokens = await loginService.generateUserTokens({userId: user.id,- ip,- userAgent,- authMethod: decodedToken.authMethod,- organizationId: decodedToken.organizationId+ ip: dto.ip,+ userAgent: dto.userAgent,+ authMethod,+ organizationId});- return { tokens, user };+ return {+ user,+ isInvitedUser,+ accessToken: tokens.access,+ refreshToken: tokens.refresh,+ authMethod+ };};return {beginEmailSignupProcess,verifyEmailSignup,- completeAccountSignup,- verifyAlias+ completeAccount};};diff --git a/backend/src/services/auth/auth-signup-type.ts b/backend/src/services/auth/auth-signup-type.tsindex 97f691c9fa..058529a8f0 100644--- a/backend/src/services/auth/auth-signup-type.ts+++ b/backend/src/services/auth/auth-signup-type.ts@@ -1,11 +1,30 @@-export type TCompleteAccountSignupDTO = {+export enum CompleteAccountType {+ Email = "email",+ Alias = "alias"+}++type TCompleteAccountBase = {+ ip: string;+ userAgent: string;+ authorization: string;+ organizationName?: string;+};++type TCompleteAccountEmail = TCompleteAccountBase & {+ type: CompleteAccountType.Email;email: string;password: string;firstName: string;lastName?: string;- organizationName?: string;- attributionSource?: string | undefined;- ip: string;- userAgent: string;- authorization: string;+ attributionSource?: string;+};++type TCompleteAccountAlias = TCompleteAccountBase & {+ type: CompleteAccountType.Alias;+ code: string;};++export type TCompleteAccountDTO = TCompleteAccountEmail | TCompleteAccountAlias;++// Keep old type as alias for any remaining references+export type TCompleteAccountSignupDTO = TCompleteAccountEmail;diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.tsindex 2ac7ffb426..177352b4f2 100644--- a/backend/src/services/super-admin/super-admin-service.ts+++ b/backend/src/services/super-admin/super-admin-service.ts@@ -510,20 +510,13 @@ export const superAdminServiceFactory = ({isGhost: false,isAccepted: true,authMethods: [AuthMethod.EMAIL],- isEmailVerified: true- },- tx- );- const userEnc = await userDAL.createUserEncryption(- {- encryptionVersion: 2,- userId: newUser.id,+ isEmailVerified: true,hashedPassword},tx);- return { user: newUser, enc: userEnc };+ return { user: { ...newUser, hashedPassword: null } };});const initialOrganizationName = appCfg.INITIAL_ORGANIZATION_NAME ?? "Admin Org";diff --git a/frontend/src/components/auth/UserInfoStep.tsx b/frontend/src/components/auth/UserInfoStep.tsxindex 413db75090..c02aa68de3 100644--- a/frontend/src/components/auth/UserInfoStep.tsx+++ b/frontend/src/components/auth/UserInfoStep.tsx@@ -124,6 +124,7 @@ export default function UserInfoStep({}const response = await completeSignup({+ type: "email",email,password: formData.password,firstName: formData.name.split(" ")[0],diff --git a/frontend/src/config/request.ts b/frontend/src/config/request.tsindex 04adc7338c..a1bfbd42a2 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 (signupTempToken) {+ if (token) {+ // eslint-disable-next-line no-param-reassign+ config.headers.Authorization = `Bearer ${token}`;+ } else if (signupTempToken) {// eslint-disable-next-line no-param-reassignconfig.headers.Authorization = `Bearer ${signupTempToken}`;} else if (mfaTempToken) {// eslint-disable-next-line no-param-reassignconfig.headers.Authorization = `Bearer ${mfaTempToken}`;- } else if (token) {- // eslint-disable-next-line no-param-reassign- config.headers.Authorization = `Bearer ${token}`;} else if (providerAuthToken) {// eslint-disable-next-line no-param-reassignconfig.headers.Authorization = `Bearer ${providerAuthToken}`;diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsxindex cd0828465e..5b4992776a 100644--- a/frontend/src/hooks/api/auth/queries.tsx+++ b/frontend/src/hooks/api/auth/queries.tsx@@ -103,6 +103,9 @@ export const useSelectOrganization = () => {return data;},onSuccess: () => {+ // Invalidate the auth token cache so the authenticate middleware+ // re-calls fetchAuthToken (which reads the new in-memory token with orgId)+ queryClient.invalidateQueries({ queryKey: authKeys.getAuthToken });queryClient.invalidateQueries({queryKey: [organizationKeys.getUserOrganizations, projectKeys.getAllUserProjects]});@@ -151,20 +154,6 @@ export const useCompleteAccountSignup = () => {});};-export const verifyAlias = async (details: { code: string }) => {- const { data } = await apiRequest.post<{ accessToken: string; refreshToken: string }>(- "/api/v3/signup/verify-alias",- details- );- return data;-};--export const useVerifyAlias = () => {- return useMutation({- mutationFn: verifyAlias- });-};-export const useSendMfaToken = () => {return useMutation<object, object, SendMfaTokenDTO>({mutationFn: async ({ email }) => {diff --git a/frontend/src/hooks/api/auth/refresh.ts b/frontend/src/hooks/api/auth/refresh.tsindex 2891c5f075..043953c416 100644--- a/frontend/src/hooks/api/auth/refresh.ts+++ b/frontend/src/hooks/api/auth/refresh.ts@@ -1,6 +1,7 @@import axios from "axios";+import { jwtDecode } from "jwt-decode";-import { setAuthToken } from "../reactQuery";+import { getAuthToken, setAuthToken } from "../reactQuery";import { GetAuthTokenAPI } from "./types";// BroadcastChannel for cross-tab token synchronization@@ -21,10 +22,27 @@ let activeRefreshPromise: Promise<GetAuthTokenAPI> | null = null;/*** Refresh the auth token using the httpOnly refresh token cookie.- * Uses a standalone axios call (not apiRequest) to avoid circular imports with request.ts.- * Deduplicates concurrent calls and broadcasts the new token to other tabs.+ * If an in-memory token already exists (e.g. after selectOrganization),+ * decode it directly to avoid stale cache from the refresh endpoint.*/export const fetchAuthToken = async (): Promise<GetAuthTokenAPI> => {+ // If we already have an in-memory token, decode org context from it directly+ const currentToken = getAuthToken();+ if (currentToken) {+ try {+ const decoded = jwtDecode<{ organizationId?: string; subOrganizationId?: string }>(+ currentToken+ );+ return {+ token: currentToken,+ organizationId: decoded.organizationId,+ subOrganizationId: decoded.subOrganizationId+ };+ } catch {+ // decode failed — fall through to refresh+ }+ }+if (activeRefreshPromise) {return activeRefreshPromise;}diff --git a/frontend/src/hooks/api/auth/types.ts b/frontend/src/hooks/api/auth/types.tsindex a735caefa1..cac703614c 100644--- a/frontend/src/hooks/api/auth/types.ts+++ b/frontend/src/hooks/api/auth/types.ts@@ -95,14 +95,21 @@ export type LoginLDAPRes = {nextUrl: string;};-export type CompleteAccountSignupDTO = {- email: string;- firstName: string;- lastName: string;- password: string;- attributionSource?: string;- organizationName?: string;-};+export type CompleteAccountSignupDTO =+ | {+ type: "email";+ email: string;+ firstName: string;+ lastName: string;+ password: string;+ attributionSource?: string;+ organizationName?: string;+ }+ | {+ type: "alias";+ code: string;+ organizationName?: string;+ };export type VerifySignupInviteDTO = {email: string;diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex 54c0759b4a..6660f9c311 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -354,7 +354,6 @@ export const useLogoutUser = () => {setAuthToken("");// Remove the login check cache immediately so the restrict-login-signup// middleware doesn't find stale auth data and redirect to select-organization.- qc.removeQueries({ queryKey: authKeys.getLoginCheck });qc.removeQueries({ queryKey: authKeys.getAuthToken });await logoutUser();},diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsxindex 0eebefe726..74c75c2f31 100644--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx@@ -269,7 +269,6 @@ export const Navbar = () => {const logout = useLogoutUser();const logOutUser = async () => {try {- console.log("Triggering logout");await logout.mutateAsync();navigate({ to: "/login" });} catch (error) {diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsx b/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsxindex 79d250c6cc..288328a52f 100644--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsx+++ b/frontend/src/pages/auth/SelectOrgPage/SelectOrgSection.tsx@@ -23,7 +23,7 @@ import {useSelectOrganization} from "@app/hooks/api";import { MfaMethod, UserAgentType } from "@app/hooks/api/auth/types";-import { getAuthToken, isLoggedIn } from "@app/hooks/api/reactQuery";+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";@@ -214,6 +214,7 @@ export const SelectOrganizationSection = () => {});navigate({ to: "/cli-redirect" });} else {+ setAuthToken(token);navigateUserToOrg({ navigate, organizationId: organization.id });}},diff --git a/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx b/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsxindex 99a07a61d2..2246b466a2 100644--- a/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx+++ b/frontend/src/pages/auth/SignUpSsoPage/SignUpSsoPage.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useEffect, useState } from "react";import ReactCodeInput from "react-code-input";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";@@ -10,10 +10,15 @@ import { AuthPageBackground } from "@app/components/auth/AuthPageBackground";import { AuthPageFooter } from "@app/components/auth/AuthPageFooter";import { createNotification } from "@app/components/notifications";import SecurityClient from "@app/components/utilities/SecurityClient";-import { Button } from "@app/components/v2";+import { Button, Input } from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";import { useSendEmailVerificationCode } from "@app/hooks/api";-import { verifyAlias } from "@app/hooks/api/auth/queries";+import { useCompleteAccountSignup } from "@app/hooks/api/auth/queries";++enum SignupSsoStep {+ VerifyCode = "verify-code",+ OrgName = "org-name"+}const codeInputProps = {inputStyle: {@@ -59,9 +64,12 @@ export const SignupSsoPage = () => {const search = useSearch({ from: ROUTE_PATHS.Auth.SignUpSsoPage.id });const token = search.token as string;+ const [step, setStep] = useState(SignupSsoStep.VerifyCode);const [code, setCode] = useState("");- const [codeError, setCodeError] = useState(false);- const [isLoading, setIsLoading] = useState(false);+ const [organizationName, setOrganizationName] = useState("");+ const [orgNameError, setOrgNameError] = useState(false);++ const completeAccountSignup = useCompleteAccountSignup();const decoded = jwtDecode(token) as {email?: string;@@ -73,35 +81,59 @@ export const SignupSsoPage = () => {organizationId?: string;};- // Store the signup token so the Axios interceptor uses it for Authorization headers- SecurityClient.setSignupToken(token);+ // If token has an organizationId, the user already belongs to an org (IdP or invited)+ const needsOrgName = !decoded.organizationId;const { mutateAsync: sendEmailVerificationCode } = useSendEmailVerificationCode();- const handleVerify = async () => {- setIsLoading(true);- try {- const { accessToken, refreshToken } = await verifyAlias({ code });+ useEffect(() => {+ SecurityClient.setSignupToken(token);+ }, [token]);- setCodeError(false);- SecurityClient.setSignupToken("");- SecurityClient.setToken(accessToken);+ const handleSubmit = async () => {+ const { token: accessToken } = await completeAccountSignup.mutateAsync({+ type: "alias",+ code,+ organizationName: organizationName || undefined+ });- createNotification({- text: "Successfully verified",- type: "success"- });+ SecurityClient.setSignupToken("");+ SecurityClient.setToken(accessToken);+ const { organizationId } = jwtDecode(accessToken) as { organizationId?: string };- // refreshToken is set as jid cookie by the backend response- // Navigate to org selection- void refreshToken; // used by backend cookie, not needed here+ createNotification({+ text: "Successfully verified",+ type: "success"+ });+ if (decoded.organizationId || organizationId) {+ navigate({+ to: "/organizations/$orgId/projects",+ params: { orgId: decoded.organizationId || organizationId || "" }+ });+ } else {navigate({ to: "/login/select-organization" });- } catch {- setCodeError(true);- setIsLoading(false);}};+ const handleCodeNext = async () => {+ if (needsOrgName) {+ // Move to org name step — code will be submitted together with org name+ setStep(SignupSsoStep.OrgName);+ } else {+ // No org needed, submit directly+ await handleSubmit();+ }+ };++ const handleOrgNameSubmit = async () => {+ if (!organizationName.trim()) {+ setOrgNameError(true);+ return;+ }+ setOrgNameError(false);+ await handleSubmit();+ };+const handleResendCode = async () => {try {await sendEmailVerificationCode(token);@@ -138,61 +170,119 @@ export const SignupSsoPage = () => {</div></Link><div className="mx-auto h-full w-full pb-4 md:px-8">- <p className="text-md flex justify-center text-bunker-200">- We've sent a verification code to {decoded.email}- </p>- <div className="mx-auto hidden w-max min-w-[20rem] md:block">- <ReactCodeInput- name=""- inputMode="tel"- type="text"- fields={6}- onChange={setCode}- {...codeInputProps}- className="mt-6 mb-2"- />- </div>- <div className="mx-auto mt-4 block w-max md:hidden">- <ReactCodeInput- name=""- inputMode="tel"- type="text"- fields={6}- onChange={setCode}- {...codeInputPropsPhone}- className="mt-2 mb-2"- />- </div>- {codeError && <Error text="Oops. Your code is wrong. Please try again." />}- <div className="mx-auto mt-2 flex w-1/4 max-w-xs min-w-[20rem] flex-col items-center justify-center text-center text-sm md:max-w-md md:text-left lg:w-[19%]">- <div className="text-l w-full py-1 text-lg">- <Button- type="submit"- onClick={handleVerify}- size="sm"- isFullWidth- className="h-14"- colorSchema="primary"- variant="outline_bg"- isLoading={isLoading}- >- Verify- </Button>- </div>- </div>- <div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2">- <div className="flex flex-row items-baseline gap-1 text-sm">- <span className="text-bunker-400">Don't see the code?</span>- <div className="text-md mt-2 flex flex-row text-bunker-400">- <button disabled={isLoading} onClick={handleResendCode} type="button">- <span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">- Resend- </span>- </button>+ {step === SignupSsoStep.VerifyCode && (+ <>+ <p className="text-md flex justify-center text-bunker-200">+ We've sent a verification code to {decoded.email}+ </p>+ <div className="mx-auto hidden w-max min-w-[20rem] md:block">+ <ReactCodeInput+ name=""+ inputMode="tel"+ type="text"+ fields={6}+ onChange={setCode}+ {...codeInputProps}+ className="mt-6 mb-2"+ />+ </div>+ <div className="mx-auto mt-4 block w-max md:hidden">+ <ReactCodeInput+ name=""+ inputMode="tel"+ type="text"+ fields={6}+ onChange={setCode}+ {...codeInputPropsPhone}+ className="mt-2 mb-2"+ />+ </div>+ {completeAccountSignup.isError && (+ <Error text="Oops. Your code is wrong. Please try again." />+ )}+ <div className="mx-auto mt-2 flex w-1/4 max-w-xs min-w-[20rem] flex-col items-center justify-center text-center text-sm md:max-w-md md:text-left lg:w-[19%]">+ <div className="text-l w-full py-1 text-lg">+ <Button+ type="submit"+ onClick={handleCodeNext}+ size="sm"+ isFullWidth+ className="h-14"+ colorSchema="primary"+ variant="outline_bg"+ isLoading={completeAccountSignup.isPending}+ >+ {needsOrgName ? "Next" : "Verify"}+ </Button>+ </div>+ </div>+ <div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2">+ <div className="flex flex-row items-baseline gap-1 text-sm">+ <span className="text-bunker-400">Don't see the code?</span>+ <div className="text-md mt-2 flex flex-row text-bunker-400">+ <button+ disabled={completeAccountSignup.isPending}+ onClick={handleResendCode}+ type="button"+ >+ <span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">+ Resend+ </span>+ </button>+ </div>+ </div>+ <p className="pb-2 text-sm text-bunker-400">Make sure to check your spam inbox.</p>+ </div>+ </>+ )}+ {step === SignupSsoStep.OrgName && (+ <div className="mx-auto flex w-full max-w-xs flex-col items-center">+ <p className="text-md mb-6 text-bunker-200">Create your organization</p>+ <div className="w-full">+ <p className="mb-1 ml-1 text-sm font-medium text-bunker-300">Organization Name</p>+ <Input+ value={organizationName}+ onChange={(e) => {+ setOrganizationName(e.target.value);+ if (e.target.value.trim()) setOrgNameError(false);+ }}+ placeholder="Infisical"+ maxLength={64}+ isError={orgNameError}+ />+ {orgNameError && (+ <p className="mt-1 text-xs text-red-500">Please enter an organization name.</p>+ )}+ </div>+ {completeAccountSignup.isError && (+ <Error text="Something went wrong. Please try again." />+ )}+ <div className="mt-6 flex w-full gap-2">+ <Button+ onClick={() => setStep(SignupSsoStep.VerifyCode)}+ size="sm"+ className="h-14"+ colorSchema="secondary"+ variant="outline_bg"+ isDisabled={completeAccountSignup.isPending}+ >+ Back+ </Button>+ <Button+ type="submit"+ onClick={handleOrgNameSubmit}+ size="sm"+ isFullWidth+ className="h-14"+ colorSchema="primary"+ variant="outline_bg"+ isLoading={completeAccountSignup.isPending}+ >+ Complete+ </Button></div></div>- <p className="pb-2 text-sm text-bunker-400">Make sure to check your spam inbox.</p>- </div>+ )}</div></div><AuthPageFooter />diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsxdeleted file mode 100644index 71843de811..0000000000--- a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx+++ /dev/null@@ -1,235 +0,0 @@-import crypto from "crypto";--import { useEffect, useState } from "react";-import { useTranslation } from "react-i18next";-import { useNavigate } from "@tanstack/react-router";--import { Mfa } from "@app/components/auth/Mfa";-import SecurityClient from "@app/components/utilities/SecurityClient";-import {- Button,- FieldError,- TextArea,- UnstableCard,- UnstableCardContent,- UnstableCardHeader,- UnstableCardTitle,- UnstableInput-} from "@app/components/v3";-import { isInfisicalCloud } from "@app/helpers/platform";-import { initProjectHelper } from "@app/helpers/project";-import { useToggle } from "@app/hooks";-import { completeAccountSignup, useSelectOrganization } from "@app/hooks/api/auth/queries";-import { MfaMethod } from "@app/hooks/api/auth/types";-import { fetchOrganizations } from "@app/hooks/api/organization/queries";--type Props = {- username: string;- password: string;- setPassword: (value: string) => void;- name: string;- providerOrganizationName: string;- forceDefaultOrg?: boolean;-};--export const UserInfoSSOStep = ({- username,- name,- providerOrganizationName,- password,- setPassword,- forceDefaultOrg-}: Props) => {- const [nameError, setNameError] = useState(false);- const [organizationName, setOrganizationName] = useState("");- const [organizationNameError, setOrganizationNameError] = useState(false);- const [attributionSource, setAttributionSource] = useState("");- const [shouldShowMfa, toggleShowMfa] = useToggle(false);- const [requiredMfaMethod, setRequiredMfaMethod] = useState(MfaMethod.EMAIL);- const [isLoading, setIsLoading] = useState(false);- const { t } = useTranslation();- const { mutateAsync: selectOrganization } = useSelectOrganization();- const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});- const navigate = useNavigate();-- useEffect(() => {- const randomPassword = crypto.randomBytes(32).toString("hex");- setPassword(randomPassword);- if (providerOrganizationName !== undefined) {- setOrganizationName(providerOrganizationName);- }- }, []);-- // Verifies if the information that the users entered (name, workspace)- // is there, and if the password matches the criteria.- const signupErrorCheck = async () => {- setIsLoading(true);- let errorCheck = false;- if (!name) {- setNameError(true);- errorCheck = true;- } else {- setNameError(false);- }- if (!organizationName && !forceDefaultOrg) {- setOrganizationNameError(true);- errorCheck = true;- } else {- setOrganizationNameError(false);- }-- if (!errorCheck) {- try {- const response = await completeAccountSignup({- email: username,- password,- firstName: name.split(" ")[0],- lastName: name.split(" ").slice(1).join(" "),- organizationName,- attributionSource- });-- // unset signup JWT token and set JWT token- SecurityClient.setSignupToken("");- SecurityClient.setToken(response.token);- SecurityClient.setProviderAuthToken("");-- if (isInfisicalCloud()) {- window.dataLayer = window.dataLayer || [];- window.dataLayer.push({ event: "signup_completed" });- }-- const userOrgs = await fetchOrganizations();- const orgId = userOrgs[0]?.id;-- const completeSignupFlow = async () => {- try {- const { isMfaEnabled, token, mfaMethod } = await selectOrganization({- organizationId: orgId- });-- if (isMfaEnabled) {- SecurityClient.setMfaToken(token);- if (mfaMethod) {- setRequiredMfaMethod(mfaMethod);- }- toggleShowMfa.on();- setMfaSuccessCallback(() => completeSignupFlow);- return;- }-- // only create example project if not joining existing org- if (!providerOrganizationName) {- await initProjectHelper({- projectName: "Example Project"- });- }-- localStorage.setItem("orgData.id", orgId);- navigate({- to: "/organizations/$orgId/projects",- params: { orgId }- });- } catch (error) {- setIsLoading(false);- console.error(error);- }- };-- await completeSignupFlow();- } catch (error) {- setIsLoading(false);- console.error(error);- }- } else {- setIsLoading(false);- }- };-- useEffect(() => {- if (password && providerOrganizationName) {- signupErrorCheck();- }- }, [providerOrganizationName, password]);-- if (shouldShowMfa) {- return (- <Mfa- hideLogo- email={username}- successCallback={mfaSuccessCallback}- method={requiredMfaMethod}- closeMfa={() => toggleShowMfa.off()}- />- );- }-- return (- <div className="mx-auto flex w-full flex-col items-center justify-center">- <UnstableCard className="mx-auto w-full max-w-sm items-stretch gap-0 p-6">- <UnstableCardHeader className="mb-4 gap-2">- <UnstableCardTitle className="bg-linear-to-b from-white to-bunker-200 bg-clip-text text-[1.65rem] font-medium text-transparent">- {t("signup.step3-message")}- </UnstableCardTitle>- </UnstableCardHeader>- <UnstableCardContent>- <div className="flex w-full flex-col items-stretch py-2">- <p className="mb-1 ml-1 text-sm font-medium text-bunker-300">Your Name</p>- <UnstableInput- placeholder="Jane Doe"- value={name}- disabled- required- autoComplete="given-name"- isError={nameError}- />- {nameError && <FieldError>Please, specify your name</FieldError>}- </div>- {!forceDefaultOrg && providerOrganizationName === undefined && (- <div className="flex w-full flex-col items-stretch py-2">- <p className="mb-1 ml-1 text-sm font-medium text-bunker-300">Organization Name</p>- <UnstableInput- placeholder="Infisical"- value={organizationName}- onChange={(e) => setOrganizationName(e.target.value)}- required- maxLength={64}- disabled={forceDefaultOrg}- isError={organizationNameError}- />- {organizationNameError && (- <FieldError>Please, specify your organization name</FieldError>- )}- </div>- )}- {providerOrganizationName === undefined && (- <div className="flex w-full flex-col items-stretch py-2">- <p className="mb-1 ml-1 text-sm font-medium text-bunker-300">- Where did you hear about us? <span className="font-light">(optional)</span>- </p>- <TextArea- placeholder=""- onChange={(e) => setAttributionSource(e.target.value)}- value={attributionSource}- rows={2}- />- </div>- )}- <div className="mt-4 w-full">- <Button- type="submit"- onClick={signupErrorCheck}- variant="project"- size="lg"- isFullWidth- isPending={isLoading}- isDisabled={isLoading}- >- {String(t("signup.signup"))}- </Button>- </div>- </UnstableCardContent>- </UnstableCard>- </div>- );-};diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/index.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/index.tsxdeleted file mode 100644index d62267cd34..0000000000--- a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/index.tsx+++ /dev/null@@ -1 +0,0 @@-export { UserInfoSSOStep } from "./UserInfoSSOStep";diff --git a/frontend/src/pages/middlewares/authenticate.tsx b/frontend/src/pages/middlewares/authenticate.tsxindex cfc531f0d5..92c8c98f38 100644--- a/frontend/src/pages/middlewares/authenticate.tsx+++ b/frontend/src/pages/middlewares/authenticate.tsx@@ -16,7 +16,7 @@ export const Route = createFileRoute("/_authenticate")({}const data = await context.queryClient- .ensureQueryData({+ .fetchQuery({queryKey: authKeys.getAuthToken,queryFn: fetchAuthToken})@@ -65,7 +65,7 @@ export const Route = createFileRoute("/_authenticate")({text: "Something went wrong with your session. Please log in again."});}- clearSession(true);+ clearSession();await logoutUser();throw redirect({diff --git a/frontend/src/pages/middlewares/restrict-login-signup.tsx b/frontend/src/pages/middlewares/restrict-login-signup.tsxindex 3799c491a5..7f877ad01f 100644--- a/frontend/src/pages/middlewares/restrict-login-signup.tsx+++ b/frontend/src/pages/middlewares/restrict-login-signup.tsx@@ -82,10 +82,12 @@ export const Route = createFileRoute("/_restrict-login-signup")({throw redirect({ to: "/admin/signup" });}- const data = await context.queryClient.ensureQueryData({- queryKey: authKeys.getAuthToken,- queryFn: fetchAuthToken- });+ const data = await context.queryClient+ .ensureQueryData({+ queryKey: authKeys.getAuthToken,+ queryFn: fetchAuthToken+ })+ .catch(() => null);if (!data) return;setAuthToken(data.token);diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsxindex bd37e5620b..a6e5e33a9c 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx@@ -119,7 +119,7 @@ export const ChangeEmailSection = () => {setTypedOTP("");// Clear frontend session/token to ensure proper logout- clearSession(true);+ clearSession();// Redirect to login after a short delaysetTimeout(() => {