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: simpliying auth page
=e48c0310117d
diff --git a/frontend/src/components/auth/CodeInputStep.tsx b/frontend/src/components/auth/CodeInputStep.tsxindex 61e7779585..d551340b4b 100644--- a/frontend/src/components/auth/CodeInputStep.tsx+++ b/frontend/src/components/auth/CodeInputStep.tsx@@ -12,7 +12,9 @@ import {UnstableCardHeader,UnstableCardTitle} from "@app/components/v3";-import { useSendVerificationEmail } from "@app/hooks/api";+import { useSendVerificationEmail, useVerifySignupEmailVerificationCode } from "@app/hooks/api";++import SecurityClient from "../utilities/SecurityClient";// Matches v3 input theme: transparent bg, border (#2b2c30), foreground text (#ebebeb), ring on focus (#2d2f33)const codeInputStyle = {@@ -54,44 +56,23 @@ const codeInputStylePhone = {interface CodeInputStepProps {email: string;- incrementStep: () => void;- setCode: (value: string) => void;- codeError: boolean;- isCodeInputCheckLoading: boolean;+ onComplete: () => void;}-/**- * This is the second step of sign up where users need to verify their email- * @param {object} obj- * @param {string} obj.email - user's email to which we just sent a verification email- * @param {function} obj.incrementStep - goes to the next step of signup- * @param {function} obj.setCode - state updating function that set the current value of the emai verification code- * @param {boolean} obj.codeError - whether the code was inputted wrong or now- * @returns- */-export default function CodeInputStep({- email,- incrementStep,- setCode,- codeError,- isCodeInputCheckLoading-}: CodeInputStepProps): JSX.Element {- const { mutateAsync } = useSendVerificationEmail();- const [isLoading, setIsLoading] = useState(false);- const [isResendingVerificationEmail, setIsResendingVerificationEmail] = useState(false);+export default function CodeInputStep({ email, onComplete }: CodeInputStepProps): JSX.Element {+ const { mutateAsync: resendEmail, isPending: isResending } = useSendVerificationEmail();+ const {+ mutateAsync: verifyCode,+ isPending: isVerifying,+ isError: isCodeError+ } = useVerifySignupEmailVerificationCode();+ const [code, setCode] = useState("");const { t } = useTranslation();- const resendVerificationEmail = async () => {- setIsResendingVerificationEmail(true);- setIsLoading(true);- try {- await mutateAsync({ email });- } finally {- setTimeout(() => {- setIsLoading(false);- setIsResendingVerificationEmail(false);- }, 1000);- }+ const handleVerify = async () => {+ const { token } = await verifyCode({ email, code });+ SecurityClient.setSignupToken(token);+ onComplete();};return (@@ -126,26 +107,30 @@ export default function CodeInputStep({className="code-input-v3 mt-2 mb-2"/></div>- {codeError && <FieldError>{t("signup.step2-code-error")}</FieldError>}+ {isCodeError && <FieldError>{t("signup.step2-code-error")}</FieldError>}<div className="mt-4 w-full"><Buttontype="submit"- onClick={incrementStep}+ onClick={handleVerify}variant="project"size="lg"isFullWidth- isPending={isCodeInputCheckLoading}- isDisabled={isCodeInputCheckLoading}+ isPending={isVerifying}+ isDisabled={isVerifying}>{String(t("signup.verify"))}</Button></div><div className="mt-6 flex flex-col items-center gap-2 text-xs text-label"><div className="flex flex-row items-baseline gap-1">- <button disabled={isLoading} onClick={resendVerificationEmail} type="button">+ <button+ disabled={isResending}+ onClick={() => resendEmail({ email })}+ type="button"+ ><span className="cursor-pointer duration-200 hover:text-foreground hover:underline hover:decoration-project/45 hover:underline-offset-2">{t("signup.step2-resend-alert")}{" "}- {isResendingVerificationEmail+ {isResending? t("signup.step2-resend-progress"): t("signup.step2-resend-submit")}</span>diff --git a/frontend/src/components/auth/UserInfoStep.tsx b/frontend/src/components/auth/UserInfoStep.tsxindex d6238fdfb5..413db75090 100644--- a/frontend/src/components/auth/UserInfoStep.tsx+++ b/frontend/src/components/auth/UserInfoStep.tsx@@ -1,6 +1,9 @@-import { useState } from "react";+import { useCallback, useRef, useState } from "react";+import { useForm } from "react-hook-form";import { useTranslation } from "react-i18next";+import { zodResolver } from "@hookform/resolvers/zod";import { Eye, EyeOff, X } from "lucide-react";+import { z } from "zod";import {Button,@@ -18,203 +21,199 @@ import {} from "@app/components/v3";import { isInfisicalCloud } from "@app/helpers/platform";import { initProjectHelper } from "@app/helpers/project";-import { completeAccountSignup, useSelectOrganization } from "@app/hooks/api/auth/queries";+import { useCompleteAccountSignup } from "@app/hooks/api/auth/queries";import { fetchOrganizations } from "@app/hooks/api/organization/queries";-import { onRequestError } from "@app/hooks/api/reactQuery";-import checkPassword from "../utilities/checks/password/checkPassword";+import { checkIsPasswordBreached } from "../utilities/checks/password/checkIsPasswordBreached";+import {+ escapeCharRegex,+ letterCharRegex,+ lowEntropyRegexes,+ numAndSpecialCharRegex,+ repeatedCharRegex+} from "../utilities/checks/password/passwordRegexes";import SecurityClient from "../utilities/SecurityClient";+const passwordSchema = z+ .string()+ .min(1, "Password is required")+ .min(14, "at least 14 characters")+ .max(100, "at most 100 characters")+ .regex(letterCharRegex, "at least 1 letter character")+ .regex(numAndSpecialCharRegex, "at least 1 number or special character")+ .refine((pwd) => !repeatedCharRegex.test(pwd), "at most 3 repeated, consecutive characters")+ .refine((pwd) => !escapeCharRegex.test(pwd), "No escape characters allowed")+ .refine(+ (pwd) => !lowEntropyRegexes.some((regex) => regex.test(pwd)),+ "Password contains personal info"+ );++const createUserInfoFormSchema = (isInvite: boolean) =>+ z.object({+ name: z.string().min(1, "Please, specify your name"),+ organizationName: isInvite+ ? z.string().optional()+ : z.string().min(1, "Please, specify your organization name").max(64),+ password: passwordSchema,+ attributionSource: z.string().optional()+ });++type UserInfoFormData = z.infer<ReturnType<typeof createUserInfoFormSchema>>;+interface UserInfoStepProps {- incrementStep: () => void;+ onComplete: () => void;email: string;- password: string;- setPassword: (value: string) => void;- name: string;- setName: (value: string) => void;- organizationName: string;- setOrganizationName: (value: string) => void;- attributionSource: string;- setAttributionSource: (value: string) => void;- providerAuthToken?: string;+ isInvite?: boolean;}-type Errors = {- tooShort?: string;- tooLong?: string;- noLetterChar?: string;- noNumOrSpecialChar?: string;- repeatedChar?: string;- escapeChar?: string;- lowEntropy?: string;- breached?: string;-};+const BREACH_CHECK_DEBOUNCE_MS = 1000;-/**- * This is the step of the sign up flow where people provife their name/surname and password- * @param {object} obj- * @param {string} obj.verificationToken - the token which we use to verify the legitness of a user- * @param {string} obj.incrementStep - a function to move to the next signup step- * @param {string} obj.email - email of a user who is signing up- * @param {string} obj.password - user's password- * @param {string} obj.setPassword - function managing the state of user's password- * @param {string} obj.firstName - user's first name- * @param {string} obj.setFirstName - function managing the state of user's first name- * @param {string} obj.lastName - user's lastName- * @param {string} obj.setLastName - function managing the state of user's last name- */export default function UserInfoStep({- incrementStep,+ onComplete,email,- password,- setPassword,- name,- setName,- organizationName,- setOrganizationName,- attributionSource,- setAttributionSource,- providerAuthToken+ isInvite = false}: UserInfoStepProps): JSX.Element {- const [nameError, setNameError] = useState(false);- const [organizationNameError, setOrganizationNameError] = useState(false);const [showPassword, setShowPassword] = useState(false);+ const [breachWarning, setBreachWarning] = useState<string | null>(null);+ const breachTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const [errors, setErrors] = useState<Errors>({});-- const { mutateAsync: selectOrganization } = useSelectOrganization();- const [isLoading, setIsLoading] = useState(false);+ const { mutateAsync: completeSignup, isPending: isLoading } = useCompleteAccountSignup();const { t } = useTranslation();- // 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) {- setOrganizationNameError(true);- errorCheck = true;- } else {- setOrganizationNameError(false);+ const {+ register,+ handleSubmit,+ watch,+ formState: { errors }+ } = useForm<UserInfoFormData>({+ resolver: zodResolver(createUserInfoFormSchema(isInvite)),+ criteriaMode: "all",+ defaultValues: {+ name: "",+ organizationName: "",+ password: "",+ attributionSource: ""}+ });- errorCheck = await checkPassword({- password,- setErrors- });+ const passwordValue = watch("password");+ const passwordIssues = errors.password?.types+ ? (Object.values(errors.password.types).flat().filter(Boolean) as string[])+ : [];- if (!errorCheck) {- try {- const response = await completeAccountSignup({- email,- password,- firstName: name.split(" ")[0],- lastName: name.split(" ").slice(1).join(" "),- providerAuthToken,- organizationName,- attributionSource- });+ const debouncedBreachCheck = useCallback((pwd: string) => {+ if (breachTimerRef.current) {+ clearTimeout(breachTimerRef.current);+ }+ if (pwd.length < 14) {+ setBreachWarning(null);+ return;+ }+ breachTimerRef.current = setTimeout(async () => {+ const isBreached = await checkIsPasswordBreached(pwd);+ setBreachWarning(isBreached ? "Password was found in a data breach" : null);+ }, BREACH_CHECK_DEBOUNCE_MS);+ }, []);- // unset signup JWT token and set JWT token- SecurityClient.setSignupToken("");- SecurityClient.setToken(response.token);- SecurityClient.setProviderAuthToken("");+ const onSubmit = async (formData: UserInfoFormData) => {+ // Run breach check synchronously on submit if not already checked+ const isBreached = await checkIsPasswordBreached(formData.password);+ if (isBreached) {+ setBreachWarning("Password was found in a data breach");+ return;+ }- if (isInfisicalCloud()) {- window.dataLayer = window.dataLayer || [];- window.dataLayer.push({ event: "signup_completed" });- }+ const response = await completeSignup({+ email,+ password: formData.password,+ firstName: formData.name.split(" ")[0],+ lastName: formData.name.split(" ").slice(1).join(" "),+ organizationName: formData.organizationName || undefined,+ attributionSource: formData.attributionSource+ });- if (response.organizationId) {- await selectOrganization({ organizationId: response.organizationId });- }+ SecurityClient.setSignupToken("");+ SecurityClient.setToken(response.token);+ SecurityClient.setProviderAuthToken("");- const userOrgs = await fetchOrganizations();+ if (isInfisicalCloud()) {+ window.dataLayer = window.dataLayer || [];+ window.dataLayer.push({ event: "signup_completed" });+ }- const orgId = userOrgs[0]?.id;- await initProjectHelper({- projectName: "Example Project"- });+ const userOrgs = await fetchOrganizations();+ const orgId = userOrgs[0]?.id;- localStorage.setItem("orgData.id", orgId);+ if (!isInvite) {+ await initProjectHelper({+ projectName: "Example Project"+ });+ }- incrementStep();- } catch (error) {- onRequestError(error);- setIsLoading(false);- console.error(error);- }- } else {- setIsLoading(false);+ if (orgId) {+ localStorage.setItem("orgData.id", orgId);}++ onComplete();};+ const allIssues = [...passwordIssues, ...(breachWarning ? [breachWarning] : [])];+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")}+ {isInvite ? "Set up your account" : 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+ {...register("name")}placeholder="Jane Doe"- onChange={(e) => setName(e.target.value)}- value={name}- requiredautoComplete="given-name"- isError={nameError}- />- {nameError && <FieldError>Please, specify your name</FieldError>}- </div>- <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"- onChange={(e) => setOrganizationName(e.target.value)}- value={organizationName}- maxLength={64}- required- isError={organizationNameError}- />- {organizationNameError && (- <FieldError>Please, specify your organization name</FieldError>- )}- </div>- <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}+ isError={!!errors.name}/>+ {errors.name && <FieldError>{errors.name.message}</FieldError>}</div>+ {!isInvite && (+ <>+ <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+ {...register("organizationName")}+ placeholder="Infisical"+ maxLength={64}+ isError={!!errors.organizationName}+ />+ {errors.organizationName && (+ <FieldError>{errors.organizationName.message}</FieldError>+ )}+ </div>+ <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 {...register("attributionSource")} placeholder="" rows={2} />+ </div>+ </>+ )}<div className="flex w-full flex-col items-stretch py-2"><p className="mb-1 ml-1 text-sm font-medium text-bunker-300">{t("section.password.password")}</p><InputGroup className="h-10"><InputGroupInput- value={password}- onChange={async (e) => {- setPassword(e.target.value);- await checkPassword({ password: e.target.value, setErrors });- }}+ {...register("password", {+ onChange(e) {+ setBreachWarning(null);+ debouncedBreachCheck(e.target.value);+ }+ })}type={showPassword ? "text" : "password"}placeholder="Enter a strong password..."- requiredautoComplete="new-password"id="new-password"/>@@ -229,29 +228,24 @@ export default function UserInfoStep({</UnstableIconButton></InputGroupAddon></InputGroup>- {Object.keys(errors).length > 0 && (+ {allIssues.length > 0 && passwordValue.length > 0 && (<div className="mt-4 flex w-full flex-col items-start rounded-md border border-border bg-container px-3 py-2.5"><div className="mb-1 text-sm text-gray-400">{t("section.password.validate-base")}</div>- {Object.keys(errors).map((key) => {- if (errors[key as keyof Errors]) {- return (- <div className="items-top flex flex-row justify-start" key={key}>- <X className="mt-0.5 mr-2 size-4 shrink-0 text-danger" />- <p className="text-sm text-gray-400">{errors[key as keyof Errors]}</p>- </div>- );- }- return null;- })}+ {allIssues.map((issue) => (+ <div className="items-top flex flex-row justify-start" key={issue}>+ <X className="mt-0.5 mr-2 size-4 shrink-0 text-danger" />+ <p className="text-sm text-gray-400">{issue}</p>+ </div>+ ))}</div>)}</div><div className="mt-4 w-full"><Buttontype="submit"- onClick={signupErrorCheck}+ onClick={handleSubmit(onSubmit)}variant="project"size="lg"isFullWidthdiff --git a/frontend/src/components/utilities/attemptCliLogin.ts b/frontend/src/components/utilities/attemptCliLogin.tsindex f8339aecfb..d0f8fca241 100644--- a/frontend/src/components/utilities/attemptCliLogin.ts+++ b/frontend/src/components/utilities/attemptCliLogin.ts@@ -1,17 +1,8 @@-/* eslint-disable prefer-destructuring */-import axios from "axios";-import jsrp from "jsrp";+import { loginV3 } from "@app/hooks/api/auth/queries";-import { login1, login2, loginV3 } from "@app/hooks/api/auth/queries";--import { createNotification } from "../notifications";import Telemetry from "./telemetry/Telemetry";-import { LoginMode } from "./attemptLogin";import SecurityClient from "./SecurityClient";-// eslint-disable-next-line new-cap-const client = new jsrp.client();-export interface IsCliLoginSuccessful {loginResponse?: {email: string;@@ -21,122 +12,38 @@ export interface IsCliLoginSuccessful {success: boolean;}-/**- * Return whether or not login is successful for user with email [email]- * and password [password]- * @param {string} email - email of user to log in- * @param {string} password - password of user to log in- */const attemptLogin = async ({email,password,- providerAuthToken,- captchaToken,- loginMode = LoginMode.ServerSide+ captchaToken}: {email: string;password: string;- providerAuthToken?: string;captchaToken?: string;- loginMode?: LoginMode;}): Promise<IsCliLoginSuccessful> => {const telemetry = new Telemetry().getInstance();- if (loginMode === LoginMode.ServerSide) {- console.log("Attempting login with server side...");- const data = await loginV3({- email,- password,- providerAuthToken,- captchaToken- }).catch((err) => {- if (axios.isAxiosError(err) && err.response?.status === 400) {- if (err.response?.data?.error === "LegacyEncryptionScheme") {- createNotification({- text: "Failed to login without SRP, attempting to authenticate with legacy SRP authentication.",- type: "info"- });-- return null;- }- }-- throw err;- });-- if (data === null) {- return attemptLogin({- email,- password,- providerAuthToken,- captchaToken,- loginMode: LoginMode.LegacySrp- });- }-- SecurityClient.setProviderAuthToken("");- SecurityClient.setToken(data.accessToken);+ console.log("Attempting login with server side...");+ const data = await loginV3({+ email,+ password,+ captchaToken+ });- return {- success: true,- loginResponse: {- email,- privateKey: "",- JTWToken: data.accessToken- }- };+ SecurityClient.setProviderAuthToken("");+ SecurityClient.setToken(data.accessToken);+ if (email) {+ telemetry.identify(email, email);+ telemetry.capture("User Logged In");}-- return new Promise((resolve, reject) => {- client.init(- {- username: email,- password- },- async () => {- try {- const clientPublicKey = client.getPublicKey();- const { serverPublicKey, salt } = await login1({- email,- clientPublicKey,- providerAuthToken- });-- client.setSalt(salt);- client.setServerPublicKey(serverPublicKey);- const clientProof = client.getProof(); // called M1-- const { encryptionVersion, token, encryptedPrivateKey, iv, tag } = await login2({- email,- password,- clientProof,- providerAuthToken,- captchaToken- });- if (encryptionVersion && encryptedPrivateKey && iv && tag && token) {- SecurityClient.setProviderAuthToken("");- SecurityClient.setToken(token);-- if (email) {- telemetry.identify(email, email);- telemetry.capture("User Logged In");- }-- resolve({- loginResponse: {- email,- privateKey: "",- JTWToken: token- },- success: true- });- }- } catch (err) {- reject(err);- }- }- );- });+ return {+ success: true,+ loginResponse: {+ email,+ privateKey: "",+ JTWToken: data.accessToken+ }+ };};export default attemptLogin;diff --git a/frontend/src/components/utilities/attemptLogin.ts b/frontend/src/components/utilities/attemptLogin.tsindex bdaf790422..8e918fe0ca 100644--- a/frontend/src/components/utilities/attemptLogin.ts+++ b/frontend/src/components/utilities/attemptLogin.ts@@ -1,10 +1,6 @@-/* eslint-disable prefer-destructuring */-import axios from "axios";-import jsrp from "jsrp";+import { loginV3 } from "@app/hooks/api/auth/queries";+import { setAuthToken } from "@app/hooks/api/reactQuery";-import { login1, login2, loginV3 } from "@app/hooks/api/auth/queries";--import { createNotification } from "../notifications";import Telemetry from "./telemetry/Telemetry";import SecurityClient from "./SecurityClient";@@ -27,103 +23,31 @@ const attemptLogin = async ({email,password,providerAuthToken,- captchaToken,- loginMode = LoginMode.ServerSide+ captchaToken}: {email: string;password: string;providerAuthToken?: string;captchaToken?: string;- loginMode?: LoginMode;}): Promise<IsLoginSuccessful> => {const telemetry = new Telemetry().getInstance();- if (loginMode === LoginMode.ServerSide) {- console.log("Attempting login with server side...");- const data = await loginV3({- email,- password,- providerAuthToken,- captchaToken- }).catch((err) => {- if (axios.isAxiosError(err) && err.response?.status === 400) {- if (err.response?.data?.error === "LegacyEncryptionScheme") {- createNotification({- text: "Failed to login without SRP, attempting to authenticate with legacy SRP authentication.",- type: "info"- });-- return null;- }- }-- throw err;- });-- if (data === null) {- return attemptLogin({- email,- password,- providerAuthToken,- captchaToken,- loginMode: LoginMode.LegacySrp- });- }-- SecurityClient.setProviderAuthToken("");- SecurityClient.setToken(data.accessToken);-- if (email) {- telemetry.identify(email, email);- telemetry.capture("User Logged In");- }-- return {- success: true- };- }-- // eslint-disable-next-line new-cap- const client = new jsrp.client();- await new Promise((resolve) => {- client.init({ username: email, password }, () => resolve(null));- });- const clientPublicKey = client.getPublicKey();-- const { serverPublicKey, salt } = await login1({- email,- clientPublicKey,- providerAuthToken- });-- client.setSalt(salt);- client.setServerPublicKey(serverPublicKey);- const clientProof = client.getProof(); // called M1-- const { encryptionVersion, token, encryptedPrivateKey, iv, tag } = await login2({- captchaToken,+ const data = await loginV3({email,password,- clientProof,- providerAuthToken+ providerAuthToken,+ captchaToken});- if (encryptionVersion && encryptedPrivateKey && iv && tag && token) {- // unset provider auth token in case it was used- SecurityClient.setProviderAuthToken("");- // set JWT token- SecurityClient.setToken(token);+ SecurityClient.setProviderAuthToken("");+ setAuthToken(data.accessToken);- if (email) {- telemetry.identify(email, email);- telemetry.capture("User Logged In");- }-- return {- success: true- };+ if (email) {+ telemetry.identify(email, email);+ telemetry.capture("User Logged In");}- return { success: false };++ return { success: true };};export default attemptLogin;diff --git a/frontend/src/components/v3/generic/InputGroup/InputGroup.tsx b/frontend/src/components/v3/generic/InputGroup/InputGroup.tsxindex 2f56bc114f..00dd52640c 100644--- a/frontend/src/components/v3/generic/InputGroup/InputGroup.tsx+++ b/frontend/src/components/v3/generic/InputGroup/InputGroup.tsx@@ -121,18 +121,23 @@ function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {);}-function InputGroupInput({ className, ...props }: React.ComponentProps<"input">) {- return (- <UnstableInput- data-slot="input-group-control"- className={cn(- "flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",- className- )}- {...props}- />- );-}+const InputGroupInput = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(+ ({ className, ...props }, ref) => {+ return (+ <UnstableInput+ ref={ref}+ data-slot="input-group-control"+ className={cn(+ "flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",+ className+ )}+ {...props}+ />+ );+ }+);++InputGroupInput.displayName = "InputGroupInput";// function InputGroupTextarea({ className, ...props }: React.ComponentProps<"textarea">) {// return (diff --git a/frontend/src/config/request.ts b/frontend/src/config/request.tsindex a37b38cb6b..04adc7338c 100644--- a/frontend/src/config/request.ts+++ b/frontend/src/config/request.ts@@ -1,9 +1,10 @@-import axios from "axios";+import axios, { AxiosRequestConfig } from "axios";import { addSeconds, formatISO } from "date-fns";import { createNotification } from "@app/components/notifications";import SecurityClient from "@app/components/utilities/SecurityClient";import { SessionStorageKeys } from "@app/const";+import { fetchAuthToken } from "@app/hooks/api/auth/refresh";import {getAuthToken,getMfaTempToken,@@ -49,23 +50,54 @@ const resetRedirectingFlag = () => {isRedirecting = false;};+let refreshPromise: Promise<string> | null = null;++const isTokenExpiredError = (message: string) => {+ const lower = message.toLowerCase();+ return lower.includes("token expired") || lower.includes("stalesession");+};+apiRequest.interceptors.response.use((response) => response,async (error) => {- const { response } = error;+ const { response, config } = error;if (response && (response.status === 401 || response.status === 403)) {const currentToken = getAuthToken();const isAuthenticatedRequest = Boolean(currentToken);- if (isAuthenticatedRequest && !isRedirecting) {- // Check if the error indicates token expiration+ if (isAuthenticatedRequest) {const errorMessage = response.data?.message || "";- const isTokenExpired = errorMessage- .toLowerCase()- .includes("your token has expired. please re-authenticate.");- if (isTokenExpired) {+ // 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 (!isRedirecting) {isRedirecting = true;try {diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsxindex 9f88e71e4b..2700bf15fd 100644--- a/frontend/src/hooks/api/auth/queries.tsx+++ b/frontend/src/hooks/api/auth/queries.tsx@@ -6,12 +6,9 @@ import { SessionStorageKeys } from "@app/const";import { organizationKeys } from "../organization/queries";import { projectKeys } from "../projects";-import { setAuthToken } from "../reactQuery";import { TGenerateAuthenticationOptionsResponse, TVerifyAuthenticationDTO } from "../webauthn";import {- CompleteAccountDTO,CompleteAccountSignupDTO,- GetAuthTokenAPI,GetBackupEncryptedPrivateKeyDTO,Login1DTO,Login1Res,@@ -145,9 +142,10 @@ export const completeAccountSignup = async (details: CompleteAccountSignupDTO) =return data;};-export const completeAccountSignupInvite = async (details: CompleteAccountDTO) => {- const { data } = await apiRequest.post("/api/v3/signup/complete-account/invite", details);- return data;+export const useCompleteAccountSignup = () => {+ return useMutation({+ mutationFn: completeAccountSignup+ });};export const useSendMfaToken = () => {@@ -286,15 +284,11 @@ export const useResetUserPasswordV2 = () => {});};-// Refresh token is set as cookie when logged in-// Using that we fetch the auth bearer token needed for auth calls-export const fetchAuthToken = async () => {- const { data } = await apiRequest.post<GetAuthTokenAPI>("/api/v1/auth/token", undefined, {- withCredentials: true- });- setAuthToken(data.token);- return data;-};+// Re-export from refresh.ts to maintain backwards compatibility+// The actual implementation lives in refresh.ts to avoid circular imports with request.ts+import { fetchAuthToken } from "./refresh";++export { fetchAuthToken };export const useGetAuthToken = () =>useQuery({diff --git a/frontend/src/hooks/api/auth/refresh.ts b/frontend/src/hooks/api/auth/refresh.tsnew file mode 100644index 0000000000..2891c5f075--- /dev/null+++ b/frontend/src/hooks/api/auth/refresh.ts@@ -0,0 +1,49 @@+import axios from "axios";++import { setAuthToken } from "../reactQuery";+import { GetAuthTokenAPI } from "./types";++// BroadcastChannel for cross-tab token synchronization+const tokenBroadcastChannel =+ typeof BroadcastChannel !== "undefined" ? new BroadcastChannel("infisical-token-refresh") : null;++// Listen for token updates from other tabs+if (tokenBroadcastChannel) {+ tokenBroadcastChannel.onmessage = (event: MessageEvent<{ token: string }>) => {+ if (event.data?.token) {+ setAuthToken(event.data.token);+ }+ };+}++// Shared promise to deduplicate concurrent refresh calls+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.+ */+export const fetchAuthToken = async (): Promise<GetAuthTokenAPI> => {+ if (activeRefreshPromise) {+ return activeRefreshPromise;+ }++ activeRefreshPromise = axios+ .post<GetAuthTokenAPI>("/api/v1/auth/token", undefined, {+ withCredentials: true+ })+ .then(({ data }) => {+ setAuthToken(data.token);++ // Notify other tabs of the refreshed token+ tokenBroadcastChannel?.postMessage({ token: data.token });++ return data;+ })+ .finally(() => {+ activeRefreshPromise = null;+ });++ return activeRefreshPromise;+};diff --git a/frontend/src/hooks/api/auth/types.ts b/frontend/src/hooks/api/auth/types.tsindex f30f0eacfd..a735caefa1 100644--- a/frontend/src/hooks/api/auth/types.ts+++ b/frontend/src/hooks/api/auth/types.ts@@ -1,5 +1,6 @@export type GetAuthTokenAPI = {token: string;+ refreshToken?: string;organizationId?: string;subOrganizationId?: string;};@@ -94,19 +95,13 @@ export type LoginLDAPRes = {nextUrl: string;};-export type CompleteAccountDTO = {+export type CompleteAccountSignupDTO = {email: string;firstName: string;lastName: string;password: string;- tokenMetadata?: string;-};--export type CompleteAccountSignupDTO = CompleteAccountDTO & {- providerAuthToken?: string;attributionSource?: string;- organizationName: string;- useDefaultOrg?: boolean;+ organizationName?: string;};export type VerifySignupInviteDTO = {diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex 26c5b45b76..7f553b5720 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -345,7 +345,13 @@ export const clearSession = (keepQueryClient?: boolean) => {export const useLogoutUser = (keepQueryClient?: boolean) => {return useMutation({- mutationFn: logoutUser,+ mutationFn: async () => {+ // Cancel all in-flight queries and clear token before the logout call+ // to prevent 401 interceptor from triggering refresh attempts+ qc.cancelQueries();+ setAuthToken("");+ await logoutUser();+ },onSuccess: () => clearSession(keepQueryClient)});};diff --git a/frontend/src/pages/auth/LoginPage/Login.utils.tsx b/frontend/src/pages/auth/LoginPage/Login.utils.tsxindex 8f2c63f832..489a4afe7a 100644--- a/frontend/src/pages/auth/LoginPage/Login.utils.tsx+++ b/frontend/src/pages/auth/LoginPage/Login.utils.tsx@@ -11,6 +11,12 @@ type NavigateUserToOrgParams = {navigateTo?: string;};+export enum LoginSection {+ Initial = "initial",+ SAML = "saml",+ OIDC = "oidc"+}+export const navigateUserToOrg = async ({navigate,organizationId,diff --git a/frontend/src/pages/auth/LoginPage/LoginPage.tsx b/frontend/src/pages/auth/LoginPage/LoginPage.tsxindex d499573345..d6b8aab5d2 100644--- a/frontend/src/pages/auth/LoginPage/LoginPage.tsx+++ b/frontend/src/pages/auth/LoginPage/LoginPage.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useState } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";import { Link } from "@tanstack/react-router";@@ -7,61 +7,22 @@ import { AuthPageBackground } from "@app/components/auth/AuthPageBackground";import { AuthPageFooter } from "@app/components/auth/AuthPageFooter";import { AuthPageHeader } from "@app/components/auth/AuthPageHeader";import { Button } from "@app/components/v3";-import { isLoggedIn } from "@app/hooks/api/reactQuery";import { InitialStep, SSOStep } from "./components";-import { useNavigateToSelectOrganization } from "./Login.utils";+import { LoginSection } from "./Login.utils";export const LoginPage = ({ isAdmin }: { isAdmin?: boolean }) => {const { t } = useTranslation();- const [step, setStep] = useState<number | null>(null);- const [email, setEmail] = useState("");- const [password, setPassword] = useState("");- const { navigateToSelectOrganization } = useNavigateToSelectOrganization();-- const queryParams = new URLSearchParams(window.location.search);-- useEffect(() => {- // TODO(akhilmhdh): workspace will be controlled by a workspace context- const handleRedirects = async () => {- try {- const callbackPort = queryParams?.get("callback_port");- // case: a callback port is set, meaning it's a cli login request: redirect to select org with callback port- if (callbackPort) {- navigateToSelectOrganization(callbackPort);- } else {- // case: no callback port, meaning it's a regular login request: redirect to select org- navigateToSelectOrganization();- }- } catch {- console.log("Error - Not logged in yet");- }- };-- if (isLoggedIn()) {- handleRedirects();- } else {- setStep(0);- }- }, []);+ const [section, setSection] = useState<LoginSection>(LoginSection.Initial);const renderView = () => {- switch (step) {- case 0:- return (- <InitialStep- isAdmin={isAdmin}- setStep={setStep}- email={email}- setEmail={setEmail}- password={password}- setPassword={setPassword}- />- );- case 2:- return <SSOStep setStep={setStep} type="SAML" />;- case 3:- return <SSOStep setStep={setStep} type="OIDC" />;+ switch (section) {+ case LoginSection.Initial:+ return <InitialStep isAdmin={isAdmin} setSection={setSection} />;+ case LoginSection.SAML:+ return <SSOStep setSection={setSection} type="SAML" />;+ case LoginSection.OIDC:+ return <SSOStep setSection={setSection} type="OIDC" />;default:return <div />;}diff --git a/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx b/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsxindex a118bd5d20..e951fc7b3a 100644--- a/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx+++ b/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx@@ -1,14 +1,16 @@-import { FormEvent, useEffect, useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";+import { useForm } from "react-hook-form";import { useTranslation } from "react-i18next";import { faGithub, faGitlab, faGoogle } from "@fortawesome/free-brands-svg-icons";import HCaptcha from "@hcaptcha/react-hcaptcha";+import { zodResolver } from "@hookform/resolvers/zod";import { Link, useNavigate } from "@tanstack/react-router";import { Eye, EyeOff } from "lucide-react";+import { z } from "zod";import Error from "@app/components/basic/Error";import { RegionSelect } from "@app/components/navigation/RegionSelect";import { createNotification } from "@app/components/notifications";-import attemptCliLogin from "@app/components/utilities/attemptCliLogin";import attemptLogin from "@app/components/utilities/attemptLogin";import {Badge,@@ -31,27 +33,23 @@ import { LoginMethod } from "@app/hooks/api/admin/types";import { AuthMethod } from "@app/hooks/api/users/types";import { useLastLogin } from "@app/hooks/useLastLogin";-import { useNavigateToSelectOrganization } from "../../Login.utils";+import { LoginSection, useNavigateToSelectOrganization } from "../../Login.utils";import { OrgLoginButton } from "../OrgLoginButton";import { SocialLoginButton } from "../SocialLoginButton";+const loginFormSchema = z.object({+ email: z.string().email("Please enter a valid email").min(1, "Email is required"),+ password: z.string().min(1, "Password is required")+});++type LoginFormData = z.infer<typeof loginFormSchema>;+type Props = {- setStep: (step: number) => void;- email: string;- setEmail: (email: string) => void;- password: string;- setPassword: (email: string) => void;+ setSection: (section: LoginSection) => void;isAdmin?: boolean;};-export const InitialStep = ({- setStep,- email,- setEmail,- password,- setPassword,- isAdmin-}: Props) => {+export const InitialStep = ({ setSection, isAdmin }: Props) => {const navigate = useNavigate();const { t } = useTranslation();@@ -70,6 +68,18 @@ export const InitialStep = ({const callbackPort = queryParams.get("callback_port");+ const {+ register,+ handleSubmit,+ formState: { errors }+ } = useForm<LoginFormData>({+ resolver: zodResolver(loginFormSchema),+ defaultValues: {+ email: "",+ password: ""+ }+ });+const redirectToSaml = (orgSlug: string) => {const redirectUrl = `/api/v1/sso/redirect/saml2/organizations/${orgSlug}${callbackPort ? `?callback_port=${callbackPort}` : ""@@ -96,7 +106,7 @@ export const InitialStep = ({saveLastLogin({ method: LoginMethod.SAML, orgSlug: config.defaultAuthOrgSlug });redirectToSaml(config.defaultAuthOrgSlug);} else {- setStep(2);+ setSection(LoginSection.SAML);}};@@ -105,7 +115,7 @@ export const InitialStep = ({saveLastLogin({ method: LoginMethod.OIDC, orgSlug: config.defaultAuthOrgSlug });redirectToOidc(config.defaultAuthOrgSlug);} else {- setStep(3);+ setSection(LoginSection.OIDC);}};@@ -130,83 +140,77 @@ export const InitialStep = ({const shouldDisplayLoginMethod = (method: LoginMethod) =>isAdmin || !config.enabledLoginMethods || config.enabledLoginMethods.includes(method);- const handleLogin = async (e: FormEvent<HTMLFormElement>) => {- e.preventDefault();- try {- if (!email || !password) {- return;- }-- setIsLoading(true);- if (callbackPort) {- const isCliLoginSuccessful = await attemptCliLogin({- email: email.toLowerCase(),- password,- captchaToken- });+ const handleLoginFailure = () => {+ setLoginError(true);+ const errorMessage = callbackPort+ ? "CLI login unsuccessful. Double-check your credentials and try again."+ : "Login unsuccessful. Double-check your credentials and try again.";- if (isCliLoginSuccessful && isCliLoginSuccessful.success) {- navigateToSelectOrganization(callbackPort);- } else {- setLoginError(true);- createNotification({- text: "CLI login unsuccessful. Double-check your credentials and try again.",- type: "error"- });- }- } else {- const isLoginSuccessful = await attemptLogin({- email: email.toLowerCase(),- password,- captchaToken- });-- if (isLoginSuccessful && isLoginSuccessful.success) {- saveLastLogin({ method: LoginMethod.EMAIL });- navigateToSelectOrganization(undefined, isAdmin);- createNotification({- text: "Successfully logged in",- type: "success"- });- }- }- } catch (err: any) {- console.error(err);- if (err.response.data.error === "User Locked") {- createNotification({- title: err.response.data.error,- text: err.response.data.message,- type: "error"- });- setIsLoading(false);- return;- }-- if (err.response.data.error === "Captcha Required") {- setShouldShowCaptcha(true);- setIsLoading(false);- return;- }+ createNotification({+ text: errorMessage,+ type: "error"+ });+ };- setLoginError(true);+ const handleLoginError = (err: any) => {+ const errorType = err.response?.data?.error;+ if (errorType === "User Locked") {createNotification({- text: "Login unsuccessful. Double-check your credentials and try again.",+ title: err.response.data.error,+ text: err.response.data.message,type: "error"});+ return;}- if (captchaRef.current) {- captchaRef.current.resetCaptcha();+ if (errorType === "Captcha Required") {+ setShouldShowCaptcha(true);+ return;}+ handleLoginFailure();+ };++ const resetCaptcha = () => {+ captchaRef.current?.resetCaptcha();setCaptchaToken("");- setIsLoading(false);+ };++ const handleEmailLogin = async (formData: LoginFormData) => {+ setIsLoading(true);++ try {+ const loginResult = await attemptLogin({+ email: formData.email.toLowerCase(),+ password: formData.password,+ captchaToken+ });++ const isLoginSuccessful = loginResult?.success;++ if (isLoginSuccessful) {+ saveLastLogin({ method: LoginMethod.EMAIL });+ navigateToSelectOrganization(callbackPort || undefined, isAdmin);+ createNotification({+ text: "Successfully logged in",+ type: "success"+ });+ } else {+ handleLoginFailure();+ }+ } catch (err: any) {+ console.error(err);+ handleLoginError(err);+ } finally {+ resetCaptcha();+ setIsLoading(false);+ }};if (config.defaultAuthOrgAuthEnforced && config.defaultAuthOrgAuthMethod && !isAdmin) {return (<form- onSubmit={handleLogin}+ onSubmit={handleSubmit(handleEmailLogin)}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">@@ -233,7 +237,7 @@ export const InitialStep = ({return (<form- onSubmit={handleLogin}+ onSubmit={handleSubmit(handleEmailLogin)}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">@@ -250,23 +254,22 @@ export const InitialStep = ({<><div className="w-full"><UnstableInput- value={email}- onChange={(e) => setEmail(e.target.value)}+ {...register("email")}type="email"placeholder="Enter your email..."- requiredautoComplete="username"className="h-10"/>+ {errors.email && (+ <span className="mt-1 text-xs text-red-500">{errors.email.message}</span>+ )}</div><div className="mt-2 w-full"><InputGroup className="h-10"><InputGroupInput- value={password}- onChange={(e) => setPassword(e.target.value)}+ {...register("password")}type={showPassword ? "text" : "password"}placeholder="Enter your password..."- requiredautoComplete="current-password"id="current-password"/>@@ -281,6 +284,9 @@ export const InitialStep = ({</UnstableIconButton></InputGroupAddon></InputGroup>+ {errors.password && (+ <span className="mt-1 text-xs text-red-500">{errors.password.message}</span>+ )}</div>{shouldShowCaptcha && envConfig.CAPTCHA_SITE_KEY && (<div className="mt-4 flex justify-center [&>div]:!w-full">diff --git a/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsx b/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsxdeleted file mode 100644index 938a131715..0000000000--- a/frontend/src/pages/auth/LoginPage/components/PasswordStep/PasswordStep.tsx+++ /dev/null@@ -1,381 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { useTranslation } from "react-i18next";-import HCaptcha from "@hcaptcha/react-hcaptcha";-import { Link, useNavigate } from "@tanstack/react-router";-import axios from "axios";-import { addSeconds, formatISO } from "date-fns";-import { jwtDecode } from "jwt-decode";--import { Mfa } from "@app/components/auth/Mfa";-import { createNotification } from "@app/components/notifications";-import attemptCliLogin from "@app/components/utilities/attemptCliLogin";-import attemptLogin from "@app/components/utilities/attemptLogin";-import SecurityClient from "@app/components/utilities/SecurityClient";-import { Button, ContentLoader, Input } from "@app/components/v2";-import { envConfig } from "@app/config/env";-import { SessionStorageKeys } from "@app/const";-import { useToggle } from "@app/hooks";-import { useOauthTokenExchange, useSelectOrganization } from "@app/hooks/api";-import { MfaMethod } from "@app/hooks/api/auth/types";-import { fetchOrganizations } from "@app/hooks/api/organization/queries";-import { fetchUserDuplicateAccounts } from "@app/hooks/api/users/queries";-import { EmailDuplicationConfirmation } from "@app/pages/auth/SelectOrgPage/EmailDuplicationConfirmation";--import { navigateUserToOrg, useNavigateToSelectOrganization } from "../../Login.utils";--type Props = {- providerAuthToken: string;- email: string;- password: string;- setPassword: (password: string) => void;- isAdminLogin?: boolean;-};--export const PasswordStep = ({- providerAuthToken,- email,- password,- setPassword,- isAdminLogin-}: Props) => {- const [isLoading, setIsLoading] = useState(false);- const { t } = useTranslation();- const navigate = useNavigate();- const [removeDuplicateLater, setRemoveDuplicateLater] = useState(true);- const { mutateAsync: selectOrganization } = useSelectOrganization();- const { mutateAsync: oauthTokenExchange } = useOauthTokenExchange();- const [shouldShowMfa, toggleShowMfa] = useToggle(false);- const [requiredMfaMethod, setRequiredMfaMethod] = useState(MfaMethod.EMAIL);- const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});-- const { navigateToSelectOrganization } = useNavigateToSelectOrganization();-- const { callbackPort, organizationId, hasExchangedPrivateKey } = jwtDecode(- providerAuthToken- ) as any;-- const handleExchange = async () => {- try {- setIsLoading(true);- const oauthLogin = await oauthTokenExchange({- email,- providerAuthToken- });-- if (oauthLogin.isMfaEnabled) {- SecurityClient.setMfaToken(oauthLogin.token);- if (oauthLogin.mfaMethod) {- setRequiredMfaMethod(oauthLogin.mfaMethod);- }- toggleShowMfa.on();- // After MFA verification succeeds, the Mfa component sets the real auth token.- // Navigate to org selection as the post-login step (do NOT re-call handleExchange- // which would hit the token exchange endpoint and trigger MFA again in a loop).- setMfaSuccessCallback(() => async () => {- SecurityClient.setProviderAuthToken("");- if (callbackPort) {- navigateToSelectOrganization(callbackPort, isAdminLogin);- } else {- navigateToSelectOrganization(undefined, isAdminLogin);- }- });- setIsLoading(false);- return;- }-- // unset provider auth token in case it was used- SecurityClient.setProviderAuthToken("");- // set JWT token- SecurityClient.setToken(oauthLogin.token);-- if (callbackPort) {- navigateToSelectOrganization(callbackPort, isAdminLogin);- return;- }-- if (organizationId) {- const userDuplicateAccount = await fetchUserDuplicateAccounts();- const hasDuplicate = userDuplicateAccount?.length > 1;- if (hasDuplicate) {- setRemoveDuplicateLater(false);- return;- }- }-- // case: user has orgs, so we navigate the user to select an org- const userOrgs = await fetchOrganizations();-- if (userOrgs.length > 0) {- navigateToSelectOrganization(undefined, isAdminLogin);- }- // case: no orgs found, so we navigate the user to create an org- else {- await navigateUserToOrg({ navigate });- }- } catch (err: any) {- setIsLoading(false);- console.error(err);-- if (err.response.data.error === "User Locked") {- createNotification({- title: err.response.data.error,- text: err.response.data.message,- type: "error"- });- return;- }-- createNotification({- text: "Login unsuccessful. Double-check your master password and try again.",- type: "error"- });- }- };-- useEffect(() => {- if (hasExchangedPrivateKey) {- handleExchange();- }- }, []);-- const [captchaToken, setCaptchaToken] = useState("");- const [shouldShowCaptcha, setShouldShowCaptcha] = useState(false);- const captchaRef = useRef<HCaptcha>(null);-- const handleLogin = async (e: React.FormEvent) => {- e.preventDefault();- try {- setIsLoading(true);-- if (callbackPort) {- // attemptCliLogin- const isCliLoginSuccessful = await attemptCliLogin({- email,- password,- providerAuthToken,- captchaToken- });-- if (isCliLoginSuccessful && isCliLoginSuccessful.success) {- const cliUrl = `http://127.0.0.1:${callbackPort}/`;-- // case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org- if (organizationId) {- const finishWithOrgWorkflow = async () => {- const { token, isMfaEnabled, mfaMethod } = await selectOrganization({- organizationId- });-- if (isMfaEnabled) {- SecurityClient.setMfaToken(token);- if (mfaMethod) {- setRequiredMfaMethod(mfaMethod);- }- toggleShowMfa.on();- setMfaSuccessCallback(() => finishWithOrgWorkflow);- return;- }-- console.log("organization id was present. new JWT token to be used in CLI:", token);-- const instance = axios.create();- const payload = {- ...isCliLoginSuccessful.loginResponse,- JTWToken: token- };- await instance.post(cliUrl, payload).catch(() => {- // if error happens to communicate we set the token with an expiry in sessino storage- // the cli-redirect page has logic to show this to user and ask them to paste it in terminal- sessionStorage.setItem(- SessionStorageKeys.CLI_TERMINAL_TOKEN,- JSON.stringify({- expiry: formatISO(addSeconds(new Date(), 30)),- data: window.btoa(JSON.stringify(payload))- })- );- });- navigate({ to: "/cli-redirect" });- };-- await finishWithOrgWorkflow();- return;- }-- // case: no organization ID is present -- navigate to the select org page IF the user has any orgs- // if the user has no orgs, navigate to the create org page- const userOrgs = await fetchOrganizations();-- // case: user has orgs, so we navigate the user to select an org- if (userOrgs.length > 0) {- navigateToSelectOrganization(callbackPort, isAdminLogin);- }- // case: no orgs found, so we navigate the user to create an org- else {- await navigateUserToOrg({ navigate });- }- }- } else {- const loginAttempt = await attemptLogin({- email,- password,- providerAuthToken,- captchaToken- });-- if (loginAttempt && loginAttempt.success) {- // case: login was successful- setIsLoading(false);- createNotification({- text: "Successfully logged in",- type: "success"- });-- // case: organization ID is present from the provider auth token -- navigate directly to the org- if (organizationId) {- await navigateUserToOrg({ navigate, organizationId });- }- // case: no organization ID is present -- navigate to the select org page IF the user has any orgs- // if the user has no orgs, navigate to the create org page- else {- const userOrgs = await fetchOrganizations();-- if (userOrgs.length > 0) {- navigateToSelectOrganization(undefined, isAdminLogin);- } else {- await navigateUserToOrg({ navigate });- }- }- }- }- } catch (err: any) {- setIsLoading(false);- console.error(err);-- if (err.response.data.error === "User Locked") {- createNotification({- title: err.response.data.error,- text: err.response.data.message,- type: "error"- });- return;- }-- if (err.response.data.error === "Captcha Required") {- setShouldShowCaptcha(true);- return;- }-- createNotification({- text: "Login unsuccessful. Double-check your master password and try again.",- type: "error"- });- }-- if (captchaRef.current) {- captchaRef.current.resetCaptcha();- }- setCaptchaToken("");- };-- if (shouldShowMfa) {- return (- <div className="flex max-h-screen min-h-screen flex-col items-center justify-center gap-2 overflow-y-auto bg-linear-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">- <Mfa- email={email}- successCallback={mfaSuccessCallback}- method={requiredMfaMethod}- closeMfa={() => toggleShowMfa.off()}- />- </div>- );- }-- if (!removeDuplicateLater) {- return (- <EmailDuplicationConfirmation- onRemoveDuplicateLater={() =>- navigateUserToOrg({ navigate, organizationId }).catch(() =>- createNotification({ text: "Failed to navigate user", type: "error" })- )- }- />- );- }-- if (hasExchangedPrivateKey) {- return (- <div className="fixed top-0 left-0 h-screen w-screen bg-bunker-800">- <ContentLoader />- </div>- );- }-- return (- <form onSubmit={handleLogin} className="mx-auto h-full w-full max-w-md px-6 pt-8">- <div className="mb-8">- <p className="mx-auto mb-4 flex w-max justify-center bg-linear-to-b from-white to-bunker-200 bg-clip-text text-center text-xl font-medium text-transparent">- What's your Infisical password?- </p>- </div>- <div className="relative mx-auto flex max-h-24 w-full min-w-88 items-center justify-center rounded-lg md:max-h-28 lg:w-1/6">- <div className="flex max-h-24 w-full items-center justify-center rounded-lg md:max-h-28">- <Input- value={password}- onChange={(e) => setPassword(e.target.value)}- type="password"- placeholder="Enter your password..."- isRequired- autoComplete="current-password"- id="current-password"- className="h-12"- />- </div>- </div>- {shouldShowCaptcha && envConfig.CAPTCHA_SITE_KEY && (- <div className="mx-auto mt-4 flex w-full min-w-88 items-center justify-center lg:w-1/6">- <HCaptcha- theme="dark"- sitekey={envConfig.CAPTCHA_SITE_KEY}- onVerify={(token) => setCaptchaToken(token)}- ref={captchaRef}- />- </div>- )}- <div className="mx-auto mt-4 flex w-full min-w-88 items-center justify-center rounded-md text-center lg:w-1/6">- <Button- disabled={shouldShowCaptcha && captchaToken === ""}- type="submit"- colorSchema="primary"- variant="outline_bg"- isFullWidth- isLoading={isLoading}- className="h-14"- >- {t("login.login")}- </Button>- </div>- <div className="mx-auto mt-4 flex w-max flex-col items-center text-xs text-bunker-400">- <span className="max-w-sm px-4 text-center duration-200">- Infisical Master Password serves as a decryption mechanism so that even Google is not able- to access your secrets.- </span>- <Link to="/account-recovery">- <span className="mt-2 cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">- {t("login.forgot-password")}- </span>- </Link>- </div>- <div className="flex flex-row items-center justify-center">- <button- onClick={() => {- navigate({ to: "/login" });- }}- type="button"- className="mt-2 cursor-pointer text-xs text-bunker-400 duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4"- >- {t("login.other-option")}- </button>- </div>- </form>- );-};diff --git a/frontend/src/pages/auth/LoginPage/components/PasswordStep/index.tsx b/frontend/src/pages/auth/LoginPage/components/PasswordStep/index.tsxdeleted file mode 100644index e2d3993e4e..0000000000--- a/frontend/src/pages/auth/LoginPage/components/PasswordStep/index.tsx+++ /dev/null@@ -1 +0,0 @@-export { PasswordStep } from "./PasswordStep";diff --git a/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx b/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsxindex 7d9c1683bd..64a4601201 100644--- a/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx+++ b/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx@@ -12,12 +12,14 @@ import {import { LoginMethod } from "@app/hooks/api/admin/types";import { useLastLogin } from "@app/hooks/useLastLogin";+import { LoginSection } from "../../Login.utils";+type Props = {- setStep: (step: number) => void;+ setSection: (section: LoginSection) => void;type: "SAML" | "OIDC";};-export const SSOStep = ({ setStep, type }: Props) => {+export const SSOStep = ({ setSection, type }: Props) => {const { lastLogin, saveLastLogin } = useLastLogin();const { t } = useTranslation();@@ -76,7 +78,7 @@ export const SSOStep = ({ setStep, type }: Props) => {</Button></div><div className="mt-6 flex flex-row justify-center text-xs text-muted">- <button onClick={() => setStep(0)} type="button">+ <button onClick={() => setSection(LoginSection.Initial)} type="button"><span className="cursor-pointer duration-200 hover:text-label hover:underline hover:decoration-project/45 hover:underline-offset-2">{t("login.other-option")}</span>diff --git a/frontend/src/pages/auth/LoginPage/components/index.tsx b/frontend/src/pages/auth/LoginPage/components/index.tsxindex 84ad4f73da..7aeb255156 100644--- a/frontend/src/pages/auth/LoginPage/components/index.tsx+++ b/frontend/src/pages/auth/LoginPage/components/index.tsx@@ -1,5 +1,2 @@export { InitialStep } from "./InitialStep";export { SSOStep } from "./SSOStep";--// SSO-specific step-export { PasswordStep } from "./PasswordStep";diff --git a/frontend/src/pages/auth/LoginSsoPage/LoginSsoPage.tsx b/frontend/src/pages/auth/LoginSsoPage/LoginSsoPage.tsxdeleted file mode 100644index b66ebe9e4a..0000000000--- a/frontend/src/pages/auth/LoginSsoPage/LoginSsoPage.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { useEffect, useState } from "react";-import { Helmet } from "react-helmet";-import { useTranslation } from "react-i18next";-import { Link, useSearch } from "@tanstack/react-router";-import { jwtDecode } from "jwt-decode";--import { ROUTE_PATHS } from "@app/const/routes";--import { PasswordStep } from "../LoginPage/components";--export const LoginSsoPage = () => {- const { t } = useTranslation();- const search = useSearch({ from: ROUTE_PATHS.Auth.LoginSSO.id });- const token = search.token as string;- const [step, setStep] = useState(0);- const [password, setPassword] = useState("");-- const { username, isUserCompleted } = jwtDecode(token) as any;-- useEffect(() => {- if (isUserCompleted) {- setStep(1);- }- }, []);-- const renderView = () => {- switch (step) {- case 0:- return <div />;- case 1:- return (- <PasswordStep- providerAuthToken={token}- email={username}- password={password}- setPassword={setPassword}- isAdminLogin={search.isAdminLogin}- />- );- default:- return <div />;- }- };-- return (- <div className="flex h-screen flex-col justify-center bg-linear-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700 px-6 pb-28">- <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>- <Link to="/">- <div className="mt-20 mb-4 flex justify-center">- <img- src="/images/gradientLogo.svg"- style={{ height: "90px", width: "120px" }}- alt="Infisical logo"- />- </div>- </Link>- <div>{renderView()}</div>- </div>- );-};diff --git a/frontend/src/pages/auth/LoginSsoPage/route.tsx b/frontend/src/pages/auth/LoginSsoPage/route.tsxdeleted file mode 100644index f66925b935..0000000000--- a/frontend/src/pages/auth/LoginSsoPage/route.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";-import { zodValidator } from "@tanstack/zod-adapter";-import { z } from "zod";--import { LoginSsoPage } from "./LoginSsoPage";--const LoginSSOQueryParamsSchema = z.object({- token: z.string(),- isAdminLogin: z.boolean().optional().catch(false)-});--export const Route = createFileRoute("/_restrict-login-signup/login/sso")({- component: LoginSsoPage,- validateSearch: zodValidator(LoginSSOQueryParamsSchema)-});diff --git a/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx b/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsxindex 96012e433d..098a97883c 100644--- a/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx+++ b/frontend/src/pages/auth/SignUpInvitePage/SignUpInvitePage.tsx@@ -1,292 +1,10 @@-import { useState } from "react";-import { Helmet } from "react-helmet";-import { faXmark } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { Link, useNavigate, useSearch } from "@tanstack/react-router";-import { AxiosError } from "axios";+import { useSearch } from "@tanstack/react-router";-import { Mfa } from "@app/components/auth/Mfa";-import InputField from "@app/components/basic/InputField";-import checkPassword from "@app/components/utilities/checks/password/checkPassword";-import SecurityClient from "@app/components/utilities/SecurityClient";-import { Button } from "@app/components/v2";-import { useToggle } from "@app/hooks";-import {- completeAccountSignupInvite,- useSelectOrganization,- verifySignupInvite-} from "@app/hooks/api/auth/queries";-import { MfaMethod } from "@app/hooks/api/auth/types";-import { fetchOrganizations } from "@app/hooks/api/organization/queries";-import { isLoggedIn } from "@app/hooks/api/reactQuery";--type Errors = {- tooShort?: string;- tooLong?: string;- noLetterChar?: string;- noNumOrSpecialChar?: string;- repeatedChar?: string;- escapeChar?: string;- lowEntropy?: string;- breached?: string;-};+import { SignUpPage } from "../SignUpPage/SignUpPage";export const SignupInvitePage = () => {- const [password, setPassword] = useState("");- const [firstName, setFirstName] = useState("");- const [lastName, setLastName] = useState("");- const [firstNameError, setFirstNameError] = useState(false);- const [lastNameError, setLastNameError] = useState(false);- const [isLoading, setIsLoading] = useState(false);- const [step, setStep] = useState(1);- const [errors, setErrors] = useState<Errors>({});-- const [shouldShowMfa, toggleShowMfa] = useToggle(false);- const [requiredMfaMethod, setRequiredMfaMethod] = useState(MfaMethod.EMAIL);- const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});- const navigate = useNavigate();const search = useSearch({ from: "/_restrict-login-signup/signupinvite" });- const parsedUrl = search;- const token = parsedUrl.token as string;- const organizationId = parsedUrl.organization_id as string;- const email = (parsedUrl.to as string)?.replace(" ", "+").trim();-- const queryParams = new URLSearchParams(window.location.search);-- const metadata = queryParams.get("metadata") || undefined;-- const { mutateAsync: selectOrganization } = useSelectOrganization();-- const loggedIn = isLoggedIn();-- // Verifies if the information that the users entered (name, workspace) is there, and if the password matched the criteria.- const signupErrorCheck = async () => {- setIsLoading(true);-- let errorCheck = await checkPassword({- password,- setErrors- });-- if (!firstName) {- setFirstNameError(true);- errorCheck = true;- } else {- setFirstNameError(false);- }- if (!lastName) {- setLastNameError(true);- errorCheck = true;- } else {- setLastNameError(false);- }-- if (!errorCheck) {- try {- const { token: jwtToken } = await completeAccountSignupInvite({- email,- password,- firstName,- lastName,- tokenMetadata: metadata- });-- // unset temporary signup JWT token and set JWT token- SecurityClient.setSignupToken("");- SecurityClient.setToken(jwtToken);-- const userOrgs = await fetchOrganizations();-- const orgId = userOrgs[0].id;-- if (!orgId) throw new Error("You are not part of any organization");-- const completeSignupFlow = async () => {- const {- token: mfaToken,- isMfaEnabled,- mfaMethod- } = await selectOrganization({- organizationId: orgId- });-- if (isMfaEnabled) {- SecurityClient.setMfaToken(mfaToken);- if (mfaMethod) {- setRequiredMfaMethod(mfaMethod);- }- toggleShowMfa.on();- setMfaSuccessCallback(() => completeSignupFlow);- return;- }-- localStorage.setItem("orgData.id", orgId);-- navigate({- to: "/organizations/$orgId/projects",- params: { orgId }- });- };-- await completeSignupFlow();- } catch (error) {- setIsLoading(false);- console.error(error);- }- } else {- setIsLoading(false);- }- };-- // Step 4 of the sign up process (download the emergency kit pdf)- const stepConfirmEmail = (- <div className="mx-1 mt-14 mb-36 flex w-full max-w-xs flex-col items-center rounded-xl border border-mineshaft-600 bg-mineshaft-800 px-4 py-8 drop-shadow-xl md:mb-16 md:max-w-lg md:px-6">- <p className="mb-2 flex justify-center text-center text-4xl font-medium text-primary-100">- Confirm your email- </p>- <div className="mx-auto mt-4 mb-2 flex max-h-24 max-w-md flex-col items-center justify-center px-4 text-lg md:p-2">- <Button- onClick={async () => {- try {- const response = await verifySignupInvite({- email,- code: token,- organizationId- });-- if (response) {- // user will have temp token if doesn't have an account- // then continue with account setup workflow- if (response?.token) {- SecurityClient.setSignupToken(response.token);- setStep(2);- } else if (loggedIn) {- navigate({ to: "/login/select-organization", search: { force: true } });- } else {- navigate({ to: "/login" });- }- }- } catch (err) {- console.error(err);- const message = ((err as AxiosError)?.response?.data as { message?: string })- ?.message;- const reason = message?.includes("already a member") ? "already_member" : "expired";- navigate({ to: "/requestnewinvite", search: { reason } });- }- }}- size="lg"- >- Confirm Email- </Button>- </div>- </div>- );-- // Because this is the invite signup - we directly go to the last step of signup (email is already verified)- const main = (- <div className="mx-auto mt-14 mb-32 w-max rounded-xl border border-mineshaft-600 bg-mineshaft-800 px-8 py-10 drop-shadow-xl md:mb-16">- <p className="mx-8 mb-6 flex justify-center bg-linear-to-tr from-mineshaft-300 to-white bg-clip-text text-4xl font-bold text-transparent md:mx-16">- Almost there!- </p>- <div className="relative z-0 flex max-h-24 w-full items-center justify-end rounded-lg md:p-2">- <InputField- label="First Name"- onChangeHandler={setFirstName}- type="name"- value={firstName}- isRequired- errorText="Please input your first name."- error={firstNameError}- autoComplete="given-name"- />- </div>- <div className="flex max-h-24 w-full items-center justify-center rounded-lg md:p-2">- <InputField- label="Last Name"- onChangeHandler={setLastName}- type="name"- value={lastName}- isRequired- errorText="Please input your last name."- error={lastNameError}- autoComplete="family-name"- />- </div>- <div className="mt-2 flex max-h-60 w-full flex-col items-center justify-center rounded-lg md:p-2">- <InputField- label="Password"- onChangeHandler={(pass) => {- setPassword(pass);- checkPassword({- password: pass,- setErrors- });- }}- type="password"- value={password}- isRequired- error={Object.keys(errors).length > 0}- autoComplete="new-password"- id="new-password"- />- {Object.keys(errors).length > 0 && (- <div className="mt-4 flex w-full flex-col items-start rounded-md bg-white/5 px-2 py-2">- <div className="mb-2 text-sm text-gray-400">Password should contain at least:</div>- {Object.keys(errors).map((key) => {- if (errors[key as keyof Errors]) {- return (- <div className="items-top ml-1 flex flex-row justify-start" key={key}>- <div>- <FontAwesomeIcon icon={faXmark} className="text-md mr-2.5 ml-0.5 text-red" />- </div>- <p className="text-sm text-gray-400">{errors[key as keyof Errors]}</p>- </div>- );- }-- return null;- })}- </div>- )}- </div>- <div className="mx-auto mt-2 flex max-h-24 max-w-max flex-col items-center justify-center px-2 py-3 text-lg md:px-4 md:py-5">- <Button- onClick={() => {- signupErrorCheck();- }}- isLoading={isLoading}- size="lg"- >- Sign Up- </Button>- </div>- </div>- );+ const email = (search.to as string)?.replace(" ", "+").trim();- return (- <div className="flex h-screen flex-col items-center justify-center bg-linear-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">- <Helmet>- <title>Sign Up</title>- <link rel="icon" href="/infisical.ico" />- </Helmet>- {shouldShowMfa ? (- <Mfa- email={email}- successCallback={mfaSuccessCallback}- method={requiredMfaMethod}- closeMfa={() => toggleShowMfa.off()}- />- ) : (- <>- <Link to="/">- <div className="mt-20 mb-4 flex justify-center">- <img src="/images/gradientLogo.svg" height={90} width={120} alt="Infisical Logo" />- </div>- </Link>- {step === 1 && stepConfirmEmail}- {step === 2 && main}- </>- )}- </div>- );+ return <SignUpPage invite={{ email }} />;};diff --git a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsxindex bda7211757..c1fdbec83e 100644--- a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx+++ b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx@@ -1,4 +1,3 @@-/* eslint-disable no-nested-ternary */import { useEffect, useState } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";@@ -11,115 +10,101 @@ import CodeInputStep from "@app/components/auth/CodeInputStep";import InitialSignupStep from "@app/components/auth/InitialSignupStep";import TeamInviteStep from "@app/components/auth/TeamInviteStep";import UserInfoStep from "@app/components/auth/UserInfoStep";-import SecurityClient from "@app/components/utilities/SecurityClient";import { Button } from "@app/components/v3";import { useServerConfig } from "@app/context";-import { useVerifySignupEmailVerificationCode } from "@app/hooks/api";+import { useSelectOrganization } from "@app/hooks/api/auth/queries";+import { fetchOrganizations } from "@app/hooks/api/organization/queries";import { useFetchServerStatus } from "@app/hooks/api/serverDetails";+import { createNotification } from "@app/components/notifications";-export const SignUpPage = () => {- const [email, setEmail] = useState("");- const [password, setPassword] = useState("");- const [name, setName] = useState("");- const [organizationName, setOrganizationName] = useState("");- const [attributionSource, setAttributionSource] = useState("");- const [code, setCode] = useState("123456");- const [codeError, setCodeError] = useState(false);- const [step, setStep] = useState(1);+enum SignupSection {+ Email = "email",+ VerifyCode = "verify-code",+ UserInfo = "user-info",+ InviteTeam = "invite-team"+}++export interface SignUpPageProps {+ invite?: {+ email: string;+ };+}++export const SignUpPage = ({ invite }: SignUpPageProps) => {+ const isInvite = Boolean(invite);+ const [email, setEmail] = useState(invite?.email ?? "");+ const [section, setSection] = useState<SignupSection>(+ isInvite ? SignupSection.UserInfo : SignupSection.Email+ );const navigate = useNavigate();const { data: serverDetails } = useFetchServerStatus();- const [isCodeInputCheckLoading, setIsCodeInputCheckLoading] = useState(false);const { t } = useTranslation();- const { mutateAsync } = useVerifySignupEmailVerificationCode();const { config } = useServerConfig();+ const { mutateAsync: selectOrganization } = useSelectOrganization();useEffect(() => {- if (!config.allowSignUp) {+ if (!isInvite && !config.allowSignUp) {+ createNotification({+ text: "Sign up is disabled"+ });navigate({ to: "/login" });}}, [config.allowSignUp]);- /**- * Goes to the following step (out of 5) of the signup process.- * Step 1 is submitting your email- * Step 2 is Verifying your email with the code that you received- * Step 3 is asking the final info.- * Step 4 is downloading a backup pdf- * Step 5 is inviting users- */- const incrementStep = async () => {- if (step === 1 || step === 3 || step === 4) {- setStep(step + 1);- } else if (step === 2) {- setIsCodeInputCheckLoading(true);- // Checking if the code matches the email.- try {- const { token } = await mutateAsync({ email, code });- SecurityClient.setSignupToken(token);- setStep(3);- } catch (err) {- console.error(err);- setCodeError(true);- }- setIsCodeInputCheckLoading(false);+ const handleEmailComplete = () => {+ if (serverDetails?.emailConfigured) {+ setSection(SignupSection.VerifyCode);+ } else {+ setSection(SignupSection.UserInfo);}};- // when email service is not configured, skip step 2 and 5- useEffect(() => {- (async () => {- if (!serverDetails?.emailConfigured && step === 2) {- incrementStep();- }+ const handleCodeVerified = () => {+ setSection(SignupSection.UserInfo);+ };- if (!serverDetails?.emailConfigured && step === 4) {+ const handleUserInfoComplete = async () => {+ if (isInvite) {+ const userOrgs = await fetchOrganizations();+ const orgId = userOrgs[0]?.id;++ if (orgId) {+ await selectOrganization({ organizationId: orgId });navigate({- to: "/"+ to: "/organizations/$orgId/projects",+ params: { orgId }});+ } else {+ navigate({ to: "/login" });}- })();- }, [step]);-- const renderView = (registerStep: number) => {- if (registerStep === 1) {- return <InitialSignupStep email={email} setEmail={setEmail} incrementStep={incrementStep} />;- }-- if (registerStep === 2) {- return (- <CodeInputStep- email={email}- incrementStep={incrementStep}- setCode={setCode}- codeError={codeError}- isCodeInputCheckLoading={isCodeInputCheckLoading}- />- );- }-- if (registerStep === 3) {- return (- <UserInfoStep- incrementStep={incrementStep}- email={email}- password={password}- setPassword={setPassword}- name={name}- setName={setName}- organizationName={organizationName}- setOrganizationName={setOrganizationName}- attributionSource={attributionSource}- setAttributionSource={setAttributionSource}- providerAuthToken={undefined}- />- );+ } else if (serverDetails?.emailConfigured) {+ setSection(SignupSection.InviteTeam);+ } else {+ navigate({ to: "/" });}+ };- if (serverDetails?.emailConfigured) {- return <TeamInviteStep />;+ const renderView = () => {+ switch (section) {+ case SignupSection.Email:+ return (+ <InitialSignupStep+ email={email}+ setEmail={setEmail}+ incrementStep={handleEmailComplete}+ />+ );+ case SignupSection.VerifyCode:+ return <CodeInputStep email={email} onComplete={handleCodeVerified} />;+ case SignupSection.UserInfo:+ return (+ <UserInfoStep onComplete={handleUserInfoComplete} email={email} isInvite={isInvite} />+ );+ case SignupSection.InviteTeam:+ return <TeamInviteStep />;+ default:+ return null;}-- return "";};return (@@ -139,7 +124,7 @@ export const SignUpPage = () => {</AuthPageHeader><div className="relative z-10 my-auto flex flex-col items-center py-10"><form className="w-full" onSubmit={(e) => e.preventDefault()}>- {renderView(step)}+ {renderView()}</form></div><AuthPageFooter />diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsxindex 1dd6208911..f490c3efa2 100644--- a/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx+++ b/frontend/src/pages/auth/SignUpSsoPage/components/UserInfoSSOStep/UserInfoSSOStep.tsx@@ -39,7 +39,6 @@ export const UserInfoSSOStep = ({providerOrganizationName,password,setPassword,- providerAuthToken,forceDefaultOrg}: Props) => {const [nameError, setNameError] = useState(false);@@ -87,10 +86,8 @@ export const UserInfoSSOStep = ({password,firstName: name.split(" ")[0],lastName: name.split(" ").slice(1).join(" "),- providerAuthToken,organizationName,- attributionSource,- useDefaultOrg: forceDefaultOrg+ attributionSource});// unset signup JWT token and set JWT tokendiff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex 814bb0af3b..0930ae8cdf 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -31,7 +31,6 @@ import { Route as organizationLayoutImport } from './pages/organization/layout'import { Route as publicViewSharedSecretByIDPageRouteImport } from './pages/public/ViewSharedSecretByIDPage/route'import { Route as publicViewSecretRequestByIDPageRouteImport } from './pages/public/ViewSecretRequestByIDPage/route'import { Route as authSignUpSsoPageRouteImport } from './pages/auth/SignUpSsoPage/route'-import { Route as authLoginSsoPageRouteImport } from './pages/auth/LoginSsoPage/route'import { Route as authSelectOrgPageRouteImport } from './pages/auth/SelectOrgPage/route'import { Route as authLoginLdapPageRouteImport } from './pages/auth/LoginLdapPage/route'import { Route as authAdminLoginPageRouteImport } from './pages/auth/AdminLoginPage/route'@@ -531,12 +530,6 @@ const authSignUpSsoPageRouteRoute = authSignUpSsoPageRouteImport.update({getParentRoute: () => RestrictLoginSignupSignupRoute,} as any)-const authLoginSsoPageRouteRoute = authLoginSsoPageRouteImport.update({- id: '/sso',- path: '/sso',- getParentRoute: () => RestrictLoginSignupLoginRoute,-} as any)-const authSelectOrgPageRouteRoute = authSelectOrgPageRouteImport.update({id: '/select-organization',path: '/select-organization',@@ -2681,13 +2674,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof authSelectOrgPageRouteImportparentRoute: typeof RestrictLoginSignupLoginImport}- '/_restrict-login-signup/login/sso': {- id: '/_restrict-login-signup/login/sso'- path: '/sso'- fullPath: '/login/sso'- preLoaderRoute: typeof authLoginSsoPageRouteImport- parentRoute: typeof RestrictLoginSignupLoginImport- }'/_restrict-login-signup/signup/sso': {id: '/_restrict-login-signup/signup/sso'path: '/sso'@@ -5664,7 +5650,6 @@ interface RestrictLoginSignupLoginRouteChildren {authAdminLoginPageRouteRoute: typeof authAdminLoginPageRouteRouteauthLoginLdapPageRouteRoute: typeof authLoginLdapPageRouteRouteauthSelectOrgPageRouteRoute: typeof authSelectOrgPageRouteRoute- authLoginSsoPageRouteRoute: typeof authLoginSsoPageRouteRouteauthProviderErrorPageRouteRoute: typeof authProviderErrorPageRouteRouteauthProviderSuccessPageRouteRoute: typeof authProviderSuccessPageRouteRoute}@@ -5675,7 +5660,6 @@ const RestrictLoginSignupLoginRouteChildren: RestrictLoginSignupLoginRouteChildrauthAdminLoginPageRouteRoute: authAdminLoginPageRouteRoute,authLoginLdapPageRouteRoute: authLoginLdapPageRouteRoute,authSelectOrgPageRouteRoute: authSelectOrgPageRouteRoute,- authLoginSsoPageRouteRoute: authLoginSsoPageRouteRoute,authProviderErrorPageRouteRoute: authProviderErrorPageRouteRoute,authProviderSuccessPageRouteRoute: authProviderSuccessPageRouteRoute,}@@ -5755,7 +5739,6 @@ export interface FileRoutesByFullPath {'/login/admin': typeof authAdminLoginPageRouteRoute'/login/ldap': typeof authLoginLdapPageRouteRoute'/login/select-organization': typeof authSelectOrgPageRouteRoute- '/login/sso': typeof authLoginSsoPageRouteRoute'/signup/sso': typeof authSignUpSsoPageRouteRoute'/secret-request/secret/$secretRequestId': typeof publicViewSecretRequestByIDPageRouteRoute'/shared/secret/$secretId': typeof publicViewSharedSecretByIDPageRouteRoute@@ -6025,7 +6008,6 @@ export interface FileRoutesByTo {'/login/admin': typeof authAdminLoginPageRouteRoute'/login/ldap': typeof authLoginLdapPageRouteRoute'/login/select-organization': typeof authSelectOrgPageRouteRoute- '/login/sso': typeof authLoginSsoPageRouteRoute'/signup/sso': typeof authSignUpSsoPageRouteRoute'/secret-request/secret/$secretRequestId': typeof publicViewSecretRequestByIDPageRouteRoute'/shared/secret/$secretId': typeof publicViewSharedSecretByIDPageRouteRoute@@ -6281,7 +6263,6 @@ export interface FileRoutesById {'/_restrict-login-signup/login/admin': typeof authAdminLoginPageRouteRoute'/_restrict-login-signup/login/ldap': typeof authLoginLdapPageRouteRoute'/_restrict-login-signup/login/select-organization': typeof authSelectOrgPageRouteRoute- '/_restrict-login-signup/login/sso': typeof authLoginSsoPageRouteRoute'/_restrict-login-signup/signup/sso': typeof authSignUpSsoPageRouteRoute'/secret-request/secret/$secretRequestId': typeof publicViewSecretRequestByIDPageRouteRoute'/shared/secret/$secretId': typeof publicViewSharedSecretByIDPageRouteRoute@@ -6565,7 +6546,6 @@ export interface FileRouteTypes {| '/login/admin'| '/login/ldap'| '/login/select-organization'- | '/login/sso'| '/signup/sso'| '/secret-request/secret/$secretRequestId'| '/shared/secret/$secretId'@@ -6834,7 +6814,6 @@ export interface FileRouteTypes {| '/login/admin'| '/login/ldap'| '/login/select-organization'- | '/login/sso'| '/signup/sso'| '/secret-request/secret/$secretRequestId'| '/shared/secret/$secretId'@@ -7088,7 +7067,6 @@ export interface FileRouteTypes {| '/_restrict-login-signup/login/admin'| '/_restrict-login-signup/login/ldap'| '/_restrict-login-signup/login/select-organization'- | '/_restrict-login-signup/login/sso'| '/_restrict-login-signup/signup/sso'| '/secret-request/secret/$secretRequestId'| '/shared/secret/$secretId'@@ -7476,7 +7454,6 @@ export const routeTree = rootRoute"/_restrict-login-signup/login/admin","/_restrict-login-signup/login/ldap","/_restrict-login-signup/login/select-organization",- "/_restrict-login-signup/login/sso","/_restrict-login-signup/login/provider/error","/_restrict-login-signup/login/provider/success"]@@ -7525,10 +7502,6 @@ export const routeTree = rootRoute"filePath": "auth/SelectOrgPage/route.tsx","parent": "/_restrict-login-signup/login"},- "/_restrict-login-signup/login/sso": {- "filePath": "auth/LoginSsoPage/route.tsx",- "parent": "/_restrict-login-signup/login"- },"/_restrict-login-signup/signup/sso": {"filePath": "auth/SignUpSsoPage/route.tsx","parent": "/_restrict-login-signup/signup"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 4d75233a96..d7c95e53d8 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -451,7 +451,6 @@ export const routes = rootRoute("root.tsx", [index("auth/LoginPage/route.tsx"),route("/admin", "auth/AdminLoginPage/route.tsx"),route("/select-organization", "auth/SelectOrgPage/route.tsx"),- route("/sso", "auth/LoginSsoPage/route.tsx"),route("/ldap", "auth/LoginLdapPage/route.tsx"),route("/provider/success", "auth/ProviderSuccessPage/route.tsx"),route("/provider/error", "auth/ProviderErrorPage/route.tsx")