@burdenoff/microfe-auth 2026.1101.3 → 2026.1102.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/pages/LoginPage.js +250 -239
- package/dist/auth/pages/LoginPage.js.map +1 -1
- package/dist/auth/utils/redirect.d.ts +7 -0
- package/dist/auth/utils/redirect.js +14 -2
- package/dist/auth/utils/redirect.js.map +1 -1
- package/dist/auth/utils/validation.js +5 -5
- package/dist/auth/utils/validation.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LoginPage.js","names":["_Fragment","isNativeShell","w","toSameOriginPath","target","url","hasValidAccessToken","raw","token","padded","payload","decodeSameOriginReturnTo","returnTo","stripStaleSsoParams","param","options","search","cleanReturnToValue","LoginPage","tr","useTr","navigate","useNavigate","location","useLocation","searchParams","useSearchParams","useAuthOperations","useMyWorkspaces","useActiveContext","useAuth","useOAuthOperations","mfaRequired","useAuthStore","state","executeCaptchaV3","useCaptchaV3","isCompletingAuth","setIsCompletingAuth","useState","isSsoRedirecting","setIsSsoRedirecting","buildPostLoginUrl","useCallback","intendedPath","bridge","resolveAuthBridgeConfig","bridgeUrl","currentOrigin","absoluteIntended","profileId","resolveActiveProfileId","tokens","getProfileTokens","user","getProfileUser","workspaceToken","getProfileWorkspaceToken","depositTokens","resolveGatewayUrls","minted","mintSsoSessionTokens","globalBaseUrl","markSsoDepositPending","buildSsoDepositUrl","getProfiles","redirectInitiatedRef","useRef","redirectAfterLogin","safePath","sanitizePostLoginPath","path","resolve","beginSsoNavigation","showPassword","setShowPassword","isAccountInactive","setIsAccountInactive","isAccountDeleted","setIsAccountDeleted","isAccountSuspended","setIsAccountSuspended","isOAuthOnlyAccount","setIsOAuthOnlyAccount","isEmailNotVerified","setIsEmailNotVerified","isResendingVerification","setIsResendingVerification","resendSuccess","setResendSuccess","oauthError","setOauthError","infoMessage","setInfoMessage","formData","setFormData","validationError","setValidationError","isDuplicateAccount","setIsDuplicateAccount","isAddAccountMode","initialReturnToRef","reasonParam","useEffect","isSsoNavigationPending","ssoUrl","getSSORedirectUrl","rememberedEmail","prev","error","checkErrorType","code","err","lowerErr","emailFromUrl","newUrl","handleSubmit","emailTrimmed","p","recaptchaToken","result","signIn","postMfaPath","defaultPostLoginPath","MFA_REDIRECT","domain","domainPart","securePart","ssoValue","postLoginPath","authFlowResult","completeAuthFlow","setWorkspace","setOrganization","authFlowError","errorMsg","storeErrorCode","errorType","errorCode","handleGoogleLogin","handleMicrosoftLogin","handleResendVerification","resendVerification","isGoogleConfigured","isProviderConfigured","isMicrosoftConfigured","oauthProviders","GoogleIcon","MicrosoftIcon","SSORedirectSpinner","AuthLayout","PagePurpose","AlertIcon","Fragment","SpinnerIcon","EmailIcon","LockIcon","jsx","EyeOffIcon","EyeIcon","Checkbox","isChecked","checked","Button","isLoading","provider"],"sources":["../../../src/auth/pages/LoginPage.tsx"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from \"react\";\nimport { useNavigate, useSearchParams, useLocation } from \"react-router\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell\";\nimport { useTr } from \"../../shared/hooks/useTr\";\nimport {\n getSSORedirectUrl,\n SSORedirectSpinner,\n} from \"@burdenoff/fe-libs/shared/components\";\nimport { resolveAuthBridgeConfig } from \"@burdenoff/fe-libs/shared/config\";\nimport { resolveGatewayUrls } from \"@burdenoff/fe-libs/shared/config/gatewayUrls\";\nimport {\n beginSsoNavigation,\n buildSsoDepositUrl,\n isSsoNavigationPending,\n markSsoDepositPending,\n mintSsoSessionTokens,\n} from \"@burdenoff/fe-libs/shared/utils\";\nimport { Button } from \"@burdenoff/fe-libs/button\";\nimport { Checkbox, PagePurpose } from \"@burdenoff/fe-libs/ui\";\n\nimport {\n getProfileTokens,\n getProfileUser,\n getProfiles,\n getProfileWorkspaceToken,\n resolveActiveProfileId,\n} from \"@burdenoff/fe-libs/shared/providers/shell/ProfileStorageManager\";\nimport { useAuthOperations } from \"../hooks/useAuthOperations\";\nimport { useMyWorkspaces } from \"../hooks/useMyWorkspaces\";\nimport { useOAuthOperations } from \"../hooks/useOAuthOperations\";\nimport { sanitizePostLoginPath } from \"../utils/redirect\";\nimport { useAuthStore } from \"../store/authStore\";\nimport { useAuth } from \"../providers/AuthProvider\";\nimport { AuthLayout } from \"../components/AuthLayout\";\nimport {\n EmailIcon,\n LockIcon,\n EyeIcon,\n EyeOffIcon,\n AlertIcon,\n SpinnerIcon,\n GoogleIcon,\n // GitHubIcon,\n MicrosoftIcon,\n} from \"../components/AuthIcons\";\nimport { useCaptchaV3 } from \"../hooks/useCaptchaV3\";\nimport { MFA_REDIRECT } from \"../constants/sessionKeys\";\nimport type { SignInInput } from \"../types\";\n\n/**\n * Detect whether the bundle is running inside a native shell (Capacitor on\n * iOS/Android, or Electron). Cross-origin SSO deposit/relay detours only make\n * sense in a multi-origin web context — in a native shell there is one product\n * origin, tokens already live in localStorage, and `window.location.assign` to\n * an external https URL escapes the embedded webview.\n *\n * Detection is runtime-only and avoids importing any platform-specific module\n * so this stays valid when microfe-auth is consumed by a pure web shell too.\n */\nfunction isNativeShell(): boolean {\n if (typeof window === \"undefined\") return false;\n const w = window as typeof window & {\n Capacitor?: { isNativePlatform?: () => boolean };\n };\n if (typeof w.Capacitor?.isNativePlatform === \"function\") {\n try {\n if (w.Capacitor.isNativePlatform()) return true;\n } catch {\n /* fall through */\n }\n }\n if (\n typeof navigator !== \"undefined\" &&\n /Electron/i.test(navigator.userAgent || \"\")\n ) {\n return true;\n }\n return false;\n}\n\nfunction toSameOriginPath(target: string): string {\n if (typeof window === \"undefined\") return target;\n try {\n const url = new URL(target, window.location.origin);\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return target;\n }\n}\n\nfunction hasValidAccessToken(token: string): boolean {\n try {\n const raw = token.split(\".\")[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = raw.padEnd(Math.ceil(raw.length / 4) * 4, \"=\");\n const payload = JSON.parse(atob(padded)) as { exp?: unknown };\n return typeof payload.exp === \"number\" && payload.exp > Date.now() / 1000;\n } catch {\n return false;\n }\n}\n\nfunction decodeSameOriginReturnTo(returnTo: string | null): string | null {\n if (!returnTo) return null;\n try {\n const decoded = decodeURIComponent(returnTo);\n const url = new URL(decoded, window.location.origin);\n if (url.origin !== window.location.origin) return null;\n return stripStaleSsoParams(url, { includeOrigin: false });\n } catch {\n return null;\n }\n}\n\nfunction stripStaleSsoParams(\n url: URL,\n options: { includeOrigin: boolean },\n): string {\n for (const param of [\"sso_failed\", \"sso-failed\", \"sso-attempted\"] as const) {\n url.searchParams.delete(param);\n }\n\n if (options.includeOrigin) {\n return url.toString();\n }\n\n const search = url.searchParams.toString();\n return `${url.pathname}${search ? `?${search}` : \"\"}${url.hash}`;\n}\n\nfunction cleanReturnToValue(returnTo: string): string {\n try {\n const decoded = decodeURIComponent(returnTo);\n const url = new URL(decoded, window.location.origin);\n // Preserve cross-origin absolute returnTo values (e.g., redirects back to\n // another product's app shell) — only strip stale SSO params.\n const isCrossOrigin = url.origin !== window.location.origin;\n return stripStaleSsoParams(url, { includeOrigin: isCrossOrigin });\n } catch {\n return returnTo;\n }\n}\n\n/**\n * Login page with professional design\n * Provides email/password login and social OAuth options\n */\nexport function LoginPage() {\n const tr = useTr();\n const navigate = useNavigate();\n const location = useLocation();\n const [searchParams] = useSearchParams();\n\n const { signIn, isLoading, error, errorCode, resendVerification } =\n useAuthOperations();\n const { completeAuthFlow } = useMyWorkspaces();\n const { setWorkspace, setOrganization } = useActiveContext();\n const { defaultPostLoginPath } = useAuth();\n const { initiateGoogleOAuth, initiateMicrosoftOAuth, isProviderConfigured } =\n useOAuthOperations();\n const mfaRequired = useAuthStore((state) => state.mfaRequired);\n const { executeRecaptcha: executeCaptchaV3 } = useCaptchaV3();\n const [isCompletingAuth, setIsCompletingAuth] = useState(false);\n const [isSsoRedirecting, setIsSsoRedirecting] = useState(false);\n\n /**\n * Build the URL that should receive the post-login redirect.\n *\n * For cross-eTLD+1 SSO on alpha/prod we detour through the central bridge\n * host (alphaapp/app.burdenoff.com) so the freshly-issued tokens land in\n * the bridge origin's first-party (unpartitioned) localStorage. Without\n * this step, a later direct visit to the bridge host has no local tokens\n * and no shared cookie (cross-eTLD+1 cookies don't propagate), so the user\n * sees the login page again.\n *\n * Skipped when:\n * - Already on the bridge host origin (would be a no-op self-redirect).\n * - The user's intended destination is itself on the bridge host\n * (likely an in-product navigation, no deposit needed).\n * - The freshly-stored profile snapshot can't be read (best-effort only —\n * login still succeeds via the direct redirect).\n */\n const buildPostLoginUrl = useCallback(\n async (intendedPath: string): Promise<string> => {\n if (typeof window === \"undefined\") return intendedPath;\n // Native shells (Electron, Capacitor iOS/Android) run as a single origin —\n // skip the cross-eTLD+1 deposit detour, which would otherwise navigate to\n // an external https URL and escape the embedded webview.\n if (isNativeShell()) return intendedPath;\n try {\n const bridge = resolveAuthBridgeConfig();\n const bridgeUrl = new URL(bridge.url);\n const currentOrigin = window.location.origin;\n if (bridgeUrl.origin === currentOrigin) return intendedPath;\n\n // intendedPath can be a path or an absolute URL; resolve to absolute\n // against current origin so the bridge host knows where to send the\n // user back.\n const absoluteIntended = new URL(intendedPath, currentOrigin).href;\n\n const profileId = resolveActiveProfileId();\n if (!profileId) return intendedPath;\n const tokens = getProfileTokens(profileId);\n const user = getProfileUser(profileId);\n if (!tokens || !user) return intendedPath;\n const workspaceToken = getProfileWorkspaceToken(profileId);\n\n // BOFF-4463: mint a DEDICATED refresh-token lineage for the bridge\n // host. Copying this origin's pair verbatim meant the bridge (and\n // every product it later relayed to) shared ONE rotating refresh\n // token — the first origin to refresh revoked it for all others,\n // surfacing as \"products log me out after minutes/hours\". Falls back\n // to the legacy copy if the mutation is unreachable (rollout gap /\n // transient failure) so SSO keeps working.\n let depositTokens: Record<string, unknown> = {\n ...tokens,\n workspaceToken,\n };\n if (tokens.refreshToken) {\n const { globalBaseUrl } = resolveGatewayUrls();\n const { tokens: minted } = await mintSsoSessionTokens(\n `${globalBaseUrl}/global/graphql`,\n tokens.refreshToken,\n );\n if (minted) {\n depositTokens = { ...minted, workspaceToken };\n }\n }\n\n markSsoDepositPending(profileId);\n return buildSsoDepositUrl(bridgeUrl.origin, absoluteIntended, {\n profileId,\n tokens: JSON.stringify(depositTokens),\n user: JSON.stringify(user),\n profiles: JSON.stringify(getProfiles()),\n });\n } catch {\n return intendedPath;\n }\n },\n [],\n );\n\n // Once a cross-document post-login redirect is initiated, the login page\n // must FREEZE: resetting isCompletingAuth re-runs the auto-redirect effect\n // and any state churn schedules same-document navigations that cancel the\n // provisional deposit hop (BOFF-4463).\n const redirectInitiatedRef = useRef(false);\n\n const redirectAfterLogin = useCallback(\n (path: string) => {\n const safePath = sanitizePostLoginPath(path);\n if (typeof window === \"undefined\") {\n navigate(safePath);\n return;\n }\n try {\n sessionStorage.setItem(\"bf-post-login-return-to\", safePath);\n } catch {\n // Ignore storage failures; redirect still proceeds.\n }\n // In native shells use SPA navigation so the embedded webview stays in\n // the app — no full reload, no chance of the OS opening the URL\n // externally. Tokens are already in this origin's localStorage.\n if (isNativeShell()) {\n navigate(toSameOriginPath(safePath));\n return;\n }\n redirectInitiatedRef.current = true;\n void (async () => {\n // Cap the bridge URL build so a hanging SSO token mint cannot keep the\n // login page stuck on the spinner (BOFF-6807). The sanitized path is\n // always safe to redirect to directly.\n const target = await Promise.race([\n buildPostLoginUrl(safePath),\n new Promise<string>((resolve) => {\n window.setTimeout(() => resolve(safePath), 3000);\n }),\n ]);\n if (target.includes(\"/auth/sso-deposit\")) {\n // Cross-document deposit hop: suppress same-document navigators\n // while it is provisional, and retry once if it still gets\n // cancelled — on a committed navigation this document unloads and\n // the timer never fires.\n beginSsoNavigation();\n window.location.assign(target);\n window.setTimeout(() => {\n beginSsoNavigation();\n window.location.replace(target);\n }, 2500);\n } else {\n window.location.assign(target);\n }\n // Fallback: if the document is still stuck on the login page after a\n // full redirect attempt, force an in-app navigation so the spinner\n // cannot stall forever (BOFF-6807). This only fires when the browser\n // failed to leave /auth/login, e.g. because the computed target was\n // still an auth URL or the location.assign was a no-op.\n window.setTimeout(() => {\n if (\n typeof window !== \"undefined\" &&\n window.location.pathname === \"/auth/login\"\n ) {\n navigate(\"/dashboard\");\n }\n }, 3500);\n })();\n },\n [navigate, buildPostLoginUrl],\n );\n const [showPassword, setShowPassword] = useState(false);\n const [isAccountInactive, setIsAccountInactive] = useState(false);\n const [isAccountDeleted, setIsAccountDeleted] = useState(false);\n const [isAccountSuspended, setIsAccountSuspended] = useState(false);\n const [isOAuthOnlyAccount, setIsOAuthOnlyAccount] = useState(false);\n const [isEmailNotVerified, setIsEmailNotVerified] = useState(false);\n const [isResendingVerification, setIsResendingVerification] = useState(false);\n const [resendSuccess, setResendSuccess] = useState(false);\n const [oauthError, setOauthError] = useState<string | null>(null);\n const [infoMessage, setInfoMessage] = useState<string | null>(null);\n const [formData, setFormData] = useState<\n SignInInput & { rememberMe?: boolean }\n >({\n email: \"\",\n password: \"\",\n rememberMe: false,\n });\n const [validationError, setValidationError] = useState<string | null>(null);\n const [isDuplicateAccount, setIsDuplicateAccount] = useState(false);\n\n // Detect add-account mode and returnTo from URL params\n const isAddAccountMode = searchParams.get(\"mode\") === \"add-account\";\n const returnTo = searchParams.get(\"returnTo\");\n const initialReturnToRef = useRef<string | null>(returnTo);\n\n // Tell the user WHY they are back on the login page. `session-expired` is\n // set by the shell's forced logout (expired session whose refresh failed);\n // `logout` covers explicit sign-outs and the SSO-clear fallback (which can\n // rewrite a session-expired redirect's reason on the cross-product bounce).\n // Without this the auto-logout looked like a silent, unexplained kick-out.\n const reasonParam = searchParams.get(\"reason\");\n useEffect(() => {\n if (reasonParam === \"session-expired\") {\n setInfoMessage(\n tr(\n \"auth.login.sessionExpired\",\n \"Your session has expired. Please sign in again.\",\n ),\n );\n } else if (reasonParam === \"logout\") {\n setInfoMessage(tr(\"auth.login.signedOut\", \"You have been signed out.\"));\n }\n }, [reasonParam, tr]);\n\n useEffect(() => {\n if (!initialReturnToRef.current && returnTo) {\n initialReturnToRef.current = returnTo;\n }\n }, [returnTo]);\n\n useEffect(() => {\n if (isAddAccountMode || isCompletingAuth) return;\n // A cross-document SSO navigation (deposit/relay hop) is already in\n // flight — issuing another redirect here would cancel it (BOFF-4463).\n if (redirectInitiatedRef.current || isSsoNavigationPending()) return;\n\n const profileId = resolveActiveProfileId();\n if (profileId) {\n const tokens = getProfileTokens(profileId);\n const user = getProfileUser(profileId);\n if (\n tokens?.accessToken &&\n user &&\n hasValidAccessToken(tokens.accessToken)\n ) {\n useAuthStore.getState().loadFromProfile(profileId);\n redirectAfterLogin(decodeSameOriginReturnTo(returnTo) ?? \"/\");\n return;\n }\n }\n\n const ssoUrl = getSSORedirectUrl();\n if (ssoUrl) {\n setIsSsoRedirecting(true);\n window.location.replace(ssoUrl);\n }\n }, [isAddAccountMode, isCompletingAuth, redirectAfterLogin, returnTo]);\n\n // Load remembered email on mount and clean up any legacy plaintext password storage\n useEffect(() => {\n try {\n // Security cleanup: remove any previously stored plaintext passwords\n localStorage.removeItem(\"remembered_password\");\n\n const rememberedEmail = localStorage.getItem(\"remembered_email\");\n\n if (rememberedEmail) {\n setFormData((prev) => ({\n ...prev,\n email: rememberedEmail,\n rememberMe: true,\n }));\n }\n } catch (error) {\n console.warn(\"[LoginPage] Failed to load remembered email:\", error);\n }\n }, []);\n\n // Check for redirect message and email from location state (e.g., from expired MFA or SSO redirect)\n useEffect(() => {\n const state = location.state as { message?: string; email?: string } | null;\n if (state?.message) {\n setInfoMessage(state.message);\n }\n if (state?.email) {\n setFormData((prev) => ({ ...prev, email: state.email }));\n }\n // Clear state to prevent showing message on refresh\n if (state) {\n window.history.replaceState({}, document.title);\n }\n }, [location.state]);\n\n // Determine error type from GraphQL error code (primary) or message (fallback).\n // The backend sends structured codes in extensions.code which are propagated\n // through useAuthOperations → authStore.errorCode.\n const checkErrorType = (\n err: string | null,\n code?: string | null,\n ):\n | \"DELETED\"\n | \"SUSPENDED\"\n | \"OAUTH_ONLY\"\n | \"INACTIVE\"\n | \"EMAIL_NOT_VERIFIED\"\n | null => {\n // Primary: match on GraphQL error code from extensions\n if (code) {\n switch (code) {\n case \"ACCOUNT_DELETED\":\n return \"DELETED\";\n case \"ACCOUNT_SUSPENDED\":\n return \"SUSPENDED\";\n case \"OAUTH_ONLY_ACCOUNT\":\n return \"OAUTH_ONLY\";\n case \"ACCOUNT_INACTIVE\":\n return \"INACTIVE\";\n case \"EMAIL_NOT_VERIFIED\":\n return \"EMAIL_NOT_VERIFIED\";\n default:\n break;\n }\n }\n\n // Fallback: match on error message for non-GraphQL errors or legacy responses\n if (!err) return null;\n const lowerErr = err.toLowerCase();\n\n if (\n lowerErr.includes(\"deleted\") ||\n lowerErr.includes(\"permanently deleted\")\n ) {\n return \"DELETED\";\n }\n if (lowerErr.includes(\"suspended\")) {\n return \"SUSPENDED\";\n }\n if (\n lowerErr.includes(\"oauth provider\") ||\n lowerErr.includes(\"oauth-only\") ||\n lowerErr.includes(\"oauth only\")\n ) {\n return \"OAUTH_ONLY\";\n }\n if (\n lowerErr.includes(\"inactive\") ||\n lowerErr.includes(\"deactivated\") ||\n lowerErr.includes(\"not active\")\n ) {\n return \"INACTIVE\";\n }\n if (\n lowerErr.includes(\"verify your email\") ||\n lowerErr.includes(\"email not verified\") ||\n lowerErr.includes(\"email_not_verified\")\n ) {\n return \"EMAIL_NOT_VERIFIED\";\n }\n return null;\n };\n\n // Pre-fill email from URL query parameter (e.g., after email verification)\n useEffect(() => {\n const emailFromUrl = searchParams.get(\"email\");\n if (emailFromUrl) {\n setFormData((prev) => ({ ...prev, email: emailFromUrl }));\n }\n\n // Check for expired session redirect\n const isExpired = searchParams.get(\"expired\");\n if (isExpired === \"true\") {\n setInfoMessage(\n tr(\n \"auth.login.sessionExpired\",\n \"Your session has expired. Please sign in again.\",\n ),\n );\n // Clear the query param to prevent showing on refresh\n const newUrl = window.location.pathname;\n window.history.replaceState({}, document.title, newUrl);\n }\n }, [searchParams, tr]);\n\n // Redirect to MFA verification when required\n useEffect(() => {\n if (mfaRequired) {\n navigate(\"/auth/mfa-verify\");\n }\n }, [mfaRequired, navigate]);\n\n const handleSubmit = async (e: React.FormEvent) => {\n e.preventDefault();\n setIsAccountInactive(false);\n setIsAccountDeleted(false);\n setIsAccountSuspended(false);\n setIsOAuthOnlyAccount(false);\n setIsEmailNotVerified(false);\n setIsDuplicateAccount(false);\n setResendSuccess(false);\n setValidationError(null);\n\n // Client-side validation\n const emailTrimmed = (formData.email ?? \"\").trim();\n if (!emailTrimmed) {\n setValidationError(\n tr(\n \"auth.login.enterEmailOrUsername\",\n \"Please enter your email or username\",\n ),\n );\n return;\n }\n\n // Basic email format validation (if it contains @)\n if (emailTrimmed.includes(\"@\")) {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(emailTrimmed)) {\n setValidationError(\n tr(\"auth.login.invalidEmail\", \"Please enter a valid email address\"),\n );\n return;\n }\n }\n\n if (!formData.password || formData.password.length < 1) {\n setValidationError(\n tr(\"auth.login.enterPassword\", \"Please enter your password\"),\n );\n return;\n }\n\n // In add-account mode, check if this email is already signed in\n if (isAddAccountMode) {\n const existingProfiles = getProfiles();\n const alreadySignedIn = existingProfiles.some(\n (p) => p.email.toLowerCase() === emailTrimmed.toLowerCase(),\n );\n if (alreadySignedIn) {\n setIsDuplicateAccount(true);\n setValidationError(null);\n return;\n }\n }\n setIsDuplicateAccount(false);\n\n try {\n // Get reCAPTCHA v3 token (no-op when captcha is disabled)\n const recaptchaToken = await executeCaptchaV3(\"login\");\n\n const result = await signIn({\n email: emailTrimmed,\n password: formData.password,\n rememberMe: formData.rememberMe,\n ...(recaptchaToken ? { recaptchaToken } : {}),\n });\n\n // If MFA is required, the useEffect above will handle redirect\n if (result.requiresMFA) {\n // Persist the post-login destination so MfaVerifyPage honors\n // `returnTo` and `defaultPostLoginPath` after the user completes\n // verification — otherwise the MFA path falls back to \"/\" and the\n // host-configured home (e.g. \"/vibecontrols\") is lost.\n const effectiveReturnTo = initialReturnToRef.current || returnTo;\n const postMfaPath = effectiveReturnTo\n ? cleanReturnToValue(effectiveReturnTo)\n : cleanReturnToValue(defaultPostLoginPath ?? \"/dashboard\");\n try {\n sessionStorage.setItem(MFA_REDIRECT, postMfaPath);\n } catch {\n // sessionStorage may be unavailable (private mode, quota) — the\n // MFA page still works, it just defaults to \"/\" on completion.\n }\n return;\n }\n\n // Successful login - complete auth flow (fetch workspaces + issue token)\n if (result.success) {\n try {\n const profileId = result.user?.id;\n if (profileId) {\n const hostname = window.location.hostname;\n const domain = hostname.endsWith(\".local.burdenoff.com\")\n ? \".local.burdenoff.com\"\n : undefined;\n const domainPart = domain ? `; domain=${domain}` : \"\";\n const securePart =\n window.location.protocol === \"https:\" ? \"; secure\" : \"\";\n const ssoValue = JSON.stringify({\n id: profileId,\n origin: window.location.origin,\n });\n document.cookie = `bf-sso=${encodeURIComponent(ssoValue)}${domainPart}; path=/; samesite=lax${securePart}; max-age=86400`;\n document.cookie = `bf-sso-profile=${encodeURIComponent(ssoValue)}${domainPart}; path=/; samesite=lax${securePart}; max-age=86400`;\n }\n } catch {\n // Best effort only. Login can continue without the fast-path cookie.\n }\n\n // Handle Remember Me: Save or clear email only (never store passwords)\n try {\n if (formData.rememberMe) {\n localStorage.setItem(\"remembered_email\", emailTrimmed);\n } else {\n localStorage.removeItem(\"remembered_email\");\n }\n } catch (error) {\n console.warn(\n \"[LoginPage] Failed to save/clear remembered email:\",\n error,\n );\n }\n\n setIsCompletingAuth(true);\n // In add-account mode, redirect back to where the user was\n const effectiveReturnTo = initialReturnToRef.current || returnTo;\n const postLoginPath = effectiveReturnTo\n ? cleanReturnToValue(effectiveReturnTo)\n : cleanReturnToValue(defaultPostLoginPath ?? \"/dashboard\");\n try {\n type AuthFlowResult = Awaited<ReturnType<typeof completeAuthFlow>>;\n // Pass the token directly to avoid race condition with React state updates\n const authFlowResult = await Promise.race<AuthFlowResult>([\n completeAuthFlow(result.token),\n new Promise<AuthFlowResult>((resolve) => {\n window.setTimeout(() => {\n resolve({\n success: false,\n error: \"Auth flow timed out after login\",\n });\n }, 5000);\n }),\n ]);\n\n if (authFlowResult.success) {\n // Sync workspace and organization to ActiveContext\n // This is critical for global search and other workspace-scoped features\n if (authFlowResult.workspace) {\n setWorkspace(authFlowResult.workspace.id);\n if (authFlowResult.workspace.organizationId) {\n setOrganization(authFlowResult.workspace.organizationId);\n }\n }\n\n // Full auth flow completed - redirect to dashboard or returnTo\n redirectAfterLogin(postLoginPath);\n } else if (authFlowResult.error?.includes(\"No workspaces found\")) {\n // No workspaces - redirect to onboarding/workspace creation\n navigate(\"/onboarding/create-workspace\");\n } else {\n // Partial success or error - still sync workspace if available and redirect\n if (authFlowResult.workspace) {\n setWorkspace(authFlowResult.workspace.id);\n if (authFlowResult.workspace.organizationId) {\n setOrganization(authFlowResult.workspace.organizationId);\n }\n }\n console.warn(\"Auth flow warning:\", authFlowResult.error);\n redirectAfterLogin(postLoginPath);\n }\n } catch (authFlowError) {\n // Auth flow failed but login succeeded - still redirect\n console.error(\"Auth flow error (login succeeded):\", authFlowError);\n redirectAfterLogin(postLoginPath);\n } finally {\n // Keep the completing state (spinner) once a redirect is in\n // flight: resetting it re-arms the auto-redirect effect whose\n // competing navigation cancels the deposit hop (BOFF-4463). The\n // page is about to unload anyway.\n if (!redirectInitiatedRef.current) {\n setIsCompletingAuth(false);\n }\n }\n }\n } catch (err) {\n if (import.meta.env.DEV) {\n console.error(\"Sign in failed:\", err);\n }\n // Check error type using error code (from store) and message\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (errorMsg.includes(\"reCAPTCHA\")) {\n setValidationError(errorMsg);\n }\n const storeErrorCode = useAuthStore.getState().errorCode;\n const errorType = checkErrorType(errorMsg, storeErrorCode);\n if (errorType === \"DELETED\") {\n setIsAccountDeleted(true);\n } else if (errorType === \"SUSPENDED\") {\n setIsAccountSuspended(true);\n } else if (errorType === \"OAUTH_ONLY\") {\n setIsOAuthOnlyAccount(true);\n } else if (errorType === \"INACTIVE\") {\n setIsAccountInactive(true);\n } else if (errorType === \"EMAIL_NOT_VERIFIED\") {\n setIsEmailNotVerified(true);\n }\n }\n };\n\n // Also check the error from useAuthOperations\n useEffect(() => {\n if (error) {\n const errorType = checkErrorType(error, errorCode);\n if (errorType === \"DELETED\") {\n setIsAccountDeleted(true);\n } else if (errorType === \"SUSPENDED\") {\n setIsAccountSuspended(true);\n } else if (errorType === \"OAUTH_ONLY\") {\n setIsOAuthOnlyAccount(true);\n } else if (errorType === \"INACTIVE\") {\n setIsAccountInactive(true);\n } else if (errorType === \"EMAIL_NOT_VERIFIED\") {\n setIsEmailNotVerified(true);\n }\n }\n }, [error, errorCode]);\n\n /**\n * Handle Google OAuth login\n */\n const handleGoogleLogin = () => {\n setOauthError(null);\n try {\n initiateGoogleOAuth();\n } catch (err) {\n setOauthError(\n err instanceof Error\n ? err.message\n : tr(\n \"auth.login.googleSignInFailed\",\n \"Failed to initiate Google sign in\",\n ),\n );\n }\n };\n\n /**\n * Handle Microsoft OAuth login\n */\n const handleMicrosoftLogin = () => {\n setOauthError(null);\n try {\n initiateMicrosoftOAuth();\n } catch (err) {\n setOauthError(\n err instanceof Error\n ? err.message\n : tr(\n \"auth.login.microsoftSignInFailed\",\n \"Failed to initiate Microsoft sign in\",\n ),\n );\n }\n };\n\n /**\n * Handle resend verification email\n */\n const handleResendVerification = async () => {\n setIsResendingVerification(true);\n setResendSuccess(false);\n try {\n const emailTrimmed = (formData.email ?? \"\").trim();\n const result = await resendVerification(emailTrimmed);\n if (result.success) {\n setResendSuccess(true);\n } else {\n setValidationError(\n tr(\n \"auth.login.resendFailed\",\n \"Failed to resend verification email. Please try again.\",\n ),\n );\n }\n } catch (err) {\n console.error(\"Failed to resend verification email:\", err);\n setValidationError(\n err instanceof Error\n ? err.message\n : tr(\n \"auth.login.resendFailed\",\n \"Failed to resend verification email. Please try again.\",\n ),\n );\n } finally {\n setIsResendingVerification(false);\n }\n };\n\n // Check if OAuth providers are configured\n const isGoogleConfigured = isProviderConfigured(\"google\");\n const isMicrosoftConfigured = isProviderConfigured(\"microsoft\");\n\n const oauthProviders = [\n {\n name: \"Google\",\n icon: GoogleIcon,\n onClick: handleGoogleLogin,\n disabled: !isGoogleConfigured,\n tooltip: isGoogleConfigured\n ? undefined\n : tr(\n \"auth.login.googleNotConfigured\",\n \"Google sign in is not configured\",\n ),\n },\n // {\n // name: \"GitHub\",\n // icon: GitHubIcon,\n // onClick: () => {},\n // disabled: true,\n // tooltip: tr(\n // \"auth.login.githubNotConfigured\",\n // \"GitHub sign in is not configured\",\n // ),\n // },\n {\n name: \"Microsoft\",\n icon: MicrosoftIcon,\n onClick: handleMicrosoftLogin,\n disabled: !isMicrosoftConfigured,\n tooltip: isMicrosoftConfigured\n ? undefined\n : tr(\n \"auth.login.microsoftNotConfigured\",\n \"Microsoft sign in is not configured\",\n ),\n },\n ];\n\n if (isSsoRedirecting) {\n return <SSORedirectSpinner />;\n }\n\n return (\n <AuthLayout\n title={tr(\"auth.login.welcomeBack\", \"Welcome back\")}\n subtitle={tr(\n \"auth.login.enterCredentials\",\n \"Enter your credentials to continue\",\n )}\n >\n <PagePurpose className=\"mb-5\">\n {tr(\n \"auth.login.purpose\",\n \"Sign in to reach your workspaces, agents, and settings. Use your email and password, a social provider, or a passwordless magic link.\",\n )}\n </PagePurpose>\n <form onSubmit={handleSubmit} className=\"space-y-5\">\n {/* Info Message (e.g., from expired MFA redirect) */}\n {infoMessage && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-info-bg-subtle border-status-info-border\">\n <svg\n className=\"size-5 flex-shrink-0 mt-0.5 text-text-link\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\"\n />\n </svg>\n <p className=\"text-sm text-status-info-text\">{infoMessage}</p>\n </div>\n )}\n\n {/* Validation Error */}\n {validationError && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-warning-bg-subtle border-status-warning-border\">\n <AlertIcon className=\"size-5 flex-shrink-0 mt-0.5 text-status-warning-text\" />\n <p className=\"text-sm text-status-warning-text\">\n {validationError}\n </p>\n </div>\n )}\n\n {/* Duplicate Account Warning (Add Account mode) */}\n {isDuplicateAccount && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-warning-bg-subtle border-status-warning-border\">\n <AlertIcon className=\"size-5 flex-shrink-0 mt-0.5 text-status-warning-text\" />\n <div className=\"flex-1\">\n <p className=\"text-sm font-medium text-status-warning-text\">\n {tr(\n \"auth.login.duplicateAccount\",\n \"This account is already signed in.\",\n )}\n </p>\n <p className=\"mt-1 text-sm text-status-warning-text/80\">\n {tr(\n \"auth.login.duplicateAccountHint\",\n \"Please use a different account, or go back and switch to this account from the profile menu.\",\n )}\n </p>\n {(initialReturnToRef.current || returnTo) && (\n <button\n type=\"button\"\n onClick={() =>\n navigate(\n decodeURIComponent(\n initialReturnToRef.current || returnTo || \"/dashboard\",\n ),\n )\n }\n className=\"mt-3 inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-status-warning-border bg-bg-surface text-status-warning-text text-sm font-medium hover:bg-status-warning-bg-subtle hover:border-status-warning-border transition-all shadow-sm\"\n >\n <svg\n className=\"size-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M10 19l-7-7m0 0l7-7m-7 7h18\"\n />\n </svg>\n {tr(\n \"auth.login.goBackSwitchAccount\",\n \"Go back and switch account\",\n )}\n </button>\n )}\n </div>\n </div>\n )}\n\n {/* Error Alert */}\n {error && !validationError && !isDuplicateAccount && (\n <div\n className={`flex items-start gap-3 p-4 rounded-xl border ${\n isAccountInactive || isOAuthOnlyAccount || isEmailNotVerified\n ? \"bg-status-warning-bg-subtle border-status-warning-border\"\n : \"bg-status-error-bg-subtle border-status-error-border\"\n }`}\n >\n <AlertIcon\n className={`size-5 flex-shrink-0 mt-0.5 ${\n isAccountInactive || isOAuthOnlyAccount || isEmailNotVerified\n ? \"text-status-warning-text\"\n : \"text-status-error-text\"\n }`}\n />\n <div className=\"flex-1\">\n <p\n className={`text-sm ${\n isAccountInactive || isOAuthOnlyAccount || isEmailNotVerified\n ? \"text-status-warning-text\"\n : \"text-status-error-text\"\n }`}\n >\n {isAccountDeleted\n ? tr(\n \"auth.login.accountDeleted\",\n \"This account has been permanently deleted and cannot be recovered.\",\n )\n : isAccountSuspended\n ? tr(\n \"auth.login.accountSuspended\",\n \"Your account has been suspended. Please contact support for assistance.\",\n )\n : isAccountInactive\n ? tr(\n \"auth.login.accountDeactivated\",\n \"Your account has been deactivated.\",\n )\n : isOAuthOnlyAccount\n ? tr(\n \"auth.login.oauthOnly\",\n \"This account uses OAuth sign-in. Please use Google or Microsoft to sign in.\",\n )\n : isEmailNotVerified\n ? tr(\n \"auth.login.emailNotVerified\",\n \"Please verify your email before signing in. Check your inbox for the verification link.\",\n )\n : error}\n </p>\n {isAccountInactive && (\n <button\n type=\"button\"\n onClick={() =>\n navigate(\"/auth/reactivate\", {\n state: { email: formData.email },\n })\n }\n className=\"mt-2 text-sm font-semibold text-status-warning-text hover:text-status-warning-text underline underline-offset-2\"\n >\n {tr(\n \"auth.login.clickReactivate\",\n \"Click here to reactivate your account\",\n )}\n </button>\n )}\n {isEmailNotVerified && (\n <div className=\"mt-3\">\n {resendSuccess ? (\n <div className=\"flex items-center gap-2 text-sm text-status-success-text\">\n <svg\n className=\"size-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M5 13l4 4L19 7\"\n />\n </svg>\n {tr(\n \"auth.login.verificationSent\",\n \"Verification email sent! Please check your inbox.\",\n )}\n </div>\n ) : (\n <button\n type=\"button\"\n onClick={handleResendVerification}\n disabled={isResendingVerification}\n className=\"inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-status-warning-border bg-bg-surface text-status-warning-text text-sm font-medium hover:bg-status-warning-bg-subtle hover:border-status-warning-border transition-all shadow-sm disabled:opacity-50 disabled:cursor-not-allowed\"\n >\n {isResendingVerification ? (\n <>\n <SpinnerIcon className=\"size-4 animate-spin\" />\n {tr(\"auth.login.sending\", \"Sending...\")}\n </>\n ) : (\n <>\n <svg\n className=\"size-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z\"\n />\n </svg>\n {tr(\n \"auth.login.resendVerification\",\n \"Resend verification email\",\n )}\n </>\n )}\n </button>\n )}\n </div>\n )}\n {isOAuthOnlyAccount && (\n <div className=\"mt-3 flex flex-col gap-2\">\n {isProviderConfigured(\"google\") && (\n <button\n type=\"button\"\n onClick={handleGoogleLogin}\n className=\"inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-border-default bg-bg-surface text-text-primary text-sm font-medium hover:bg-bg-canvas hover:border-border-default transition-all shadow-sm\"\n >\n <GoogleIcon className=\"size-5\" />\n {tr(\"auth.login.signInWithGoogle\", \"Sign in with Google\")}\n </button>\n )}\n {isProviderConfigured(\"microsoft\") && (\n <button\n type=\"button\"\n onClick={handleMicrosoftLogin}\n className=\"inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-border-default bg-bg-surface text-text-primary text-sm font-medium hover:bg-bg-canvas hover:border-border-default transition-all shadow-sm\"\n >\n <MicrosoftIcon className=\"size-5\" />\n {tr(\n \"auth.login.signInWithMicrosoft\",\n \"Sign in with Microsoft\",\n )}\n </button>\n )}\n </div>\n )}\n </div>\n </div>\n )}\n\n {/* Email Input */}\n <div className=\"space-y-2\">\n <label\n htmlFor=\"email\"\n className=\"block text-sm font-medium text-[var(--color-text-primary)]\"\n >\n {tr(\"auth.login.emailLabel\", \"Email\")}\n </label>\n <div className=\"relative\">\n <div className=\"absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none\">\n <EmailIcon className=\"size-5 text-[var(--color-text-tertiary)]\" />\n </div>\n <input\n id=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n required\n aria-required=\"true\"\n aria-label={tr(\"auth.login.emailLabel\", \"Email\")}\n value={formData.email}\n onChange={(e) =>\n setFormData({ ...formData, email: e.target.value })\n }\n className=\"block w-full pl-[3.5rem] pr-4 py-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-2 focus:ring-action-primary-bg/20 focus:border-action-primary-bg transition-all\"\n placeholder={tr(\"auth.login.emailPlaceholder\", \"you@example.com\")}\n />\n </div>\n </div>\n\n {/* Password Input */}\n <div className=\"space-y-2\">\n <label\n htmlFor=\"password\"\n className=\"block text-sm font-medium text-[var(--color-text-primary)]\"\n >\n {tr(\"auth.login.passwordLabel\", \"Password\")}\n </label>\n <div className=\"relative\">\n <div className=\"absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none\">\n <LockIcon className=\"size-5 text-[var(--color-text-tertiary)]\" />\n </div>\n <input\n id=\"password\"\n type={showPassword ? \"text\" : \"password\"}\n autoComplete=\"current-password\"\n required\n aria-required=\"true\"\n aria-label={tr(\"auth.login.passwordLabel\", \"Password\")}\n value={formData.password}\n onChange={(e) =>\n setFormData({ ...formData, password: e.target.value })\n }\n className=\"block w-full pl-[3.5rem] pr-12 py-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-2 focus:ring-action-primary-bg/20 focus:border-action-primary-bg transition-all\"\n placeholder={tr(\n \"auth.login.passwordPlaceholder\",\n \"Enter your password\",\n )}\n />\n <button\n type=\"button\"\n onClick={() => setShowPassword(!showPassword)}\n aria-label={\n showPassword\n ? tr(\"auth.login.hidePassword\", \"Hide password\")\n : tr(\"auth.login.showPassword\", \"Show password\")\n }\n className=\"absolute inset-y-0 right-0 pr-3.5 flex items-center text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] transition-colors\"\n >\n {showPassword ? (\n <EyeOffIcon className=\"size-5\" />\n ) : (\n <EyeIcon className=\"size-5\" />\n )}\n </button>\n </div>\n </div>\n\n {/* Remember & Forgot */}\n <div className=\"flex items-center justify-between\">\n <label\n htmlFor=\"remember-me\"\n className=\"flex items-center gap-2 cursor-pointer group\"\n >\n <Checkbox\n id=\"remember-me\"\n checked={formData.rememberMe}\n onCheckedChange={(checked: boolean | \"indeterminate\") => {\n const isChecked = checked === true;\n setFormData({ ...formData, rememberMe: isChecked });\n\n // Clear saved email immediately when unchecked\n if (!isChecked) {\n try {\n localStorage.removeItem(\"remembered_email\");\n } catch (error) {\n console.warn(\n \"[LoginPage] Failed to clear remembered email:\",\n error,\n );\n }\n }\n }}\n aria-label={tr(\"auth.login.rememberMe\", \"Remember me\")}\n />\n <span className=\"text-sm text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] transition-colors\">\n {tr(\"auth.login.rememberMe\", \"Remember me\")}\n </span>\n </label>\n <button\n type=\"button\"\n onClick={() => navigate(\"/auth/reset-password\")}\n className=\"text-sm font-medium text-text-link hover:text-text-linkHover transition-colors\"\n >\n {tr(\"auth.login.forgotPassword\", \"Forgot password?\")}\n </button>\n </div>\n\n {/* Submit Button */}\n <Button\n type=\"submit\"\n disabled={isLoading || isCompletingAuth}\n variant=\"default\"\n size=\"lg\"\n className=\"w-full font-semibold\"\n >\n {isLoading || isCompletingAuth ? (\n <>\n <SpinnerIcon className=\"size-5 animate-spin\" />\n <span>\n {isCompletingAuth\n ? tr(\n \"auth.login.settingUpWorkspace\",\n \"Setting up workspace...\",\n )\n : tr(\"auth.login.signingIn\", \"Signing in...\")}\n </span>\n </>\n ) : (\n tr(\"auth.login.signIn\", \"Sign in\")\n )}\n </Button>\n </form>\n\n {/* Divider */}\n <div className=\"relative my-8\">\n <div className=\"absolute inset-0 flex items-center\">\n <div className=\"w-full border-t border-[var(--color-border-default)]\" />\n </div>\n <div className=\"relative flex justify-center\">\n <span className=\"px-4 bg-[var(--color-bg-canvas)] text-sm text-[var(--color-text-tertiary)]\">\n {tr(\"auth.login.orContinueWith\", \"or continue with\")}\n </span>\n </div>\n </div>\n\n {/* OAuth Error */}\n {oauthError && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-error-bg-subtle border-status-error-border\">\n <AlertIcon className=\"size-5 flex-shrink-0 mt-0.5 text-status-error-text\" />\n <p className=\"text-sm text-status-error-text\">{oauthError}</p>\n </div>\n )}\n\n {/* OAuth Buttons */}\n <div className=\"grid grid-cols-3 gap-3\">\n {oauthProviders.map((provider) => (\n <button\n key={provider.name}\n type=\"button\"\n onClick={provider.onClick}\n disabled={provider.disabled}\n title={provider.tooltip}\n aria-label={provider.name}\n className={`flex items-center justify-center gap-2 px-4 py-3 rounded-xl border transition-all duration-200 group ${\n provider.disabled\n ? \"border-[var(--color-border-subtle)] bg-[var(--color-bg-disabled)] cursor-not-allowed opacity-50\"\n : \"border-[var(--color-border-default)] bg-[var(--color-bg-surface)] hover:bg-[var(--color-bg-sunken)] hover:border-[var(--color-border-strong)]\"\n }`}\n >\n <provider.icon\n className={`size-5 ${provider.disabled ? \"opacity-50\" : \"\"}`}\n />\n <span\n className={`sr-only sm:not-sr-only text-sm font-medium transition-colors ${\n provider.disabled\n ? \"text-[var(--color-text-disabled)]\"\n : \"text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)]\"\n }`}\n >\n {provider.name}\n </span>\n </button>\n ))}\n </div>\n\n {/* Enterprise SSO Option — temporarily hidden */}\n {/* <div className=\"mt-6\">\n <button type=\"button\"\n onClick={() => navigate(\"/auth/sso/login\")}\n className=\"w-full flex items-center justify-center gap-3 px-4 py-3 rounded-xl border-2 border-dashed border-[var(--color-border-default)] hover:border-action-primary-bg bg-[var(--color-bg-surface)] hover:bg-status-info-bg-subtle transition-all duration-200 group\"\n >\n <svg\n className=\"size-5 text-[var(--color-text-tertiary)] group-hover:text-text-link\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n d=\"M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4\"\n />\n </svg>\n <span className=\"text-sm font-medium text-[var(--color-text-secondary)] group-hover:text-text-link\">\n {tr(\"auth.login.enterpriseSso\", \"Sign in with Enterprise SSO\")}\n </span>\n </button>\n </div> */}\n\n {/* Magic Link Option */}\n <div className=\"mt-4 text-center\">\n <button\n type=\"button\"\n onClick={() => navigate(\"/auth/magic-link\")}\n className=\"text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors\"\n >\n {tr(\"auth.login.preferPasswordless\", \"Prefer passwordless login?\")}{\" \"}\n <span className=\"font-semibold text-text-link hover:text-text-linkHover\">\n {tr(\"auth.login.signInMagicLink\", \"Sign in with Magic Link\")}\n </span>\n </button>\n </div>\n\n {/* Sign Up Link */}\n <p className=\"mt-6 text-center text-sm text-[var(--color-text-secondary)]\">\n {tr(\"auth.login.dontHaveAccount\", \"Don't have an account?\")}{\" \"}\n <button\n type=\"button\"\n onClick={() => navigate(\"/auth/register\")}\n className=\"font-semibold text-text-link hover:text-text-linkHover transition-colors\"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,WAAU;KAAkC,UAAA9D;IAAc,CAAA,CAC1D;;GAIP,kBAAC,OAAD;IAAK,WAAU;IACZ,UAAAwD,GAAe,KAAK,MACnB,kBAAC,UAAD;KAEE,MAAK;KACL,SAASmB,EAAS;KAClB,UAAUA,EAAS;KACnB,OAAOA,EAAS;KAChB,cAAYA,EAAS;KACrB,WAAW,wGACTA,EAAS,WACL,oGACA;KAVR,UAAA,CAaE,kBAACA,EAAS,MAAV,EACE,WAAW,UAAUA,EAAS,WAAW,eAAe,KACzD,CAAA,GACD,kBAAC,QAAD;MACE,WAAW,gEACTA,EAAS,WACL,sCACA;MAGL,UAAAA,EAAS;KACN,CAAA,CACA;IAxBD,GAAAA,EAAS,IAwBR,CACT;GACE,CAAA;GA4BL,kBAAC,OAAD;IAAK,WAAU;IACb,UAAA,kBAAC,UAAD;KACE,MAAK;KACL,eAAehJ,EAAS,kBAAkB;KAC1C,WAAU;KAHZ,UAAA;MAKGF,EAAG,iCAAiC,4BAA4B;MAAG;MACpE,kBAAC,QAAD;OAAM,WAAU;OACb,UAAAA,EAAG,8BAA8B,yBAAyB;MACvD,CAAA;KACA;;GACL,CAAA;GAGL,kBAAC,KAAD;IAAG,WAAU;IAAb,UAAA;KACGA,EAAG,8BAA8B,wBAAwB;KAAG;KAC7D,kBAAC,UAAD;MACE,MAAK;MACL,eAAeE,EAAS,gBAAgB;MACxC,WAAU;MAET,UAAAF,EAAG,qBAAqB,SAAS;KAC5B,CAAA;IACP;;EACO;;AAEhB"}
|
|
1
|
+
{"version":3,"file":"LoginPage.js","names":["_Fragment","isNativeShell","w","toSameOriginPath","target","url","hasValidAccessToken","raw","token","padded","payload","decodeSameOriginReturnTo","returnTo","stripStaleSsoParams","param","options","search","cleanReturnToValue","LoginPage","tr","useTr","navigate","useNavigate","location","useLocation","searchParams","useSearchParams","useAuthOperations","useMyWorkspaces","useActiveContext","navigateHost","useAuth","useOAuthOperations","mfaRequired","useAuthStore","state","executeCaptchaV3","useCaptchaV3","isCompletingAuth","setIsCompletingAuth","useState","isSsoRedirecting","setIsSsoRedirecting","buildPostLoginUrl","useCallback","intendedPath","bridge","resolveAuthBridgeConfig","bridgeUrl","currentOrigin","absoluteIntended","profileId","resolveActiveProfileId","tokens","getProfileTokens","user","getProfileUser","workspaceToken","getProfileWorkspaceToken","depositTokens","resolveGatewayUrls","minted","mintSsoSessionTokens","globalBaseUrl","markSsoDepositPending","buildSsoDepositUrl","getProfiles","redirectInitiatedRef","useRef","redirectAfterLogin","safePath","sanitizePostLoginPath","path","fragmentPath","sameOriginFragmentPath","resolve","beginSsoNavigation","showPassword","setShowPassword","isAccountInactive","setIsAccountInactive","isAccountDeleted","setIsAccountDeleted","isAccountSuspended","setIsAccountSuspended","isOAuthOnlyAccount","setIsOAuthOnlyAccount","isEmailNotVerified","setIsEmailNotVerified","isResendingVerification","setIsResendingVerification","resendSuccess","setResendSuccess","oauthError","setOauthError","infoMessage","setInfoMessage","formData","setFormData","validationError","setValidationError","isDuplicateAccount","setIsDuplicateAccount","isAddAccountMode","initialReturnToRef","reasonParam","useEffect","isSsoNavigationPending","defaultPostLoginPath","ssoUrl","getSSORedirectUrl","rememberedEmail","prev","error","checkErrorType","code","err","lowerErr","emailFromUrl","newUrl","handleSubmit","emailTrimmed","p","recaptchaToken","result","signIn","postMfaPath","MFA_REDIRECT","domain","domainPart","securePart","ssoValue","postLoginPath","authFlowResult","completeAuthFlow","setWorkspace","setOrganization","hostFragmentContinuation","authFlowError","errorMsg","storeErrorCode","errorType","errorCode","handleGoogleLogin","handleMicrosoftLogin","handleResendVerification","resendVerification","isGoogleConfigured","isProviderConfigured","isMicrosoftConfigured","oauthProviders","GoogleIcon","MicrosoftIcon","SSORedirectSpinner","AuthLayout","PagePurpose","AlertIcon","Fragment","SpinnerIcon","EmailIcon","LockIcon","jsx","EyeOffIcon","EyeIcon","Checkbox","isChecked","checked","Button","isLoading","provider"],"sources":["../../../src/auth/pages/LoginPage.tsx"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from \"react\";\nimport { useNavigate, useSearchParams, useLocation } from \"react-router\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell\";\nimport { useTr } from \"../../shared/hooks/useTr\";\nimport {\n getSSORedirectUrl,\n SSORedirectSpinner,\n} from \"@burdenoff/fe-libs/shared/components\";\nimport { resolveAuthBridgeConfig } from \"@burdenoff/fe-libs/shared/config\";\nimport { resolveGatewayUrls } from \"@burdenoff/fe-libs/shared/config/gatewayUrls\";\nimport {\n beginSsoNavigation,\n buildSsoDepositUrl,\n isSsoNavigationPending,\n markSsoDepositPending,\n mintSsoSessionTokens,\n} from \"@burdenoff/fe-libs/shared/utils\";\nimport { Button } from \"@burdenoff/fe-libs/button\";\nimport { Checkbox, PagePurpose } from \"@burdenoff/fe-libs/ui\";\n\nimport {\n getProfileTokens,\n getProfileUser,\n getProfiles,\n getProfileWorkspaceToken,\n resolveActiveProfileId,\n} from \"@burdenoff/fe-libs/shared/providers/shell/ProfileStorageManager\";\nimport { useAuthOperations } from \"../hooks/useAuthOperations\";\nimport { useMyWorkspaces } from \"../hooks/useMyWorkspaces\";\nimport { useOAuthOperations } from \"../hooks/useOAuthOperations\";\nimport {\n hostFragmentContinuation,\n sameOriginFragmentPath,\n sanitizePostLoginPath,\n} from \"../utils/redirect\";\nimport { useAuthStore } from \"../store/authStore\";\nimport { useAuth } from \"../providers/AuthProvider\";\nimport { AuthLayout } from \"../components/AuthLayout\";\nimport {\n EmailIcon,\n LockIcon,\n EyeIcon,\n EyeOffIcon,\n AlertIcon,\n SpinnerIcon,\n GoogleIcon,\n // GitHubIcon,\n MicrosoftIcon,\n} from \"../components/AuthIcons\";\nimport { useCaptchaV3 } from \"../hooks/useCaptchaV3\";\nimport { MFA_REDIRECT } from \"../constants/sessionKeys\";\nimport type { SignInInput } from \"../types\";\n\n/**\n * Detect whether the bundle is running inside a native shell (Capacitor on\n * iOS/Android, or Electron). Cross-origin SSO deposit/relay detours only make\n * sense in a multi-origin web context — in a native shell there is one product\n * origin, tokens already live in localStorage, and `window.location.assign` to\n * an external https URL escapes the embedded webview.\n *\n * Detection is runtime-only and avoids importing any platform-specific module\n * so this stays valid when microfe-auth is consumed by a pure web shell too.\n */\nfunction isNativeShell(): boolean {\n if (typeof window === \"undefined\") return false;\n const w = window as typeof window & {\n Capacitor?: { isNativePlatform?: () => boolean };\n };\n if (typeof w.Capacitor?.isNativePlatform === \"function\") {\n try {\n if (w.Capacitor.isNativePlatform()) return true;\n } catch {\n /* fall through */\n }\n }\n if (\n typeof navigator !== \"undefined\" &&\n /Electron/i.test(navigator.userAgent || \"\")\n ) {\n return true;\n }\n return false;\n}\n\nfunction toSameOriginPath(target: string): string {\n if (typeof window === \"undefined\") return target;\n try {\n const url = new URL(target, window.location.origin);\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return target;\n }\n}\n\nfunction hasValidAccessToken(token: string): boolean {\n try {\n const raw = token.split(\".\")[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = raw.padEnd(Math.ceil(raw.length / 4) * 4, \"=\");\n const payload = JSON.parse(atob(padded)) as { exp?: unknown };\n return typeof payload.exp === \"number\" && payload.exp > Date.now() / 1000;\n } catch {\n return false;\n }\n}\n\nfunction decodeSameOriginReturnTo(returnTo: string | null): string | null {\n if (!returnTo) return null;\n try {\n const decoded = decodeURIComponent(returnTo);\n const url = new URL(decoded, window.location.origin);\n if (url.origin !== window.location.origin) return null;\n return stripStaleSsoParams(url, { includeOrigin: false });\n } catch {\n return null;\n }\n}\n\nfunction stripStaleSsoParams(\n url: URL,\n options: { includeOrigin: boolean },\n): string {\n for (const param of [\"sso_failed\", \"sso-failed\", \"sso-attempted\"] as const) {\n url.searchParams.delete(param);\n }\n\n if (options.includeOrigin) {\n return url.toString();\n }\n\n const search = url.searchParams.toString();\n return `${url.pathname}${search ? `?${search}` : \"\"}${url.hash}`;\n}\n\nfunction cleanReturnToValue(returnTo: string): string {\n try {\n const decoded = decodeURIComponent(returnTo);\n const url = new URL(decoded, window.location.origin);\n // Preserve cross-origin absolute returnTo values (e.g., redirects back to\n // another product's app shell) — only strip stale SSO params.\n const isCrossOrigin = url.origin !== window.location.origin;\n return stripStaleSsoParams(url, { includeOrigin: isCrossOrigin });\n } catch {\n return returnTo;\n }\n}\n\n/**\n * Login page with professional design\n * Provides email/password login and social OAuth options\n */\nexport function LoginPage() {\n const tr = useTr();\n const navigate = useNavigate();\n const location = useLocation();\n const [searchParams] = useSearchParams();\n\n const { signIn, isLoading, error, errorCode, resendVerification } =\n useAuthOperations();\n const { completeAuthFlow } = useMyWorkspaces();\n const { setWorkspace, setOrganization } = useActiveContext();\n const { defaultPostLoginPath, navigate: navigateHost } = useAuth();\n const { initiateGoogleOAuth, initiateMicrosoftOAuth, isProviderConfigured } =\n useOAuthOperations();\n const mfaRequired = useAuthStore((state) => state.mfaRequired);\n const { executeRecaptcha: executeCaptchaV3 } = useCaptchaV3();\n const [isCompletingAuth, setIsCompletingAuth] = useState(false);\n const [isSsoRedirecting, setIsSsoRedirecting] = useState(false);\n\n /**\n * Build the URL that should receive the post-login redirect.\n *\n * For cross-eTLD+1 SSO on alpha/prod we detour through the central bridge\n * host (alphaapp/app.burdenoff.com) so the freshly-issued tokens land in\n * the bridge origin's first-party (unpartitioned) localStorage. Without\n * this step, a later direct visit to the bridge host has no local tokens\n * and no shared cookie (cross-eTLD+1 cookies don't propagate), so the user\n * sees the login page again.\n *\n * Skipped when:\n * - Already on the bridge host origin (would be a no-op self-redirect).\n * - The user's intended destination is itself on the bridge host\n * (likely an in-product navigation, no deposit needed).\n * - The freshly-stored profile snapshot can't be read (best-effort only —\n * login still succeeds via the direct redirect).\n */\n const buildPostLoginUrl = useCallback(\n async (intendedPath: string): Promise<string> => {\n if (typeof window === \"undefined\") return intendedPath;\n // Native shells (Electron, Capacitor iOS/Android) run as a single origin —\n // skip the cross-eTLD+1 deposit detour, which would otherwise navigate to\n // an external https URL and escape the embedded webview.\n if (isNativeShell()) return intendedPath;\n try {\n const bridge = resolveAuthBridgeConfig();\n const bridgeUrl = new URL(bridge.url);\n const currentOrigin = window.location.origin;\n if (bridgeUrl.origin === currentOrigin) return intendedPath;\n\n // intendedPath can be a path or an absolute URL; resolve to absolute\n // against current origin so the bridge host knows where to send the\n // user back.\n const absoluteIntended = new URL(intendedPath, currentOrigin).href;\n\n const profileId = resolveActiveProfileId();\n if (!profileId) return intendedPath;\n const tokens = getProfileTokens(profileId);\n const user = getProfileUser(profileId);\n if (!tokens || !user) return intendedPath;\n const workspaceToken = getProfileWorkspaceToken(profileId);\n\n // BOFF-4463: mint a DEDICATED refresh-token lineage for the bridge\n // host. Copying this origin's pair verbatim meant the bridge (and\n // every product it later relayed to) shared ONE rotating refresh\n // token — the first origin to refresh revoked it for all others,\n // surfacing as \"products log me out after minutes/hours\". Falls back\n // to the legacy copy if the mutation is unreachable (rollout gap /\n // transient failure) so SSO keeps working.\n let depositTokens: Record<string, unknown> = {\n ...tokens,\n workspaceToken,\n };\n if (tokens.refreshToken) {\n const { globalBaseUrl } = resolveGatewayUrls();\n const { tokens: minted } = await mintSsoSessionTokens(\n `${globalBaseUrl}/global/graphql`,\n tokens.refreshToken,\n );\n if (minted) {\n depositTokens = { ...minted, workspaceToken };\n }\n }\n\n markSsoDepositPending(profileId);\n return buildSsoDepositUrl(bridgeUrl.origin, absoluteIntended, {\n profileId,\n tokens: JSON.stringify(depositTokens),\n user: JSON.stringify(user),\n profiles: JSON.stringify(getProfiles()),\n });\n } catch {\n return intendedPath;\n }\n },\n [],\n );\n\n // Once a cross-document post-login redirect is initiated, the login page\n // must FREEZE: resetting isCompletingAuth re-runs the auto-redirect effect\n // and any state churn schedules same-document navigations that cancel the\n // provisional deposit hop (BOFF-4463).\n const redirectInitiatedRef = useRef(false);\n\n const redirectAfterLogin = useCallback(\n (path: string) => {\n const safePath = sanitizePostLoginPath(path);\n if (typeof window === \"undefined\") {\n navigate(safePath);\n return;\n }\n const fragmentPath = sameOriginFragmentPath(\n safePath,\n window.location.origin,\n );\n if (fragmentPath) {\n // The authenticated profile is already stored on this origin. Do not\n // copy a fragment capability into bridge payloads or return storage.\n navigateHost(fragmentPath);\n return;\n }\n try {\n sessionStorage.setItem(\"bf-post-login-return-to\", safePath);\n } catch {\n // Ignore storage failures; redirect still proceeds.\n }\n // In native shells use SPA navigation so the embedded webview stays in\n // the app — no full reload, no chance of the OS opening the URL\n // externally. Tokens are already in this origin's localStorage.\n if (isNativeShell()) {\n navigate(toSameOriginPath(safePath));\n return;\n }\n redirectInitiatedRef.current = true;\n void (async () => {\n // Cap the bridge URL build so a hanging SSO token mint cannot keep the\n // login page stuck on the spinner (BOFF-6807). The sanitized path is\n // always safe to redirect to directly.\n const target = await Promise.race([\n buildPostLoginUrl(safePath),\n new Promise<string>((resolve) => {\n window.setTimeout(() => resolve(safePath), 3000);\n }),\n ]);\n if (target.includes(\"/auth/sso-deposit\")) {\n // Cross-document deposit hop: suppress same-document navigators\n // while it is provisional, and retry once if it still gets\n // cancelled — on a committed navigation this document unloads and\n // the timer never fires.\n beginSsoNavigation();\n window.location.assign(target);\n window.setTimeout(() => {\n beginSsoNavigation();\n window.location.replace(target);\n }, 2500);\n } else {\n window.location.assign(target);\n }\n // Fallback: if the document is still stuck on the login page after a\n // full redirect attempt, force an in-app navigation so the spinner\n // cannot stall forever (BOFF-6807). This only fires when the browser\n // failed to leave /auth/login, e.g. because the computed target was\n // still an auth URL or the location.assign was a no-op.\n window.setTimeout(() => {\n if (\n typeof window !== \"undefined\" &&\n window.location.pathname === \"/auth/login\"\n ) {\n navigate(\"/dashboard\");\n }\n }, 3500);\n })();\n },\n [navigate, navigateHost, buildPostLoginUrl],\n );\n const [showPassword, setShowPassword] = useState(false);\n const [isAccountInactive, setIsAccountInactive] = useState(false);\n const [isAccountDeleted, setIsAccountDeleted] = useState(false);\n const [isAccountSuspended, setIsAccountSuspended] = useState(false);\n const [isOAuthOnlyAccount, setIsOAuthOnlyAccount] = useState(false);\n const [isEmailNotVerified, setIsEmailNotVerified] = useState(false);\n const [isResendingVerification, setIsResendingVerification] = useState(false);\n const [resendSuccess, setResendSuccess] = useState(false);\n const [oauthError, setOauthError] = useState<string | null>(null);\n const [infoMessage, setInfoMessage] = useState<string | null>(null);\n const [formData, setFormData] = useState<\n SignInInput & { rememberMe?: boolean }\n >({\n email: \"\",\n password: \"\",\n rememberMe: false,\n });\n const [validationError, setValidationError] = useState<string | null>(null);\n const [isDuplicateAccount, setIsDuplicateAccount] = useState(false);\n\n // Detect add-account mode and returnTo from URL params\n const isAddAccountMode = searchParams.get(\"mode\") === \"add-account\";\n const returnTo = searchParams.get(\"returnTo\");\n const initialReturnToRef = useRef<string | null>(returnTo);\n\n // Tell the user WHY they are back on the login page. `session-expired` is\n // set by the shell's forced logout (expired session whose refresh failed);\n // `logout` covers explicit sign-outs and the SSO-clear fallback (which can\n // rewrite a session-expired redirect's reason on the cross-product bounce).\n // Without this the auto-logout looked like a silent, unexplained kick-out.\n const reasonParam = searchParams.get(\"reason\");\n useEffect(() => {\n if (reasonParam === \"session-expired\") {\n setInfoMessage(\n tr(\n \"auth.login.sessionExpired\",\n \"Your session has expired. Please sign in again.\",\n ),\n );\n } else if (reasonParam === \"logout\") {\n setInfoMessage(tr(\"auth.login.signedOut\", \"You have been signed out.\"));\n }\n }, [reasonParam, tr]);\n\n useEffect(() => {\n if (!initialReturnToRef.current && returnTo) {\n initialReturnToRef.current = returnTo;\n }\n }, [returnTo]);\n\n useEffect(() => {\n if (isAddAccountMode || isCompletingAuth) return;\n // A cross-document SSO navigation (deposit/relay hop) is already in\n // flight — issuing another redirect here would cancel it (BOFF-4463).\n if (redirectInitiatedRef.current || isSsoNavigationPending()) return;\n\n const profileId = resolveActiveProfileId();\n if (profileId) {\n const tokens = getProfileTokens(profileId);\n const user = getProfileUser(profileId);\n if (\n tokens?.accessToken &&\n user &&\n hasValidAccessToken(tokens.accessToken)\n ) {\n useAuthStore.getState().loadFromProfile(profileId);\n redirectAfterLogin(\n decodeSameOriginReturnTo(returnTo) ?? defaultPostLoginPath ?? \"/\",\n );\n return;\n }\n }\n\n // A same-origin fragment continuation must remain here during\n // sign-in too, not only after it. Only the host-declared destination can\n // select this flow; an arbitrary returnTo query must not suppress SSO.\n // Credential/MFA checks above and below still apply unchanged.\n if (\n sameOriginFragmentPath(defaultPostLoginPath ?? \"\", window.location.origin)\n ) {\n return;\n }\n const ssoUrl = getSSORedirectUrl();\n if (ssoUrl) {\n setIsSsoRedirecting(true);\n window.location.replace(ssoUrl);\n }\n }, [\n isAddAccountMode,\n isCompletingAuth,\n redirectAfterLogin,\n returnTo,\n defaultPostLoginPath,\n ]);\n\n // Load remembered email on mount and clean up any legacy plaintext password storage\n useEffect(() => {\n try {\n // Security cleanup: remove any previously stored plaintext passwords\n localStorage.removeItem(\"remembered_password\");\n\n const rememberedEmail = localStorage.getItem(\"remembered_email\");\n\n if (rememberedEmail) {\n setFormData((prev) => ({\n ...prev,\n email: rememberedEmail,\n rememberMe: true,\n }));\n }\n } catch (error) {\n console.warn(\"[LoginPage] Failed to load remembered email:\", error);\n }\n }, []);\n\n // Check for redirect message and email from location state (e.g., from expired MFA or SSO redirect)\n useEffect(() => {\n const state = location.state as { message?: string; email?: string } | null;\n if (state?.message) {\n setInfoMessage(state.message);\n }\n if (state?.email) {\n setFormData((prev) => ({ ...prev, email: state.email }));\n }\n // Clear state to prevent showing message on refresh\n if (state) {\n window.history.replaceState({}, document.title);\n }\n }, [location.state]);\n\n // Determine error type from GraphQL error code (primary) or message (fallback).\n // The backend sends structured codes in extensions.code which are propagated\n // through useAuthOperations → authStore.errorCode.\n const checkErrorType = (\n err: string | null,\n code?: string | null,\n ):\n | \"DELETED\"\n | \"SUSPENDED\"\n | \"OAUTH_ONLY\"\n | \"INACTIVE\"\n | \"EMAIL_NOT_VERIFIED\"\n | null => {\n // Primary: match on GraphQL error code from extensions\n if (code) {\n switch (code) {\n case \"ACCOUNT_DELETED\":\n return \"DELETED\";\n case \"ACCOUNT_SUSPENDED\":\n return \"SUSPENDED\";\n case \"OAUTH_ONLY_ACCOUNT\":\n return \"OAUTH_ONLY\";\n case \"ACCOUNT_INACTIVE\":\n return \"INACTIVE\";\n case \"EMAIL_NOT_VERIFIED\":\n return \"EMAIL_NOT_VERIFIED\";\n default:\n break;\n }\n }\n\n // Fallback: match on error message for non-GraphQL errors or legacy responses\n if (!err) return null;\n const lowerErr = err.toLowerCase();\n\n if (\n lowerErr.includes(\"deleted\") ||\n lowerErr.includes(\"permanently deleted\")\n ) {\n return \"DELETED\";\n }\n if (lowerErr.includes(\"suspended\")) {\n return \"SUSPENDED\";\n }\n if (\n lowerErr.includes(\"oauth provider\") ||\n lowerErr.includes(\"oauth-only\") ||\n lowerErr.includes(\"oauth only\")\n ) {\n return \"OAUTH_ONLY\";\n }\n if (\n lowerErr.includes(\"inactive\") ||\n lowerErr.includes(\"deactivated\") ||\n lowerErr.includes(\"not active\")\n ) {\n return \"INACTIVE\";\n }\n if (\n lowerErr.includes(\"verify your email\") ||\n lowerErr.includes(\"email not verified\") ||\n lowerErr.includes(\"email_not_verified\")\n ) {\n return \"EMAIL_NOT_VERIFIED\";\n }\n return null;\n };\n\n // Pre-fill email from URL query parameter (e.g., after email verification)\n useEffect(() => {\n const emailFromUrl = searchParams.get(\"email\");\n if (emailFromUrl) {\n setFormData((prev) => ({ ...prev, email: emailFromUrl }));\n }\n\n // Check for expired session redirect\n const isExpired = searchParams.get(\"expired\");\n if (isExpired === \"true\") {\n setInfoMessage(\n tr(\n \"auth.login.sessionExpired\",\n \"Your session has expired. Please sign in again.\",\n ),\n );\n // Clear the query param to prevent showing on refresh\n const newUrl = window.location.pathname;\n window.history.replaceState({}, document.title, newUrl);\n }\n }, [searchParams, tr]);\n\n // Redirect to MFA verification when required\n useEffect(() => {\n if (mfaRequired) {\n navigate(\"/auth/mfa-verify\");\n }\n }, [mfaRequired, navigate]);\n\n const handleSubmit = async (e: React.FormEvent) => {\n e.preventDefault();\n setIsAccountInactive(false);\n setIsAccountDeleted(false);\n setIsAccountSuspended(false);\n setIsOAuthOnlyAccount(false);\n setIsEmailNotVerified(false);\n setIsDuplicateAccount(false);\n setResendSuccess(false);\n setValidationError(null);\n\n // Client-side validation\n const emailTrimmed = (formData.email ?? \"\").trim();\n if (!emailTrimmed) {\n setValidationError(\n tr(\n \"auth.login.enterEmailOrUsername\",\n \"Please enter your email or username\",\n ),\n );\n return;\n }\n\n // Basic email format validation (if it contains @)\n if (emailTrimmed.includes(\"@\")) {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(emailTrimmed)) {\n setValidationError(\n tr(\"auth.login.invalidEmail\", \"Please enter a valid email address\"),\n );\n return;\n }\n }\n\n if (!formData.password || formData.password.length < 1) {\n setValidationError(\n tr(\"auth.login.enterPassword\", \"Please enter your password\"),\n );\n return;\n }\n\n // In add-account mode, check if this email is already signed in\n if (isAddAccountMode) {\n const existingProfiles = getProfiles();\n const alreadySignedIn = existingProfiles.some(\n (p) => p.email.toLowerCase() === emailTrimmed.toLowerCase(),\n );\n if (alreadySignedIn) {\n setIsDuplicateAccount(true);\n setValidationError(null);\n return;\n }\n }\n setIsDuplicateAccount(false);\n\n try {\n // Get reCAPTCHA v3 token (no-op when captcha is disabled)\n const recaptchaToken = await executeCaptchaV3(\"login\");\n\n const result = await signIn({\n email: emailTrimmed,\n password: formData.password,\n rememberMe: formData.rememberMe,\n ...(recaptchaToken ? { recaptchaToken } : {}),\n });\n\n // If MFA is required, the useEffect above will handle redirect\n if (result.requiresMFA) {\n // Persist the post-login destination so MfaVerifyPage honors\n // `returnTo` and `defaultPostLoginPath` after the user completes\n // verification — otherwise the MFA path falls back to \"/\" and the\n // host-configured home (e.g. \"/vibecontrols\") is lost.\n const effectiveReturnTo = initialReturnToRef.current || returnTo;\n const postMfaPath = effectiveReturnTo\n ? cleanReturnToValue(effectiveReturnTo)\n : cleanReturnToValue(defaultPostLoginPath ?? \"/dashboard\");\n try {\n sessionStorage.setItem(MFA_REDIRECT, postMfaPath);\n } catch {\n // sessionStorage may be unavailable (private mode, quota) — the\n // MFA page still works, it just defaults to \"/\" on completion.\n }\n return;\n }\n\n // Successful login - complete auth flow (fetch workspaces + issue token)\n if (result.success) {\n try {\n const profileId = result.user?.id;\n if (profileId) {\n const hostname = window.location.hostname;\n const domain = hostname.endsWith(\".local.burdenoff.com\")\n ? \".local.burdenoff.com\"\n : undefined;\n const domainPart = domain ? `; domain=${domain}` : \"\";\n const securePart =\n window.location.protocol === \"https:\" ? \"; secure\" : \"\";\n const ssoValue = JSON.stringify({\n id: profileId,\n origin: window.location.origin,\n });\n document.cookie = `bf-sso=${encodeURIComponent(ssoValue)}${domainPart}; path=/; samesite=lax${securePart}; max-age=86400`;\n document.cookie = `bf-sso-profile=${encodeURIComponent(ssoValue)}${domainPart}; path=/; samesite=lax${securePart}; max-age=86400`;\n }\n } catch {\n // Best effort only. Login can continue without the fast-path cookie.\n }\n\n // Handle Remember Me: Save or clear email only (never store passwords)\n try {\n if (formData.rememberMe) {\n localStorage.setItem(\"remembered_email\", emailTrimmed);\n } else {\n localStorage.removeItem(\"remembered_email\");\n }\n } catch (error) {\n console.warn(\n \"[LoginPage] Failed to save/clear remembered email:\",\n error,\n );\n }\n\n setIsCompletingAuth(true);\n // In add-account mode, redirect back to where the user was\n const effectiveReturnTo = initialReturnToRef.current || returnTo;\n const postLoginPath = effectiveReturnTo\n ? cleanReturnToValue(effectiveReturnTo)\n : cleanReturnToValue(defaultPostLoginPath ?? \"/dashboard\");\n try {\n type AuthFlowResult = Awaited<ReturnType<typeof completeAuthFlow>>;\n // Pass the token directly to avoid race condition with React state updates\n const authFlowResult = await Promise.race<AuthFlowResult>([\n completeAuthFlow(result.token),\n new Promise<AuthFlowResult>((resolve) => {\n window.setTimeout(() => {\n resolve({\n success: false,\n error: \"Auth flow timed out after login\",\n });\n }, 5000);\n }),\n ]);\n\n if (authFlowResult.success) {\n // Sync workspace and organization to ActiveContext\n // This is critical for global search and other workspace-scoped features\n if (authFlowResult.workspace) {\n setWorkspace(authFlowResult.workspace.id);\n if (authFlowResult.workspace.organizationId) {\n setOrganization(authFlowResult.workspace.organizationId);\n }\n }\n\n // Full auth flow completed - redirect to dashboard or returnTo\n redirectAfterLogin(postLoginPath);\n } else if (authFlowResult.error?.includes(\"No workspaces found\")) {\n // A context-free invitation can establish canonical membership after\n // sign-in. Do not force a new organization/workspace first merely\n // because this authenticated actor has no discovery inventory yet.\n if (\n hostFragmentContinuation(\n postLoginPath,\n defaultPostLoginPath,\n window.location.origin,\n )\n ) {\n redirectAfterLogin(postLoginPath);\n } else {\n navigate(\"/onboarding/create-workspace\");\n }\n } else {\n // Partial success or error - still sync workspace if available and redirect\n if (authFlowResult.workspace) {\n setWorkspace(authFlowResult.workspace.id);\n if (authFlowResult.workspace.organizationId) {\n setOrganization(authFlowResult.workspace.organizationId);\n }\n }\n console.warn(\"Auth flow warning:\", authFlowResult.error);\n redirectAfterLogin(postLoginPath);\n }\n } catch (authFlowError) {\n // Auth flow failed but login succeeded - still redirect\n console.error(\"Auth flow error (login succeeded):\", authFlowError);\n redirectAfterLogin(postLoginPath);\n } finally {\n // Keep the completing state (spinner) once a redirect is in\n // flight: resetting it re-arms the auto-redirect effect whose\n // competing navigation cancels the deposit hop (BOFF-4463). The\n // page is about to unload anyway.\n if (!redirectInitiatedRef.current) {\n setIsCompletingAuth(false);\n }\n }\n }\n } catch (err) {\n if (import.meta.env.DEV) {\n console.error(\"Sign in failed:\", err);\n }\n // Check error type using error code (from store) and message\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (errorMsg.includes(\"reCAPTCHA\")) {\n setValidationError(errorMsg);\n }\n const storeErrorCode = useAuthStore.getState().errorCode;\n const errorType = checkErrorType(errorMsg, storeErrorCode);\n if (errorType === \"DELETED\") {\n setIsAccountDeleted(true);\n } else if (errorType === \"SUSPENDED\") {\n setIsAccountSuspended(true);\n } else if (errorType === \"OAUTH_ONLY\") {\n setIsOAuthOnlyAccount(true);\n } else if (errorType === \"INACTIVE\") {\n setIsAccountInactive(true);\n } else if (errorType === \"EMAIL_NOT_VERIFIED\") {\n setIsEmailNotVerified(true);\n }\n }\n };\n\n // Also check the error from useAuthOperations\n useEffect(() => {\n if (error) {\n const errorType = checkErrorType(error, errorCode);\n if (errorType === \"DELETED\") {\n setIsAccountDeleted(true);\n } else if (errorType === \"SUSPENDED\") {\n setIsAccountSuspended(true);\n } else if (errorType === \"OAUTH_ONLY\") {\n setIsOAuthOnlyAccount(true);\n } else if (errorType === \"INACTIVE\") {\n setIsAccountInactive(true);\n } else if (errorType === \"EMAIL_NOT_VERIFIED\") {\n setIsEmailNotVerified(true);\n }\n }\n }, [error, errorCode]);\n\n /**\n * Handle Google OAuth login\n */\n const handleGoogleLogin = () => {\n setOauthError(null);\n try {\n initiateGoogleOAuth();\n } catch (err) {\n setOauthError(\n err instanceof Error\n ? err.message\n : tr(\n \"auth.login.googleSignInFailed\",\n \"Failed to initiate Google sign in\",\n ),\n );\n }\n };\n\n /**\n * Handle Microsoft OAuth login\n */\n const handleMicrosoftLogin = () => {\n setOauthError(null);\n try {\n initiateMicrosoftOAuth();\n } catch (err) {\n setOauthError(\n err instanceof Error\n ? err.message\n : tr(\n \"auth.login.microsoftSignInFailed\",\n \"Failed to initiate Microsoft sign in\",\n ),\n );\n }\n };\n\n /**\n * Handle resend verification email\n */\n const handleResendVerification = async () => {\n setIsResendingVerification(true);\n setResendSuccess(false);\n try {\n const emailTrimmed = (formData.email ?? \"\").trim();\n const result = await resendVerification(emailTrimmed);\n if (result.success) {\n setResendSuccess(true);\n } else {\n setValidationError(\n tr(\n \"auth.login.resendFailed\",\n \"Failed to resend verification email. Please try again.\",\n ),\n );\n }\n } catch (err) {\n console.error(\"Failed to resend verification email:\", err);\n setValidationError(\n err instanceof Error\n ? err.message\n : tr(\n \"auth.login.resendFailed\",\n \"Failed to resend verification email. Please try again.\",\n ),\n );\n } finally {\n setIsResendingVerification(false);\n }\n };\n\n // Check if OAuth providers are configured\n const isGoogleConfigured = isProviderConfigured(\"google\");\n const isMicrosoftConfigured = isProviderConfigured(\"microsoft\");\n\n const oauthProviders = [\n {\n name: \"Google\",\n icon: GoogleIcon,\n onClick: handleGoogleLogin,\n disabled: !isGoogleConfigured,\n tooltip: isGoogleConfigured\n ? undefined\n : tr(\n \"auth.login.googleNotConfigured\",\n \"Google sign in is not configured\",\n ),\n },\n // {\n // name: \"GitHub\",\n // icon: GitHubIcon,\n // onClick: () => {},\n // disabled: true,\n // tooltip: tr(\n // \"auth.login.githubNotConfigured\",\n // \"GitHub sign in is not configured\",\n // ),\n // },\n {\n name: \"Microsoft\",\n icon: MicrosoftIcon,\n onClick: handleMicrosoftLogin,\n disabled: !isMicrosoftConfigured,\n tooltip: isMicrosoftConfigured\n ? undefined\n : tr(\n \"auth.login.microsoftNotConfigured\",\n \"Microsoft sign in is not configured\",\n ),\n },\n ];\n\n if (isSsoRedirecting) {\n return <SSORedirectSpinner />;\n }\n\n return (\n <AuthLayout\n title={tr(\"auth.login.welcomeBack\", \"Welcome back\")}\n subtitle={tr(\n \"auth.login.enterCredentials\",\n \"Enter your credentials to continue\",\n )}\n >\n <PagePurpose className=\"mb-5\">\n {tr(\n \"auth.login.purpose\",\n \"Sign in to reach your workspaces, agents, and settings. Use your email and password, a social provider, or a passwordless magic link.\",\n )}\n </PagePurpose>\n <form onSubmit={handleSubmit} className=\"space-y-5\">\n {/* Info Message (e.g., from expired MFA redirect) */}\n {infoMessage && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-info-bg-subtle border-status-info-border\">\n <svg\n className=\"size-5 flex-shrink-0 mt-0.5 text-text-link\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\"\n />\n </svg>\n <p className=\"text-sm text-status-info-text\">{infoMessage}</p>\n </div>\n )}\n\n {/* Validation Error */}\n {validationError && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-warning-bg-subtle border-status-warning-border\">\n <AlertIcon className=\"size-5 flex-shrink-0 mt-0.5 text-status-warning-text\" />\n <p className=\"text-sm text-status-warning-text\">\n {validationError}\n </p>\n </div>\n )}\n\n {/* Duplicate Account Warning (Add Account mode) */}\n {isDuplicateAccount && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-warning-bg-subtle border-status-warning-border\">\n <AlertIcon className=\"size-5 flex-shrink-0 mt-0.5 text-status-warning-text\" />\n <div className=\"flex-1\">\n <p className=\"text-sm font-medium text-status-warning-text\">\n {tr(\n \"auth.login.duplicateAccount\",\n \"This account is already signed in.\",\n )}\n </p>\n <p className=\"mt-1 text-sm text-status-warning-text/80\">\n {tr(\n \"auth.login.duplicateAccountHint\",\n \"Please use a different account, or go back and switch to this account from the profile menu.\",\n )}\n </p>\n {(initialReturnToRef.current || returnTo) && (\n <button\n type=\"button\"\n onClick={() =>\n navigate(\n decodeURIComponent(\n initialReturnToRef.current || returnTo || \"/dashboard\",\n ),\n )\n }\n className=\"mt-3 inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-status-warning-border bg-bg-surface text-status-warning-text text-sm font-medium hover:bg-status-warning-bg-subtle hover:border-status-warning-border transition-all shadow-sm\"\n >\n <svg\n className=\"size-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M10 19l-7-7m0 0l7-7m-7 7h18\"\n />\n </svg>\n {tr(\n \"auth.login.goBackSwitchAccount\",\n \"Go back and switch account\",\n )}\n </button>\n )}\n </div>\n </div>\n )}\n\n {/* Error Alert */}\n {error && !validationError && !isDuplicateAccount && (\n <div\n className={`flex items-start gap-3 p-4 rounded-xl border ${\n isAccountInactive || isOAuthOnlyAccount || isEmailNotVerified\n ? \"bg-status-warning-bg-subtle border-status-warning-border\"\n : \"bg-status-error-bg-subtle border-status-error-border\"\n }`}\n >\n <AlertIcon\n className={`size-5 flex-shrink-0 mt-0.5 ${\n isAccountInactive || isOAuthOnlyAccount || isEmailNotVerified\n ? \"text-status-warning-text\"\n : \"text-status-error-text\"\n }`}\n />\n <div className=\"flex-1\">\n <p\n className={`text-sm ${\n isAccountInactive || isOAuthOnlyAccount || isEmailNotVerified\n ? \"text-status-warning-text\"\n : \"text-status-error-text\"\n }`}\n >\n {isAccountDeleted\n ? tr(\n \"auth.login.accountDeleted\",\n \"This account has been permanently deleted and cannot be recovered.\",\n )\n : isAccountSuspended\n ? tr(\n \"auth.login.accountSuspended\",\n \"Your account has been suspended. Please contact support for assistance.\",\n )\n : isAccountInactive\n ? tr(\n \"auth.login.accountDeactivated\",\n \"Your account has been deactivated.\",\n )\n : isOAuthOnlyAccount\n ? tr(\n \"auth.login.oauthOnly\",\n \"This account uses OAuth sign-in. Please use Google or Microsoft to sign in.\",\n )\n : isEmailNotVerified\n ? tr(\n \"auth.login.emailNotVerified\",\n \"Please verify your email before signing in. Check your inbox for the verification link.\",\n )\n : error}\n </p>\n {isAccountInactive && (\n <button\n type=\"button\"\n onClick={() =>\n navigate(\"/auth/reactivate\", {\n state: { email: formData.email },\n })\n }\n className=\"mt-2 text-sm font-semibold text-status-warning-text hover:text-status-warning-text underline underline-offset-2\"\n >\n {tr(\n \"auth.login.clickReactivate\",\n \"Click here to reactivate your account\",\n )}\n </button>\n )}\n {isEmailNotVerified && (\n <div className=\"mt-3\">\n {resendSuccess ? (\n <div className=\"flex items-center gap-2 text-sm text-status-success-text\">\n <svg\n className=\"size-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M5 13l4 4L19 7\"\n />\n </svg>\n {tr(\n \"auth.login.verificationSent\",\n \"Verification email sent! Please check your inbox.\",\n )}\n </div>\n ) : (\n <button\n type=\"button\"\n onClick={handleResendVerification}\n disabled={isResendingVerification}\n className=\"inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-status-warning-border bg-bg-surface text-status-warning-text text-sm font-medium hover:bg-status-warning-bg-subtle hover:border-status-warning-border transition-all shadow-sm disabled:opacity-50 disabled:cursor-not-allowed\"\n >\n {isResendingVerification ? (\n <>\n <SpinnerIcon className=\"size-4 animate-spin\" />\n {tr(\"auth.login.sending\", \"Sending...\")}\n </>\n ) : (\n <>\n <svg\n className=\"size-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z\"\n />\n </svg>\n {tr(\n \"auth.login.resendVerification\",\n \"Resend verification email\",\n )}\n </>\n )}\n </button>\n )}\n </div>\n )}\n {isOAuthOnlyAccount && (\n <div className=\"mt-3 flex flex-col gap-2\">\n {isProviderConfigured(\"google\") && (\n <button\n type=\"button\"\n onClick={handleGoogleLogin}\n className=\"inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-border-default bg-bg-surface text-text-primary text-sm font-medium hover:bg-bg-canvas hover:border-border-default transition-all shadow-sm\"\n >\n <GoogleIcon className=\"size-5\" />\n {tr(\"auth.login.signInWithGoogle\", \"Sign in with Google\")}\n </button>\n )}\n {isProviderConfigured(\"microsoft\") && (\n <button\n type=\"button\"\n onClick={handleMicrosoftLogin}\n className=\"inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl border border-border-default bg-bg-surface text-text-primary text-sm font-medium hover:bg-bg-canvas hover:border-border-default transition-all shadow-sm\"\n >\n <MicrosoftIcon className=\"size-5\" />\n {tr(\n \"auth.login.signInWithMicrosoft\",\n \"Sign in with Microsoft\",\n )}\n </button>\n )}\n </div>\n )}\n </div>\n </div>\n )}\n\n {/* Email Input */}\n <div className=\"space-y-2\">\n <label\n htmlFor=\"email\"\n className=\"block text-sm font-medium text-[var(--color-text-primary)]\"\n >\n {tr(\"auth.login.emailLabel\", \"Email\")}\n </label>\n <div className=\"relative\">\n <div className=\"absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none\">\n <EmailIcon className=\"size-5 text-[var(--color-text-tertiary)]\" />\n </div>\n <input\n id=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n required\n aria-required=\"true\"\n aria-label={tr(\"auth.login.emailLabel\", \"Email\")}\n value={formData.email}\n onChange={(e) =>\n setFormData({ ...formData, email: e.target.value })\n }\n className=\"block w-full pl-[3.5rem] pr-4 py-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-2 focus:ring-action-primary-bg/20 focus:border-action-primary-bg transition-all\"\n placeholder={tr(\"auth.login.emailPlaceholder\", \"you@example.com\")}\n />\n </div>\n </div>\n\n {/* Password Input */}\n <div className=\"space-y-2\">\n <label\n htmlFor=\"password\"\n className=\"block text-sm font-medium text-[var(--color-text-primary)]\"\n >\n {tr(\"auth.login.passwordLabel\", \"Password\")}\n </label>\n <div className=\"relative\">\n <div className=\"absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none\">\n <LockIcon className=\"size-5 text-[var(--color-text-tertiary)]\" />\n </div>\n <input\n id=\"password\"\n type={showPassword ? \"text\" : \"password\"}\n autoComplete=\"current-password\"\n required\n aria-required=\"true\"\n aria-label={tr(\"auth.login.passwordLabel\", \"Password\")}\n value={formData.password}\n onChange={(e) =>\n setFormData({ ...formData, password: e.target.value })\n }\n className=\"block w-full pl-[3.5rem] pr-12 py-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-2 focus:ring-action-primary-bg/20 focus:border-action-primary-bg transition-all\"\n placeholder={tr(\n \"auth.login.passwordPlaceholder\",\n \"Enter your password\",\n )}\n />\n <button\n type=\"button\"\n onClick={() => setShowPassword(!showPassword)}\n aria-label={\n showPassword\n ? tr(\"auth.login.hidePassword\", \"Hide password\")\n : tr(\"auth.login.showPassword\", \"Show password\")\n }\n className=\"absolute inset-y-0 right-0 pr-3.5 flex items-center text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] transition-colors\"\n >\n {showPassword ? (\n <EyeOffIcon className=\"size-5\" />\n ) : (\n <EyeIcon className=\"size-5\" />\n )}\n </button>\n </div>\n </div>\n\n {/* Remember & Forgot */}\n <div className=\"flex items-center justify-between\">\n <label\n htmlFor=\"remember-me\"\n className=\"flex items-center gap-2 cursor-pointer group\"\n >\n <Checkbox\n id=\"remember-me\"\n checked={formData.rememberMe}\n onCheckedChange={(checked: boolean | \"indeterminate\") => {\n const isChecked = checked === true;\n setFormData({ ...formData, rememberMe: isChecked });\n\n // Clear saved email immediately when unchecked\n if (!isChecked) {\n try {\n localStorage.removeItem(\"remembered_email\");\n } catch (error) {\n console.warn(\n \"[LoginPage] Failed to clear remembered email:\",\n error,\n );\n }\n }\n }}\n aria-label={tr(\"auth.login.rememberMe\", \"Remember me\")}\n />\n <span className=\"text-sm text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)] transition-colors\">\n {tr(\"auth.login.rememberMe\", \"Remember me\")}\n </span>\n </label>\n <button\n type=\"button\"\n onClick={() => navigate(\"/auth/reset-password\")}\n className=\"text-sm font-medium text-text-link hover:text-text-linkHover transition-colors\"\n >\n {tr(\"auth.login.forgotPassword\", \"Forgot password?\")}\n </button>\n </div>\n\n {/* Submit Button */}\n <Button\n type=\"submit\"\n disabled={isLoading || isCompletingAuth}\n variant=\"default\"\n size=\"lg\"\n className=\"w-full font-semibold\"\n >\n {isLoading || isCompletingAuth ? (\n <>\n <SpinnerIcon className=\"size-5 animate-spin\" />\n <span>\n {isCompletingAuth\n ? tr(\n \"auth.login.settingUpWorkspace\",\n \"Setting up workspace...\",\n )\n : tr(\"auth.login.signingIn\", \"Signing in...\")}\n </span>\n </>\n ) : (\n tr(\"auth.login.signIn\", \"Sign in\")\n )}\n </Button>\n </form>\n\n {/* Divider */}\n <div className=\"relative my-8\">\n <div className=\"absolute inset-0 flex items-center\">\n <div className=\"w-full border-t border-[var(--color-border-default)]\" />\n </div>\n <div className=\"relative flex justify-center\">\n <span className=\"px-4 bg-[var(--color-bg-canvas)] text-sm text-[var(--color-text-tertiary)]\">\n {tr(\"auth.login.orContinueWith\", \"or continue with\")}\n </span>\n </div>\n </div>\n\n {/* OAuth Error */}\n {oauthError && (\n <div className=\"flex items-start gap-3 p-4 rounded-xl border bg-status-error-bg-subtle border-status-error-border\">\n <AlertIcon className=\"size-5 flex-shrink-0 mt-0.5 text-status-error-text\" />\n <p className=\"text-sm text-status-error-text\">{oauthError}</p>\n </div>\n )}\n\n {/* OAuth Buttons */}\n <div className=\"grid grid-cols-3 gap-3\">\n {oauthProviders.map((provider) => (\n <button\n key={provider.name}\n type=\"button\"\n onClick={provider.onClick}\n disabled={provider.disabled}\n title={provider.tooltip}\n aria-label={provider.name}\n className={`flex items-center justify-center gap-2 px-4 py-3 rounded-xl border transition-all duration-200 group ${\n provider.disabled\n ? \"border-[var(--color-border-subtle)] bg-[var(--color-bg-disabled)] cursor-not-allowed opacity-50\"\n : \"border-[var(--color-border-default)] bg-[var(--color-bg-surface)] hover:bg-[var(--color-bg-sunken)] hover:border-[var(--color-border-strong)]\"\n }`}\n >\n <provider.icon\n className={`size-5 ${provider.disabled ? \"opacity-50\" : \"\"}`}\n />\n <span\n className={`sr-only sm:not-sr-only text-sm font-medium transition-colors ${\n provider.disabled\n ? \"text-[var(--color-text-disabled)]\"\n : \"text-[var(--color-text-secondary)] group-hover:text-[var(--color-text-primary)]\"\n }`}\n >\n {provider.name}\n </span>\n </button>\n ))}\n </div>\n\n {/* Enterprise SSO Option — temporarily hidden */}\n {/* <div className=\"mt-6\">\n <button type=\"button\"\n onClick={() => navigate(\"/auth/sso/login\")}\n className=\"w-full flex items-center justify-center gap-3 px-4 py-3 rounded-xl border-2 border-dashed border-[var(--color-border-default)] hover:border-action-primary-bg bg-[var(--color-bg-surface)] hover:bg-status-info-bg-subtle transition-all duration-200 group\"\n >\n <svg\n className=\"size-5 text-[var(--color-text-tertiary)] group-hover:text-text-link\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={1.5}\n d=\"M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4\"\n />\n </svg>\n <span className=\"text-sm font-medium text-[var(--color-text-secondary)] group-hover:text-text-link\">\n {tr(\"auth.login.enterpriseSso\", \"Sign in with Enterprise SSO\")}\n </span>\n </button>\n </div> */}\n\n {/* Magic Link Option */}\n <div className=\"mt-4 text-center\">\n <button\n type=\"button\"\n onClick={() => navigate(\"/auth/magic-link\")}\n className=\"text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors\"\n >\n {tr(\"auth.login.preferPasswordless\", \"Prefer passwordless login?\")}{\" \"}\n <span className=\"font-semibold text-text-link hover:text-text-linkHover\">\n {tr(\"auth.login.signInMagicLink\", \"Sign in with Magic Link\")}\n </span>\n </button>\n </div>\n\n {/* Sign Up Link */}\n <p className=\"mt-6 text-center text-sm text-[var(--color-text-secondary)]\">\n {tr(\"auth.login.dontHaveAccount\", \"Don't have an account?\")}{\" \"}\n <button\n type=\"button\"\n onClick={() => navigate(\"/auth/register\")}\n className=\"font-semibold text-text-link hover:text-text-linkHover transition-colors\"\n >\n {tr(\"auth.login.signUp\", \"Sign up\")}\n </button>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C,QAAD;MAAM,WAAU;MACb,UAAAA,EAAG,6BAA6B,kBAAkB;KAC/C,CAAA;IACH,CAAA,CACF;;GAGJ0E,MACC,kBAAC,OAAD;IAAK,WAAU;IAAf,UAAA,CACE,kBAAC+D,GAAD,EAAW,WAAU,qDAAsD,CAAA,GAC3E,kBAAC,KAAD;KAAG,WAAU;KAAkC,UAAA/D;IAAc,CAAA,CAC1D;;GAIP,kBAAC,OAAD;IAAK,WAAU;IACZ,UAAAyD,GAAe,KAAK,MACnB,kBAAC,UAAD;KAEE,MAAK;KACL,SAASmB,EAAS;KAClB,UAAUA,EAAS;KACnB,OAAOA,EAAS;KAChB,cAAYA,EAAS;KACrB,WAAW,wGACTA,EAAS,WACL,oGACA;KAVR,UAAA,CAaE,kBAACA,EAAS,MAAV,EACE,WAAW,UAAUA,EAAS,WAAW,eAAe,KACzD,CAAA,GACD,kBAAC,QAAD;MACE,WAAW,gEACTA,EAAS,WACL,sCACA;MAGL,UAAAA,EAAS;KACN,CAAA,CACA;IAxBD,GAAAA,EAAS,IAwBR,CACT;GACE,CAAA;GA4BL,kBAAC,OAAD;IAAK,WAAU;IACb,UAAA,kBAAC,UAAD;KACE,MAAK;KACL,eAAepJ,EAAS,kBAAkB;KAC1C,WAAU;KAHZ,UAAA;MAKGF,EAAG,iCAAiC,4BAA4B;MAAG;MACpE,kBAAC,QAAD;OAAM,WAAU;OACb,UAAAA,EAAG,8BAA8B,yBAAyB;MACvD,CAAA;KACA;;GACL,CAAA;GAGL,kBAAC,KAAD;IAAG,WAAU;IAAb,UAAA;KACGA,EAAG,8BAA8B,wBAAwB;KAAG;KAC7D,kBAAC,UAAD;MACE,MAAK;MACL,eAAeE,EAAS,gBAAgB;MACxC,WAAU;MAET,UAAAF,EAAG,qBAAqB,SAAS;KAC5B,CAAA;IACP;;EACO;;AAEhB"}
|
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
* Keeps redirect-sanitization logic pure and unit-testable so the login page
|
|
5
5
|
* cannot accidentally redirect back into an auth route (BOFF-6807).
|
|
6
6
|
*/
|
|
7
|
+
/** Keep fragment-bearing destinations on this origin instead of encoding a
|
|
8
|
+
* potential capability into a cross-origin SSO bridge return query. This only
|
|
9
|
+
* chooses navigation after authentication; it grants no identity or context. */
|
|
10
|
+
export declare function sameOriginFragmentPath(path: string, origin: string): string | null;
|
|
11
|
+
/** A host can nominate a context-free invitation destination, but a query-only
|
|
12
|
+
* return path cannot opt an actor out of ordinary workspace onboarding. */
|
|
13
|
+
export declare function hostFragmentContinuation(path: string, hostPath: string | undefined, origin: string): string | null;
|
|
7
14
|
/**
|
|
8
15
|
* Ensure the post-login destination never lands back on an auth route.
|
|
9
16
|
* Falls back to `/dashboard` when the supplied path is empty, "/", or an
|
|
@@ -7,9 +7,21 @@ function e(e) {
|
|
|
7
7
|
return !1;
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
function t(t) {
|
|
10
|
+
function t(e, t) {
|
|
11
|
+
try {
|
|
12
|
+
let n = new URL(e, t);
|
|
13
|
+
return n.origin !== t || !["http:", "https:"].includes(n.protocol) || !n.hash || n.username || n.password || n.pathname.startsWith("/auth") ? null : `${n.pathname}${n.search}${n.hash}`;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function n(e, n, r) {
|
|
19
|
+
let i = t(n ?? "", r);
|
|
20
|
+
return i && i === t(e, r) ? i : null;
|
|
21
|
+
}
|
|
22
|
+
function r(t) {
|
|
11
23
|
return typeof window > "u" ? t : !t || t === "/" || e(t) ? "/dashboard" : t;
|
|
12
24
|
}
|
|
13
|
-
export { t as sanitizePostLoginPath };
|
|
25
|
+
export { n as hostFragmentContinuation, t as sameOriginFragmentPath, r as sanitizePostLoginPath };
|
|
14
26
|
|
|
15
27
|
//# sourceMappingURL=redirect.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redirect.js","names":["isAuthRoutePath","path","sanitizePostLoginPath"],"sources":["../../../src/auth/utils/redirect.ts"],"sourcesContent":["/**\n * Redirect helpers for the post-login flow.\n *\n * Keeps redirect-sanitization logic pure and unit-testable so the login page\n * cannot accidentally redirect back into an auth route (BOFF-6807).\n */\n\nfunction isAuthRoutePath(path: string): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n const url = new URL(path, window.location.origin);\n return url.pathname.startsWith(\"/auth\");\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure the post-login destination never lands back on an auth route.\n * Falls back to `/dashboard` when the supplied path is empty, \"/\", or an\n * `/auth/*` path.\n */\nexport function sanitizePostLoginPath(path: string): string {\n if (typeof window === \"undefined\") return path;\n if (!path || path === \"/\" || isAuthRoutePath(path)) {\n return \"/dashboard\";\n }\n return path;\n}\n"],"mappings":";AAOA,SAASA,EAAgB,GAAuB;CAC9C,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAI;EAEF,OAAO,IADS,IAAIC,GAAM,OAAO,SAAS,MACnC,CAAA,CAAI,SAAS,WAAW,OAAO;CACxC,QAAQ;EACN,OAAO;CACT;AACF;
|
|
1
|
+
{"version":3,"file":"redirect.js","names":["isAuthRoutePath","path","sameOriginFragmentPath","url","origin","hostFragmentContinuation","declared","hostPath","sanitizePostLoginPath"],"sources":["../../../src/auth/utils/redirect.ts"],"sourcesContent":["/**\n * Redirect helpers for the post-login flow.\n *\n * Keeps redirect-sanitization logic pure and unit-testable so the login page\n * cannot accidentally redirect back into an auth route (BOFF-6807).\n */\n\nfunction isAuthRoutePath(path: string): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n const url = new URL(path, window.location.origin);\n return url.pathname.startsWith(\"/auth\");\n } catch {\n return false;\n }\n}\n\n/** Keep fragment-bearing destinations on this origin instead of encoding a\n * potential capability into a cross-origin SSO bridge return query. This only\n * chooses navigation after authentication; it grants no identity or context. */\nexport function sameOriginFragmentPath(\n path: string,\n origin: string,\n): string | null {\n try {\n const url = new URL(path, origin);\n if (\n url.origin !== origin ||\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n !url.hash ||\n url.username ||\n url.password ||\n url.pathname.startsWith(\"/auth\")\n ) {\n return null;\n }\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return null;\n }\n}\n\n/** A host can nominate a context-free invitation destination, but a query-only\n * return path cannot opt an actor out of ordinary workspace onboarding. */\nexport function hostFragmentContinuation(\n path: string,\n hostPath: string | undefined,\n origin: string,\n): string | null {\n const declared = sameOriginFragmentPath(hostPath ?? \"\", origin);\n return declared && declared === sameOriginFragmentPath(path, origin)\n ? declared\n : null;\n}\n\n/**\n * Ensure the post-login destination never lands back on an auth route.\n * Falls back to `/dashboard` when the supplied path is empty, \"/\", or an\n * `/auth/*` path.\n */\nexport function sanitizePostLoginPath(path: string): string {\n if (typeof window === \"undefined\") return path;\n if (!path || path === \"/\" || isAuthRoutePath(path)) {\n return \"/dashboard\";\n }\n return path;\n}\n"],"mappings":";AAOA,SAASA,EAAgB,GAAuB;CAC9C,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAI;EAEF,OAAO,IADS,IAAIC,GAAM,OAAO,SAAS,MACnC,CAAA,CAAI,SAAS,WAAW,OAAO;CACxC,QAAQ;EACN,OAAO;CACT;AACF;AAKA,SAAgBC,EACd,GACA,GACe;CACf,IAAI;EACF,IAAMC,IAAM,IAAI,IAAIF,GAAMG,CAAM;EAWhC,OATED,EAAI,WAAWC,KACf,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,SAASD,EAAI,QAAQ,KAC1C,CAACA,EAAI,QACLA,EAAI,YACJA,EAAI,YACJA,EAAI,SAAS,WAAW,OAAO,IAExB,OAEF,GAAGA,EAAI,WAAWA,EAAI,SAASA,EAAI;CAC5C,QAAQ;EACN,OAAO;CACT;AACF;AAIA,SAAgBE,EACd,GACA,GACA,GACe;CACf,IAAMC,IAAWJ,EAAuBK,KAAY,IAAIH,CAAM;CAC9D,OAAOE,KAAYA,MAAaJ,EAAuBD,GAAMG,CAAM,IAC/DE,IACA;AACN;AAOA,SAAgBE,EAAsB,GAAsB;CAK1D,OAJI,OAAO,SAAW,MAAoBP,IACtC,CAACA,KAAQA,MAAS,OAAOD,EAAgBC,CAAI,IACxC,eAEFA;AACT"}
|
|
@@ -12,7 +12,7 @@ function t(e) {
|
|
|
12
12
|
function n(e) {
|
|
13
13
|
return [...e].length;
|
|
14
14
|
}
|
|
15
|
-
var r = /^[\p{L}\p{M} '.\-\u00B7\u30FB\u200C\u200D]
|
|
15
|
+
var r = /^[\p{L}\p{M} '.\-\u00B7\u30FB\u200C\u200D]+$/u, i = /[\u2018\u2019\u02BC]/g, a = /[\u2010\u2011]/g;
|
|
16
16
|
function o(e) {
|
|
17
17
|
let t = (e ?? "").normalize("NFC").replace(i, "'").replace(a, "-").trim();
|
|
18
18
|
return n(t) < 1 ? {
|
|
@@ -23,10 +23,7 @@ function o(e) {
|
|
|
23
23
|
valid: !1,
|
|
24
24
|
code: "too_long",
|
|
25
25
|
message: "Name must be 100 characters or fewer"
|
|
26
|
-
} : r.test(t) ? {
|
|
27
|
-
valid: !0,
|
|
28
|
-
value: t
|
|
29
|
-
} : /\p{L}/u.test(t) ? {
|
|
26
|
+
} : !/\p{L}/u.test(t) || !r.test(t) ? /\p{L}/u.test(t) ? {
|
|
30
27
|
valid: !1,
|
|
31
28
|
code: "invalid_chars",
|
|
32
29
|
message: "Name can only contain letters, spaces, periods, hyphens, and apostrophes"
|
|
@@ -34,6 +31,9 @@ function o(e) {
|
|
|
34
31
|
valid: !1,
|
|
35
32
|
code: "no_letter",
|
|
36
33
|
message: "Name must contain at least one letter"
|
|
34
|
+
} : {
|
|
35
|
+
valid: !0,
|
|
36
|
+
value: t
|
|
37
37
|
};
|
|
38
38
|
}
|
|
39
39
|
var s = /^[a-zA-Z0-9_-]+$/;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":["validateEmail","email","validatePassword","errors","password","lengthInCodePoints","s","NAME_ALLOWED_CHARS","TYPOGRAPHIC_APOSTROPHES","TYPOGRAPHIC_HYPHENS","validateName","trimmed","name","USERNAME_ALLOWED_CHARS","validateUsername","value","username","validateUserFields","requireAll","options","isBlank","v","firstName","input","lastName","valueOr","result","fallback","validatePhoneNumber","phone","digits"],"sources":["../../../src/auth/utils/validation.ts"],"sourcesContent":["import type { PasswordStrength } from \"../types\";\n\n/**\n * Validate email format\n */\nexport function validateEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Validate password requirements\n */\nexport function validatePassword(password: string): {\n valid: boolean;\n errors: string[];\n} {\n const errors: string[] = [];\n\n if (password.length < 12) {\n errors.push(\"Password must be at least 12 characters long\");\n }\n\n if (!/[A-Z]/.test(password)) {\n errors.push(\"Password must contain at least one uppercase letter\");\n }\n\n if (!/[a-z]/.test(password)) {\n errors.push(\"Password must contain at least one lowercase letter\");\n }\n\n if (!/[0-9]/.test(password)) {\n errors.push(\"Password must contain at least one number\");\n }\n\n if (!/[!@#$%^&*(),.?\":{}|<>]/.test(password)) {\n errors.push(\"Password must contain at least one special character\");\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Calculate password strength using Zxcvbn-like algorithm\n * Returns a score from 0-4 (0 = very weak, 4 = very strong)\n */\nexport function calculatePasswordStrength(password: string): PasswordStrength {\n let score: 0 | 1 | 2 | 3 | 4 = 0;\n const feedback: string[] = [];\n\n // Length check\n if (password.length >= 8) score++;\n if (password.length >= 12) score++;\n if (password.length >= 16) score++;\n\n // Complexity checks\n if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;\n if (/[0-9]/.test(password)) score++;\n if (/[!@#$%^&*(),.?\":{}|<>]/.test(password)) score++;\n\n // Common patterns\n if (/^[a-z]+$/.test(password.toLowerCase())) {\n feedback.push(\"Add uppercase letters, numbers, and symbols\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n if (/^[0-9]+$/.test(password)) {\n feedback.push(\"Avoid using only numbers\");\n score = 0;\n }\n\n if (/(.)\\1{2,}/.test(password)) {\n feedback.push(\"Avoid repeating characters\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n // Common passwords\n const commonPasswords = [\"password\", \"123456\", \"qwerty\", \"admin\", \"letmein\"];\n if (commonPasswords.some((p) => password.toLowerCase().includes(p))) {\n feedback.push(\"Avoid using common passwords\");\n score = 0;\n }\n\n // Ensure score is 0-4\n score = Math.min(4, Math.max(0, score)) as 0 | 1 | 2 | 3 | 4;\n\n // Crack time estimation\n const crackTime =\n score === 0\n ? \"less than 1 second\"\n : score === 1\n ? \"less than 1 minute\"\n : score === 2\n ? \"less than 1 hour\"\n : score === 3\n ? \"less than 1 day\"\n : \"centuries\";\n\n return { score, feedback, crackTime };\n}\n\n/**\n * Validate MFA code format (6 digits)\n */\nexport function validateMfaCode(code: string): boolean {\n return /^\\d{6}$/.test(code);\n}\n\n/**\n * Validate API key name\n */\nexport function validateApiKeyName(name: string): {\n valid: boolean;\n error?: string;\n} {\n if (!name || name.trim().length === 0) {\n return { valid: false, error: \"API key name is required\" };\n }\n\n if (name.length > 100) {\n return {\n valid: false,\n error: \"API key name must be less than 100 characters\",\n };\n }\n\n return { valid: true };\n}\n/**\n * Minimum/maximum lengths for a person's name (first or last), measured in\n * Unicode code points (NOT JavaScript `.length`, which counts UTF-16 code\n * units — see `lengthInCodePoints`).\n *\n * Picked to stay well under the 255-char Prisma `User.firstName/lastName`\n * columns with headroom.\n */\nconst NAME_MIN_LENGTH = 1;\nconst NAME_MAX_LENGTH = 100;\n\n/**\n * Count Unicode code points in `s` instead of UTF-16 code units. Names\n * written in scripts that live in the supplementary plane (Adlam 𞤁𞤔𞤣,\n * many CJK extensions, etc.) have each letter encoded as two UTF-16 units,\n * so a 51-letter Adlam name would otherwise be miscounted as 102 and\n * rejected as too long (Codex P2 review).\n *\n * Code-point counting is sufficient for the name validator — grapheme-\n * cluster counting would also handle emoji ZWJ sequences, but the name\n * regex already disallows emoji.\n */\nfunction lengthInCodePoints(s: string): number {\n return [...s].length;\n}\n\n/**\n * Regex for an acceptable name. Must contain at least one letter (so \"12345\",\n * \"12 34\", \"---\" all fail). Every character must be a letter, mark, literal\n * space, hyphen, apostrophe, period, middle-dot, or join control —\n * diacritics-friendly across scripts (Latin, Tamil, Chinese, etc.).\n *\n * Note: a literal space, not `\\s` — `\\s` matches tabs/newlines/other Unicode\n * whitespace which has no business being inside a person's name (review #2).\n *\n * Two middle-dot codepoints are allowed as-is, NOT folded to `.` — they're\n * orthographically distinct and silently rewriting the user's name would\n * corrupt their identity (Codex P2 reviews):\n * U+00B7 — middle dot, used in Catalan (`Joan·Maria`), Chinese\n * (`阿布杜拉·阿扎姆`), and Russian.\n * U+30FB — katakana middle dot, the standard Japanese separator for\n * foreign personal names (`ジョン・スミス`).\n *\n * Zero-width join controls are also allowed as-is:\n * U+200C ZERO WIDTH NON-JOINER — required for Persian compound names\n * like `محمدرضا` so the letters don't ligate.\n * U+200D ZERO WIDTH JOINER — used in some Indic scripts and emoji\n * sequences (we don't allow emoji ZWJ, but the codepoint is\n * accepted as a generic join marker).\n *\n * Typographic apostrophes (U+2018 / U+2019) and modifier letter apostrophe\n * (U+02BC), and typographic hyphens (U+2010 / U+2011), ARE folded to their\n * ASCII equivalents before validation — they're typographic variants of the\n * same character, not semantically distinct (Codex P2 review).\n *\n * BOFF-7214.\n */\nconst NAME_ALLOWED_CHARS =\n /^[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]*\\p{L}[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]*$/u;\nconst TYPOGRAPHIC_APOSTROPHES = /[\\u2018\\u2019\\u02BC]/g;\nconst TYPOGRAPHIC_HYPHENS = /[\\u2010\\u2011]/g;\n\n/**\n * Machine-readable name-validation error codes. The caller maps each code\n * to a distinct i18n key (review #1) so that one validator error doesn't\n * collapse N different messages into one translated string.\n */\nexport type NameErrorCode =\n | \"required\"\n | \"too_long\"\n | \"no_letter\"\n | \"invalid_chars\";\n\nexport type NameValidationResult =\n | { valid: true; value: string }\n | { valid: false; code: NameErrorCode; message: string };\n\n/**\n * Validate a person's name (first or last).\n * Accepts `string | undefined | null` because the signup form types name\n * fields as optional (matching the `SignUpInput` contract); an absent value\n * is treated as \"missing\" and fails the validation.\n * On success the result carries the canonicalised `value` (trimmed, with\n * typographic apostrophes folded to ASCII) so the caller can submit the\n * exact same string the validator approved — otherwise the validated\n * string and the value sent to `signUp()` would diverge (e.g. user types\n * `\" O'Connor \"`, validator normalises to `\"O'Connor\"`, but signUp\n * receives the original raw value).\n * Returns a structured result so the caller can decide how to render errors.\n */\nexport function validateName(\n name: string | undefined | null,\n): NameValidationResult {\n // Normalise typographic apostrophes and hyphens to their ASCII\n // equivalents before testing — these are typographic variants of the\n // same character, so the canonical ASCII form is what reaches the DB.\n // (Middle-dot U+00B7 is preserved as-is: see NAME_ALLOWED_CHARS comment.)\n // NFC normalisation happens before trim/length so combining-mark\n // sequences (e.g. `e\\u0301` for `é`) fold to their precomposed\n // form first — otherwise `(\"e\\u0301\").repeat(51)` would over-count\n // to 102 code points and reject a valid 51-character name (Codex P2).\n const trimmed = (name ?? \"\")\n .normalize(\"NFC\")\n .replace(TYPOGRAPHIC_APOSTROPHES, \"'\")\n .replace(TYPOGRAPHIC_HYPHENS, \"-\")\n .trim();\n\n if (lengthInCodePoints(trimmed) < NAME_MIN_LENGTH) {\n return { valid: false, code: \"required\", message: \"Name is required\" };\n }\n\n if (lengthInCodePoints(trimmed) > NAME_MAX_LENGTH) {\n return {\n valid: false,\n code: \"too_long\",\n message: `Name must be ${NAME_MAX_LENGTH} characters or fewer`,\n };\n }\n\n if (!NAME_ALLOWED_CHARS.test(trimmed)) {\n // The combined regex distinguishes the two failure modes that matter\n // to the user: a value with no letters vs. a value with disallowed\n // characters. Surface the right hint for each.\n if (!/\\p{L}/u.test(trimmed)) {\n return {\n valid: false,\n code: \"no_letter\",\n message: \"Name must contain at least one letter\",\n };\n }\n return {\n valid: false,\n code: \"invalid_chars\",\n message:\n \"Name can only contain letters, spaces, periods, hyphens, and apostrophes\",\n };\n }\n\n return { valid: true, value: trimmed };\n}\n\n/**\n * Regex for characters allowed in a username. Letters, digits, underscores,\n * hyphens — the existing rule. The new rule layered on top (BOFF-7214):\n * a username must contain at least one letter, so an attacker cannot create\n * an account like \"12345\" with a throwaway email.\n */\nconst USERNAME_ALLOWED_CHARS = /^[a-zA-Z0-9_-]+$/;\nconst USERNAME_MIN_LENGTH = 3;\nconst USERNAME_MAX_LENGTH = 30;\n/**\n * Machine-readable username-validation error codes — one per failing rule\n * (review #1) so each can map to its own i18n key.\n */\nexport type UsernameErrorCode =\n | \"required\"\n | \"too_short\"\n | \"too_long\"\n | \"invalid_chars\"\n | \"no_letter\";\n\nexport type UsernameValidationResult =\n | { valid: true; value: string }\n | {\n valid: false;\n errors: Array<{ code: UsernameErrorCode; message: string }>;\n };\n\n/**\n * Validate a username.\n * Accepts `string | undefined | null` for parity with `validateName` and the\n * optional `SignUpInput.username` contract.\n *\n * Surrounding whitespace is trimmed before the length / character checks —\n * a pasted `\" alice_01 \"` would otherwise fail with a misleading\n * \"can only contain letters, numbers, underscores, and hyphens\" error\n * when the actual problem is invisible whitespace. On success the result\n * carries the trimmed `value` so the caller submits the same string the\n * validator approved (Claude LOW review).\n * Returns a structured result with a list of errors so the caller can\n * render every failing rule at once (mirrors `validatePassword`).\n */\nexport function validateUsername(\n username: string | undefined | null,\n): UsernameValidationResult {\n const errors: Array<{ code: UsernameErrorCode; message: string }> = [];\n const value = (username ?? \"\").trim();\n\n if (lengthInCodePoints(value) === 0) {\n errors.push({\n code: \"required\",\n message: \"Username is required\",\n });\n } else {\n if (lengthInCodePoints(value) < USERNAME_MIN_LENGTH) {\n errors.push({\n code: \"too_short\",\n message: `Username must be at least ${USERNAME_MIN_LENGTH} characters`,\n });\n }\n\n if (lengthInCodePoints(value) > USERNAME_MAX_LENGTH) {\n errors.push({\n code: \"too_long\",\n message: `Username must be ${USERNAME_MAX_LENGTH} characters or fewer`,\n });\n }\n\n if (!USERNAME_ALLOWED_CHARS.test(value)) {\n errors.push({\n code: \"invalid_chars\",\n message:\n \"Username can only contain letters, numbers, underscores, and hyphens\",\n });\n }\n\n // Must contain at least one letter — guards against all-numeric or\n // all-symbol usernames slipping through. Pure numeric values like\n // \"12345\" previously passed the character allow-list alone.\n if (\n lengthInCodePoints(value) >= USERNAME_MIN_LENGTH &&\n !/[a-zA-Z]/.test(value)\n ) {\n errors.push({\n code: \"no_letter\",\n message: \"Username must contain at least one letter\",\n });\n }\n }\n\n return errors.length === 0\n ? { valid: true, value }\n : { valid: false, errors };\n}\n\n/**\n * Bundle validation across all three user-identity fields so callers\n * (RegisterPage, UserProfilePage, UsersPage) can fail fast on the whole\n * form instead of piecemeal — and so the BOFF-7214 invariant\n * (firstName / lastName contain a letter; username contains a letter)\n * is enforced at every mutation surface, not just signup.\n *\n * On success, the result carries the canonicalised values from each\n * individual validator so the caller submits the same strings the\n * validators approved (no validate/submit divergence).\n *\n * The caller is responsible for mapping each `{ field, code, message }`\n * error to its own i18n key — different surfaces have different key\n * namespaces (`auth.register.*`, `auth.profile.*`, `auth.users.*`).\n */\nexport type UserFieldKey = \"firstName\" | \"lastName\" | \"username\";\n\nexport interface UserFieldError {\n field: UserFieldKey;\n code: string;\n message: string;\n}\n\nexport interface ValidatedUserFields {\n firstName: string;\n lastName: string;\n username: string;\n}\n\nexport type UserFieldsValidationResult =\n | { valid: true; values: ValidatedUserFields }\n | { valid: false; errors: UserFieldError[] };\n\nexport function validateUserFields(\n input: {\n firstName?: string | null;\n lastName?: string | null;\n username?: string | null;\n },\n options: { requireAll?: boolean } = {},\n): UserFieldsValidationResult {\n // Default to requiring every field. Profile-edit surfaces pass\n // `requireAll: false` so an existing user whose optional firstName /\n // lastName is unset (e.g. provisioned via an identity provider) can\n // still update unrelated fields like phone or role (Codex P2 review).\n const requireAll = options.requireAll ?? true;\n const errors: UserFieldError[] = [];\n\n // Skip the validator entirely when a field is empty AND requireAll is\n // false — that means \"user is leaving this field blank\". The signup\n // form always requires every field; profile edit does not.\n const isBlank = (v: string | null | undefined): boolean =>\n !v || v.trim().length === 0;\n\n const firstName =\n !isBlank(input.firstName) || requireAll\n ? validateName(input.firstName)\n : null;\n if (firstName && !firstName.valid) {\n errors.push({\n field: \"firstName\",\n code: firstName.code,\n message: firstName.message,\n });\n }\n\n const lastName =\n !isBlank(input.lastName) || requireAll\n ? validateName(input.lastName)\n : null;\n if (lastName && !lastName.valid) {\n errors.push({\n field: \"lastName\",\n code: lastName.code,\n message: lastName.message,\n });\n }\n\n const username =\n !isBlank(input.username) || requireAll\n ? validateUsername(input.username)\n : null;\n if (username && !username.valid) {\n for (const e of username.errors) {\n errors.push({ field: \"username\", code: e.code, message: e.message });\n }\n }\n\n if (errors.length > 0) return { valid: false, errors };\n\n // Return canonical values: trimmed/NFC-normalised when validated, the\n // original trimmed value when the field was optional and left blank.\n // The cast is sound because the `errors.length > 0` early-return above\n // guarantees each result, when non-null, is the `{ valid: true }` arm.\n const valueOr = (\n result: { valid: true; value: string } | null,\n fallback: string | null | undefined,\n ): string => (result ? result.value : (fallback ?? \"\").trim());\n\n return {\n valid: true,\n values: {\n firstName: valueOr(\n firstName as { valid: true; value: string } | null,\n input.firstName,\n ),\n lastName: valueOr(\n lastName as { valid: true; value: string } | null,\n input.lastName,\n ),\n username: valueOr(\n username as { valid: true; value: string } | null,\n input.username,\n ),\n },\n };\n}\n\n/**\n * Validate a phone number (BOFF-7216).\n *\n * Phone numbers are optional on profile / admin edit forms — an empty input\n * is accepted. When a value is supplied it must:\n * - contain only digits, spaces, and the formatting characters + - ( )\n * - include 7–15 digits (E.164-style length bounds; we don't strip \"+\"\n * country prefix here, we just count digits)\n * - start with +, a digit, or (\n *\n * Returns `{ valid: true }` on an empty / whitespace-only input.\n * Returns `{ valid: false, error }` with a human-readable message on\n * rejection. The message is intentionally plain English so the caller can\n * either display it verbatim or pipe it through `tr()` with an i18n key.\n */\nexport function validatePhoneNumber(phone: string): {\n valid: boolean;\n error?: string;\n} {\n const trimmed = phone.trim();\n\n if (trimmed.length === 0) {\n return { valid: true };\n }\n\n if (!/^[0-9+\\-() ]+$/.test(trimmed)) {\n return {\n valid: false,\n error:\n \"Phone number can only contain digits, spaces, and the characters + - ( )\",\n };\n }\n\n const digits = trimmed.replace(/[^\\d]/g, \"\");\n if (digits.length < 7) {\n return { valid: false, error: \"Phone number is too short\" };\n }\n\n if (digits.length > 15) {\n return { valid: false, error: \"Phone number is too long\" };\n }\n\n if (!/^[+\\d(]/.test(trimmed)) {\n return {\n valid: false,\n error: \"Phone number must start with +, a digit, or (\",\n };\n }\n\n return { valid: true };\n}\n"],"mappings":";AAKA,SAAgBA,EAAc,GAAwB;CAEpD,OAAO,6BAAW,KAAKC,CAAK;AAC9B;AAKA,SAAgBC,EAAiB,GAG/B;CACA,IAAMC,IAAmB,CAAC;CAsB1B,OApBIC,EAAS,SAAS,MACpBD,EAAO,KAAK,8CAA8C,GAGvD,QAAQ,KAAKC,CAAQ,KACxBD,EAAO,KAAK,qDAAqD,GAG9D,QAAQ,KAAKC,CAAQ,KACxBD,EAAO,KAAK,qDAAqD,GAG9D,QAAQ,KAAKC,CAAQ,KACxBD,EAAO,KAAK,2CAA2C,GAGpD,yBAAyB,KAAKC,CAAQ,KACzCD,EAAO,KAAK,sDAAsD,GAG7D;EACL,OAAOA,EAAO,WAAW;EACzB;CACF;AACF;AA8GA,SAASE,EAAmB,GAAmB;CAC7C,OAAO,CAAC,GAAGC,CAAC,CAAC,CAAC;AAChB;AAiCA,IAAMC,IACJ,gGACIC,IAA0B,yBAC1BC,IAAsB;AA8B5B,SAAgBC,EACd,GACsB;CAStB,IAAMC,KAAWC,KAAQ,GAAA,CACtB,UAAU,KAAK,CAAC,CAChB,QAAQJ,GAAyB,GAAG,CAAC,CACrC,QAAQC,GAAqB,GAAG,CAAC,CACjC,K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AKnB,CAAO,IAOpB,EAAE,OAAO,GAAK,IANZ;EACL,OAAO;EACP,OAAO;CACT;AAIJ"}
|
|
1
|
+
{"version":3,"file":"validation.js","names":["validateEmail","email","validatePassword","errors","password","lengthInCodePoints","s","NAME_ALLOWED_CHARS","TYPOGRAPHIC_APOSTROPHES","TYPOGRAPHIC_HYPHENS","validateName","trimmed","name","USERNAME_ALLOWED_CHARS","validateUsername","value","username","validateUserFields","requireAll","options","isBlank","v","firstName","input","lastName","valueOr","result","fallback","validatePhoneNumber","phone","digits"],"sources":["../../../src/auth/utils/validation.ts"],"sourcesContent":["import type { PasswordStrength } from \"../types\";\n\n/**\n * Validate email format\n */\nexport function validateEmail(email: string): boolean {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\n/**\n * Validate password requirements\n */\nexport function validatePassword(password: string): {\n valid: boolean;\n errors: string[];\n} {\n const errors: string[] = [];\n\n if (password.length < 12) {\n errors.push(\"Password must be at least 12 characters long\");\n }\n\n if (!/[A-Z]/.test(password)) {\n errors.push(\"Password must contain at least one uppercase letter\");\n }\n\n if (!/[a-z]/.test(password)) {\n errors.push(\"Password must contain at least one lowercase letter\");\n }\n\n if (!/[0-9]/.test(password)) {\n errors.push(\"Password must contain at least one number\");\n }\n\n if (!/[!@#$%^&*(),.?\":{}|<>]/.test(password)) {\n errors.push(\"Password must contain at least one special character\");\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Calculate password strength using Zxcvbn-like algorithm\n * Returns a score from 0-4 (0 = very weak, 4 = very strong)\n */\nexport function calculatePasswordStrength(password: string): PasswordStrength {\n let score: 0 | 1 | 2 | 3 | 4 = 0;\n const feedback: string[] = [];\n\n // Length check\n if (password.length >= 8) score++;\n if (password.length >= 12) score++;\n if (password.length >= 16) score++;\n\n // Complexity checks\n if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;\n if (/[0-9]/.test(password)) score++;\n if (/[!@#$%^&*(),.?\":{}|<>]/.test(password)) score++;\n\n // Common patterns\n if (/^[a-z]+$/.test(password.toLowerCase())) {\n feedback.push(\"Add uppercase letters, numbers, and symbols\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n if (/^[0-9]+$/.test(password)) {\n feedback.push(\"Avoid using only numbers\");\n score = 0;\n }\n\n if (/(.)\\1{2,}/.test(password)) {\n feedback.push(\"Avoid repeating characters\");\n score = Math.max(0, score - 1) as 0 | 1 | 2 | 3 | 4;\n }\n\n // Common passwords\n const commonPasswords = [\"password\", \"123456\", \"qwerty\", \"admin\", \"letmein\"];\n if (commonPasswords.some((p) => password.toLowerCase().includes(p))) {\n feedback.push(\"Avoid using common passwords\");\n score = 0;\n }\n\n // Ensure score is 0-4\n score = Math.min(4, Math.max(0, score)) as 0 | 1 | 2 | 3 | 4;\n\n // Crack time estimation\n const crackTime =\n score === 0\n ? \"less than 1 second\"\n : score === 1\n ? \"less than 1 minute\"\n : score === 2\n ? \"less than 1 hour\"\n : score === 3\n ? \"less than 1 day\"\n : \"centuries\";\n\n return { score, feedback, crackTime };\n}\n\n/**\n * Validate MFA code format (6 digits)\n */\nexport function validateMfaCode(code: string): boolean {\n return /^\\d{6}$/.test(code);\n}\n\n/**\n * Validate API key name\n */\nexport function validateApiKeyName(name: string): {\n valid: boolean;\n error?: string;\n} {\n if (!name || name.trim().length === 0) {\n return { valid: false, error: \"API key name is required\" };\n }\n\n if (name.length > 100) {\n return {\n valid: false,\n error: \"API key name must be less than 100 characters\",\n };\n }\n\n return { valid: true };\n}\n/**\n * Minimum/maximum lengths for a person's name (first or last), measured in\n * Unicode code points (NOT JavaScript `.length`, which counts UTF-16 code\n * units — see `lengthInCodePoints`).\n *\n * Picked to stay well under the 255-char Prisma `User.firstName/lastName`\n * columns with headroom.\n */\nconst NAME_MIN_LENGTH = 1;\nconst NAME_MAX_LENGTH = 100;\n\n/**\n * Count Unicode code points in `s` instead of UTF-16 code units. Names\n * written in scripts that live in the supplementary plane (Adlam 𞤁𞤔𞤣,\n * many CJK extensions, etc.) have each letter encoded as two UTF-16 units,\n * so a 51-letter Adlam name would otherwise be miscounted as 102 and\n * rejected as too long (Codex P2 review).\n *\n * Code-point counting is sufficient for the name validator — grapheme-\n * cluster counting would also handle emoji ZWJ sequences, but the name\n * regex already disallows emoji.\n */\nfunction lengthInCodePoints(s: string): number {\n return [...s].length;\n}\n\n/**\n * Allowed-character regex; a separate letter check rejects \"12345\",\n * \"12 34\", and \"---\" without overlapping repetitions (BOFF-8547).\n * Every character must be a letter, mark, literal\n * space, hyphen, apostrophe, period, middle-dot, or join control —\n * diacritics-friendly across scripts (Latin, Tamil, Chinese, etc.).\n *\n * Note: a literal space, not `\\s` — `\\s` matches tabs/newlines/other Unicode\n * whitespace which has no business being inside a person's name (review #2).\n *\n * Two middle-dot codepoints are allowed as-is, NOT folded to `.` — they're\n * orthographically distinct and silently rewriting the user's name would\n * corrupt their identity (Codex P2 reviews):\n * U+00B7 — middle dot, used in Catalan (`Joan·Maria`), Chinese\n * (`阿布杜拉·阿扎姆`), and Russian.\n * U+30FB — katakana middle dot, the standard Japanese separator for\n * foreign personal names (`ジョン・スミス`).\n *\n * Zero-width join controls are also allowed as-is:\n * U+200C ZERO WIDTH NON-JOINER — required for Persian compound names\n * like `محمدرضا` so the letters don't ligate.\n * U+200D ZERO WIDTH JOINER — used in some Indic scripts and emoji\n * sequences (we don't allow emoji ZWJ, but the codepoint is\n * accepted as a generic join marker).\n *\n * Typographic apostrophes (U+2018 / U+2019) and modifier letter apostrophe\n * (U+02BC), and typographic hyphens (U+2010 / U+2011), ARE folded to their\n * ASCII equivalents before validation — they're typographic variants of the\n * same character, not semantically distinct (Codex P2 review).\n *\n * BOFF-7214.\n */\nconst NAME_ALLOWED_CHARS = /^[\\p{L}\\p{M} '.\\-\\u00B7\\u30FB\\u200C\\u200D]+$/u;\nconst TYPOGRAPHIC_APOSTROPHES = /[\\u2018\\u2019\\u02BC]/g;\nconst TYPOGRAPHIC_HYPHENS = /[\\u2010\\u2011]/g;\n\n/**\n * Machine-readable name-validation error codes. The caller maps each code\n * to a distinct i18n key (review #1) so that one validator error doesn't\n * collapse N different messages into one translated string.\n */\nexport type NameErrorCode =\n | \"required\"\n | \"too_long\"\n | \"no_letter\"\n | \"invalid_chars\";\n\nexport type NameValidationResult =\n | { valid: true; value: string }\n | { valid: false; code: NameErrorCode; message: string };\n\n/**\n * Validate a person's name (first or last).\n * Accepts `string | undefined | null` because the signup form types name\n * fields as optional (matching the `SignUpInput` contract); an absent value\n * is treated as \"missing\" and fails the validation.\n * On success the result carries the canonicalised `value` (trimmed, with\n * typographic apostrophes folded to ASCII) so the caller can submit the\n * exact same string the validator approved — otherwise the validated\n * string and the value sent to `signUp()` would diverge (e.g. user types\n * `\" O'Connor \"`, validator normalises to `\"O'Connor\"`, but signUp\n * receives the original raw value).\n * Returns a structured result so the caller can decide how to render errors.\n */\nexport function validateName(\n name: string | undefined | null,\n): NameValidationResult {\n // Normalise typographic apostrophes and hyphens to their ASCII\n // equivalents before testing — these are typographic variants of the\n // same character, so the canonical ASCII form is what reaches the DB.\n // (Middle-dot U+00B7 is preserved as-is: see NAME_ALLOWED_CHARS comment.)\n // NFC normalisation happens before trim/length so combining-mark\n // sequences (e.g. `e\\u0301` for `é`) fold to their precomposed\n // form first — otherwise `(\"e\\u0301\").repeat(51)` would over-count\n // to 102 code points and reject a valid 51-character name (Codex P2).\n const trimmed = (name ?? \"\")\n .normalize(\"NFC\")\n .replace(TYPOGRAPHIC_APOSTROPHES, \"'\")\n .replace(TYPOGRAPHIC_HYPHENS, \"-\")\n .trim();\n\n if (lengthInCodePoints(trimmed) < NAME_MIN_LENGTH) {\n return { valid: false, code: \"required\", message: \"Name is required\" };\n }\n\n if (lengthInCodePoints(trimmed) > NAME_MAX_LENGTH) {\n return {\n valid: false,\n code: \"too_long\",\n message: `Name must be ${NAME_MAX_LENGTH} characters or fewer`,\n };\n }\n\n if (!/\\p{L}/u.test(trimmed) || !NAME_ALLOWED_CHARS.test(trimmed)) {\n // Independent linear scans distinguish the two failure modes that matter\n // to the user: a value with no letters vs. a value with disallowed\n // characters. Surface the right hint for each.\n if (!/\\p{L}/u.test(trimmed)) {\n return {\n valid: false,\n code: \"no_letter\",\n message: \"Name must contain at least one letter\",\n };\n }\n return {\n valid: false,\n code: \"invalid_chars\",\n message:\n \"Name can only contain letters, spaces, periods, hyphens, and apostrophes\",\n };\n }\n\n return { valid: true, value: trimmed };\n}\n\n/**\n * Regex for characters allowed in a username. Letters, digits, underscores,\n * hyphens — the existing rule. The new rule layered on top (BOFF-7214):\n * a username must contain at least one letter, so an attacker cannot create\n * an account like \"12345\" with a throwaway email.\n */\nconst USERNAME_ALLOWED_CHARS = /^[a-zA-Z0-9_-]+$/;\nconst USERNAME_MIN_LENGTH = 3;\nconst USERNAME_MAX_LENGTH = 30;\n/**\n * Machine-readable username-validation error codes — one per failing rule\n * (review #1) so each can map to its own i18n key.\n */\nexport type UsernameErrorCode =\n | \"required\"\n | \"too_short\"\n | \"too_long\"\n | \"invalid_chars\"\n | \"no_letter\";\n\nexport type UsernameValidationResult =\n | { valid: true; value: string }\n | {\n valid: false;\n errors: Array<{ code: UsernameErrorCode; message: string }>;\n };\n\n/**\n * Validate a username.\n * Accepts `string | undefined | null` for parity with `validateName` and the\n * optional `SignUpInput.username` contract.\n *\n * Surrounding whitespace is trimmed before the length / character checks —\n * a pasted `\" alice_01 \"` would otherwise fail with a misleading\n * \"can only contain letters, numbers, underscores, and hyphens\" error\n * when the actual problem is invisible whitespace. On success the result\n * carries the trimmed `value` so the caller submits the same string the\n * validator approved (Claude LOW review).\n * Returns a structured result with a list of errors so the caller can\n * render every failing rule at once (mirrors `validatePassword`).\n */\nexport function validateUsername(\n username: string | undefined | null,\n): UsernameValidationResult {\n const errors: Array<{ code: UsernameErrorCode; message: string }> = [];\n const value = (username ?? \"\").trim();\n\n if (lengthInCodePoints(value) === 0) {\n errors.push({\n code: \"required\",\n message: \"Username is required\",\n });\n } else {\n if (lengthInCodePoints(value) < USERNAME_MIN_LENGTH) {\n errors.push({\n code: \"too_short\",\n message: `Username must be at least ${USERNAME_MIN_LENGTH} characters`,\n });\n }\n\n if (lengthInCodePoints(value) > USERNAME_MAX_LENGTH) {\n errors.push({\n code: \"too_long\",\n message: `Username must be ${USERNAME_MAX_LENGTH} characters or fewer`,\n });\n }\n\n if (!USERNAME_ALLOWED_CHARS.test(value)) {\n errors.push({\n code: \"invalid_chars\",\n message:\n \"Username can only contain letters, numbers, underscores, and hyphens\",\n });\n }\n\n // Must contain at least one letter — guards against all-numeric or\n // all-symbol usernames slipping through. Pure numeric values like\n // \"12345\" previously passed the character allow-list alone.\n if (\n lengthInCodePoints(value) >= USERNAME_MIN_LENGTH &&\n !/[a-zA-Z]/.test(value)\n ) {\n errors.push({\n code: \"no_letter\",\n message: \"Username must contain at least one letter\",\n });\n }\n }\n\n return errors.length === 0\n ? { valid: true, value }\n : { valid: false, errors };\n}\n\n/**\n * Bundle validation across all three user-identity fields so callers\n * (RegisterPage, UserProfilePage, UsersPage) can fail fast on the whole\n * form instead of piecemeal — and so the BOFF-7214 invariant\n * (firstName / lastName contain a letter; username contains a letter)\n * is enforced at every mutation surface, not just signup.\n *\n * On success, the result carries the canonicalised values from each\n * individual validator so the caller submits the same strings the\n * validators approved (no validate/submit divergence).\n *\n * The caller is responsible for mapping each `{ field, code, message }`\n * error to its own i18n key — different surfaces have different key\n * namespaces (`auth.register.*`, `auth.profile.*`, `auth.users.*`).\n */\nexport type UserFieldKey = \"firstName\" | \"lastName\" | \"username\";\n\nexport interface UserFieldError {\n field: UserFieldKey;\n code: string;\n message: string;\n}\n\nexport interface ValidatedUserFields {\n firstName: string;\n lastName: string;\n username: string;\n}\n\nexport type UserFieldsValidationResult =\n | { valid: true; values: ValidatedUserFields }\n | { valid: false; errors: UserFieldError[] };\n\nexport function validateUserFields(\n input: {\n firstName?: string | null;\n lastName?: string | null;\n username?: string | null;\n },\n options: { requireAll?: boolean } = {},\n): UserFieldsValidationResult {\n // Default to requiring every field. Profile-edit surfaces pass\n // `requireAll: false` so an existing user whose optional firstName /\n // lastName is unset (e.g. provisioned via an identity provider) can\n // still update unrelated fields like phone or role (Codex P2 review).\n const requireAll = options.requireAll ?? true;\n const errors: UserFieldError[] = [];\n\n // Skip the validator entirely when a field is empty AND requireAll is\n // false — that means \"user is leaving this field blank\". The signup\n // form always requires every field; profile edit does not.\n const isBlank = (v: string | null | undefined): boolean =>\n !v || v.trim().length === 0;\n\n const firstName =\n !isBlank(input.firstName) || requireAll\n ? validateName(input.firstName)\n : null;\n if (firstName && !firstName.valid) {\n errors.push({\n field: \"firstName\",\n code: firstName.code,\n message: firstName.message,\n });\n }\n\n const lastName =\n !isBlank(input.lastName) || requireAll\n ? validateName(input.lastName)\n : null;\n if (lastName && !lastName.valid) {\n errors.push({\n field: \"lastName\",\n code: lastName.code,\n message: lastName.message,\n });\n }\n\n const username =\n !isBlank(input.username) || requireAll\n ? validateUsername(input.username)\n : null;\n if (username && !username.valid) {\n for (const e of username.errors) {\n errors.push({ field: \"username\", code: e.code, message: e.message });\n }\n }\n\n if (errors.length > 0) return { valid: false, errors };\n\n // Return canonical values: trimmed/NFC-normalised when validated, the\n // original trimmed value when the field was optional and left blank.\n // The cast is sound because the `errors.length > 0` early-return above\n // guarantees each result, when non-null, is the `{ valid: true }` arm.\n const valueOr = (\n result: { valid: true; value: string } | null,\n fallback: string | null | undefined,\n ): string => (result ? result.value : (fallback ?? \"\").trim());\n\n return {\n valid: true,\n values: {\n firstName: valueOr(\n firstName as { valid: true; value: string } | null,\n input.firstName,\n ),\n lastName: valueOr(\n lastName as { valid: true; value: string } | null,\n input.lastName,\n ),\n username: valueOr(\n username as { valid: true; value: string } | null,\n input.username,\n ),\n },\n };\n}\n\n/**\n * Validate a phone number (BOFF-7216).\n *\n * Phone numbers are optional on profile / admin edit forms — an empty input\n * is accepted. When a value is supplied it must:\n * - contain only digits, spaces, and the formatting characters + - ( )\n * - include 7–15 digits (E.164-style length bounds; we don't strip \"+\"\n * country prefix here, we just count digits)\n * - start with +, a digit, or (\n *\n * Returns `{ valid: true }` on an empty / whitespace-only input.\n * Returns `{ valid: false, error }` with a human-readable message on\n * rejection. The message is intentionally plain English so the caller can\n * either display it verbatim or pipe it through `tr()` with an i18n key.\n */\nexport function validatePhoneNumber(phone: string): {\n valid: boolean;\n error?: string;\n} {\n const trimmed = phone.trim();\n\n if (trimmed.length === 0) {\n return { valid: true };\n }\n\n if (!/^[0-9+\\-() ]+$/.test(trimmed)) {\n return {\n valid: false,\n error:\n \"Phone number can only contain digits, spaces, and the characters + - ( )\",\n };\n }\n\n const digits = trimmed.replace(/[^\\d]/g, \"\");\n if (digits.length < 7) {\n return { valid: false, error: \"Phone number is too short\" };\n }\n\n if (digits.length > 15) {\n return { valid: false, error: \"Phone number is too long\" };\n }\n\n if (!/^[+\\d(]/.test(trimmed)) {\n return {\n valid: false,\n error: \"Phone number must start with +, a digit, or (\",\n };\n }\n\n return { valid: true };\n}\n"],"mappings":";AAKA,SAAgBA,EAAc,GAAwB;CAEpD,OAAO,6BAAW,KAAKC,CAAK;AAC9B;AAKA,SAAgBC,EAAiB,GAG/B;CACA,IAAMC,IAAmB,CAAC;CAsB1B,OApBIC,EAAS,SAAS,MACpBD,EAAO,KAAK,8CAA8C,GAGvD,QAAQ,KAAKC,CAAQ,KACxBD,EAAO,KAAK,qDAAqD,GAG9D,QAAQ,KAAKC,CAAQ,KACxBD,EAAO,KAAK,qDAAqD,GAG9D,QAAQ,KAAKC,CAAQ,KACxBD,EAAO,KAAK,2CAA2C,GAGpD,yBAAyB,KAAKC,CAAQ,KACzCD,EAAO,KAAK,sDAAsD,GAG7D;EACL,OAAOA,EAAO,WAAW;EACzB;CACF;AACF;AA8GA,SAASE,EAAmB,GAAmB;CAC7C,OAAO,CAAC,GAAGC,CAAC,CAAC,CAAC;AAChB;AAkCA,IAAMC,IAAqB,iDACrBC,IAA0B,yBAC1BC,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