@passflow/react 0.27.0 → 0.28.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":["unhandled","subscribe","withQuestionMark","_Fragment","flags","_Fragment","error","error","error","logoRed","eyeOn","eyeOff","caretDown","onePassword","browserChrome","dotsVertical","linkedin","validationError","_Fragment","_Fragment","ERROR_ID","_Fragment","_Fragment","_Fragment","err","error","error","_Fragment","_Fragment","completionOptions","queryString","Wrapper","_Fragment","Wrapper","queryString","queryString","Dialog","challengeTypeFullString","Wrapper","Wrapper","FETCH_PRIORITY_OIDC","Passflow","PassflowEvent","SERVICE_UNAVAILABLE_ERROR_ID","SERVICE_UNAVAILABLE_MESSAGE","classifyUpgradeError","isEmailVerificationStep","isValidJWTFormat","parseToken","parseUpgradeChallenge","registerFetchMiddleware","requiredAcrLevel","React","cloneElement","createContext","forwardRef","useCallback","useContext","useEffect","useId","useLayoutEffect","useMemo","useReducer","useRef","useState","useSyncExternalStore","clsx","Fragment","jsx","jsxs","Yup","DialogPrimitive","OTPInput","REGEXP_ONLY_DIGITS","REGEXP_ONLY_DIGITS_AND_CHARS","getCountryForTimezone","defaultCountries","parseCountry","usePhoneInput","qs","phone","Controller","useForm","PopoverPrimitive","ErrorBoundary","from","window","passflowReactAppVersion","console","log","AUTH_ERROR_COPY","password","message","scope","passwordless","passkey","verificationLinkErrorMessage","verificationRequestErrorMessage","passwordChangeRequiredReason","authErrorFor","flow","operation","SERVER_MESSAGE_ERROR_IDS","Set","readField","value","field","readServerError","error","response","body","status","serverMessageFor","serverError","id","has","trimmed","trim","REFUSED_PARENT_COPY","Map","authErrorFrom","refusedParent","get","startAgain","authRedirectErrorFrom","emailCodeErrorMessage","serverMessage","passwordlessLinkExpiredMessage","passwordlessSignInFailedMessage","approvalInvalidMessage","approvalUnavailableMessage","approvalAlreadyDecidedMessage","approvalConnectionMessage","approvalMatchMessage","attemptsLeft","approvalErrorFrom","terminal","resetLinkInvalidMessage","isPasswordSavedRateLimit","twoFactorSignInOverMessage","twoFactorRateLimitedMessage","twoFactorWrongCodeMessage","twoFactorSendFailedMessage","twoFactorBackToSignInLabel","twoFactorSignInLabel","serverErrorIdFrom","serverErrorStatusFrom","OVER_PARENT_IDS","OVER_MESSAGES","enrollmentFailureFrom","DEVICE_ERROR_COPY","code_required","code_invalid","code_expired","code_declined","code_already_approved","too_many_attempts","mode_disabled","app_unavailable","bad_credentials","missing_credentials","second_factor_invalid","missing_second_factor","account_blocked","passkey_failed","passkey_unsupported","offline","generic","RECOVERABLE","REASON_TO_TYPE","invalid_user_code","unknown_user_code","expired_user_code","denied","already_approved","unknown_client","passkey_unavailable","unavailable","blocked","WEBAUTHN_NAME_TO_TYPE","NotAllowedError","AbortError","TimeoutError","UnknownError","NotSupportedError","InvalidStateError","ConstraintError","SecurityError","UNSUPPORTED_MESSAGE_PATTERNS","DeviceApiError","Error","reason","code","constructor","params","super","description","this","name","build","type","detail","isRecoverable","classifyDeviceError","err","isDOMExceptionLike","raw","lowered","toLowerCase","some","p","includes","byName","deviceErrorOfType","classifyTwoFactorError","errorTypeOf","isTerminalTwoFactorError","getUserFriendlyErrorMessage","cn","classes","messageOr","fallback","readEmailVerificationStep","answer","challengeId","challenge_id","kind","initialEmailCodeStepState","step","emailCodeStepReducer","state","event","submitFormPost","action","fields","form","document","createElement","method","style","display","key","Object","entries","input","appendChild","submit","getAuthMethods","strategies","methods","internal","username","email","otp","magicLink","fim","providers","hasEmailMethods","hasSignInEmailMethods","hasPhoneMethods","hasSignInPhoneMethods","hasUsernameMethods","hasSignInUsernameMethods","strategy","identity","challenge","fim_type","fimType","push","getIdentityLabel","getPasswordlessData","currentMethod","label","challengeType","decodeOnceMore","decodeURIComponent","getUrlErrors","subUrl","searchParams","URLSearchParams","split","location","search","DEFAULT_HAND_OFF_SCOPES","withScope","list","handOffScopes","handOff","scopes","undefinedOnCatch","fn","t","authAction","title","completion","getInvitationAuthChrome","inviteToken","intent","invitation","tenantName","tenant_name","inviterName","inviter_name","subtitle","subscribe$1","onClient","onServer","useHydrated","usePassflow","context","PassflowContext","passflow","AuthContext","AuthProvider","children","onSessionExpired","hydrated","isLoading","setIsLoading","isSessionExpired","setIsSessionExpired","isSignedIn","setIsSignedIn","isAuthenticated","subscriber","onAuthChange","eventType","payload","SessionExpired","SignIn","Register","subscribe","SignOut","unsubscribe","getTokens","async","doRefresh","tokens","parsedTokens","getParsedTokens","e","logout","options","logOut","Provider","defaultNavigate","to","replace","searchParam","startsWith","href","NavigationContext","navigate","setNavigate","router","initialState","appSettings","passwordPolicy","url","appId","createTenantForNewUser","parseQueryParams","isDiscoveringAppId","hasSettingsError","passflowReducer","update","found","length","handOffScopesUpdate","keys","routes","signin","path","signup","verify_otp","verify_magic_link","forgot_password","forgot_password_success","reset_password","two_factor_verify","two_factor_recovery","two_factor_setup","two_factor_setup_magic_link","addressBarSearch","read","write","pathname","hash","history","replaceState","pushState","SearchContext","useSearchSource","UpgradeContext","noop","INERT_UPGRADE_CONTEXT","enabled","prompt","selectedFactor","selectFactor","cancel","dismiss","elevate","Promise","resolve","isValidUrl","newUrl","URL","protocol","withoutTrailingSlash","isSameOriginPath","target","origin","signInSearch","delete","toString","routeToSecondFactor","twoFactorVerifyPath","isTwoFactorVerificationRequired","urlCarriesTwoFactorToken","substring","urlCarriesAccessToken","STORAGE_KEY_PREFIX","REDIRECT_COUNT_KEY","LAST_ERROR_KEY","TwoFactorLoopPrevention","canRedirect","getRedirectCount","incrementRedirect","count","sessionStorage","setItem","String","getItem","Number","parseInt","reset","removeItem","setLastErrorType","errorType","getLastErrorType","isRepeatingError","getLoopDetectedMessage","activeInstance","pendingRelease","registerUpgradeAuthInstance","instance","queueMicrotask","releaseUpgradeAuthInstance","requireInstance","withAuth","next","attachAuth","withQuestionMark$1","readParentChallengeIdFromURL","Array","urlWithoutParentChallenge","hashAt","indexOf","slice","beforeHash","queryAt","kept","filter","pair","isParentChallengePair","join","useUrlParams","defaultValues","source","replaceAll","hasChanged","set","getAll","newSearchParams","emailRegex","passwordValidation","string","required","test","errors","restrict_min_password_length","restrictMinPasswordLength","min_password_length","minPasswordLength","require_lowercase","requireLowerCase","require_number","requireNumber","require_symbol","requireSymbol","require_uppercase","requireUpperCase","validationError","inner","ValidationError","Ripple","size","x","y","className","width","height","left","top","Button","variant","onClick","withIcon","asIcon","withRipple","pressed","rest","ripples","setRipples","styles","ariaDisabled","timer","setTimeout","clearTimeout","preventDefault","rect","currentTarget","getBoundingClientRect","rippleSize","Math","max","clientX","clientY","newRipple","Date","now","prev","ContinuingStatus","appName","role","COUNTRY_FLAG_POSITIONS","ad","ae","af","ag","ai","al","am","an","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","br","bs","bt","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gg","gh","gi","gl","gm","gn","gq","gr","gs","gt","gu","gw","gy","hk","hn","hr","ht","hu","ic","ie","il","im","in","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","xk","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pn","pr","ps","pt","pw","py","qa","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sk","sl","sm","sn","so","sr","ss","st","sv","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","tr","tt","tv","tw","tz","ua","ug","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","ye","za","zm","zw","COUNTRY_FLAG_ALIASES","bq","gf","gp","io","pm","re","yt","CountryFlag","iso2","country","normalized","candidate","getSupportedCountry","toUpperCase","backgroundImage","backgroundPosition","Dialog","Root","DialogTrigger","Trigger","DialogPortal","Portal","DialogClose","Close","DialogOverlay","props","ref","Overlay","displayName","DialogContent","Content","DialogHeader","DialogFooter","DialogTitle","Title","DialogDescription","Description","CHARSETS","numeric","pattern","inputMode","alphanumeric","Slot","char","isActive","hasFakeCaret","FieldOtp","onChange","onComplete","charset","labelledBy","describedBy","autoFocus","maxLength","autoComplete","disabled","noScriptCSSFallback","containerClassName","render","slots","map","slot","position","htmlFor","FieldPassword","withMessages","validationErrors","isError","isShowPassword","setIsShowPassword","errorStyles","changeIcon","handleShowPassword","requirementsMessage","requires","requiresString","requirements","Intl","ListFormat","format","requirement","generateMessage","Icon","decorative","nonEmpty","getBackgroundImage","image","applyLoginThemeStyles","root","property","primary_color","text_color","content_color","secondary_text_color","background_color","background_image","card_color","input_background_color","input_border_color","button_text_color","passkey_button_text_color","passkey_button_background_color","divider_color","federated_button_background_color","federated_button_text_color","getLoginThemeCssVariables","removeProperty","setProperty","useIsomorphicLayoutEffect","useAppSettings","setIsError","errorMessage","setErrorMessage","isFetchingRef","dispatch","current","discovered","urlsToTry","r","fetch","ok","settings","json","discoveredAppId","login_app","app_id","setAppId","discoveredScopes","createTenant","create_tenant_for_new_user","discoveryError","warn","getAppSettings","finalStateUpdates","defaultScopes","defaults","defaultCreateTenant","auth_strategies","getPasswordPolicySettings","fetchAllSettings","currentTheme","theme","matchMedia","matches","login_app_theme","color_scheme","getCurrentTheme","selectedStyle","dark_style","light_style","documentElement","loginAppTheme","currentStyles","useAuth","useAuthCloudRedirect","cloudPassflowUrl","authRedirect","catch","readConsentChallengeId","requestPath","consentChallengeId","encodeURIComponent","useConsent","setStatus","info","setInfo","granted","setGranted","setError","cancelled","res","credentials","headers","Accept","error_description","data","requested_scopes","fetchInfo","toggleScope","add","decide","decision","base","endpoint","granted_scopes","csrf_token","JSON","stringify","errBody","allow","deny","metadataByScope","scope_metadata","meta","scopeMetadata","grantedScopes","DEVICE_ENDPOINTS","SECOND_FACTOR_METHODS","parseDeviceResponse","useDeviceVerify","setEmail","userCode","setUserCode","ticketRef","firstFactorTicketRef","approveAfterSecondFactorRef","secondFactorMethods","setSecondFactorMethods","activeRef","csrf","post","user_code","fail","classified","loadInfo","submitCode","holdTicket","second_factor_required","approval_ticket","known","m","toSecondFactorMethods","second_factor_methods","authenticatePassword","emailValue","owesSecondFactor","authenticatePasskey","PublicKeyCredential","DOMException","start","startAuthentication","assertion","optionsJSON","publicKey","passkey_challenge_id","passkey_data","approveWithTicket","signInWithPassword","signInWithPasskey","approve","confirmWithPassword","confirmWithPasskey","submitSecondFactor","clearError","isSecondFactorPending","useEmailCodeStep","isVerifying","setIsVerifying","isResending","setIsResending","epochRef","verifyingRef","resendingRef","stepRef","optionsRef","enter","onRelease","verify","epoch","verifyEmailCode","resend","repeat","leaving","twoFactor","clearPartialAuthState","canResend","Boolean","useForgotPassword","sendPasswordResetEmail","useJoinInvite","token","joinInvitation","invitationJoinErrorFrom","useLogout","parseSearch","parsed","parse","fromEntries","useNavigation","setTwoFactorVerifyPath","signInPath","setSignInPath","newNavigate","searchParamDefault","useOutsideClick","onClickOutside","handleClick","contains","addEventListener","removeEventListener","usePassflowStore","events","onStoreChange","bscr","_eventType","_payload","getCachedTokens","getSnapshot","getServerSnapshot","usePasswordlessComplete","passwordlessSignInComplete","passwordlessCompleteErrorMessage","getFullRedirectUrl","redirectUrl","getLoginPageLandingUrl","redirectTo","useProvider","federatedLanding","landsOnLoginPage","pkce_enabled","pkceEnabled","redirect_url","create_tenant","parent_challenge_id","entry","federatedWithPopup","provider","federatedAuthWithPopup","invite_token","federatedWithRedirect","federatedAuthWithRedirect","IDLE","isFailing","since","nextRetryAt","EVENTS","RefreshFailing","RefreshRecovered","useRefreshStatus","failing","useResetPassword","isPasswordSaved","setIsPasswordSaved","emailCode","newPassword","resetToken","resetPassword","newPasswordErrorMessage","useSessionExpired","expiredReason","setExpiredReason","resetSessionExpired","FieldText","linkedin_default","matchTextColor","icons","general","logo","warning","mail","edit","close","check","trash","google","gitlab","apple","atlassian","bitbucket","discord","dropbox","facebook","github","hubspot","linear","linkedin","linledin","microsoft","notion","slack","tiktok","twitch","twitter","xero","src","alt","LoginAlert","tone","useFocusAfterBusy","busy","inputRef","wasBusy","focus","LoginDivider","LoginActionStack","LoginProgress","onCancel","LoginScreenNotice","codeTestId","appNameTestId","LoginCodeEntry","initialCode","submitLabel","testId","onSubmit","setCode","normalizedCode","autoCapitalize","autoCorrect","spellCheck","Switch","checked","generatedId","inputId","LoginConsent","allowLabel","denyLabel","busyLabel","allowTestId","denyTestId","onToggleScope","onAllow","onDeny","item","Link","ProvidersBox","initialValues","email_or_username","LoginCredentials","computedDefaultMethod","initialMethod","identities","getDefaultMethod","defaultMethod","setDefaultMethod","passkeyOnly","setPasskeyOnly","forcePasskey","previousComputedMethod","previousForcePasskey","control","getValues","trigger","watch","formState","isDirty","isValid","isSubmitted","touchedFields","handleSubmit","mode","nextForcePasskey","currentIdentity","find","hasPassword","hasPasswordless","passwordlessLabel","hasPasskey","hasIdentity","showCredentialFields","showStandalonePasskey","hasCredentialActions","controlsDisabled","errorScope","hasIdentityError","hasPasswordError","isNewPassword","credentialPurpose","identityError","toCredentials","values","emailOrUsername","handleReset","onReset","handleMethodChange","submitCurrentMethod","onPassword","onPasswordless","selectedIdentityValue","alternateIdentity","formAlert","onStartAgain","notice","allowPasskeyToggle","handlePasskeyExperienceChange","primaryLabel","selectLabel","rules","requiredMessage","validate","FieldPhone","forgotPassword","getSearch","validateSync","primaryTestId","submitPasswordless","passwordlessLabelPrefix","onPasskey","passkeyLabel","footer","onProvider","LoginDeviceApproval","actionLabel","actionTestId","onApprove","VisuallyHidden","PROMPT_ID","ERROR_ID$1","RESEND_HINT_ID","EmailCodeResendButton","cooldownSeconds","locked","onResend","remaining","setRemaining","seconds","coolingDown","LoginEmailCode","secondaryAction","seenOutcome","setSeenOutcome","restartKey","seenRestartKey","setSeenRestartKey","LoginGeneralError","onAction","LoginInvitation","acceptLabel","switchAccountLabel","createAccountLabel","acceptTestId","onAccept","onSwitchAccount","onCreateAccount","ERROR_ID","VALIDATION_ERROR_ID","LoginNewPassword","hint","validationMessage","showValidationAlert","messages","LoginPasskeyProgress","working","recoverable","retryLabel","onRetry","LoginPasswordlessApprovalForm","browser","os","requestedAt","LoginPasswordlessApproval","loading","LoginPasswordlessWaiting","METHOD_COPY","totp","switchLabel","recovery_codes","LoginSecondFactor","onMethodChange","setMethod","alternate","copy","isTOTP","LoginScreenShell","iconId","customCss","customLogo","customLogoAlt","removeBranding","LoginStatus","primaryAction","canRetry","LoginTwoFactorCode","factor","trustDevice","canSubmit","alert","onCodeChange","alertId","digits","placeholder","LoginTwoFactorRecoveryCodes","codes","copyLabel","continueLabel","onCopy","onContinue","SecondaryAction","LoginTwoFactorSetupStart","startLabel","onStart","LoginTwoFactorSetupCode","qrCode","qrAlt","secret","secretLabel","showSecretLabel","hideSecretLabel","codeLabel","secretShown","setSecretShown","shown","LoginTwoFactorSetup","LoginScreen","chrome","content","UpgradeFactorList","factors","selected","onSelect","CODE_FIELD_ID","CODE_ERROR_ID","UpgradeChallengeView","showAlternatives","cancelLabel","alternativesLabel","onSelectFactor","onToggleAlternatives","reported","active","codeContract","needsCode","hasAlternatives","report","noValidate","DEFAULT_FACTOR_LABELS","email_otp","sms_otp","UPGRADE_UNSATISFIABLE_DETAIL","countOf","unit","upgradeRateLimitedMessage","retryAfter","serverText","minutes","ceil","hours","waitDuration","OTP_CODE_CONTRACT","freeze","TOTP_CODE_CONTRACT","UPGRADE_FACTOR_CODE_CONTRACTS","toDialogFactors","labels","override","readString","readRecord","DIALOG_KIND_BY_UPGRADE_KIND","wrong_code","challenge_spent","not_registered","prepare_not_required","exhausted","attempts_exhausted","rate_limited","session_changed","fatal","network","upgradeKindOf","record","tagged","hasOwn","hasTransportFacts","dialogOutcomeFromError","readAssuranceBar","bar","acrValues","level","maxAge","describeAssuranceBar","parts","challengeBar","requiredLevel","terminalFromError","handlers","onDismiss","obtained","onSignIn","retryable","toDialogState","outcome","ui","previousKind","previousError","suggested","upgradeDialogDismissHandler","Spinner","TONE","success","insufficient","unsatisfiable","transport","BarRow","term","UpgradeStatus","autoClose","autoCloseMs","autoDismiss","signInLabel","dismissLabel","DESCRIPTION_ID","UpgradeDialog","open","onOpenChange","errorStateOf","summaryError","summary","proof","factorsSignature","replaySignature","replay","maxBodyBytes","allowStreamingBody","UpgradeProvider","facade","backend","interceptFetch","requireChallengeChannel","shouldIntercept","onUpgradeDiagnostic","maxAttempts","relyingPartyId","onSignInRequired","failures","renderDialog","upgradeFacade","upgrade","setPrompt","setState","setSelectedFactor","setBusy","setShowAlternatives","setOutcome","installed","setInstalled","resolveRef","requestRef","reportedSelectionRef","userCancelledRef","cancelRequestedRef","shouldInterceptRef","diagnosticRef","signInRef","failuresRef","factorsRef","replayRef","replayPredicate","policy","settlePrompt","result","clearPromptView","promptHandler","request","onRequirementRaised","f","handleFlightSettled","summaryToState","signInRequired","userCancelled","summaryToOutcome","teardown","enable","d","onFlightSettled","isArray","elevatesHostedSession","hostedUpgrade","onFactorSelected","signInAgain","toggleAlternatives","requested","statedBar","waiter","channels","imperativeChallenge","asError","dialogState","dialogProps","SignInReturnFailed","onSignInAgain","StepUpFailed","AUTH_ENDPOINT_PATTERN","PASSWORDLESS_STATUS_PATTERN","bootParentChallengeId","oidcRedirectFollowed","hasFollowedOIDCRedirect","useOIDCInterceptor","parentChallengeId","isAuthURL","followsAnswer","injectParentChallenge","obj","followRedirectURL","formPost","form_post","assign","unregisterFetchMiddleware","init","Request","outInit","rewritten","text","clone","priority","OriginalXHROpen","XMLHttpRequest","prototype","OriginalXHRSend","send","tracker","WeakMap","urlStr","isAuth","follows","responseText","call","outBody","relyingPartyErrorDescriptions","login_required","interaction_required","unmet_authentication_requirements","carriesAnswer","useSessionExchangeOnMount","landedWithTwoFactorToken","currentPassflow","baseUrl","exchangeState","setExchangeState","stepUpFailure","setStepUpFailure","parentMeta","setParentMeta","attemptedRef","exchange","showForm","answerOrShowForm","redirect_uri","response_mode","dest","answerRelyingParty","oidc_prompt_none","readBody","retry","run","OIDCExchangeContext","PassflowProvider","initialNavigate","config","appIdFromToken","apiUrl","audience","aud","twoFactorTokenAppId","needsDiscovery","appIdPropRef","mountHandOff","landedWithAccessToken","takeTokensFromUrl","fixedConfig","keyStoragePrefix","tokenExchange","platform","refreshCoordination","refreshStrikes","passflowRef","liveInstanceConfig","instanceConfigRef","instanceConfig","scopesKey","deferFederatedLanding","pending","scheduled","dispose","useDisposeOnReplace","discoveryAttemptedRef","discoverAppId","passflowValue","handleSetNavigate","flowTwoFactorVerifyPath","setFlowTwoFactorVerifyPath","resolvedTwoFactorVerifyPath","flowSignInPath","setFlowSignInPath","federatedLandingOutcome","signInReturnFailed","setPending","setFederatedLandingOutcome","setSignInReturnFailed","takenRef","currentPassflowRef","TwoFactorRequired","signIn","setTokens","completeFederatedLanding","tokensTakenRef","handleTokensRedirect","landingTakenRef","useSecondFactorLanding","navigationValue","oidcExchangeValue","hosted","upgradeEnabled","upgradeOptions","signInForStepUp","showContinuing","app_name","useSignInEnding","ending","setEnding","lastEnding","latestSignInPath","handOver","address","sent","refresh_token","tokenParams","getUrlWithTokens","leaveFor","checkRedirectUrl","last","finishSignIn","appDefault","isSignInPage","useSignIn","onPasswordChangeRequired","onPasswordChangeRequiredRef","lastPasswordPayloadRef","resendPasswordRequest","pendingOperation","setPendingOperation","attemptRef","attempt","isCurrent","passwordlessSignIn","passkeyAuthenticate","handlePasswordChange","cancelPasskey","useSignUp","signUp","cleanup","passwordlessResponse","passkeyRegister","useTrustedDevices","setData","devices","getTrustedDevices","revoke","deviceId","revokeTrustedDevice","device","refetch","useTwoFactorChallenge","setChallenge","selectedMethod","setSelectedMethod","requestChallenge","firstFactorMethod","first_factor_method","verifyV2","trust_device","switchMethod","switchToAlternative","useTwoFactorManage","recoveryCodes","setRecoveryCodes","disable","disableTwoFactor","regenerateCodes","regenerateTwoFactorRecoveryCodes","useTwoFactorMethods","availableMethods","setAvailableMethods","registeredMethods","setRegisteredMethods","refresh","getRegisteredMethods","available","removeMethod","methodId","setupErrorMessage","failure","useTwoFactorSetup","setupData","setSetupData","setStep","checkedRef","getTwoFactorStatus","beginSetup","beginTwoFactorSetup","confirmSetup","confirmTwoFactorSetup","finish","knownErrorCodes","useTwoFactorSetupMagicLink","isDiscovering","isRetrying","setIsRetrying","isValidated","setIsValidated","sessionToken","setSessionToken","userId","setUserId","expiresIn","setExpiresIn","validatedOnMount","shouldClearOnUnmount","validateToken","validateTwoFactorSetupMagicLink","clearMagicLinkSession","useTwoFactorStatus","useTwoFactorVerify","setErrorType","errorDetails","setErrorDetails","isVerificationRequired","handleError","verifyTwoFactor","useRecoveryCode","useTwoFactorRecoveryCode","EMPTY_FACTORS","useUpgrade","readPromptFactors","factorTypes","errorKind","USER_EVENTS","Refresh","claim","id_token","access_token","readUser","sub","phonenumber","signedOut","useUser","user","setUser","sameUser","b","a","useUserPasskeys","getUserPasskeys","createUserPasskey","passkeyUsername","passkeyDisplayName","addUserPasskey","editUserPasskey","newName","passkeyId","renameUserPasskey","userPasskeys","deleteUserPasskey","inputProps","startingValue","show","setShow","filterValue","setFilterValue","isFocused","setIsFocused","refWrapper","searchInputRef","userTZ","DateTimeFormat","resolvedOptions","timeZone","userCountry","countrySwitchRef","inputValue","setCountry","handlePhoneValueChange","defaultCountry","toLocaleLowerCase","nextValue","filteredCountries","defCountry","countryName","preferredCountries","allCountries","preferredIso","handleClose","restoreFocus","querySelector","handleChangeCountry","renderCountry","dialCode","tabIndex","onKeyDown","querySelectorAll","currentIndex","min","handleOptionKeyDown","onFocus","onBlur","HSL_TRIPLET","toCssColor","COLOR_VARIABLES","THEME_ATTRIBUTES","useShadcnTheme","element","applied","clear","apply","getComputedStyle","properties","color","getPropertyValue","readShadcnTheme","observer","MutationObserver","observe","attributes","attributeFilter","colorScheme","disconnect","LoginButtonView","signOutDescription","appearance","buttonRef","descriptionId","own","defaultPrevented","signedIn","Popover","PopoverTrigger","PopoverAnchor","Anchor","PopoverContent","align","sideOffset","withHydration","Component","Hydrated","ConsentFlow","screen","consent","client_id","app_logo_url","getConsentLoginScreenProps","toCredentialsError","getDeviceLoginScreenProps","authenticated","getDeviceLoginMethods","deviceNotice","DeviceVerifyFlow","attemptedPasskeyChallenge","challengeKey","isAutomaticPasskeyReady","getTwoFactorSetupStartScreen","getTwoFactorSetupCodeScreen","fallbackDigits","totp_digits","qr_code","getTwoFactorRecoveryCodesScreen","navigator","clipboard","writeText","TwoFactorSetupForm","onBackToSignIn","numInputs","shownError","backToSignIn","handleComplete","skipsCodes","skipCodesRef","TwoFactorSetupFlow","shouldBlockRender","setShouldBlockRender","MAGIC_LINK_SEGMENT","ERROR_SUBTITLES","EXPIRED_TOKEN","INVALID_TOKEN","REVOKED_TOKEN","SERVER_ERROR","errorState","TwoFactorSetupMagicLinkFlow","tokenProp","onSuccess","onError","redirectOnSuccess","exec","tokenFromUrl","searchSource","goToSignIn","SIGNED_IN_MESSAGE","COULD_NOT_FINISH","screens","checking","refused","SignInEndingScreen","custom_css","logo_url","application_name","remove_passflow_logo","TwoFactorRecoveryForm","onBack","onEnded","trustDeviceLabel","deviceTrustAvailable","setTrustDevice","redeemRecoveryCode","onEndedRef","completionOptions$1","TwoFactorVerifyForm","onUseRecovery","shouldAutoFocus","totpDigits","getTotpDigits","computedSubtitle","completionOptions","TITLE","TwoFactorVerifyFlow","successAuthRedirect","setMode","pendingOnLanding","enrollment","onFinished","setScreen","readOnMount","notAllowedReread","beganAgain","heldCode","updateDirect","patch","endSignIn","handleFailure","stay","getTwoFactorEnrollment","device_trust_available","sends","screenFor","beginEnrollment","beginTwoFactorEnrollment","complete","verifyHeldCode","sendLink","email_sent","emailSent","sendTwoFactorSetupLink","begin","confirm","confirmTwoFactorEnrollment","end","useTwoFactorEnrollment","redirect","continueSignIn","screenProps","getTwoFactorEnrollmentScreenProps","searchParamsForgotPasswordSchema","object","shape","oneOf","ForgotPassword","successResetRedirect","forgotPasswordSuccessPath","default_method","isErrorApp","errorApp","authMethods","showPasswordChangeNotice","abortEarly","currentSubscriptions","usesPhone","isEmail","match","isUsername","validatedPhone","isPhone","phoneNumber","currentSearchParams","newParams","searchParamsForgotPasswordSuccessSchema","identityValue","nullable","ForgotPasswordSuccess","resendPayload","ErrorComponent","goBackRedirectTo","toErrorMessage","excludeRoutes","withError","route","FallbackComponent","InvitationJoin","signUpPath","joinInvite","invitationToken","invitationTokenData","parsedTokenCache","hasAuthenticatedSession","acceptInvitation","searchParamsResetPasswordSchema","ResetPassword","resetTokenData","isContinuation","registration_continuation","completeSignIn","answerRedirectUrl","savePassword","heading","SignInFormScreen","hostname","verifyOTPPath","verifyMagicLinkPath","forgotPasswordPath","loginMethods","getLoginMethodConfig","errorUrl","messageUrl","invitationChrome","passwordIdentityRef","completeAuthentication","handlePassword","userPayload","submitPassword","handlePasswordless","challenge_type","match_code","_matchCode","startAnswer","handlePasskey","passkeyPayload","submitPasskey","relying_party_id","stepState","resendEmailCode","force_passwordless_login","SignInForm","SignUpFormScreen","getSignUpMethodConfig","completeRegistration","oidcMayOwnRedirect","phone_number","SignUpForm","SignUp","methodLabels","push_fcm","push_webpush","methodIcons","MethodSelector","onSelectMethod","isOpen","onClose","handleSelect","asChild","TwoFactorChallenge","otpValue","setOtpValue","isMethodSelectorOpen","setIsMethodSelectorOpen","otpId","otpLabelId","otpErrorId","handleVerify","codeLength","autoSubmitTimer","handleOtpChange","then","alternative_methods","code_sent_to","renderChallengeInput","useSecondFactorRoute","registeredPath","latest","challengeTypeFullString$1","WAIT_FAILURE_MESSAGES","expired","completed","useResendPayload","identity_value","MagicLinkSent","MagicLinkWaiting","onResent","isResendError","resendError","setFailure","controller","AbortController","signal","waitForPasswordlessSignIn","aborted","wait","abort","VerifyChallengeMagicLink","setResendCount","getPendingPasswordlessSignIn","expires_at","VerifyChallengeApproval","view","setView","loadAttempt","setLoadAttempt","getPasswordlessApproval","viewFromInfo","loadError","load","decidePasswordlessApproval","decideError","screenState","city","requested_at","toLocaleString","TimerButton","totalSecond","setSeconds","interval","setInterval","clearInterval","challengeTypeFullString","VerifyChallengeOTPManual","fetchPasswordlessComplete","valueOTP","setValueOTP","paramsError","setParamsError","fetchData","refetchResponse","onClickResendHandler","VerifyChallengeOTPRedirect","missingParameters","redirectSearchParamsVerifyChallengeOtpSchema","searchParamsVerifyChallengeOtpSchema","optional","VerifyChallengeOTP","typeChallenge","redirectParams","FLOW_SCREENS","escapeRegExp","patternSource","segment","paramNames","SCREENS_BY_LENGTH","sort","decode","normalizePrefix","prefix","trimTrailingSlash","screenPath","_","withQuestionMark","cached","compute","listenTo","listener","announceUrlChange","dispatchEvent","PopStateEvent","readHash","createHistory","routerType","initial","listeners","createMemoryHistory","noLocation","PassflowRoutes","federatedDisplayMode","pathPrefix","detectedPrefix","RegExp","detectPrefix","paths","navigateRef","query","names","index","matchScreen","strayInsideFlow","isUnderPrefix","pathnameRef","FlowScreenView","PassflowFlow","requestedRedirect","controlledLocation","controlledNavigate","errorUrlSuccess","messageUrlSuccess","inAppPath","ownLocation","useFlowLocation","forwardedRef","forward","defaultSignedInLabel","LoginButton","signedInLabel","authRedirectOptions","postLogoutRedirectUri","signingOut","setSigningOut","finally"],"sources":["../package.json","../src/utils/get-app-version.ts","../src/utils/auth-error.ts","../src/utils/classify-device-error.ts","../src/utils/classify-two-factor-error.ts","../src/utils/cn.ts","../src/utils/email-verification.ts","../src/utils/form-post.ts","../src/utils/get-auth-methods.ts","../src/utils/get-form-labels.ts","../src/utils/get-url-errors.ts","../src/utils/hand-off.ts","../src/utils/get-url-with-tokens.ts","../src/utils/undefined-on-catch.ts","../src/utils/invitation-auth-chrome.ts","../src/hooks/use-hydrated.ts","../src/hooks/use-passflow.ts","../src/context/auth-context.tsx","../src/context/navigation-context.ts","../src/context/passflow-context.ts","../src/context/router-context.ts","../src/context/search-context.ts","../src/context/upgrade-context.ts","../src/utils/validate-url.ts","../src/utils/is-sign-in-page.ts","../src/utils/second-factor.ts","../src/utils/two-factor-loop-prevention.ts","../src/utils/upgrade-auth.ts","../src/utils/url-params.ts","../src/utils/validation-schemas/index.ts","../src/components/ui/button/index.tsx","../src/components/ui/continuing-status/index.tsx","../src/assets/icons/flags.png","../src/components/ui/country-flag/positions.ts","../src/components/ui/country-flag/index.tsx","../src/components/ui/dialog/index.tsx","../src/components/ui/fields/field-otp.tsx","../src/components/ui/fields/field-password.tsx","../src/utils/login-theme.ts","../src/hooks/use-isomorphic-layout-effect.ts","../src/hooks/use-app-settings.ts","../src/hooks/use-auth.ts","../src/hooks/use-auth-cloud-redirect.ts","../src/hooks/use-consent.ts","../src/hooks/use-device-verify.ts","../src/hooks/use-email-code-step.ts","../src/hooks/use-forgot-password.ts","../src/hooks/use-join-invite.ts","../src/hooks/use-logout.ts","../src/hooks/use-navigation.ts","../src/hooks/use-outsideclick.ts","../src/hooks/use-passflow-store.ts","../src/hooks/use-passwordless-complete.ts","../src/hooks/use-provider.ts","../src/hooks/use-refresh-status.ts","../src/hooks/use-reset-password.ts","../src/hooks/use-session-expired.ts","../src/components/ui/fields/field-text.tsx","../src/assets/icons/general/browser-chrome.svg","../src/assets/icons/general/caret-down.svg","../src/assets/icons/general/check.svg","../src/assets/icons/general/close.svg","../src/assets/icons/general/dots-vertical.svg","../src/assets/icons/general/edit.svg","../src/assets/icons/general/eye-off.svg","../src/assets/icons/general/eye-on.svg","../src/assets/icons/general/key.svg","../src/assets/icons/general/label.svg","../src/assets/icons/general/logo.svg","../src/assets/icons/general/logo-red.svg","../src/assets/icons/general/mail.svg","../src/assets/icons/general/one-password.svg","../src/assets/icons/general/passkey.svg","../src/assets/icons/general/phone.svg","../src/assets/icons/general/search.svg","../src/assets/icons/general/trash.svg","../src/assets/icons/general/warning.svg","../src/assets/icons/providers/apple.svg","../src/assets/icons/providers/atlassian.svg","../src/assets/icons/providers/bitbucket.svg","../src/assets/icons/providers/discord.svg","../src/assets/icons/providers/dropbox.svg","../src/assets/icons/providers/facebook.svg","../src/assets/icons/providers/github.svg","../src/assets/icons/providers/gitlab.svg","../src/assets/icons/providers/google.svg","../src/assets/icons/providers/hubspot.svg","../src/assets/icons/providers/linear.svg","../src/assets/icons/providers/linkedin.svg","../src/assets/icons/providers/microsoft.svg","../src/assets/icons/providers/notion.svg","../src/assets/icons/providers/slack.svg","../src/assets/icons/providers/tiktok.svg","../src/assets/icons/providers/twitch.svg","../src/assets/icons/providers/twitter.svg","../src/assets/icons/providers/xero.svg","../src/components/ui/icon/index.tsx","../src/components/ui/login-screen/shared.tsx","../src/components/ui/login-screen/code-entry.tsx","../src/components/ui/switch/index.tsx","../src/components/ui/login-screen/consent.tsx","../src/components/ui/link/index.tsx","../src/components/ui/providers-box/index.tsx","../src/components/ui/login-screen/credentials.tsx","../src/components/ui/login-screen/device-approval.tsx","../src/components/ui/visually-hidden/index.tsx","../src/components/ui/login-screen/email-code.tsx","../src/components/ui/login-screen/general-error.tsx","../src/components/ui/login-screen/invitation.tsx","../src/components/ui/login-screen/new-password.tsx","../src/components/ui/login-screen/passkey-progress.tsx","../src/components/ui/login-screen/passwordless-approval.tsx","../src/components/ui/login-screen/passwordless-waiting.tsx","../src/components/ui/login-screen/second-factor.tsx","../src/components/ui/login-screen/shell.tsx","../src/components/ui/login-screen/status.tsx","../src/components/ui/login-screen/two-factor-code.tsx","../src/components/ui/login-screen/two-factor-recovery-codes.tsx","../src/components/ui/login-screen/two-factor-setup.tsx","../src/components/ui/login-screen/login-screen.tsx","../src/components/ui/upgrade-dialog/factor-list.tsx","../src/components/ui/upgrade-dialog/challenge.tsx","../src/components/ui/upgrade-dialog/state-mapping.ts","../src/components/ui/spinner/index.tsx","../src/components/ui/upgrade-dialog/status.tsx","../src/components/ui/upgrade-dialog/upgrade-dialog.tsx","../src/components/provider/upgrade-provider.tsx","../src/components/provider/use-dispose-on-replace.ts","../src/components/provider/passflow-provider.tsx","../src/hooks/use-sign-in-ending.ts","../src/hooks/use-signin.ts","../src/hooks/use-signup.ts","../src/hooks/use-trusted-devices.ts","../src/hooks/use-two-factor-challenge.ts","../src/hooks/use-two-factor-manage.ts","../src/hooks/use-two-factor-methods.ts","../src/hooks/use-two-factor-setup.ts","../src/hooks/use-two-factor-setup-magic-link.ts","../src/hooks/use-two-factor-status.ts","../src/hooks/use-two-factor-verify.ts","../src/hooks/use-upgrade.ts","../src/hooks/use-user.ts","../src/hooks/use-user-passkeys.ts","../src/components/ui/fields/field-phone.tsx","../src/components/ui/login-button/shadcn-theme.ts","../src/components/ui/login-button/use-shadcn-theme.ts","../src/components/ui/login-button/login-button.tsx","../src/components/ui/popover/index.tsx","../src/hocs/with-hydration.tsx","../src/components/flow/consent/screen.ts","../src/components/flow/consent/index.tsx","../src/components/flow/device-verify/screen.ts","../src/components/flow/device-verify/index.tsx","../src/components/form/two-factor-setup/setup-screen.ts","../src/components/form/two-factor-setup/two-factor-setup-form.tsx","../src/components/flow/two-factor-setup/index.tsx","../src/components/flow/two-factor-setup-magic-link/index.tsx","../src/components/form/signed-in/index.tsx","../src/components/form/two-factor-verify/two-factor-recovery-form.tsx","../src/components/form/two-factor-verify/two-factor-verify-form.tsx","../src/hooks/use-two-factor-enrollment.ts","../src/components/flow/two-factor-verify/screen.ts","../src/components/flow/two-factor-verify/index.tsx","../src/components/form/forgot-password/forgot-password.tsx","../src/components/form/forgot-password/forgot-password-success.tsx","../src/components/error/index.tsx","../src/hocs/with-error.tsx","../src/components/form/invitation-join/index.tsx","../src/components/form/reset-password/index.tsx","../src/components/form/signin/index.tsx","../src/components/form/signup/index.tsx","../src/components/form/two-factor-challenge/method-selector.tsx","../src/components/form/two-factor-challenge/index.tsx","../src/hooks/use-second-factor-route.ts","../src/components/form/verify-challenge/verify-challenge-magic-link.tsx","../src/components/form/verify-challenge/verify-challenge-approval.tsx","../src/components/form/verify-challenge/timer-button.tsx","../src/components/form/verify-challenge/verify-challenge-otp-manual.tsx","../src/components/form/verify-challenge/verify-challenge-otp-redirect.tsx","../src/components/form/verify-challenge/verify-challenge-otp.tsx","../src/components/flow/passflow/flow-router.ts","../src/components/flow/passflow/index.tsx","../src/components/login-button/index.tsx"],"sourcesContent":["{\n \"name\": \"@passflow/react\",\n \"description\": \"Passflow React UI Kit\",\n \"version\": \"0.27.0\",\n \"type\": \"module\",\n \"files\": [\n \"dist\",\n \"src/styles/fonts/*-OFL.txt\",\n \"CHANGELOG.md\"\n ],\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.es.js\",\n \"types\": \"dist/src/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/src/index.d.ts\",\n \"default\": \"./dist/index.es.js\"\n },\n \"require\": {\n \"types\": \"./dist/src/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./dist/style.css\": \"./dist/style.css\"\n },\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build && node scripts/check-dist-css.mjs && pnpm build:types\",\n \"build:types\": \"tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && node scripts/fix-dts-specifiers.mjs && node scripts/emit-cts-types.mjs\",\n \"prepack\": \"pnpm build\",\n \"lint\": \"biome check src\",\n \"lint:fix\": \"biome check --write src\",\n \"format\": \"biome format src\",\n \"format:fix\": \"biome format --write src\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright install chromium && playwright test --config=playwright/playwright.config.ts\",\n \"test:ui\": \"playwright install chromium && playwright test --config=playwright/playwright.ui.config.ts --ui\",\n \"test:unit\": \"vitest run && vitest run --config vitest.react18.config.ts\",\n \"test:unit:react18\": \"vitest run --config vitest.react18.config.ts\",\n \"test:unit:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"storybook\": \"storybook dev -p 6006\",\n \"build-storybook\": \"storybook build\"\n },\n \"engines\": {\n \"node\": \"^22.12.0 || ^24.0.0 || >=26.0.0\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.0.0 || ^19.0.0\",\n \"react-dom\": \"^18.0.0 || ^19.0.0\"\n },\n \"dependencies\": {\n \"@passflow/core\": \"^0.32.1\",\n \"@radix-ui/react-dialog\": \"^1.3.1\",\n \"@radix-ui/react-popover\": \"^1.3.1\",\n \"@simplewebauthn/browser\": \"^14.0.0\",\n \"clsx\": \"^2.1.1\",\n \"countries-and-timezones\": \"^3.11.0\",\n \"dayjs\": \"^1.11.23\",\n \"input-otp\": \"^1.5.0\",\n \"phone\": \"^3.1.72\",\n \"query-string\": \"^10.0.0\",\n \"react-error-boundary\": \"^6.1.6\",\n \"react-hook-form\": \"^7.91.0\",\n \"react-international-phone\": \"^4.8.0\",\n \"yup\": \"^1.7.1\"\n },\n \"devDependencies\": {\n \"@axe-core/playwright\": \"4.14.0\",\n \"@biomejs/biome\": \"^2.6.4\",\n \"@playwright/test\": \"^1.64.1\",\n \"@storybook/addon-a11y\": \"10.6.5\",\n \"@storybook/addon-docs\": \"10.6.5\",\n \"@storybook/addon-themes\": \"10.6.5\",\n \"@storybook/react-vite\": \"10.6.5\",\n \"@tanstack/react-router\": \"^1.170.46\",\n \"@testing-library/jest-dom\": \"^7.0.1\",\n \"@testing-library/react\": \"^16.3.3\",\n \"@testing-library/user-event\": \"^14.6.8\",\n \"@types/node\": \"^22.20.5\",\n \"@types/react\": \"^19.3.0\",\n \"@types/react-dom\": \"^19.3.0\",\n \"@vitejs/plugin-react\": \"^6.1.2\",\n \"@vitest/coverage-v8\": \"^5.0.5\",\n \"cssnano\": \"^9.9.0\",\n \"jsdom\": \"^30.1.3\",\n \"react\": \"^19.3.1\",\n \"react-18\": \"npm:react@18.3.1\",\n \"react-dom\": \"^19.3.1\",\n \"react-dom-18\": \"npm:react-dom@18.3.1\",\n \"react-router\": \"8.5.1\",\n \"storybook\": \"10.6.5\",\n \"terser\": \"^5.51.2\",\n \"tsc-alias\": \"^1.9.9\",\n \"typescript\": \"7.0.2\",\n \"vite\": \"^8.3.5\",\n \"vite-plugin-environment\": \"^1.1.4\",\n \"vitest\": \"^5.0.5\",\n \"wouter\": \"^3.13.0\"\n },\n \"authors\": [\n {\n \"name\": \"Ivan Holiak\",\n \"url\": \"https://github.com/IvanHoliak\"\n },\n {\n \"name\": \"Jack Rudenko\",\n \"url\": \"https://madappgang.com\"\n }\n ],\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/usepassflow/passflow-react-sdk/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/usepassflow/passflow-react-sdk.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"keywords\": [\n \"passflow\",\n \"auth\",\n \"authentication\",\n \"passwordless\",\n \"session\",\n \"jwt\",\n \"react\",\n \"ui\",\n \"ui-kit\",\n \"react-ui-kit\",\n \"passflow-react-ui-kit\"\n ],\n \"packageManager\": \"pnpm@12.16.1\"\n}\n","import { version } from '../../package.json';\n\ndeclare global {\n interface Window {\n passflowReactAppVersion: () => void;\n }\n}\n\n// Runs when the module loads, so it must not assume a browser: SSR and plain Node have no window.\nif (typeof window !== 'undefined') {\n window.passflowReactAppVersion = () => {\n // eslint-disable-next-line no-console\n console.log(`App Version: ${version}`);\n };\n}\n","import { SERVICE_UNAVAILABLE_ERROR_ID, SERVICE_UNAVAILABLE_MESSAGE } from '@passflow/core';\nimport type { AuthFlow, AuthOperation, AuthUiError } from '@/types';\n\nconst AUTH_ERROR_COPY: Record<AuthFlow, Record<AuthOperation, AuthUiError>> = {\n 'sign-in': {\n password: {\n message: \"We couldn't sign you in. Check your details and try again.\",\n scope: 'credentials',\n },\n passwordless: {\n message: \"We couldn't start passwordless sign-in. Check your connection and try again.\",\n scope: 'form',\n },\n passkey: {\n message: \"We couldn't complete passkey sign-in. Try again or use another sign-in method.\",\n scope: 'form',\n },\n },\n 'sign-up': {\n password: {\n message: \"We couldn't create your account. Check the information you entered and try again.\",\n scope: 'form',\n },\n passwordless: {\n message: \"We couldn't start passwordless registration. Check your connection and try again.\",\n scope: 'form',\n },\n passkey: {\n message: \"We couldn't create your account with a passkey. Try again or choose another method.\",\n scope: 'form',\n },\n },\n};\n\nexport const authRedirectErrorMessage = \"We couldn't continue this authentication request. Return to the app and try again.\";\n\nexport const verificationLinkErrorMessage =\n 'This verification link is invalid or incomplete. Request a new link or code and try again.';\n\nexport const invitationLinkErrorMessage = 'This invitation link is invalid or has expired.';\n\nexport const verificationRequestErrorMessage =\n 'This verification request is no longer available. Start again to request a new link or code.';\n\n/** The server refuses a sign-in until the password is changed; only the emailed reset flow can continue. */\nexport const passwordChangeRequiredErrorId = 'error.api.password.change.required';\n\n/** The `reason` value that sends a user whose password must change to forgot-password. */\nexport const passwordChangeRequiredReason = 'password_change_required';\n\n/** Shown on forgot-password for that reason. Fixed SDK copy: text from the URL is never displayed. */\nexport const passwordChangeRequiredMessage =\n 'You must change your password before you can sign in. Reset your password to continue.';\n\nexport const authErrorFor = (flow: AuthFlow, operation: AuthOperation): AuthUiError => AUTH_ERROR_COPY[flow][operation];\n\n/**\n * Server error ids whose `message` is written for the end user (localized, no operator detail) and may be shown as\n * is. Every other id keeps the SDK's fixed copy, so server text that was not meant for a sign-in screen never reaches\n * one. `error.not.found` is deliberately absent: it is a generic id across the API (its text can name a missing user).\n */\nexport const SERVER_MESSAGE_ERROR_IDS: ReadonlySet<string> = new Set([\n 'error.registration.email.domain_not_allowed',\n 'error.registration.email.required',\n 'error.registration.email.not_verified_by_provider',\n 'error.invite.email.domain_not_allowed',\n 'error.verification.code.rate_limited',\n 'error.otp.incorrect',\n 'error.otp.expired',\n 'error.otp.already.used',\n 'error.challenge.address.changed',\n 'error.challenge.app_mismatch',\n 'error.email.verification.required',\n 'error.registration.continuation.invalid',\n 'error.api.plan.upgrade_required',\n passwordChangeRequiredErrorId,\n]);\n\nconst readField = (value: unknown, field: string): unknown =>\n typeof value === 'object' && value !== null ? (value as Record<string, unknown>)[field] : undefined;\n\n/**\n * The `{ id, message, status }` body of a server error. Core converts most failures to a `PassflowError`, but it\n * rejects a 429 on a non-idempotent request (`POST /auth/validate`, `/auth/register`) with the raw axios error, whose\n * body sits at `response.data.error`; read that shape too so a rate limit is classified by its id like any other.\n */\nconst readServerError = (error: unknown): unknown => {\n if (typeof readField(error, 'id') === 'string') return error;\n const response = readField(error, 'response');\n const body = readField(readField(response, 'data'), 'error');\n if (typeof body !== 'object' || body === null) return error;\n return { status: readField(response, 'status'), ...body };\n};\n\n/**\n * The server's own message for an allow-listed error id, trimmed; `null` for anything else. Duck-typed on\n * `{ id, message }`, so it reads a `PassflowError`, a raw axios rejection's body, or a plain object such as a\n * redirect's query. A request that Passflow did not answer (no response, or a gateway 502/503/504 without a Passflow\n * body) carries core's service-unavailable id and always gets core's fixed message.\n */\nexport const serverMessageFor = (error: unknown): string | null => {\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n if (id === SERVICE_UNAVAILABLE_ERROR_ID) return SERVICE_UNAVAILABLE_MESSAGE;\n const message = readField(serverError, 'message');\n if (typeof id !== 'string' || !SERVER_MESSAGE_ERROR_IDS.has(id)) return null;\n if (typeof message !== 'string') return null;\n const trimmed = message.trim();\n return trimmed === '' ? null : trimmed;\n};\n\n/** A parent challenge the server refused: each id has its own copy, and only starting again can help. */\nconst REFUSED_PARENT_COPY: ReadonlyMap<unknown, string> = new Map([\n ['error.auth.flow.parent.expired', 'This sign-in request has expired. Start again.'],\n ['error.auth.flow.parent.not.found', \"We couldn't find this sign-in request. Start again.\"],\n ['error.auth.flow.parent.completed', 'This sign-in request was already completed. Start again.'],\n]);\n\n/** A hook's display error: a refused parent's copy, the server's message for an allow-listed id, else the operation's fixed copy. */\nexport const authErrorFrom = (error: unknown, flow: AuthFlow, operation: AuthOperation): AuthUiError => {\n const refusedParent = REFUSED_PARENT_COPY.get(readField(readServerError(error), 'id'));\n if (refusedParent !== undefined) return { message: refusedParent, scope: 'form', startAgain: true };\n\n const message = serverMessageFor(error);\n return message === null ? authErrorFor(flow, operation) : { message, scope: 'form' };\n};\n\n/**\n * The message for a federated redirect that came back as `?error=<id>&message=<text>`: the server's text when the id\n * is allow-listed, else the generic redirect copy.\n */\nexport const authRedirectErrorFrom = (error: string, message: string | null): string =>\n serverMessageFor({ id: error, message }) ?? authRedirectErrorMessage;\n\nexport const invitationJoinErrorMessage = \"We couldn't accept this invitation. Try again.\";\n\n/** Invitation join error: the server's message for an allow-listed id, else the fixed copy. */\nexport const invitationJoinErrorFrom = (error: unknown): string => serverMessageFor(error) ?? invitationJoinErrorMessage;\n\nexport const emailCodeInvalidMessage = 'This code is no longer valid. Request a new code.';\nexport const emailCodeUnavailableMessage = \"We couldn't check the code. Try again.\";\nexport const emailCodeRestartMessage = \"We couldn't verify the code. Go back and start again.\";\n\n/**\n * Error copy for the emailed-code step (`/auth/validate`, resend): allow-listed ids (wrong, expired or spent code,\n * rate limit, ...) show the server message; Passflow being unavailable shows core's message; `error.not.found`\n * (unknown or spent challenge) asks for a new code; a raw axios failure with no response (offline, CORS, timeout)\n * asks to retry; every other server answer (401, a missing PKCE verifier, an unlisted 4xx or a 5xx) asks to start\n * again, and the screen keeps its way back to the form.\n */\nexport const emailCodeErrorMessage = (error: unknown): string => {\n const serverMessage = serverMessageFor(error);\n if (serverMessage !== null) return serverMessage;\n\n if (readField(readServerError(error), 'id') === 'error.not.found') return emailCodeInvalidMessage;\n // An axios failure with no response is not converted to a PassflowError by core: nothing was decided server-side.\n if (readField(error, 'isAxiosError') === true && readField(error, 'response') === undefined) {\n return emailCodeUnavailableMessage;\n }\n return emailCodeRestartMessage;\n};\n\n// The tab waiting on a cross-device sign-in.\nexport const passwordlessWaitDeniedMessage = 'This sign-in was denied. Start again.';\nexport const passwordlessLinkExpiredMessage = 'This link expired. Start again.';\nexport const passwordlessWaitCompletedMessage = 'This sign-in was already used. Start again.';\nexport const passwordlessSignInFailedMessage = 'Sign-in failed. Start again.';\n\n// The device approving a cross-device sign-in.\nexport const approvalInvalidMessage = 'This link is not valid. Start again from the page where you signed in.';\nexport const approvalUnavailableMessage = 'This sign-in cannot be approved here. Start again.';\nexport const approvalAlreadyDecidedMessage = 'This sign-in was already decided.';\nexport const approvalAttemptsMessage = 'Too many wrong codes. This sign-in was denied. Start again.';\nexport const approvalConnectionMessage = 'Check your connection and try again.';\nexport const approvalUnknownErrorMessage = 'Something went wrong. Try again later.';\nexport const approvalApprovedMessage = 'Approved. Return to the tab that started sign-in. You can close this tab.';\nexport const approvalDeniedMessage = 'Denied. No one was signed in. You can close this tab.';\n\nexport type ApprovalError = {\n message: string;\n /** Nothing more can be done on this screen: the form goes away. */\n terminal: boolean;\n};\n\nconst approvalMatchMessage = (attemptsLeft?: number): string => {\n if (attemptsLeft === undefined) return 'That code does not match.';\n return `That code does not match. ${attemptsLeft} ${attemptsLeft === 1 ? 'try' : 'tries'} left.`;\n};\n\n/** A wrong code on the approve screen: the tries left must be read again before showing the message. */\nexport const isApprovalMatchError = (error: unknown): boolean =>\n readField(readServerError(error), 'id') === 'error.auth.passwordless.approval.match.invalid';\n\n/**\n * Error copy for the approve screen. `attemptsLeft` is the count re-read after the rejection. A request Passflow did\n * not answer carries core's service-unavailable id; a plain core error with no response body may also arrive as id\n * `error.passwordless.approval` or with status 0. Nothing was decided in either case, so the screen stays.\n */\nexport const approvalErrorFrom = (error: unknown, attemptsLeft?: number): ApprovalError => {\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n\n switch (id) {\n case 'error.auth.passwordless.approval.invalid':\n return { message: approvalInvalidMessage, terminal: true };\n case 'error.auth.passwordless.approval.unavailable':\n return { message: approvalUnavailableMessage, terminal: true };\n case 'error.otp.expired':\n return { message: passwordlessLinkExpiredMessage, terminal: true };\n case 'error.otp.already.used':\n return { message: approvalAlreadyDecidedMessage, terminal: true };\n case 'error.auth.passwordless.approval.match.invalid':\n return { message: approvalMatchMessage(attemptsLeft), terminal: false };\n case 'error.auth.passwordless.approval.attempts':\n return { message: approvalAttemptsMessage, terminal: true };\n }\n\n if (id === SERVICE_UNAVAILABLE_ERROR_ID) return { message: SERVICE_UNAVAILABLE_MESSAGE, terminal: false };\n if (id === 'error.passwordless.approval' || readField(serverError, 'status') === 0) {\n return { message: approvalConnectionMessage, terminal: false };\n }\n return { message: approvalUnknownErrorMessage, terminal: false };\n};\n\n/**\n * A failed passwordless completion. A row that only another device can approve has its own copy. Passflow being\n * unavailable (core's service-unavailable id, on the completion or the exchange) shows core's message: nothing was\n * refused, so the user can try again. A failed exchange that Passflow answered comes after the row was spent, so\n * retrying cannot work (id `error.pkce.exchange`). A raw 429 on the completion itself arrives as id\n * `error.passwordless.complete`: the code was not refused, so the user can try again.\n */\nexport const passwordlessCompleteErrorMessage = (error: unknown): string => {\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n\n if (id === 'error.auth.passwordless.approval.unavailable') return approvalUnavailableMessage;\n if (id === SERVICE_UNAVAILABLE_ERROR_ID) return SERVICE_UNAVAILABLE_MESSAGE;\n if (id === 'error.pkce.exchange') return passwordlessSignInFailedMessage;\n if (id === 'error.passwordless.complete' || readField(serverError, 'status') === 0) return approvalConnectionMessage;\n return verificationRequestErrorMessage;\n};\n\nexport const resetLinkInvalidMessage = 'This link is invalid or has expired. Request a new one.';\nexport const newPasswordUnavailableMessage = \"We couldn't save your password. Try again.\";\nexport const passwordSavedRateLimitedMessage =\n 'Your password was saved, but we cannot send a verification code right now. Wait a few minutes, then sign in with your new password.';\n\n/**\n * A 429 from `/auth/password/change`: the password was already changed, only the emailed code that should follow\n * was refused, so the screen must not ask for the password again.\n */\nexport const isPasswordSavedRateLimit = (error: unknown): boolean => {\n const serverError = readServerError(error);\n return readField(serverError, 'id') === 'error.verification.code.rate_limited' || readField(serverError, 'status') === 429;\n};\n\n/**\n * Error copy for the new-password screen (reset link or registration continuation): allow-listed ids show the server\n * message; Passflow being unavailable shows core's message; a refused or spent link (any other 4xx, an `error.token.*`\n * id) asks for a new one; any other server or network failure asks to retry. The raw message of anything else is\n * never shown.\n */\nexport const newPasswordErrorMessage = (error: unknown): string => {\n if (isPasswordSavedRateLimit(error)) return passwordSavedRateLimitedMessage;\n const serverMessage = serverMessageFor(error);\n if (serverMessage !== null) return serverMessage;\n\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n const status = readField(serverError, 'status');\n if (typeof id === 'string' && id.startsWith('error.token.')) return resetLinkInvalidMessage;\n if (typeof status === 'number' && status >= 400 && status < 500) return resetLinkInvalidMessage;\n return newPasswordUnavailableMessage;\n};\n\n// First-time 2FA enrolment and the verify screens.\nexport const twoFactorSignInOverMessage = 'Your sign-in has ended. Sign in again.';\nexport const twoFactorSetupSavedSignInMessage = 'Your setup is saved. Sign in again.';\nexport const twoFactorSetupSavedNewCodeMessage =\n 'Your setup is saved. Enter a new code from your authenticator app to finish signing in.';\nexport const twoFactorSetupCodeChangedMessage = 'Your setup code changed. Scan this new QR code.';\nexport const twoFactorRateLimitedMessage = 'Too many attempts. Sign in again later.';\nexport const twoFactorWrongCodeMessage = 'Invalid code. Please check your authenticator app and try again.';\nexport const twoFactorWrongRecoveryCodeMessage = 'Invalid recovery code.';\nexport const twoFactorNotEnabledMessage =\n 'Two-factor authentication is not enabled for your account. Please contact your administrator to enable 2FA.';\nexport const twoFactorSendFailedMessage = 'We could not send the setup email. Try again later or contact your administrator.';\nexport const twoFactorTryAgainMessage = 'Something went wrong. Try again.';\nexport const twoFactorLinkAlreadyUsedMessage = 'This link was already used. Sign in.';\nexport const twoFactorBackToSignInLabel = 'Back to sign in';\nexport const twoFactorSignInLabel = 'Sign in';\n\nexport type EnrollmentFailure =\n | 'over'\n | 'rate_limited'\n | 'wrong_code'\n | 'setup_incomplete'\n | 'not_allowed'\n | 'send_failed'\n | 'unavailable'\n | 'other';\n\n/** The id of a server error, in a `PassflowError` or a raw axios rejection's object body. */\nexport const serverErrorIdFrom = (error: unknown): unknown => readField(readServerError(error), 'id');\n\n/** The HTTP status of a server error. `readServerError` skips a raw 429's string body, so its response is read too. */\nexport const serverErrorStatusFrom = (error: unknown): unknown =>\n readField(readServerError(error), 'status') ?? readField(readField(error, 'response'), 'status');\n\n/** The refused parents: a retry gets the same answer. */\nconst OVER_PARENT_IDS: ReadonlySet<unknown> = new Set([\n 'error.auth.flow.parent.not.found',\n 'error.auth.flow.parent.expired',\n 'error.auth.flow.parent.completed',\n 'error.auth.flow.parent.kind',\n 'error.auth.flow.parent.pkce.missing',\n]);\n\n/** Core throws these with no id or status once its 5 minute pending state has gone. */\nconst OVER_MESSAGES: ReadonlySet<unknown> = new Set([\n '2FA verification expired or not required. User must sign in first.',\n 'No TFA token found. User must sign in first.',\n]);\n\n/**\n * What a failed confirm, verify, begin or send means for the sign-in. The order matters: several ids answer 401 and do\n * not mean the sign-in ended. Network errors, core's format errors and a `TypeError` from a string body are `other`.\n */\nexport const enrollmentFailureFrom = (error: unknown): EnrollmentFailure => {\n const id = serverErrorIdFrom(error);\n const status = serverErrorStatusFrom(error);\n\n if (status === 429 || id === 'error.2fa.rate_limit_exceeded') return 'rate_limited';\n if (id === 'error.api.request.2fa_code.invalid' || id === 'error.2fa.recovery_code.invalid') return 'wrong_code';\n if (id === 'error.2fa.setup.incomplete') return 'setup_incomplete';\n if (id === 'error.2fa.enrollment.not_allowed') return 'not_allowed';\n if (id === 'error.2fa.setup_link.send_failed') return 'send_failed';\n if (status === 501 || id === 'error.not.implemented') return 'unavailable';\n if (id === 'error.2fa.not_enabled' || id === 'error.2fa.storage.error') return 'other';\n if (OVER_PARENT_IDS.has(id)) return 'over';\n if (status === 401 || id === 'PKCE_VERIFIER_MISSING' || id === 'error.pkce.exchange') return 'over';\n if (OVER_MESSAGES.has(readField(error, 'message'))) return 'over';\n return 'other';\n};\n","import type { DeviceError, DeviceErrorType } from '@/types/device-errors';\n\n/**\n * Turns anything that can go wrong on the device verification page into a\n * {@link DeviceError} — a sentence a person can read, plus the technical detail\n * demoted to `detail`.\n *\n * See types/device-errors.ts for why this exists at all. In short: the raw\n * strings are written for operators, and they leak.\n */\n\n/**\n * The user-facing copy. One entry per {@link DeviceErrorType}, and this table IS\n * the contract — nothing else in the flow may produce a user-visible sentence.\n *\n * Voice notes, since these are the words on the screen where someone authorizes\n * a shell:\n * - Say what happened, then what to do. Never why, in our terms.\n * - No jargon a user did not bring with them: no \"credential\", \"authenticator\",\n * \"assertion\", \"CSRF\", \"origin\", \"token\", \"challenge\", \"resident key\".\n * \"Passkey\" stays — it is the word on the button they just tapped.\n * - Never blame them, and never imply they broke something.\n * - Where we genuinely cannot tell (see passkey_failed), say so plainly and\n * offer both remedies rather than guessing at one.\n */\nconst DEVICE_ERROR_COPY: Record<DeviceErrorType, string> = {\n code_required: 'Enter the code shown on your device to continue.',\n code_invalid: \"That code isn't right. Check the code on your device and enter it again.\",\n code_expired: 'This code has expired. Start again on your device to get a new one.',\n code_declined: 'This request was already declined. Start again on your device if you still want to sign in.',\n code_already_approved: 'This device is already signed in. You can close this page and head back to it.',\n too_many_attempts: 'Too many incorrect codes were entered. Wait a few minutes, then try again.',\n mode_disabled:\n \"This app can't be signed in to this way. Ask whoever set it up to turn on QR sign-in, or sign in from your computer instead.\",\n app_unavailable: 'The app that asked you to sign in is no longer available. Start again from your device.',\n bad_credentials: \"That email or password isn't right.\",\n missing_credentials: 'Enter your email and password to continue.',\n second_factor_invalid: \"That code isn't right. Check it and enter it again.\",\n missing_second_factor: 'Enter the code to continue.',\n account_blocked: 'This account has been blocked. Contact whoever manages it for help.',\n // The three-cause sentence is deliberate, not hedging: the browser reports\n // \"cancelled\", \"timed out\" and \"no passkey here\" identically (by design — it\n // must not become an oracle for which accounts live on a device), so naming\n // one cause would be a guess presented as a fact.\n passkey_failed:\n \"We couldn't confirm your passkey. You may have cancelled it, waited too long, or there may be no passkey for this site on this device.\",\n passkey_unsupported:\n \"This device can't use a passkey to sign in here. Use a device you've set up a passkey on, or return to the app that asked you to sign in and start again.\",\n offline: \"We couldn't reach the server. Check your connection and try again.\",\n generic: 'Something went wrong on our end. Refresh the page and try again.',\n};\n\n/** Failures the user can plausibly clear by acting on this page. */\nconst RECOVERABLE: ReadonlySet<DeviceErrorType> = new Set<DeviceErrorType>([\n 'code_required',\n 'code_invalid',\n 'bad_credentials',\n 'missing_credentials',\n 'second_factor_invalid',\n 'missing_second_factor',\n 'passkey_failed',\n 'offline',\n 'generic',\n]);\n\n/**\n * Server `reason` codes -> our types.\n *\n * The server sends a stable machine reason precisely so this mapping can exist:\n * see the deviceReason* / deviceLookupError.Code constants in\n * src/web/oidc/device_page.go and device_verify.go. Its `error_description` is\n * for operators and never reaches the screen.\n *\n * Anything absent from this table — `csrf token missing or invalid`,\n * `cross-origin request refused`, `invalid JSON body`, `auth flow manager is not\n * wired` — deliberately falls through to `generic`. Those are our bugs or our\n * attacker's business, and in both cases the user's remedy is the same and their\n * screen should say so without teaching them the word \"CSRF\".\n */\nconst REASON_TO_TYPE: Record<string, DeviceErrorType> = {\n code_required: 'code_required',\n invalid_user_code: 'code_invalid',\n unknown_user_code: 'code_invalid',\n expired_user_code: 'code_expired',\n denied: 'code_declined',\n already_approved: 'code_already_approved',\n too_many_attempts: 'too_many_attempts',\n mode_disabled: 'mode_disabled',\n unknown_client: 'app_unavailable',\n passkey_unavailable: 'app_unavailable',\n unavailable: 'app_unavailable',\n bad_credentials: 'bad_credentials',\n missing_credentials: 'missing_credentials',\n second_factor_invalid: 'second_factor_invalid',\n missing_second_factor: 'missing_second_factor',\n blocked: 'account_blocked',\n passkey_failed: 'passkey_failed',\n};\n\n/**\n * WebAuthn DOMException names -> our types.\n *\n * Only the names that reliably mean something distinct to a USER are mapped.\n * NotAllowedError is the big one and it is intentionally lossy: it covers\n * cancel, timeout AND no-matching-credential, because the spec has browsers\n * conflate them so a page cannot probe which passkeys a device holds.\n */\nconst WEBAUTHN_NAME_TO_TYPE: Record<string, DeviceErrorType> = {\n NotAllowedError: 'passkey_failed',\n AbortError: 'passkey_failed',\n TimeoutError: 'passkey_failed',\n UnknownError: 'passkey_failed',\n // The authenticator or browser cannot satisfy the request as asked.\n NotSupportedError: 'passkey_unsupported',\n InvalidStateError: 'passkey_unsupported',\n ConstraintError: 'passkey_unsupported',\n // RP ID / origin misconfiguration. A deployment bug, not a user's problem —\n // they cannot fix it, so do not invite them to retry forever.\n SecurityError: 'passkey_unsupported',\n};\n\n/**\n * Message fragments that mean \"this authenticator cannot do discoverable\n * credentials\", whatever DOMException name the browser happened to attach.\n *\n * This is here because of a specific, observed regression: a real user hit\n *\n * \"Resident credentials or empty 'allowCredentials' lists are not supported\n * at this time.\"\n *\n * — Chrome's internal string for a virtual/limited authenticator being asked for\n * a discoverable credential. Matching on text as well as on name is belt and\n * braces: the name for this case is not stable across Chrome versions, and the\n * one thing that must never happen is this sentence reaching a user again.\n */\nconst UNSUPPORTED_MESSAGE_PATTERNS: readonly string[] = [\n 'resident credentials',\n 'allowcredentials',\n 'not supported at this time',\n 'discoverable credentials',\n 'is not supported',\n];\n\n/**\n * An error carrying a server-supplied reason code. Thrown by the device API\n * client so the classifier can map precisely rather than sniff strings.\n */\nexport class DeviceApiError extends Error {\n /** Stable machine reason from the server. */\n readonly reason: string;\n /** The OAuth2 error code (`invalid_request`, `unauthorized_client`, ...). */\n readonly code: string;\n /** HTTP status. */\n readonly status: number;\n\n constructor(params: { reason: string; code: string; status: number; description: string }) {\n // The Error message is the OPERATOR's string — it goes to the console and to\n // `detail`, never to the screen. classifyDeviceError picks the user's words.\n super(params.description || params.code || `device request failed (${params.status})`);\n this.name = 'DeviceApiError';\n this.reason = params.reason;\n this.code = params.code;\n this.status = params.status;\n }\n}\n\nconst build = (type: DeviceErrorType, detail?: string): DeviceError => ({\n type,\n message: DEVICE_ERROR_COPY[type],\n detail,\n isRecoverable: RECOVERABLE.has(type),\n});\n\nconst isDOMExceptionLike = (err: unknown): err is { name: string; message: string } =>\n typeof err === 'object' && err !== null && 'name' in err && typeof (err as { name: unknown }).name === 'string';\n\n/**\n * Classify any failure from the device verification flow.\n *\n * Order matters: the server's own reason wins when we have one (it knows more\n * than we can infer), then WebAuthn's message text, then WebAuthn's name, then\n * the network, then a safe default. Every path ends in copy from\n * DEVICE_ERROR_COPY — there is deliberately no branch that forwards a raw\n * string to `message`.\n */\nexport function classifyDeviceError(err: unknown): DeviceError {\n // 1. The server told us exactly what happened.\n if (err instanceof DeviceApiError) {\n const type = REASON_TO_TYPE[err.reason] ?? 'generic';\n return build(type, `${err.code}${err.reason ? `/${err.reason}` : ''}: ${err.message}`);\n }\n\n if (isDOMExceptionLike(err)) {\n const name = err.name;\n const raw = typeof err.message === 'string' ? err.message : '';\n const detail = raw ? `${name}: ${raw}` : name;\n\n // 2. The resident-credential family, matched on text. Checked BEFORE the\n // name table because the name for this case is not dependable — see\n // UNSUPPORTED_MESSAGE_PATTERNS.\n const lowered = raw.toLowerCase();\n if (UNSUPPORTED_MESSAGE_PATTERNS.some((p) => lowered.includes(p))) {\n return build('passkey_unsupported', detail);\n }\n\n // 3. A WebAuthn name we recognise.\n const byName = WEBAUTHN_NAME_TO_TYPE[name];\n if (byName) {\n return build(byName, detail);\n }\n\n // 4. fetch() rejects with TypeError when it cannot reach the network at all.\n if (name === 'TypeError') {\n return build('offline', detail);\n }\n\n return build('generic', detail);\n }\n\n return build('generic', typeof err === 'string' ? err : undefined);\n}\n\n/**\n * The copy for a type, without an error to classify. For states that are known\n * up front rather than thrown — e.g. a browser with no WebAuthn at all.\n */\nexport function deviceErrorOfType(type: DeviceErrorType, detail?: string): DeviceError {\n return build(type, detail);\n}\n","import type { TwoFactorError, TwoFactorErrorType } from '@/types/two-factor-errors';\nimport {\n enrollmentFailureFrom,\n serverErrorIdFrom,\n twoFactorNotEnabledMessage,\n twoFactorRateLimitedMessage,\n twoFactorSignInOverMessage,\n twoFactorTryAgainMessage,\n twoFactorWrongCodeMessage,\n} from './auth-error';\n\nconst errorTypeOf = (error: unknown): TwoFactorErrorType => {\n if (serverErrorIdFrom(error) === 'error.2fa.not_enabled') return 'not_enabled';\n\n switch (enrollmentFailureFrom(error)) {\n case 'over':\n return 'expired';\n case 'rate_limited':\n return 'rate_limited';\n case 'wrong_code':\n return 'invalid_code';\n default:\n return 'generic';\n }\n};\n\n/**\n * Classify a 2FA error from the error itself, not its message: the server localises messages.\n */\nexport function classifyTwoFactorError(error: unknown): TwoFactorError {\n const type = errorTypeOf(error);\n return {\n type,\n message: (error as Error | null)?.message ?? twoFactorTryAgainMessage,\n isRecoverable: type !== 'not_enabled',\n };\n}\n\n/** No further code can be taken on the screen: only the way back to sign in is left. */\nexport const isTerminalTwoFactorError = (type: TwoFactorErrorType | undefined): boolean =>\n type === 'not_enabled' || type === 'expired' || type === 'rate_limited';\n\n/**\n * Get user-friendly error message based on error type\n */\nexport function getUserFriendlyErrorMessage(error: TwoFactorError): string {\n switch (error.type) {\n case 'expired':\n return twoFactorSignInOverMessage;\n case 'rate_limited':\n return twoFactorRateLimitedMessage;\n case 'not_enabled':\n return twoFactorNotEnabledMessage;\n case 'invalid_code':\n return twoFactorWrongCodeMessage;\n default:\n return error.message;\n }\n}\n","import clsx, { type ClassValue } from 'clsx';\n\n// Joins class names. The library styles with `passflow-*` classes only, so\n// there are no utility-class conflicts to resolve.\nexport const cn = (...classes: ClassValue[]) => clsx(classes);\n","import { isEmailVerificationStep } from '@passflow/core';\nimport type { EmailCodeStep, EmailVerificationStep } from '@/types';\n\nexport const emailCodeSentFallbackMessage = 'We sent a code to your email.';\nexport const emailLinkSentFallbackMessage = 'Check your email for a link to finish signing up.';\n\nconst messageOr = (message: unknown, fallback: string): string =>\n typeof message === 'string' && message.trim() !== '' ? message.trim() : fallback;\n\n/**\n * Reads an auth answer as an email verification step: `code` when the server emailed a code (a non-empty\n * `challenge_id`), `link` when it emailed a link instead. `null` for anything else (tokens, a 2FA token, no answer).\n */\nexport const readEmailVerificationStep = (answer: unknown): EmailVerificationStep | null => {\n if (!isEmailVerificationStep(answer)) return null;\n const challengeId = (answer as { challenge_id?: unknown }).challenge_id;\n if (typeof challengeId === 'string' && challengeId !== '') {\n return { kind: 'code', challengeId, message: messageOr(answer.message, emailCodeSentFallbackMessage) };\n }\n return { kind: 'link', message: messageOr(answer.message, emailLinkSentFallbackMessage) };\n};\n\nexport type EmailCodeStepState = {\n step: EmailCodeStep;\n /** The display message of the last failed verify or resend; cleared by the next attempt or a new code. */\n error: string | null;\n};\n\nexport type EmailCodeStepEvent =\n | { type: 'ENTER'; step: EmailVerificationStep }\n | { type: 'VERIFY_STARTED' }\n | { type: 'VERIFY_OK' }\n | { type: 'VERIFY_FAILED'; message: string }\n | { type: 'RESENT'; challengeId: string; message: string }\n | { type: 'LINK_SENT'; message: string }\n | { type: 'RESEND_FAILED'; message: string }\n | { type: 'CANCEL' };\n\nexport const initialEmailCodeStepState: EmailCodeStepState = { step: { kind: 'none' }, error: null };\n\n/**\n * The emailed-code step as a transition table. Only `ENTER` leaves `none`: a verify or resend answer that lands\n * after the user went back is a real race, not a bug, so it is ignored rather than resurrecting the step. Verify and\n * resend events only change a `code` step; in `link` there is nothing left to verify or resend.\n */\nexport const emailCodeStepReducer = (state: EmailCodeStepState, event: EmailCodeStepEvent): EmailCodeStepState => {\n switch (event.type) {\n case 'ENTER':\n return { step: event.step, error: null };\n case 'CANCEL':\n return initialEmailCodeStepState;\n case 'VERIFY_STARTED':\n case 'VERIFY_OK':\n return state.step.kind === 'code' && state.error !== null ? { ...state, error: null } : state;\n case 'VERIFY_FAILED':\n case 'RESEND_FAILED':\n return state.step.kind === 'code' ? { ...state, error: event.message } : state;\n case 'RESENT':\n return state.step.kind === 'code'\n ? { step: { kind: 'code', challengeId: event.challengeId, message: event.message }, error: null }\n : state;\n case 'LINK_SENT':\n return state.step.kind === 'code' ? { step: { kind: 'link', message: event.message }, error: null } : state;\n default: {\n const unhandled: never = event;\n return unhandled;\n }\n }\n};\n","/**\n * Execute a `form_post` answer: OIDC response_mode=form_post requires the\n * parameters to arrive as a POST body, which only a real form submission can\n * do cross-origin.\n */\nexport const submitFormPost = (action: string, fields: Record<string, string>): void => {\n const form = document.createElement('form');\n form.method = 'POST';\n form.action = action;\n form.style.display = 'none';\n\n for (const [key, value] of Object.entries(fields)) {\n const input = document.createElement('input');\n input.type = 'hidden';\n input.name = key;\n input.value = value;\n form.appendChild(input);\n }\n\n document.body.appendChild(form);\n form.submit();\n};\n","import type { AuthStrategies, FimStrategy, InternalStrategy, Providers } from '@passflow/core';\n\nexport type AuthMethods = {\n internal: {\n username: {\n password: boolean;\n };\n email: {\n password: boolean;\n otp: boolean;\n magicLink: boolean;\n };\n phone: {\n password: boolean;\n otp: boolean;\n magicLink: boolean;\n };\n };\n fim: {\n providers: Providers[];\n };\n passkey: boolean;\n hasEmailMethods: boolean;\n hasSignInEmailMethods: boolean;\n hasPhoneMethods: boolean;\n hasSignInPhoneMethods: boolean;\n hasUsernameMethods: boolean;\n hasSignInUsernameMethods: boolean;\n};\n\nexport const getAuthMethods = (strategies?: AuthStrategies[]): AuthMethods => {\n const methods: AuthMethods = {\n internal: {\n username: {\n password: false,\n },\n email: {\n password: false,\n otp: false,\n magicLink: false,\n },\n phone: {\n password: false,\n otp: false,\n magicLink: false,\n },\n },\n fim: {\n providers: [],\n },\n passkey: false,\n hasEmailMethods: false,\n hasSignInEmailMethods: false,\n hasPhoneMethods: false,\n hasSignInPhoneMethods: false,\n hasUsernameMethods: false,\n hasSignInUsernameMethods: false,\n };\n\n if (!strategies) return methods;\n\n for (const strategy of strategies) {\n const { identity, challenge, fim_type: fimType } = strategy.strategy as InternalStrategy & FimStrategy;\n\n switch (strategy.type) {\n case 'internal':\n switch (identity) {\n case 'email':\n if (challenge === 'magic_link') methods.internal.email.magicLink = true;\n else methods.internal.email[challenge as keyof AuthMethods['internal']['email']] = true;\n methods.hasEmailMethods = true;\n\n if (methods.internal.email.magicLink || methods.internal.email.otp || methods.internal.email.password)\n methods.hasSignInEmailMethods = true;\n\n break;\n case 'phone':\n if (challenge === 'magic_link') methods.internal.phone.magicLink = true;\n else methods.internal.phone[challenge as keyof AuthMethods['internal']['phone']] = true;\n methods.hasPhoneMethods = true;\n\n if (methods.internal.phone.magicLink || methods.internal.phone.otp || methods.internal.phone.password)\n methods.hasSignInPhoneMethods = true;\n\n break;\n case 'username':\n methods.internal.username[challenge as keyof AuthMethods['internal']['username']] = true;\n methods.hasUsernameMethods = true;\n\n if (methods.internal.username.password) methods.hasSignInUsernameMethods = true;\n\n break;\n default:\n throw new Error(`Unsupported identity type: ${identity}`);\n }\n break;\n case 'fim':\n methods.fim.providers.push(fimType);\n break;\n case 'passkey':\n methods.passkey = true;\n break;\n default:\n throw new Error(`Unsupported strategy type: ${strategy.type}`);\n }\n }\n\n return methods;\n};\n","import type { InternalStrategyChallenge } from '@passflow/core';\n/* eslint-disable complexity */\nimport type { DefaultMethod } from '@/types';\nimport type { AuthMethods } from './get-auth-methods';\n\nexport const getIdentityLabel = (methods: AuthMethods, type: 'label' | 'button') => {\n if (methods.hasSignInEmailMethods && methods.hasSignInUsernameMethods)\n return type === 'label' ? 'Email or username' : 'Use email or username';\n if (methods.hasSignInEmailMethods) return type === 'label' ? 'Email' : 'Use email';\n if (methods.hasSignInUsernameMethods) return type === 'label' ? 'Username' : 'Use username';\n\n return null;\n};\n\nexport const getPasswordlessData = (\n methods: AuthMethods,\n currentMethod: DefaultMethod | null,\n): { label: string; challengeType: InternalStrategyChallenge } | null => {\n if (currentMethod === 'phone') {\n if (methods.internal.phone.otp) return { label: 'SMS code', challengeType: 'otp' };\n if (methods.internal.phone.magicLink) return { label: 'SMS link', challengeType: 'magic_link' };\n }\n\n if (currentMethod === 'email_or_username') {\n if (methods.internal.email.otp) return { label: 'email code', challengeType: 'otp' };\n if (methods.internal.email.magicLink) return { label: 'email link', challengeType: 'magic_link' };\n }\n\n return null;\n};\n\nexport const getValidationErrorsLabel = (methods: AuthMethods) => {\n if (methods.hasSignInEmailMethods && methods.hasSignInUsernameMethods) return 'Email or username is required';\n if (methods.hasSignInEmailMethods) return 'Email is required';\n if (methods.hasSignInUsernameMethods) return 'Username is required';\n\n return 'Field is required';\n};\n","// URLSearchParams has already decoded the value once; a second pass undoes double encoding. A literal `%` in the\n// text (e.g. \"100%\") would make that second pass throw, so the once-decoded value is kept instead.\nconst decodeOnceMore = (value: string): string => {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n};\n\nexport const getUrlErrors = (subUrl?: string) => {\n const searchParams = new URLSearchParams(subUrl ? subUrl.split('?')[1] : window.location.search);\n const error = searchParams.get('error');\n const message = searchParams.get('message');\n\n return { error, message: message ? decodeOnceMore(message) : null };\n};\n","import type { HandOff, PassflowState } from '@/context/passflow-context';\n\n/** Hand-off scopes when the app asked for none and neither discovery nor the app's settings named any. */\nconst DEFAULT_HAND_OFF_SCOPES = ['openid', 'profile', 'id'];\n\n/** `list` with `scope` added at the end, in order and without duplicates. */\nexport const withScope = (list: readonly string[], scope: string): string[] => [...new Set([...list, scope])];\n\n/**\n * The scopes the app asked for, which decide what goes back to it. The one place they are read: `undefined` when\n * there is no hand-off (embedded use), never the sign-in scopes in `state.scopes`.\n */\nexport const handOffScopes = (handOff: HandOff | undefined): string[] | undefined =>\n handOff ? (handOff.scopes ?? DEFAULT_HAND_OFF_SCOPES) : undefined;\n\n/**\n * What found scopes write under a hand-off: the hand-off scopes (with `id`) and the sign-in scopes (also with\n * `offline`), and only while the hand-off scopes are unset, so the first value found wins and a requested value is\n * never replaced. Nothing without a hand-off or when nothing was found.\n */\nexport const handOffScopesUpdate = (state: PassflowState, found: string[] | undefined): Partial<PassflowState> => {\n if (!state.handOff || state.handOff.scopes !== undefined || !found?.length) return {};\n const scopes = withScope(found, 'id');\n return { handOff: { ...state.handOff, scopes }, scopes: withScope(scopes, 'offline') };\n};\n","import type { Passflow } from '@passflow/core';\nimport type { HandOff } from '@/context/passflow-context';\nimport { handOffScopes } from './hand-off';\n\nexport type TokenUrlFormat = 'query' | 'hash';\n\nconst grantsRefreshToken = (scopes: string[]): boolean => scopes.includes('offline') || scopes.includes('offline_access');\n\n/**\n * `url` with the stored tokens appended. Without `handOff` every token goes. With it, the refresh token goes only\n * when the app asked for `offline` or `offline_access`, and the app's `state` is appended.\n */\nexport const getUrlWithTokens = async (\n passflow: Passflow,\n url: string,\n format: TokenUrlFormat = 'hash',\n handOff?: HandOff,\n): Promise<string> => {\n const tokens = await passflow.getTokens(false);\n\n if (tokens) {\n const sent: Record<string, unknown> = { ...tokens, scopes: undefined };\n const requested = handOffScopes(handOff);\n if (requested && !grantsRefreshToken(requested)) sent.refresh_token = undefined;\n\n const params = Object.entries(sent)\n .filter(([, value]) => value)\n .map(([key, value]) => `${key}=${encodeURIComponent(value as string)}`);\n if (handOff?.state) params.push(`state=${encodeURIComponent(handOff.state)}`);\n const tokenParams = params.join('&');\n\n if (format === 'hash') {\n // Use hash fragment (more secure - not sent to server)\n return `${url}#${tokenParams}`;\n }\n // Use query parameters\n return `${url}?${tokenParams}`;\n }\n return url;\n};\n","export function undefinedOnCatch<T, K>(fn: (t: K) => T): (t: K) => T | undefined {\n return (t: K) => {\n try {\n return fn(t);\n } catch (error) {\n return undefined;\n }\n };\n}\n","import { type InvitationToken, parseToken } from '@passflow/core';\nimport { undefinedOnCatch } from './undefined-on-catch';\n\nexport type InvitationAuthIntent = 'sign-in' | 'sign-up';\n\ntype InvitationAuthChrome = {\n title: string;\n subtitle: string;\n};\n\nconst authAction = {\n 'sign-in': {\n title: 'Sign in',\n completion: 'sign in',\n },\n 'sign-up': {\n title: 'Create your account',\n completion: 'create your account',\n },\n} as const;\n\nexport const getInvitationAuthChrome = (\n inviteToken: string | null | undefined,\n intent: InvitationAuthIntent,\n): InvitationAuthChrome | null => {\n if (!inviteToken) return null;\n\n const invitation = undefinedOnCatch(parseToken)(inviteToken) as InvitationToken | undefined;\n const tenantName = invitation?.tenant_name?.trim();\n const inviterName = invitation?.inviter_name?.trim();\n const action = authAction[intent];\n\n return {\n title: tenantName ? `${action.title} to join ${tenantName}.` : `${action.title} to continue your invitation.`,\n subtitle: inviterName\n ? `${inviterName} invited you. After you ${action.completion}, you'll continue to the invitation.`\n : `After you ${action.completion}, you'll continue to the invitation.`,\n };\n};\n","import { useSyncExternalStore } from 'react';\n\nconst subscribe = () => () => undefined;\nconst onClient = () => true;\nconst onServer = () => false;\n\n/**\n * False on the server and during hydration, true from the render right after hydration and in any render that is\n * not a hydration. A session lives only in the browser, so what a component renders from it waits for this: the\n * server renders signed out, and the first client render must match it.\n */\nexport const useHydrated = (): boolean => useSyncExternalStore(subscribe, onClient, onServer);\n","import type { Passflow } from '@passflow/core';\nimport { useContext } from 'react';\nimport { PassflowContext } from '@/context';\n\nexport const usePassflow = (): Passflow => {\n const context = useContext(PassflowContext);\n if (!context) {\n throw new Error('useAuth must be used within an PassflowProvider');\n }\n\n const { passflow } = context;\n\n return passflow;\n};\n","import {\n type LogOutOptions,\n type ParsedTokens,\n PassflowEvent,\n type PassflowSubscriber,\n type SessionExpiredReason,\n type Tokens,\n} from '@passflow/core';\nimport { createContext, type FC, type PropsWithChildren, useCallback, useEffect, useState } from 'react';\nimport { useHydrated } from '../hooks/use-hydrated';\nimport { usePassflow } from '../hooks/use-passflow';\n\nexport type SessionExpiredHandler = (reason: SessionExpiredReason) => void;\n\nexport type AuthContextValue = {\n /**\n * Reads the session now. On a server-rendered page, render from `isSignedIn` instead: the server has no session, so\n * output that calls this during render differs between the server and the browser.\n */\n isAuthenticated: () => boolean;\n /** Whether a user is signed in. Updates on sign-in, sign-up, sign-out and session expiry, so a component can render on it. */\n isSignedIn: boolean;\n /**\n * Signs the user out. After a hosted sign-in core then leaves the page for the hosted login's sign-out, which ends\n * at `postLogoutRedirectUri`, so code after `await logout()` may not run.\n */\n logout: (options?: LogOutOptions) => Promise<void>;\n isLoading: boolean;\n isSessionExpired: boolean;\n getTokens: (doRefresh: boolean) => Promise<{ tokens: Tokens | undefined; parsedTokens: ParsedTokens | undefined }>;\n};\n\nexport const AuthContext = createContext<AuthContextValue | undefined>(undefined);\n\nexport type AuthProviderProps = PropsWithChildren<{\n /**\n * Called when the session has really ended: last auth strike, no successor token pair\n * in time, or another user's tokens in storage. A transient refresh failure keeps the\n * session and does not call this. Use this to redirect to your login page.\n */\n onSessionExpired?: SessionExpiredHandler;\n}>;\n\nexport const AuthProvider: FC<AuthProviderProps> = ({ children, onSessionExpired }) => {\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isSessionExpired, setIsSessionExpired] = useState<boolean>(false);\n const [isSignedIn, setIsSignedIn] = useState<boolean>(() => passflow.isAuthenticated());\n\n useEffect(() => {\n // The session may have changed between the first render and this subscription.\n setIsSignedIn(passflow.isAuthenticated());\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n setIsSignedIn(passflow.isAuthenticated());\n if (eventType === PassflowEvent.SessionExpired) {\n const reason = (payload as { reason?: SessionExpiredReason })?.reason ?? 'refresh_failed';\n setIsSessionExpired(true);\n onSessionExpired?.(reason);\n } else if (eventType === PassflowEvent.SignIn || eventType === PassflowEvent.Register) {\n // Reset session expired state on successful auth\n setIsSessionExpired(false);\n }\n },\n };\n\n passflow.subscribe(subscriber, [\n PassflowEvent.SessionExpired,\n PassflowEvent.SignIn,\n PassflowEvent.Register,\n PassflowEvent.SignOut,\n ]);\n\n return () => {\n passflow.unsubscribe(subscriber);\n };\n }, [passflow, onSessionExpired]);\n\n const isAuthenticated = useCallback(() => passflow.isAuthenticated(), [passflow]);\n\n const getTokens = useCallback(\n async (doRefresh: boolean) => {\n setIsLoading(true);\n\n try {\n const tokens = await passflow.getTokens(doRefresh);\n const parsedTokens = tokens ? passflow.getParsedTokens() : undefined;\n\n return {\n tokens,\n parsedTokens,\n };\n } catch (e) {\n return {\n tokens: undefined,\n parsedTokens: undefined,\n };\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const logout = useCallback(\n async (options?: LogOutOptions) => {\n try {\n await passflow.logOut(options);\n } finally {\n setIsSignedIn(passflow.isAuthenticated());\n }\n },\n [passflow],\n );\n\n const value = {\n isAuthenticated,\n isSignedIn: hydrated && isSignedIn,\n logout,\n isLoading,\n isSessionExpired,\n getTokens,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n};\n","import { createContext } from 'react';\n\nexport type NavigateOptions = {\n to: string;\n search?: string;\n replace?: boolean;\n};\n\nexport type RouterType = 'default' | 'react-router' | 'tanstack-router' | 'wouter';\n\nexport type NavigateFunction = (options: NavigateOptions) => void;\n\n/** `tokens-in-url`: a non-PKCE return that the server already sent to this page, so it has nowhere further to go. */\nexport type FederatedLandingOutcome = 'signed-in' | 'tokens-in-url' | 'failed';\n\nexport type NavigationContextType = {\n navigate: NavigateFunction;\n setNavigate: (navigate: NavigateFunction | null) => void;\n router: RouterType;\n /**\n * Where a sign-in that owes its second factor is sent when it lands on a\n * page outside the forms (a federated redirect carrying `#tfa_token=`).\n * `PassflowProvider` resolves it: a mounted `PassflowFlow` registers its own\n * (prefixed) route, else the provider's `twoFactorVerifyPath` prop, else\n * `routes.two_factor_verify.path`.\n */\n twoFactorVerifyPath?: string;\n /** Registers the 2FA route of a mounted flow; `null` withdraws it. */\n setTwoFactorVerifyPath?: (path: string | null) => void;\n /** The sign-in page: a sign-in whose target is this page has nowhere to go. A mounted `PassflowFlow` registers its own. */\n signInPath?: string;\n /** Registers the sign-in page of a mounted flow; `null` withdraws it. */\n setSignInPath?: (path: string | null) => void;\n /** How a PKCE federated redirect that landed on this page ended. A second factor owed is not an outcome here. */\n federatedLandingOutcome?: FederatedLandingOutcome;\n};\n\nexport const defaultNavigate: NavigateFunction = ({ to, search, replace }) => {\n const searchParam = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n if (replace) {\n window.location.replace(`${to}${searchParam}`);\n } else {\n window.location.href = `${to}${searchParam}`;\n }\n};\n\nexport const NavigationContext = createContext<NavigationContextType>({\n navigate: defaultNavigate,\n setNavigate: () => undefined,\n router: 'default',\n});\n","import type { AppSettings, Passflow, PassflowPasswordPolicySettings } from '@passflow/core';\nimport { createContext, type Dispatch } from 'react';\nimport { handOffScopesUpdate } from '@/utils/hand-off';\n\n/**\n * What the app that sent the user to the hosted login asked for. `scopes` decide what goes back to it (`id` gives an\n * ID token, `offline` or `offline_access` a refresh token); unset, they are filled from the app's configuration.\n * `state` is echoed back to the app.\n */\nexport type HandOff = { scopes?: string[]; state?: string };\n\nexport type PassflowState = {\n appSettings: AppSettings | null;\n passwordPolicy: PassflowPasswordPolicySettings | null;\n url?: string;\n appId?: string;\n scopes?: string[];\n createTenantForNewUser?: boolean;\n parseQueryParams?: boolean;\n isDiscoveringAppId?: boolean;\n hasSettingsError?: boolean;\n handOff?: HandOff;\n};\n\nexport type PassflowAction =\n /** Merged into the state: a dispatch carries only the fields it changes. */\n | { type: 'SET_PASSFLOW_STATE'; payload: Partial<PassflowState> }\n /** Scopes found in the app's configuration, applied under a hand-off against the current state. */\n | { type: 'SET_FOUND_SCOPES'; found: string[] | undefined };\n\nexport type PassflowContextType = {\n state: PassflowState;\n dispatch: Dispatch<PassflowAction>;\n passflow: Passflow;\n};\n\nexport const initialState: PassflowState = {\n appSettings: null,\n passwordPolicy: null,\n url: undefined,\n appId: undefined,\n scopes: undefined,\n createTenantForNewUser: undefined,\n parseQueryParams: true,\n isDiscoveringAppId: false,\n hasSettingsError: false,\n handOff: undefined,\n};\n\nexport const PassflowContext = createContext<PassflowContextType | undefined>(undefined);\n\nexport const passflowReducer = (state: PassflowState, action: PassflowAction): PassflowState => {\n switch (action.type) {\n case 'SET_PASSFLOW_STATE':\n return { ...state, ...action.payload };\n case 'SET_FOUND_SCOPES': {\n const update = handOffScopesUpdate(state, action.found);\n return Object.keys(update).length ? { ...state, ...update } : state;\n }\n default:\n return state;\n }\n};\n","export const routes = {\n signin: {\n path: '/signin',\n },\n signup: {\n path: '/signup',\n },\n verify_otp: {\n path: '/verify-challenge-otp',\n },\n verify_magic_link: {\n path: '/verify-challenge-magic-link',\n },\n forgot_password: {\n path: '/forgot-password',\n },\n forgot_password_success: {\n path: '/forgot-password/success',\n },\n reset_password: {\n path: '/password/reset',\n },\n invitation: {\n path: '/invitation',\n },\n passkey: {\n path: '/passkeysss',\n },\n two_factor_verify: {\n path: '/two-factor-verify',\n },\n two_factor_recovery: {\n path: '/two-factor-recovery',\n },\n two_factor_setup: {\n path: '/two-factor-setup',\n },\n two_factor_setup_magic_link: {\n path: '/two-factor-setup-magic-link/:token',\n },\n};\n","import { createContext, useContext } from 'react';\n\n/**\n * Where the forms read and write their search params (`?challenge_id=…`).\n *\n * Outside PassflowFlow it is the address bar, as it always was. Inside, PassflowFlow\n * provides its own location, so the forms see the right params when the flow keeps a\n * memory or hash history, or is driven by an app router that does not use the address\n * bar. In the default browser mode both are the same URL.\n */\nexport type SearchSource = {\n /** The current search string, with its leading `?` or empty. */\n read: () => string;\n /** Moves to the same path with a new search string. */\n write: (search: string, options: { replace: boolean }) => void;\n};\n\nexport const addressBarSearch: SearchSource = {\n read: () => window.location.search,\n write: (search, { replace }) => {\n const url = `${window.location.pathname}${search}${window.location.hash}`;\n if (replace) window.history.replaceState(null, '', url);\n else window.history.pushState(null, '', url);\n },\n};\n\nexport const SearchContext = createContext<SearchSource>(addressBarSearch);\n\nexport const useSearchSource = () => useContext(SearchContext);\n","/**\n * The assurance-upgrade context — the one channel between `UpgradeProvider`\n * and `useUpgrade` (architecture §8.2, §13.3).\n *\n * The provider owns the controller, the prompt handler and every transition;\n * this module owns only the shape they are read through. Two hooks each\n * installing a prompt handler would produce two prompts and defeat\n * single-flight, so nothing here installs anything.\n *\n * `status` is §13.5's `UpgradeHookState`, which is §13.3's settlement table\n * read down the hook column. Two consequences the types enforce:\n *\n * - **`insufficient` is a first-class state, not an error and not a success.**\n * \"Elevated to AAL2; this action requires AAL3\" is the normal path for an\n * AAL3 endpoint and a TOTP-only user, and a design cannot both claim the\n * server is the authority and delete the path by which its second refusal\n * reaches the user.\n * - **Cancellation is not a status.** It is `elevate()` resolving `null`. The\n * hook is the one surface where that is right, because there the\n * cancellation IS the whole value: the consumer is rendering a decision, not\n * handling a transport outcome.\n */\n\nimport type { AssuranceBar, UpgradeChallenge, UpgradeFactor, UpgradeFactorType } from '@passflow/core';\nimport { createContext } from 'react';\n\n/** What a protected elevation can fail with, in the hook's vocabulary (§13.3's table). */\nexport type UpgradeErrorStatusKind =\n | 'exhausted'\n | 'unsatisfiable'\n | 'unavailable'\n | 'transport'\n | 'rate_limited'\n | 'sign_in_required';\n\n/**\n * The hook's observable state. Exactly one terminal state per flight, taken\n * from the controller's outcome summary (§13.4).\n *\n * `idle` is also where a flight abandoned by a session change lands: nothing\n * happened, and nothing is reported as though it had.\n */\nexport type UpgradeHookState =\n | { status: 'idle' }\n | { status: 'challenged'; challenge: UpgradeChallenge; factors: UpgradeFactorType[] }\n | { status: 'submitting' }\n | { status: 'success' }\n | { status: 'insufficient'; obtained: AssuranceBar; required: AssuranceBar }\n | { status: 'error'; kind: UpgradeErrorStatusKind; error: Error };\n\n/** The states a flight can settle in. `null` alongside these is cancellation. */\nexport type UpgradeSettledState = Extract<UpgradeHookState, { status: 'idle' | 'success' | 'insufficient' | 'error' }>;\n\n/** A bar a caller states for itself on the imperative seam (§13.2 T10 / H-6). */\nexport type UpgradeElevateOptions = {\n acrValues?: string;\n maxAge?: number;\n};\n\n/** The open prompt, as the dialog and the hook read it. */\nexport type UpgradePromptView = {\n challenge: UpgradeChallenge;\n /** Already ranked by `selectFactors`; index 0 is the suggested factor. */\n factors: readonly UpgradeFactor[];\n /** The previous attempt's failure, when the controller re-prompted. */\n previousError?: Error;\n};\n\nexport type UpgradeContextValue = {\n /** True when the provider installed a prompt handler on this `Passflow` instance. */\n enabled: boolean;\n state: UpgradeHookState;\n /** The open prompt, or `null` when no elevation is collecting an answer. */\n prompt: UpgradePromptView | null;\n selectedFactor: UpgradeFactorType | null;\n /**\n * The factor-selection signal. Reports the user's choice to the controller\n * through `UpgradePromptRequest.onFactorSelected` the moment it is made and\n * before any answer is submitted — §13.2's late-join boundary (T3), which is\n * selection and not submission.\n */\n selectFactor: (factor: UpgradeFactorType) => void;\n /** Answers the open prompt. Resolves the controller's promise exactly once. */\n submit: (code?: string) => void;\n /** Declines the open prompt. Exactly once; never leaves the promise pending. */\n cancel: () => void;\n /** Acknowledges a terminal state, closing the dialog. Settles nothing. */\n dismiss: () => void;\n /**\n * Drives an elevation directly — a \"verify now\" button, or a headless\n * caller. Resolves **`null`** when the user cancelled, and otherwise the\n * flight's terminal state; it never rejects, because the hook's contract is\n * a rendered decision rather than a thrown transport outcome.\n */\n elevate: (options?: UpgradeElevateOptions) => Promise<UpgradeSettledState | null>;\n};\n\nexport const UpgradeContext = createContext<UpgradeContextValue | undefined>(undefined);\n\nconst noop = (): void => undefined;\n\n/**\n * What `useUpgrade` reads outside an `UpgradeProvider`: idle, inert, and it\n * does not throw (§9.5 H8) — a component that merely wants to know whether an\n * elevation is running is not a bug.\n *\n * `elevate` resolves `{ status: 'idle' }` rather than `null`: nothing was\n * asked and nothing was declined, and `null` means the user declined.\n */\nexport const INERT_UPGRADE_CONTEXT: UpgradeContextValue = {\n enabled: false,\n state: { status: 'idle' },\n prompt: null,\n selectedFactor: null,\n selectFactor: noop,\n submit: noop,\n cancel: noop,\n dismiss: noop,\n elevate: () => Promise.resolve({ status: 'idle' }),\n};\n","export const isValidUrl = (url: string): boolean => {\n try {\n const newUrl = new URL(url);\n return newUrl.protocol === 'http:' || newUrl.protocol === 'https:';\n } catch {\n return false;\n }\n};\n","import { routes } from '@/context';\nimport { isValidUrl } from './validate-url';\n\nconst withoutTrailingSlash = (path: string) => path.replace(/\\/+$/, '') || '/';\n\n/** Whether a target is a path on this page's origin, as opposed to a full address or anything that could leave it. */\nexport const isSameOriginPath = (target: string): boolean => {\n if (isValidUrl(target)) return false;\n try {\n return new URL(target, window.location.href).origin === window.location.origin;\n } catch {\n return false;\n }\n};\n\n/**\n * The path, query and fragment a target names on this page's origin, or `null` when it leads elsewhere. A full\n * address on this origin counts: it is the same app, so getting there needs no new page load.\n */\nexport const inAppPath = (target: string): string | null => {\n if (isSameOriginPath(target)) return target;\n if (!isValidUrl(target)) return null;\n const url = new URL(target);\n return url.origin === window.location.origin ? `${url.pathname}${url.search}${url.hash}` : null;\n};\n\n/** Whether a sign-in's target is the sign-in page of this app, whatever its query or fragment. */\nexport const isSignInPage = (target: string, signInPath: string = routes.signin.path): boolean => {\n try {\n const url = new URL(target, window.location.href);\n return url.origin === window.location.origin && withoutTrailingSlash(url.pathname) === withoutTrailingSlash(signInPath);\n } catch {\n return false;\n }\n};\n","import { isValidJWTFormat, type Passflow, parseToken } from '@passflow/core';\nimport type { NavigateFunction } from '@/context';\nimport { undefinedOnCatch } from './undefined-on-catch';\n\n/**\n * The search for a new sign-in or its 2FA step: the original one, without anything that belonged to this attempt. A\n * reset token must not reach the verify URL, and the attempt's own destination is not carried across 2FA.\n */\nexport const signInSearch = (search: string): string => {\n const params = new URLSearchParams(search);\n for (const key of ['challenge_id', 'expires_at', 'match_code', 'otp', 'flow', 'token', 'redirect_url']) params.delete(key);\n return params.toString();\n};\n\n/**\n * Sends a sign-in that still owes its second factor to the 2FA screen.\n *\n * Every sign-in path can end this way: the server answers with a 2FA token in\n * place of tokens, `@passflow/core` keeps it and saves no session, and\n * `isTwoFactorVerificationRequired()` reads true. The caller must then stop:\n * no success redirect, and no `getUrlWithTokens` — there are no tokens yet.\n *\n * @param search the current search; what `signInSearch` keeps goes onto the 2FA URL\n * @returns true when it navigated, so the caller returns without redirecting\n */\nexport const routeToSecondFactor = (\n passflow: Pick<Passflow, 'isTwoFactorVerificationRequired'>,\n navigate: NavigateFunction,\n twoFactorVerifyPath: string,\n search = '',\n): boolean => {\n if (!passflow.isTwoFactorVerificationRequired()) return false;\n navigate({ to: twoFactorVerifyPath, search: signInSearch(search) || undefined });\n return true;\n};\n\n/**\n * Whether the current URL is a landing that owes its second factor: a\n * federated sign-in on a non-PKCE app comes back with `#tfa_token=` in the\n * fragment and no tokens. Read it before `@passflow/core` is constructed,\n * because core adopts the token and strips the fragment as it starts.\n */\nexport const urlCarriesTwoFactorToken = (): boolean => {\n if (typeof window === 'undefined' || !window.location.hash) return false;\n return new URLSearchParams(window.location.hash.substring(1)).has('tfa_token');\n};\n\n/**\n * Whether the current URL is a return with tokens in the query or the fragment. Read it before `@passflow/core` is\n * constructed, because core adopts them and strips them as it starts.\n */\nexport const urlCarriesAccessToken = (): boolean =>\n typeof window !== 'undefined' &&\n (new URLSearchParams(window.location.search).has('access_token') ||\n new URLSearchParams(window.location.hash.substring(1)).has('access_token'));\n\n/**\n * The app a `#tfa_token=` landing belongs to: the one the token names in `aud`. A federated return carries no `appid`,\n * and the server takes the token only under that app, so discovery (which answers with the default login app) would be\n * wrong. Read for routing only: the server checks the signature and refuses any other pairing.\n *\n * Only on a page served by the API's own origin, the hosted login, which already takes its app from the URL. Any other\n * page keeps its app whatever a link says.\n */\nexport const twoFactorTokenAppId = (apiUrl: string | undefined): string | undefined => {\n if (!apiUrl || !urlCarriesTwoFactorToken()) return undefined;\n const api = undefinedOnCatch((url: string) => new URL(url, window.location.href))(apiUrl);\n if (api?.origin !== window.location.origin) return undefined;\n const token = new URLSearchParams(window.location.hash.substring(1)).get('tfa_token') ?? '';\n if (!isValidJWTFormat(token)) return undefined;\n const audience: unknown = undefinedOnCatch(parseToken)(token)?.aud;\n const appId = Array.isArray(audience) ? audience[0] : audience;\n return typeof appId === 'string' && appId ? appId : undefined;\n};\n","const STORAGE_KEY_PREFIX = 'passflow_2fa';\nconst REDIRECT_COUNT_KEY = `${STORAGE_KEY_PREFIX}_redirect_count`;\nconst LAST_ERROR_KEY = `${STORAGE_KEY_PREFIX}_last_error_type`;\nconst MAX_REDIRECTS = 3;\n\n/**\n * Loop prevention for 2FA redirect cycles\n */\nexport const TwoFactorLoopPrevention = {\n /**\n * Check if redirect should be allowed\n * @returns true if redirect is safe, false if loop detected\n */\n canRedirect(): boolean {\n try {\n const count = this.getRedirectCount();\n return count < MAX_REDIRECTS;\n } catch {\n // If sessionStorage is unavailable, allow redirect once\n return true;\n }\n },\n\n /**\n * Increment redirect counter\n */\n incrementRedirect(): void {\n try {\n const count = this.getRedirectCount();\n sessionStorage.setItem(REDIRECT_COUNT_KEY, String(count + 1));\n } catch {\n // Silently fail if sessionStorage unavailable\n }\n },\n\n /**\n * Get current redirect count\n */\n getRedirectCount(): number {\n try {\n const value = sessionStorage.getItem(REDIRECT_COUNT_KEY);\n return value ? Number.parseInt(value, 10) : 0;\n } catch {\n return 0;\n }\n },\n\n /**\n * Reset redirect counter (call on successful auth)\n */\n reset(): void {\n try {\n sessionStorage.removeItem(REDIRECT_COUNT_KEY);\n sessionStorage.removeItem(LAST_ERROR_KEY);\n } catch {\n // Silently fail if sessionStorage unavailable\n }\n },\n\n /**\n * Track last error type to detect repeated errors\n */\n setLastErrorType(errorType: string): void {\n try {\n sessionStorage.setItem(LAST_ERROR_KEY, errorType);\n } catch {\n // Silently fail if sessionStorage unavailable\n }\n },\n\n /**\n * Get last error type\n */\n getLastErrorType(): string | null {\n try {\n return sessionStorage.getItem(LAST_ERROR_KEY);\n } catch {\n return null;\n }\n },\n\n /**\n * Check if same error is repeating\n */\n isRepeatingError(errorType: string): boolean {\n const lastError = this.getLastErrorType();\n return lastError === errorType && this.getRedirectCount() > 0;\n },\n\n /**\n * Get user-friendly message when loop is detected\n */\n getLoopDetectedMessage(): string {\n return 'Unable to complete authentication. This may be a configuration issue. Please contact support.';\n },\n};\n\nexport default TwoFactorLoopPrevention;\n","/**\n * The free-function adapters — `withAuth` and `attachAuth` (§13.5).\n *\n * The core exposes both as methods on a configured `Passflow` instance, because\n * that is where the resolved interception scope is bound. The developer-facing\n * form is a bare import, so these two functions translate one into the other\n * and do nothing else:\n *\n * ```tsx\n * import { attachAuth } from '@passflow/react';\n *\n * const api = axios.create({ baseURL: 'https://api.example.com' });\n * useEffect(() => attachAuth(api), []);\n * ```\n *\n * **NO LOGIC IN AN ADAPTER.** Neither function parses a challenge, compares a\n * bar, decides scope, counts a retry or chooses an error class. Every one of\n * those decisions lives in the core's `handleChallenge`, which is what makes\n * all four surfaces behave identically.\n *\n * The instance is published by `UpgradeProvider`, which reads it from\n * `PassflowContext` — so the binding is the provider's instance, resolved at\n * call time rather than captured at import time.\n *\n * **The publication is synchronous, during the provider's render, and that is\n * load-bearing.** React runs a child's effects before its parent's in the same\n * commit, so publishing from the provider's `useEffect` would be too late for\n * the documented `useEffect(() => attachAuth(api), [])` above: the child's\n * effect would reach `requireInstance` with nothing registered and throw, and a\n * throw inside an effect tears the tree down. Attach order must not matter, so\n * the registry is written in render.\n *\n * **And the release is deferred by a microtask, which is what makes the pair\n * survive React Strict Mode.** Strict Mode mounts, unmounts and remounts\n * effects in development, and the child-before-parent effect order holds on the\n * remount pass too — while render, which is what published the instance, does\n * not run again. So an immediate release in the provider's effect cleanup\n * leaves the registry empty exactly when the remounting child's effect reads\n * it, and `attachAuth` throws again (verified: it does). Scheduling the release\n * instead means a re-registration in the same tick cancels it, which is\n * precisely a Strict Mode remount; a real unmount has no re-registration, so\n * the release lands one microtask later. Nothing observes that gap but a caller\n * reaching for an instance that has just been torn down.\n */\n\nimport type { FetchLike, Passflow, ResponseInterceptorHost, WithAuthOptions } from '@passflow/core';\n\nlet activeInstance: Passflow | null = null;\n\n/**\n * The instance a scheduled release is waiting to clear, or `null` when no\n * release is pending. Any registration clears it, which is how a Strict Mode\n * remount cancels the release its own cleanup just scheduled.\n */\nlet pendingRelease: Passflow | null = null;\n\n/**\n * Publishes the provider's `Passflow` instance to the free functions, and\n * returns an unregister suitable as a React effect cleanup.\n *\n * Last registration wins, and the returned unregister is *deferred*: it clears\n * the instance on a microtask, and only if nothing has registered in the\n * meantime. See the module comment — that deferral is what keeps a Strict Mode\n * mount → unmount → remount from leaving the free functions unbound, and it is\n * why register and release are symmetric rather than one in render and one in a\n * cleanup that nothing undoes.\n */\nexport const registerUpgradeAuthInstance = (instance: Passflow): (() => void) => {\n activeInstance = instance;\n pendingRelease = null;\n return () => {\n pendingRelease = instance;\n queueMicrotask(() => {\n // A register (or a later release) superseded this one: leave it alone.\n if (pendingRelease !== instance) return;\n pendingRelease = null;\n releaseUpgradeAuthInstance(instance);\n });\n };\n};\n\n/**\n * Clears `instance` if it is still the registered one, and does nothing\n * otherwise. Idempotent, so an effect cleanup that runs after a newer provider\n * has already published cannot unbind the live instance.\n */\nexport const releaseUpgradeAuthInstance = (instance: Passflow): void => {\n if (activeInstance === instance) activeInstance = null;\n};\n\n/** The instance the free functions bind to, or `null` outside a provider. */\nexport const upgradeAuthInstance = (): Passflow | null => activeInstance;\n\nconst requireInstance = (name: string): Passflow => {\n if (activeInstance === null) {\n throw new Error(\n `[passflow] ${name}() needs a mounted <PassflowProvider>: the interception scope is bound to a configured Passflow instance. Call it from inside your app (an effect or a component), or use passflow.${name}() from usePassflow().`,\n );\n }\n return activeInstance;\n};\n\n/**\n * Wraps a `fetch` and returns the wrapper. Installs nothing and touches no\n * global — two verbs exist because the semantics genuinely differ: an axios\n * interceptor mutates, a fetch wrapper returns.\n *\n * A token goes only to the page's own origin and the ones in `options.origins`;\n * a request to any other origin is sent without it.\n */\nexport const withAuth = (next?: FetchLike, options?: WithAuthOptions): FetchLike =>\n requireInstance('withAuth').withAuth(next, options);\n\n/**\n * Attaches step-up handling to an axios instance the caller already owns,\n * **mutating** it, and returns the `detach()` disposer — which is exactly what\n * a React effect needs.\n *\n * The parameter is typed structurally (duck-typed on\n * `interceptors.response.use`), so this package's axios version is not a\n * constraint on the caller's. `options.origins` works as it does for `withAuth`.\n */\nexport const attachAuth = (instance: ResponseInterceptorHost, options?: WithAuthOptions): (() => void) =>\n requireInstance('attachAuth').attachAuth(instance, options);\n","/**\n * Utility for native handling of URL parameters\n */\nimport { useSearchSource } from '../context/search-context';\n\n/**\n * Some mail clients deliver a link with its `&` separators HTML-escaped as `&amp;`. Only that escape is undone: any\n * wider entity decoding would read a key such as `&notice=` as the `&not` entity.\n */\nconst unescapeAmpersands = (search: string): string => search.replaceAll('&amp;', '&');\n\nconst withQuestionMark = (params: URLSearchParams) => (params.toString() ? `?${params.toString()}` : '');\n\n/**\n * Read `parent_challenge_id` from the current URL's query string.\n * Returns `undefined` when not present so callers can short-circuit\n * the OIDC interceptor on non-OIDC mounts.\n *\n * Lowercases only the parameter KEYS (not values) so the\n * KSUID-shaped value isn't corrupted on the way through. (URL params\n * are case-sensitive per RFC 3986; some Passflow URLs use mixed\n * case like `appId=...`. The lowercase-keys treatment mirrors what\n * the bundled login-app was doing pre-SDK-migration.)\n */\nexport const readParentChallengeIdFromURL = (): string | undefined => {\n if (typeof window === 'undefined') return undefined;\n const raw = new URLSearchParams(window.location.search);\n // Lowercase only keys, preserve values (values are often\n // case-sensitive — KSUIDs, JWTs, OIDC state, etc.).\n const lower = new URLSearchParams(Array.from(raw, ([key, value]) => [key.toLowerCase(), value]));\n const value = lower.get('parent_challenge_id');\n return value || undefined;\n};\n\nconst isParentChallengePair = (pair: string): boolean =>\n Array.from(new URLSearchParams(pair).keys())[0]?.toLowerCase() === 'parent_challenge_id';\n\n/**\n * The URL without `parent_challenge_id`, in any key case. Works on the raw query, so every other param keeps its\n * exact encoding.\n */\nexport const urlWithoutParentChallenge = (url: string): string => {\n const hashAt = url.indexOf('#');\n const hash = hashAt < 0 ? '' : url.slice(hashAt);\n const beforeHash = hashAt < 0 ? url : url.slice(0, hashAt);\n const queryAt = beforeHash.indexOf('?');\n if (queryAt < 0) return url;\n\n const kept = beforeHash\n .slice(queryAt + 1)\n .split('&')\n .filter((pair) => !isParentChallengePair(pair));\n return `${beforeHash.slice(0, queryAt)}${kept.length > 0 ? `?${kept.join('&')}` : ''}${hash}`;\n};\n\n/**\n * Get URL parameters. Inside PassflowFlow they come from the flow's location; outside it, from the\n * address bar.\n * @param defaultValues Default values\n * @returns Object with methods getAll, get, set\n */\nexport const useUrlParams = <T extends Record<string, string>>(defaultValues?: T) => {\n const source = useSearchSource();\n const searchParams = new URLSearchParams(unescapeAmpersands(source.read()));\n\n // Set default values if parameters don't exist\n if (defaultValues) {\n let hasChanged = false;\n\n for (const [key, value] of Object.entries(defaultValues)) {\n if (!searchParams.has(key) && value !== '') {\n searchParams.set(key, value);\n hasChanged = true;\n }\n }\n\n if (hasChanged) {\n source.write(withQuestionMark(searchParams), { replace: true });\n }\n }\n\n /**\n * Get all parameters\n */\n const getAll = () => {\n const params: Record<string, string> = {};\n\n for (const [key, value] of searchParams.entries()) {\n params[key] = value;\n }\n\n return params;\n };\n\n /**\n * Get parameter value\n * @param key Parameter key\n */\n const get = (key: string) => {\n const value = searchParams.get(key);\n return value === '' ? null : value;\n };\n\n /**\n * Set parameters\n * @param params Object with parameters\n */\n const set = (params: Record<string, string>) => {\n const newSearchParams = new URLSearchParams(source.read());\n\n for (const [key, value] of Object.entries(params)) {\n if (value === null || value === undefined || value === '') {\n newSearchParams.delete(key);\n } else {\n newSearchParams.set(key, value);\n }\n }\n\n source.write(withQuestionMark(newSearchParams), { replace: false });\n };\n\n return {\n getAll,\n get,\n set,\n };\n};\n","/* eslint-disable complexity */\n/* eslint-disable max-len */\nimport type { PassflowPasswordPolicySettings } from '@passflow/core';\nimport * as Yup from 'yup';\n\nexport const emailRegex =\n /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|.(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\nexport const phoneNumberRegex =\n /^(\\+{0,})(\\d{0,})([(]{1}\\d{1,3}[)]{0,}){0,}(\\s?\\d+|\\+\\d{2,3}\\s{1}\\d+|\\d+){1}[\\s|-]?\\d+([\\s|-]?\\d+){1,2}(\\s){0,}$/gm;\n\nexport const passwordValidation = (passwordPolicy: PassflowPasswordPolicySettings | null) =>\n Yup.string()\n .required()\n .test({\n test: (value: string) => {\n const errors: string[] = [];\n\n if (passwordPolicy) {\n const {\n restrict_min_password_length: restrictMinPasswordLength,\n min_password_length: minPasswordLength,\n require_lowercase: requireLowerCase,\n require_number: requireNumber,\n require_symbol: requireSymbol,\n require_uppercase: requireUpperCase,\n } = passwordPolicy;\n\n // An unrestricted minimum leaves only the non-empty check, which `.required()` already makes.\n // Counted in characters, as the server counts them: an emoji is one, not two UTF-16 units.\n if (restrictMinPasswordLength && [...(value ?? '')].length < minPasswordLength) errors.push('length');\n // Any script's capitals and small letters, as the server checks them.\n if (requireUpperCase && !/\\p{Lu}/u.test(value)) errors.push('uppercase');\n if (requireLowerCase && !/\\p{Ll}/u.test(value)) errors.push('lowercase');\n if (requireNumber && !/\\d/.test(value)) errors.push('number');\n // Exactly the symbols the server's password check counts; `~` and backslash are not among them.\n if (requireSymbol && !/[!$%^&*()_+{}:@[\\];'#<>?,./|\\-=]/.test(value)) errors.push('symbol');\n }\n\n if (errors.length > 0) {\n const validationError = {\n errors,\n inner: true,\n path: 'password',\n field: 'password',\n message: errors,\n value,\n name: 'ValidationError',\n } as Yup.ValidationError & {\n inner: boolean;\n field: string;\n message: string[];\n };\n\n return new Yup.ValidationError(validationError, value, 'password');\n }\n\n return true;\n },\n });\n","/* eslint-disable react/button-has-type */\n/* eslint-disable react/jsx-props-no-spreading */\nimport {\n type ButtonHTMLAttributes,\n type CSSProperties,\n type FC,\n type JSX,\n type MouseEvent,\n type PropsWithChildren,\n useEffect,\n useState,\n} from 'react';\nimport { cn } from '@/utils';\nimport '@/styles/index.css';\n\ntype RippleProps = {\n size: number;\n x: number;\n y: number;\n};\n\nexport const Ripple: FC<RippleProps> = ({ size, x, y }) => {\n const style: CSSProperties = {\n width: size,\n height: size,\n left: x,\n top: y,\n };\n\n return <span className='passflow-ripple passflow-ripple-effect' style={style} />;\n};\n\ntype TButton = PropsWithChildren &\n ButtonHTMLAttributes<HTMLButtonElement> & {\n size: 'small' | 'medium' | 'big';\n /**\n * `link` is an action set in running text: no box, link colour, no ripple.\n */\n variant: 'primary' | 'secondary' | 'outlined' | 'warning' | 'clean' | 'provider' | 'dark' | 'option' | 'link';\n type: 'button' | 'submit' | 'reset';\n withIcon?: boolean;\n asIcon?: boolean;\n className?: string;\n withRipple?: boolean;\n /**\n * The `option` variant's second line — the hint under the label. Rendered\n * only by that variant, which owns the two-line geometry. It is part of the\n * button's accessible name (\"label hint\"), because it is visible text.\n */\n description?: string;\n /**\n * Toggle state for the `option` variant: mirrored to `aria-pressed` and\n * styled by the variant itself, so no call site has to describe what\n * \"selected\" looks like.\n */\n pressed?: boolean;\n };\n\nexport const Button: FC<TButton> = ({\n size,\n variant,\n type,\n onClick,\n withIcon = false,\n asIcon = false,\n className = '',\n children,\n withRipple = true,\n description,\n pressed,\n ...rest\n}) => {\n const [ripples, setRipples] = useState<JSX.Element[]>();\n\n const styles = {\n 'passflow-button passflow-button--big': size === 'big',\n 'passflow-button passflow-button--medium': size === 'medium',\n 'passflow-button passflow-button--small': size === 'small',\n 'passflow-button--primary': variant === 'primary',\n 'passflow-button--secondary': variant === 'secondary',\n 'passflow-button--outlined': variant === 'outlined',\n 'passflow-button--warning': variant === 'warning',\n 'passflow-button--clean': variant === 'clean',\n 'passflow-button--provider': variant === 'provider',\n 'passflow-button--dark': variant === 'dark',\n 'passflow-button--option': variant === 'option',\n 'passflow-button--link': variant === 'link',\n 'passflow-button--with-icon': withIcon,\n 'passflow-button--as-icon': asIcon,\n };\n\n // `aria-disabled` is the focusable disabled state: the button keeps focus (so a\n // control that locks itself after a press, like a resend countdown, does not drop\n // the keyboard user), looks disabled, and ignores presses.\n const ariaDisabled = rest['aria-disabled'] === true || rest['aria-disabled'] === 'true';\n\n const handleClick = (e: MouseEvent<HTMLButtonElement>) => {\n if (ariaDisabled) {\n e.preventDefault();\n return;\n }\n const rect = e.currentTarget.getBoundingClientRect();\n const rippleSize = Math.max(rect.width, rect.height);\n const x = e.clientX - rect.left - rippleSize / 2;\n const y = e.clientY - rect.top - rippleSize / 2;\n\n const newRipple = <Ripple key={Date.now()} size={rippleSize} x={x} y={y} />;\n\n setRipples((prev) => (prev ? [...prev, newRipple] : [newRipple]));\n\n onClick?.(e);\n };\n\n useEffect(() => {\n let timer: NodeJS.Timeout;\n if (ripples) {\n timer = setTimeout(() => {\n setRipples(undefined);\n }, 1000);\n }\n return () => clearTimeout(timer);\n }, [ripples]);\n\n return (\n <button className={cn(styles, className)} type={type} aria-pressed={pressed} onClick={handleClick} {...rest}>\n {variant === 'option' ? (\n // WCAG 2.5.3 (Label in Name): the button is named from its content, so\n // both visible lines are in the name (\"label hint\") and a voice user can\n // say what they see. The space keeps the two lines separate words in\n // that name; the column flex layout does not render it.\n <>\n <span className='passflow-button__option-label'>{children}</span>\n {description ? (\n <>\n {' '}\n <span className='passflow-button__option-hint'>{description}</span>\n </>\n ) : null}\n </>\n ) : (\n children\n )}\n {withRipple && variant !== 'link' && (\n <div aria-hidden className='passflow-ripple-container'>\n {ripples}\n </div>\n )}\n </button>\n );\n};\n","import type { FC } from 'react';\nimport './style.css';\n\nexport type ContinuingStatusProps = {\n /** The app the user is being taken to; without it the line stays generic. */\n appName?: string;\n};\n\n/** The full-page line shown while a session is handed over to the app that asked for it. */\nexport const ContinuingStatus: FC<ContinuingStatusProps> = ({ appName }) => (\n <div className='passflow-continuing-status' role='status'>\n {appName ? `Continuing to ${appName}…` : 'Continuing…'}\n </div>\n);\n","export default \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZgAAAGACAMAAACnYISRAAADAFBMVEUAAAAxQ5cSO5wAOJP////OESYBAAAANJgAJ33SDzT80Rb/AADKAADzKDgEfj3bFRr/zgDoDi4JhQHuHCYAak0AlEIAaDt1qtv/3wAAN4rdKBAAN6lFjdwBMnwOrS3cIyADh1EAVqVLsdjCKC/44BUBeV0BcsIEm0oEKov84kLVBgcAH6UCrcoAZsPpKjv+yAABAHYAoVtysuEAZQAetTrfIA7VKCQBKGXoAxLiCxcAc89ZgbwdRIoLSqn7+fgCki+kMTYAAJcAAK0Almy/CS/+6AYiSaYAUMPiPShkz//vKi0MHIy1Bwb9mgQiXjn88u8AmQADUpP/xyIxjyyHxuMAot7p6Ob9uAs5XbXUIT352gHFCx4jnkQMsF83lQT2PzNwG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03wfqilLLGTmBCXOMUARahBp+tGbqLHqBMjTl5IMTwJJeZfEEPw94v5PTWDJkZDQ0NDQ0NDQ0NDQ+P/h3jJD3Licyom5yS8J95PphJ9YpWd/SqyWm6SkZR0JpWkJN/U/RSSTjwUxXyyeFZiqorKq8otR91uS5HF4ubFZB/bjsqVxey9/8z7zzzz/vtBDLJPaWLkYlK4LSIms30tXK2jdK16MUctlqPlRwPuNW5ruSXAiekBM0RoaGKGvl1fObT+271YDKo4rImhJyaFE7O2JQfsVK9NrJQtezObCA29lN0PaoYgNNzPCYYMMpJOPIjEkKUMyKmeRSnzeL3I0+DzeoNBD/J6PayYoWUhIjR0MXfcAdUMYNdlbQ3YRzUxRGIKbQjZCkUxmWvXwl5VMsCLz9vtsV996xVXXHG119Pg9Znw+7rGkBAakejNH6GR28+1mne8fpWUpBMPxIPF2Apt8BDFtLScql5Mg93X4PVecevExFNX2L3dPnsDK0anY0NDIhMDv1gN3/fII4/Az3Ef9d8Oo4gNy09wMclSIC4QGlFMdfUsxPi8dp/Xc/Wtn2y+9Wq7N2i3ByNi2NCoFlP07DL97c+WI1icI5J04kEXQ7yvVowvaPd5HigBHrD77EGfLy4x6KAr5JqEynjCi0nhN76UxS0GN/7xxvHx8c+9XtDki6uUYTGhgyiolTIeofkritFRYYVV2KH/L3eOjztLvD47jMqE5n8hvfnTxZSPjIwMas0fgiJuHPGKgdoV9JaMj5eM5/mCcCQbLpdV3yqgJAbYPTrvhB8uszPK1zkn/D4lLjFMENx4PB67HXZgJchgMUJcVoKPmGK0CaYAsVwK7+NPTBCGy/agNwgPO75vKpsYIi4xxWinZMjEPA46CDdxiQHACAb8MAzXS4i4xBSjncSkNv/Eegx9tEbEJaYY7bS/hoaGhobGP8xff9MS7Xw+B5wAAAAASUVORK5CYII=\"","// Coordinates in the bundled 408×384 flag sprite.\n// Geometry belongs to CountryFlag so consumers never construct sprite styles.\nexport const COUNTRY_FLAG_POSITIONS = {\n ad: '-48px -27px',\n ae: '-72px -27px',\n af: '-96px -27px',\n ag: '-120px -27px',\n ai: '-144px -27px',\n al: '-168px -27px',\n am: '-192px -27px',\n an: '-216px -27px',\n ao: '-240px -27px',\n aq: '-264px -27px',\n ar: '-288px -27px',\n as: '-312px -27px',\n at: '-336px -27px',\n au: '-360px -27px',\n aw: '-384px -27px',\n ax: '-0px -51px',\n az: '-24px -51px',\n ba: '-48px -51px',\n bb: '-72px -51px',\n bd: '-96px -51px',\n be: '-120px -51px',\n bf: '-144px -51px',\n bg: '-168px -51px',\n bh: '-192px -51px',\n bi: '-216px -51px',\n bj: '-240px -51px',\n bl: '-264px -51px',\n bm: '-288px -51px',\n bn: '-312px -51px',\n bo: '-336px -51px',\n br: '-360px -51px',\n bs: '-384px -51px',\n bt: '-0px -75px',\n bw: '-24px -75px',\n by: '-48px -75px',\n bz: '-72px -75px',\n ca: '-96px -75px',\n cc: '-120px -75px',\n cd: '-144px -75px',\n cf: '-168px -75px',\n cg: '-192px -75px',\n ch: '-216px -75px',\n ci: '-240px -75px',\n ck: '-264px -75px',\n cl: '-288px -75px',\n cm: '-312px -75px',\n cn: '-336px -75px',\n co: '-360px -75px',\n cr: '-384px -75px',\n cu: '-0px -99px',\n cv: '-24px -99px',\n cw: '-48px -99px',\n cx: '-72px -99px',\n cy: '-96px -99px',\n cz: '-120px -99px',\n de: '-144px -99px',\n dj: '-168px -99px',\n dk: '-192px -99px',\n dm: '-216px -99px',\n do: '-240px -99px',\n dz: '-264px -99px',\n ec: '-288px -99px',\n ee: '-312px -99px',\n eg: '-336px -99px',\n eh: '-360px -99px',\n er: '-384px -99px',\n es: '-0px -123px',\n et: '-24px -123px',\n eu: '-48px -123px',\n fi: '-72px -123px',\n fj: '-96px -123px',\n fk: '-120px -123px',\n fm: '-144px -123px',\n fo: '-168px -123px',\n fr: '-192px -123px',\n ga: '-216px -123px',\n gb: '-240px -123px',\n gd: '-264px -123px',\n ge: '-288px -123px',\n gg: '-312px -123px',\n gh: '-336px -123px',\n gi: '-360px -123px',\n gl: '-384px -123px',\n gm: '-0px -147px',\n gn: '-24px -147px',\n gq: '-48px -147px',\n gr: '-72px -147px',\n gs: '-96px -147px',\n gt: '-120px -147px',\n gu: '-144px -147px',\n gw: '-168px -147px',\n gy: '-192px -147px',\n hk: '-216px -147px',\n hn: '-240px -147px',\n hr: '-264px -147px',\n ht: '-288px -147px',\n hu: '-312px -147px',\n ic: '-336px -147px',\n id: '-360px -147px',\n ie: '-384px -147px',\n il: '-0px -171px',\n im: '-24px -171px',\n in: '-48px -171px',\n iq: '-72px -171px',\n ir: '-96px -171px',\n is: '-120px -171px',\n it: '-144px -171px',\n je: '-168px -171px',\n jm: '-192px -171px',\n jo: '-216px -171px',\n jp: '-240px -171px',\n ke: '-264px -171px',\n kg: '-288px -171px',\n kh: '-312px -171px',\n ki: '-336px -171px',\n xk: '-144px 3px',\n km: '-360px -171px',\n kn: '-384px -171px',\n kp: '-0px -195px',\n kr: '-24px -195px',\n kw: '-48px -195px',\n ky: '-72px -195px',\n kz: '-96px -195px',\n la: '-120px -195px',\n lb: '-144px -195px',\n lc: '-168px -195px',\n li: '-192px -195px',\n lk: '-216px -195px',\n lr: '-240px -195px',\n ls: '-264px -195px',\n lt: '-288px -195px',\n lu: '-312px -195px',\n lv: '-336px -195px',\n ly: '-360px -195px',\n ma: '-384px -195px',\n mc: '-0px -219px',\n md: '-24px -219px',\n me: '-48px -219px',\n mf: '-72px -219px',\n mg: '-96px -219px',\n mh: '-120px -219px',\n mk: '-144px -219px',\n ml: '-168px -219px',\n mm: '-192px -219px',\n mn: '-216px -219px',\n mo: '-240px -219px',\n mp: '-264px -219px',\n mq: '-288px -219px',\n mr: '-312px -219px',\n ms: '-336px -219px',\n mt: '-360px -219px',\n mu: '-384px -219px',\n mv: '-0px -243px',\n mw: '-24px -243px',\n mx: '-48px -243px',\n my: '-72px -243px',\n mz: '-96px -243px',\n na: '-120px -243px',\n nc: '-144px -243px',\n ne: '-168px -243px',\n nf: '-192px -243px',\n ng: '-216px -243px',\n ni: '-240px -243px',\n nl: '-264px -243px',\n no: '-288px -243px',\n np: '-312px -243px',\n nr: '-336px -243px',\n nu: '-360px -243px',\n nz: '-384px -243px',\n om: '-0px -267px',\n pa: '-24px -267px',\n pe: '-48px -267px',\n pf: '-72px -267px',\n pg: '-96px -267px',\n ph: '-120px -267px',\n pk: '-192px -267px',\n pl: '-216px -267px',\n pn: '-240px -267px',\n pr: '-264px -267px',\n ps: '-288px -267px',\n pt: '-312px -267px',\n pw: '-336px -267px',\n py: '-360px -267px',\n qa: '-384px -267px',\n ro: '-0px -291px',\n rs: '-24px -291px',\n ru: '-48px -291px',\n rw: '-72px -291px',\n sa: '-96px -291px',\n sb: '-120px -291px',\n sc: '-144px -291px',\n sd: '-168px -291px',\n se: '-192px -291px',\n sg: '-216px -291px',\n sh: '-240px -291px',\n si: '-264px -291px',\n sk: '-288px -291px',\n sl: '-312px -291px',\n sm: '-336px -291px',\n sn: '-360px -291px',\n so: '-384px -291px',\n sr: '-0px -315px',\n ss: '-24px -315px',\n st: '-48px -315px',\n sv: '-72px -315px',\n sy: '-96px -315px',\n sz: '-120px -315px',\n tc: '-144px -315px',\n td: '-168px -315px',\n tf: '-192px -315px',\n tg: '-216px -315px',\n th: '-240px -315px',\n tj: '-264px -315px',\n tk: '-288px -315px',\n tl: '-312px -315px',\n tm: '-336px -315px',\n tn: '-360px -315px',\n to: '-384px -315px',\n tr: '-0px -339px',\n tt: '-24px -339px',\n tv: '-48px -339px',\n tw: '-72px -339px',\n tz: '-96px -339px',\n ua: '-120px -339px',\n ug: '-144px -339px',\n us: '-168px -339px',\n uy: '-192px -339px',\n uz: '-216px -339px',\n va: '-240px -339px',\n vc: '-264px -339px',\n ve: '-288px -339px',\n vg: '-312px -339px',\n vi: '-336px -339px',\n vn: '-360px -339px',\n vu: '-384px -339px',\n wf: '-0px -363px',\n ws: '-24px -363px',\n ye: '-48px -363px',\n za: '-96px -363px',\n zm: '-120px -363px',\n zw: '-144px -363px',\n} as const;\n\nexport type SupportedCountryFlag = keyof typeof COUNTRY_FLAG_POSITIONS;\n","import type { CSSProperties, FC } from 'react';\nimport flags from '@/assets/icons/flags.png';\nimport { cn } from '@/utils';\nimport { COUNTRY_FLAG_POSITIONS, type SupportedCountryFlag } from './positions';\nimport './style.css';\n\nexport type CountryFlagProps = {\n iso2: string;\n className?: string;\n};\n\nconst COUNTRY_FLAG_ALIASES: Record<string, SupportedCountryFlag> = {\n bq: 'nl',\n gf: 'fr',\n gp: 'fr',\n io: 'gb',\n pm: 'fr',\n re: 'fr',\n yt: 'fr',\n};\n\nconst getSupportedCountry = (iso2: string): SupportedCountryFlag | null => {\n const normalized = iso2.trim().toLowerCase();\n const candidate = COUNTRY_FLAG_ALIASES[normalized] ?? normalized;\n return candidate in COUNTRY_FLAG_POSITIONS ? (candidate as SupportedCountryFlag) : null;\n};\n\nexport const CountryFlag: FC<CountryFlagProps> = ({ iso2, className }) => {\n const country = getSupportedCountry(iso2);\n\n if (!country) {\n return (\n <span\n aria-hidden='true'\n className={cn('passflow-country-flag passflow-country-flag--fallback', className)}\n data-country-flag={iso2.toLowerCase()}\n >\n {iso2.slice(0, 2).toUpperCase() || '–'}\n </span>\n );\n }\n\n const style: CSSProperties = {\n backgroundImage: `url(${flags})`,\n backgroundPosition: COUNTRY_FLAG_POSITIONS[country],\n };\n\n return (\n <span\n aria-hidden='true'\n className={cn('passflow-country-flag', className)}\n data-country-flag={iso2.toLowerCase()}\n style={style}\n />\n );\n};\n","import * as DialogPrimitive from '@radix-ui/react-dialog';\n/* eslint-disable react/jsx-props-no-spreading */\nimport { type ComponentPropsWithoutRef, type ElementRef, forwardRef, type HTMLAttributes } from 'react';\nimport { cn } from '@/utils';\n\nconst Dialog = DialogPrimitive.Root;\n\nconst DialogTrigger = DialogPrimitive.Trigger;\n\nconst DialogPortal = DialogPrimitive.Portal;\n\nconst DialogClose = DialogPrimitive.Close;\n\nconst DialogOverlay = forwardRef<\n ElementRef<typeof DialogPrimitive.Overlay>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay ref={ref} className={cn('passflow-dialog-overlay', className)} {...props} />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\nconst DialogContent = forwardRef<\n ElementRef<typeof DialogPrimitive.Content>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Content ref={ref} className={cn('passflow-dialog-content', className)} {...props}>\n {children}\n </DialogPrimitive.Content>\n </DialogPortal>\n));\nDialogContent.displayName = DialogPrimitive.Content.displayName;\n\nconst DialogHeader = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (\n <div className={cn('passflow-dialog-header', className)} {...props} />\n);\nDialogHeader.displayName = 'DialogHeader';\n\nconst DialogFooter = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (\n <div className={cn('passflow-dialog-footer', className)} {...props} />\n);\nDialogFooter.displayName = 'DialogFooter';\n\nconst DialogTitle = forwardRef<\n ElementRef<typeof DialogPrimitive.Title>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Title ref={ref} className={cn('passflow-dialog-title', className)} {...props} />\n));\nDialogTitle.displayName = DialogPrimitive.Title.displayName;\n\nconst DialogDescription = forwardRef<\n ElementRef<typeof DialogPrimitive.Description>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Description ref={ref} className={cn('passflow-dialog-description', className)} {...props} />\n));\nDialogDescription.displayName = DialogPrimitive.Description.displayName;\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n};\n","import { OTPInput, REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS, type SlotProps } from 'input-otp';\nimport { type FC, forwardRef } from 'react';\nimport { cn } from '@/utils';\nimport '@/styles/index.css';\nimport './field-otp.css';\n\nexport type FieldOtpCharset = 'numeric' | 'alphanumeric';\n\nexport type FieldOtpState = 'default' | 'error' | 'disabled';\n\ntype FieldOtpBaseProps = {\n /** Id of the one real `<input>`; the boxes are drawn from its value. */\n id: string;\n /** Form field name, for a native form submit. */\n name?: string;\n /** Number of characters in the code, and of boxes drawn. */\n length: number;\n value: string;\n onChange: (value: string) => void;\n /** Called once the code reaches `length` characters. */\n onComplete?: (value: string) => void;\n /** Which characters are accepted; also picks the on-screen keyboard. Default `numeric`. */\n charset?: FieldOtpCharset;\n /** `error` marks the code invalid (`aria-invalid`); `disabled` locks it. Default `default`. */\n state?: FieldOtpState;\n /** Id of the element that describes it, such as the error message. */\n describedBy?: string;\n autoFocus?: boolean;\n};\n\n/**\n * The code field is named either by a visible label it draws itself (`label`),\n * or by an element the screen already shows (`labelledBy`), never both. A\n * hidden-only name fails axe `label-title-only` once `describedBy` is set.\n */\nexport type FieldOtpProps = FieldOtpBaseProps &\n (\n | {\n /** Visible prompt drawn above the boxes, as the field's `<label>`. */\n label: string;\n labelledBy?: never;\n }\n | {\n /** Id of a visible element on the screen that names the code field, such as a prompt or heading. */\n labelledBy: string;\n label?: never;\n }\n );\n\nconst CHARSETS: Record<FieldOtpCharset, { pattern: string; inputMode: 'numeric' | 'text' }> = {\n numeric: { pattern: REGEXP_ONLY_DIGITS, inputMode: 'numeric' },\n alphanumeric: { pattern: REGEXP_ONLY_DIGITS_AND_CHARS, inputMode: 'text' },\n};\n\ntype SlotViewProps = SlotProps & { state: FieldOtpState };\n\nconst Slot: FC<SlotViewProps> = ({ char, isActive, hasFakeCaret, state }) => (\n <div\n className={cn('passflow-field-otp', {\n 'passflow-field-otp--active': isActive,\n 'passflow-field-otp--error': state === 'error',\n 'passflow-field-otp--disabled': state === 'disabled',\n })}\n >\n {char}\n {hasFakeCaret ? <span className='passflow-field-otp__caret' /> : null}\n </div>\n);\n\n/**\n * A one-time code entered as a row of boxes.\n *\n * There is one real `<input>` (named, `autocomplete=\"one-time-code\"`), so SMS\n * autofill, password managers and pasting a whole code all work. The boxes are\n * a drawing of its value, hidden from assistive technology. With `label` the\n * field draws its own visible label above the boxes; with `labelledBy` it is\n * named by a prompt the screen already shows. Its ref is the real `<input>`,\n * so a screen can return focus to it after the field was locked.\n */\nexport const FieldOtp = forwardRef<HTMLInputElement, FieldOtpProps>(function FieldOtp(\n {\n id,\n name,\n length,\n value,\n onChange,\n onComplete,\n charset = 'numeric',\n state = 'default',\n label,\n labelledBy,\n describedBy,\n autoFocus = false,\n },\n ref,\n) {\n const { pattern, inputMode } = CHARSETS[charset];\n\n const input = (\n <OTPInput\n ref={ref}\n id={id}\n name={name}\n maxLength={length}\n value={value}\n onChange={onChange}\n onComplete={onComplete}\n pattern={pattern}\n inputMode={inputMode}\n autoComplete='one-time-code'\n disabled={state === 'disabled'}\n aria-labelledby={labelledBy}\n aria-describedby={describedBy}\n aria-invalid={state === 'error' ? true : undefined}\n autoFocus={autoFocus}\n noScriptCSSFallback={null}\n containerClassName={cn('passflow-field-otp-group', { 'passflow-field-otp-group--disabled': state === 'disabled' })}\n render={({ slots }) => (\n <div className='passflow-field-otp-slots' aria-hidden>\n {slots.map((slot, position) => (\n // Slots are positions in the code: the index is their identity.\n // biome-ignore lint/suspicious/noArrayIndexKey: a slot is its position\n <Slot key={position} {...slot} state={state} />\n ))}\n </div>\n )}\n />\n );\n\n if (label === undefined) return input;\n\n return (\n <div className='passflow-field-otp-field'>\n <label htmlFor={id} className='passflow-field-label'>\n {label}\n </label>\n {input}\n </div>\n );\n});\n","/* eslint-disable react/jsx-props-no-spreading */\nimport { forwardRef, type InputHTMLAttributes, useState } from 'react';\nimport { Button, Icon } from '..';\nimport '@/styles/index.css';\nimport type { PassflowPasswordPolicySettings } from '@passflow/core';\nimport { cn } from '@/utils';\n\ntype TFieldPassword = InputHTMLAttributes<HTMLInputElement> & {\n id: string;\n value: string;\n passwordPolicy: PassflowPasswordPolicySettings | null;\n withMessages?: boolean;\n validationErrors?: string | string[];\n isError?: boolean;\n className?: string;\n disabled?: boolean;\n};\n\n/** The character-class line, or `null` when the policy requires no class. */\nconst generateMessage = (\n requires: Record<'requireLowerCase' | 'requireUpperCase' | 'requireSymbol' | 'requireNumber', boolean>,\n) => {\n const requiresString = {\n requireNumber: 'number',\n requireSymbol: 'symbol',\n requireLowerCase: 'lowercase letter',\n requireUpperCase: 'uppercase letter',\n };\n const requirements = Object.keys(requires).filter((key) => requires[key as keyof typeof requires]);\n if (requirements.length === 0) return null;\n const requirementsString = new Intl.ListFormat('en').format(\n requirements.map((requirement) => requiresString[requirement as keyof typeof requiresString]),\n );\n\n return `Must contain a ${requirementsString}`;\n};\n\nexport const FieldPassword = forwardRef<HTMLInputElement, TFieldPassword>(\n (\n {\n id,\n value,\n passwordPolicy,\n withMessages = false,\n validationErrors = [],\n isError = false,\n className = '',\n disabled = false,\n ...rest\n },\n ref,\n ) => {\n const [isShowPassword, setIsShowPassword] = useState(false);\n\n const styles = {\n 'passflow-field--error': isError,\n };\n\n const errorStyles = (fields: string[]) => {\n if (value.length > 0 && !fields.some((field) => validationErrors.includes(field)))\n return 'passflow-password-validation-item--success';\n return null;\n };\n\n const changeIcon = (fields: string[]) => {\n if (value.length > 0 && !fields.some((field) => validationErrors.includes(field))) return 'check';\n return 'close';\n };\n\n const handleShowPassword = () => setIsShowPassword((prev) => !prev);\n\n const minPasswordLength = passwordPolicy?.min_password_length ?? 0;\n // A minimum of zero asks for nothing beyond the non-empty password every field requires.\n const restrictMinPasswordLength = (passwordPolicy?.restrict_min_password_length ?? false) && minPasswordLength > 0;\n const requireLowerCase = passwordPolicy?.require_lowercase ?? false;\n const requireNumber = passwordPolicy?.require_number ?? false;\n const requireSymbol = passwordPolicy?.require_symbol ?? false;\n const requireUpperCase = passwordPolicy?.require_uppercase ?? false;\n const requirementsMessage = generateMessage({\n requireNumber,\n requireSymbol,\n requireLowerCase,\n requireUpperCase,\n });\n\n return (\n <>\n <div className='passflow-field-wrapper'>\n <input\n ref={ref}\n id={id}\n value={value}\n type={isShowPassword ? 'text' : 'password'}\n className={cn('passflow-field-input passflow-field--focused passflow-field-input--with-icon', styles, className)}\n disabled={disabled}\n {...rest}\n />\n {isShowPassword ? (\n <Button\n className='passflow-button-display-password passflow-field-icon-button'\n size='small'\n type='button'\n variant='clean'\n asIcon\n withIcon\n disabled={disabled}\n aria-label='Hide password'\n onClick={handleShowPassword}\n >\n <Icon size='small' type='general' id='eye-on' decorative />\n </Button>\n ) : (\n <Button\n className='passflow-button-display-password passflow-field-icon-button'\n size='small'\n type='button'\n variant='clean'\n asIcon\n withIcon\n disabled={disabled}\n aria-label='Show password'\n onClick={handleShowPassword}\n >\n <Icon size='small' type='general' id='eye-off' decorative />\n </Button>\n )}\n </div>\n {withMessages && passwordPolicy && (restrictMinPasswordLength || requirementsMessage) && (\n <div className='passflow-password-validation'>\n {restrictMinPasswordLength && (\n <p className={cn('passflow-password-validation-item', errorStyles(['length']))}>\n <Icon size='small' id={changeIcon(['length'])} type='general' className={cn(errorStyles(['length']))} />\n At least {minPasswordLength} characters\n </p>\n )}\n {requirementsMessage && (\n <p\n className={cn('passflow-password-validation-item', errorStyles(['uppercase', 'lowercase', 'number', 'symbol']))}\n >\n <Icon\n size='small'\n id={changeIcon(['uppercase', 'lowercase', 'number', 'symbol'])}\n type='general'\n className={cn(errorStyles(['uppercase', 'lowercase', 'number', 'symbol']))}\n />\n {requirementsMessage}\n </p>\n )}\n </div>\n )}\n </>\n );\n },\n);\n","import type { LoginWebAppStyle } from '@passflow/core';\n\nexport type CompatibleLoginWebAppStyle = Partial<LoginWebAppStyle> & {\n /** Legacy field used by themes created before text_color was introduced. */\n content_color?: string;\n};\n\nconst nonEmpty = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value.trim() : null);\n\nconst getBackgroundImage = (value: unknown): string | null => {\n if (typeof value !== 'string') return null;\n\n const image = nonEmpty(value);\n return image ? `url(${image})` : 'none';\n};\n\nexport const getLoginThemeCssVariables = (style: CompatibleLoginWebAppStyle): Record<string, string | null> => ({\n '--passflow-primary-color': nonEmpty(style.primary_color),\n '--passflow-text-color': nonEmpty(style.text_color) ?? nonEmpty(style.content_color),\n '--passflow-secondary-text-color': nonEmpty(style.secondary_text_color),\n '--passflow-background-color': nonEmpty(style.background_color),\n '--passflow-background-image': getBackgroundImage(style.background_image),\n '--passflow-card-color': nonEmpty(style.card_color),\n '--passflow-branding-background-color': nonEmpty(style.card_color),\n '--passflow-input-background-color': nonEmpty(style.input_background_color),\n '--passflow-input-border-color': nonEmpty(style.input_border_color),\n '--passflow-button-text-color': nonEmpty(style.button_text_color),\n '--passflow-passkey-button-text-color': nonEmpty(style.passkey_button_text_color),\n '--passflow-passkey-button-background-color': nonEmpty(style.passkey_button_background_color),\n '--passflow-divider-color': nonEmpty(style.divider_color),\n '--passflow-federated_button_background_color': nonEmpty(style.federated_button_background_color),\n '--passflow-federated_button_text_color': nonEmpty(style.federated_button_text_color),\n});\n\nexport const applyLoginThemeStyles = (root: HTMLElement, style: CompatibleLoginWebAppStyle): void => {\n for (const [property, value] of Object.entries(getLoginThemeCssVariables(style))) {\n if (value === null) root.style.removeProperty(property);\n else root.style.setProperty(property, value);\n }\n};\n","import { useEffect, useLayoutEffect } from 'react';\n\n/**\n * A layout effect in the browser and a plain effect on the server, where a layout effect does nothing and React 18\n * warns about it. Neither runs during a server render.\n */\nexport const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n","import type { AppSettings, LoginWebAppStyle, LoginWebAppTheme, PassflowPasswordPolicySettings } from '@passflow/core';\nimport { useContext, useRef, useState } from 'react';\nimport { PassflowContext, type PassflowState } from '@/context';\nimport { applyLoginThemeStyles, type CompatibleLoginWebAppStyle } from '@/utils/login-theme';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseAppSettingsProps = () => {\n appSettings: AppSettings | null;\n passwordPolicy: PassflowPasswordPolicySettings | null;\n isLoading: boolean;\n isError: boolean;\n error: string;\n reset: () => void;\n currentTheme: string;\n currentStyles: LoginWebAppStyle | null;\n scopes: string[];\n createTenantForNewUser: boolean;\n loginAppTheme?: LoginWebAppTheme;\n};\n\nconst hasPasswordStrategy = (strategies: AppSettings['auth_strategies']): boolean => {\n return strategies?.some((strategy) => strategy.type === 'internal' && strategy.strategy?.challenge === 'password') ?? false;\n};\n\nexport const useAppSettings: UseAppSettingsProps = () => {\n const passflow = usePassflow();\n const context = useContext(PassflowContext);\n const [isError, setIsError] = useState(false);\n const [errorMessage, setErrorMessage] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const isFetchingRef = useRef(false);\n\n if (!context) {\n throw new Error('useAppSetting must be used within an PassflowProvider');\n }\n\n const { state, dispatch } = context;\n\n useIsomorphicLayoutEffect(() => {\n // The provider is still looking for the app id: settings read now would be the empty default.\n if (state.isDiscoveringAppId) return;\n if (state.appSettings || state.hasSettingsError || isFetchingRef.current) return;\n\n const fetchAllSettings = async (): Promise<void> => {\n isFetchingRef.current = true;\n setIsLoading(true);\n try {\n // If appId is not provided, try to discover it from /settings endpoint\n if (!passflow.appId) {\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { isDiscoveringAppId: true } });\n const discovered: Partial<PassflowState> = { isDiscoveringAppId: false };\n\n try {\n // Try relative path first (works with dev server proxy and same-origin production)\n // Then fall back to absolute URL if configured\n const urlsToTry = ['/settings'];\n if (passflow.url) {\n urlsToTry.push(`${passflow.url}/settings`);\n }\n\n let response: Response | null = null;\n for (const url of urlsToTry) {\n try {\n const r = await fetch(url);\n if (r.ok) {\n response = r;\n break;\n }\n } catch {}\n }\n\n if (response) {\n const settings = await response.json();\n\n // Support both response formats:\n // Production: { login_app: { app_id: \"...\", ... } }\n // Dev: { appId: \"...\" }\n const discoveredAppId = settings.login_app?.app_id || settings.appId;\n\n if (discoveredAppId) {\n passflow.setAppId(discoveredAppId);\n discovered.appId = discoveredAppId;\n\n const discoveredScopes = settings.login_app?.scopes || settings.scopes;\n if (state.handOff) dispatch({ type: 'SET_FOUND_SCOPES', found: discoveredScopes });\n else if (!state.scopes && discoveredScopes) discovered.scopes = discoveredScopes;\n\n const createTenant = settings.login_app?.create_tenant_for_new_user ?? settings.createTenantForNewUser;\n if (state.createTenantForNewUser === undefined && createTenant !== undefined) {\n discovered.createTenantForNewUser = createTenant;\n }\n }\n }\n } catch (discoveryError) {\n console.warn('Failed to discover appId from /settings:', discoveryError);\n // Continue with the flow - we'll handle missing appId later\n }\n\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: discovered });\n }\n\n // Discovery has finished. With no app id this is the bare default sign-in form, on empty settings.\n let appSettings = {} as AppSettings;\n if (passflow.appId) {\n appSettings = await passflow.getAppSettings();\n }\n\n // Each dispatch carries only what it changes, so nothing written meanwhile is overwritten.\n const finalStateUpdates: Partial<PassflowState> = { appSettings };\n\n // Under a hand-off the reducer applies the found scopes to the current state: a value discovery wrote while\n // this request was open stays.\n const defaultScopes = appSettings.defaults?.scopes;\n if (state.handOff) dispatch({ type: 'SET_FOUND_SCOPES', found: defaultScopes });\n else if (!state.scopes && defaultScopes) finalStateUpdates.scopes = defaultScopes;\n const defaultCreateTenant = appSettings.defaults?.create_tenant_for_new_user;\n if (state.createTenantForNewUser === undefined && defaultCreateTenant !== undefined) {\n finalStateUpdates.createTenantForNewUser = defaultCreateTenant;\n }\n\n let passwordPolicy = null;\n if (appSettings.auth_strategies && hasPasswordStrategy(appSettings.auth_strategies)) {\n passwordPolicy = await passflow.getPasswordPolicySettings();\n }\n finalStateUpdates.passwordPolicy = passwordPolicy;\n\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: finalStateUpdates });\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n // Set error flag in context to prevent infinite retry loop\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { hasSettingsError: true } });\n } finally {\n setIsLoading(false);\n isFetchingRef.current = false;\n }\n };\n void fetchAllSettings();\n }, [dispatch, state.appSettings, state.hasSettingsError, state.isDiscoveringAppId, passflow]);\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n // Clear error flag in context to allow retry\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { hasSettingsError: false } });\n };\n\n // `custom_css` is not written here: each screen passes `currentStyles.custom_css`\n // to its shell, which renders it inline.\n const applyThemeStyles = (style: CompatibleLoginWebAppStyle) => {\n applyLoginThemeStyles(document.documentElement, style);\n };\n\n const getCurrentTheme = () => {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n\n if (state.appSettings?.login_app_theme?.color_scheme === 'system') return theme;\n\n return state.appSettings?.login_app_theme?.color_scheme ?? theme;\n };\n\n const currentTheme = getCurrentTheme();\n\n const selectedStyle = state.appSettings?.login_app_theme\n ? currentTheme === 'dark'\n ? state.appSettings?.login_app_theme.dark_style\n : state.appSettings?.login_app_theme.light_style\n : null;\n\n if (selectedStyle) {\n applyThemeStyles(selectedStyle);\n }\n\n return {\n appSettings: state.appSettings,\n scopes: state.scopes ?? [],\n createTenantForNewUser: state.createTenantForNewUser ?? false,\n loginAppTheme: state.appSettings?.login_app_theme,\n passwordPolicy: state.passwordPolicy,\n currentStyles: selectedStyle,\n currentTheme: currentTheme,\n isLoading,\n isError,\n error: errorMessage,\n reset,\n } as const;\n};\n","import { useContext } from 'react';\nimport { AuthContext, type AuthContextValue } from '@/context';\n\nexport const useAuth = (): AuthContextValue => {\n const context = useContext(AuthContext);\n if (!context) {\n throw new Error('useAuth must be used within an AuthProvider');\n }\n\n return context;\n};\n","import { usePassflow } from './use-passflow';\n\ntype UseAuthCloudRedirectProps = (cloudPassflowUrl: string) => () => void;\n\nexport const useAuthCloudRedirect: UseAuthCloudRedirectProps = (cloudPassflowUrl: string) => {\n const passflow = usePassflow();\n\n // A failed redirect is reported by core's `Error` event (operation `auth-redirect`); the page stays where it is.\n const redirect = () => {\n passflow.authRedirect({ url: cloudPassflowUrl }).catch(() => {});\n };\n\n return redirect;\n};\n","import { useCallback, useEffect, useMemo, useState } from 'react';\nimport { submitFormPost } from '@/utils/form-post';\n\n/**\n * The OIDC consent decision, as a hook.\n *\n * The URL is the bearer. `consent_challenge_id` identifies the consent step the\n * server staged for the user who just signed in, and that id is handed only to\n * this browser, in the redirect that ends sign-in. Possessing it is what\n * authorizes reading the staged request — there is no Authorization header on\n * the GET. The server hands back a `csrf_token` with the request metadata, and\n * every state-changing POST must carry it back in `X-Passflow-CSRF`. That token\n * is the only thing separating a real decision from one a third-party page\n * forged on the user's behalf, so it is never optional and never cached across\n * challenges.\n *\n * The decision endpoints answer with a discriminated response rather than a\n * redirect status, because the OIDC `response_mode` decides HOW the user gets\n * back to the client: `query` is an ordinary navigation, `form_post` must be a\n * POST with the parameters in a form body (they cannot go in a URL). The server\n * knows which; the client just executes what it is told.\n */\n\nexport type ConsentScopeMetadata = {\n scope: string;\n label: string;\n description: string;\n};\n\n/** What GET /oidc/requests/{consent_challenge_id} hands the page to render itself. */\nexport type ConsentInfo = {\n client_id: string;\n app_name: string;\n app_logo_url: string;\n requested_scopes: string[];\n scope_metadata: ConsentScopeMetadata[];\n redirect_uri: string;\n state: string;\n response_mode: '' | 'query' | 'form_post';\n first_party: boolean;\n csrf_token: string;\n};\n\ntype DecisionResponse =\n | { kind: 'redirect'; url: string }\n | { kind: 'form_post'; action: string; fields: Record<string, string> };\n\ntype ApiErrorBody = {\n error?: string;\n error_description?: string;\n};\n\nexport type ConsentStatus =\n /** Fetching the staged request. */\n | 'loading'\n /** Metadata in hand; awaiting the user's decision. */\n | 'ready'\n /** A decision is in flight. */\n | 'working'\n /** Decision accepted; the browser is on its way back to the client. */\n | 'redirecting'\n /** The link itself is unusable — missing, expired, or rejected id. Terminal. */\n | 'invalid';\n\nexport type ConsentError = {\n message: string;\n description?: string;\n};\n\nexport type UseConsentProps = {\n status: ConsentStatus;\n info: ConsentInfo | null;\n /** The scopes still switched on. A subset of `info.requested_scopes`. */\n grantedScopes: string[];\n error: ConsentError | null;\n /** Metadata for a scope, falling back to the bare scope string. */\n scopeMetadata: (scope: string) => ConsentScopeMetadata;\n /** Switch one requested scope on or off before deciding. */\n toggleScope: (scope: string) => void;\n /** Grant the currently-selected subset. */\n allow: () => Promise<void>;\n /** Refuse the request outright (OAuth2 `access_denied`). */\n deny: () => Promise<void>;\n};\n\nconst readConsentChallengeId = (): string => new URLSearchParams(window.location.search).get('consent_challenge_id') ?? '';\n\nconst requestPath = (consentChallengeId: string): string => `/oidc/requests/${encodeURIComponent(consentChallengeId)}`;\n\nexport const useConsent = (): UseConsentProps => {\n const consentChallengeId = useMemo(readConsentChallengeId, []);\n\n const [status, setStatus] = useState<ConsentStatus>('loading');\n const [info, setInfo] = useState<ConsentInfo | null>(null);\n const [granted, setGranted] = useState<Set<string>>(new Set());\n const [error, setError] = useState<ConsentError | null>(null);\n\n useEffect(() => {\n if (!consentChallengeId) {\n setStatus('invalid');\n setError({\n message: 'Invalid consent link',\n description: 'This consent link is missing required information. Please return to the application and try again.',\n });\n return;\n }\n\n let cancelled = false;\n\n const fetchInfo = async (): Promise<void> => {\n try {\n const res = await fetch(requestPath(consentChallengeId), {\n method: 'GET',\n credentials: 'same-origin',\n headers: { Accept: 'application/json' },\n });\n if (cancelled) return;\n\n if (!res.ok) {\n const body = ((await res.json().catch(() => ({}))) ?? {}) as ApiErrorBody;\n setStatus('invalid');\n setError({\n message: res.status >= 500 ? 'Something went wrong' : 'Consent request unavailable',\n description:\n body.error_description ||\n 'We could not load this consent request. Please return to the application and try again.',\n });\n return;\n }\n\n const data = (await res.json()) as ConsentInfo;\n if (cancelled) return;\n\n setInfo(data);\n // Everything asked for starts granted; the user switches OFF what they\n // do not want. Starting from none would train people to hit Allow on an\n // empty grant and wonder why the app is broken.\n setGranted(new Set(data.requested_scopes));\n setStatus('ready');\n } catch (err) {\n if (cancelled) return;\n setStatus('invalid');\n setError({\n message: 'Connection error',\n description: err instanceof Error ? err.message : 'Could not reach the server. Please check your connection.',\n });\n }\n };\n\n void fetchInfo();\n\n return () => {\n cancelled = true;\n };\n }, [consentChallengeId]);\n\n const toggleScope = useCallback((scope: string): void => {\n setGranted((prev) => {\n const next = new Set(prev);\n if (next.has(scope)) next.delete(scope);\n else next.add(scope);\n return next;\n });\n // Changing the selection invalidates whatever the last failed submit said.\n setError(null);\n }, []);\n\n const decide = useCallback(\n async (decision: 'allow' | 'deny'): Promise<void> => {\n if (!info) return;\n\n setStatus('working');\n setError(null);\n\n const base = requestPath(consentChallengeId);\n const endpoint = decision === 'allow' ? `${base}/consent` : `${base}/reject`;\n const body =\n decision === 'allow'\n ? { granted_scopes: info.requested_scopes.filter((scope) => granted.has(scope)) }\n : { error: 'access_denied', error_description: 'User denied consent' };\n\n try {\n const res = await fetch(endpoint, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'X-Passflow-CSRF': info.csrf_token,\n },\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n const errBody = ((await res.json().catch(() => ({}))) ?? {}) as ApiErrorBody;\n setStatus('ready');\n setError({\n message: errBody.error_description || 'Could not submit your decision. Please try again.',\n });\n return;\n }\n\n const data = (await res.json()) as DecisionResponse;\n\n if (data.kind === 'redirect') {\n setStatus('redirecting');\n window.location.href = data.url;\n return;\n }\n\n if (data.kind === 'form_post') {\n setStatus('redirecting');\n submitFormPost(data.action, data.fields);\n return;\n }\n\n setStatus('ready');\n setError({ message: 'Unexpected response from server.' });\n } catch (err) {\n setStatus('ready');\n setError({\n message: err instanceof Error ? err.message : 'Could not reach the server. Please try again.',\n });\n }\n },\n [granted, info, consentChallengeId],\n );\n\n const allow = useCallback(() => decide('allow'), [decide]);\n const deny = useCallback(() => decide('deny'), [decide]);\n\n const metadataByScope = useMemo(() => new Map((info?.scope_metadata ?? []).map((meta) => [meta.scope, meta])), [info]);\n\n const scopeMetadata = useCallback(\n (scope: string): ConsentScopeMetadata => metadataByScope.get(scope) ?? { scope, label: scope, description: '' },\n [metadataByScope],\n );\n\n const grantedScopes = useMemo(() => (info?.requested_scopes ?? []).filter((scope) => granted.has(scope)), [granted, info]);\n\n return { status, info, grantedScopes, error, scopeMetadata, toggleScope, allow, deny };\n};\n","import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { DeviceError } from '@/types/device-errors';\nimport { classifyDeviceError, DeviceApiError } from '@/utils';\n\n/**\n * The RFC 8628 verification flow, as a hook.\n *\n * ── The one rule the whole thing is built around ────────────────────────────\n * Signing in and approving are TWO ACTS, and this hook keeps them two. Proving\n * who you are (`/oidc/device/authenticate`) yields an approval ticket and\n * NOTHING else — no tokens, no session. Approving (`/oidc/device/approve`) is\n * what releases tokens to the waiting terminal, and it needs that ticket.\n *\n * The gap between them is not ceremony, it is RFC 8628 §5.4: an attacker can\n * start a device grant and walk a victim into approving it (STORM-2372). They\n * know the user_code — they created it — and the page is public, so they can\n * read its CSRF token too. Neither can be the authority for approval. Only the\n * ticket, held in this hook's memory and bound to the browser that actually\n * authenticated, can be.\n *\n * So: never collapse authenticate+approve into one call \"for convenience\".\n * Mode 1 puts both behind one TAP (see confirmWithPassword) — that is a UI\n * affordance and is fine, because the human still looked at the code first.\n * Mode 3 skips the tap entirely, which it earns by using an origin-bound\n * passkey; see the note on confirmWithPasskey.\n *\n * When the app requires a second factor, the first ticket cannot approve: the\n * server refuses it. The page asks for the factor (`/oidc/device/second-factor`)\n * and approves with the ticket that answers, which records both.\n */\n\n/** The UI the server resolved for this challenge. A closed set — the client does not choose. */\nexport type DeviceUIMode = 'consent' | 'full_login' | 'passkey';\n\n/** What GET /oidc/device/info hands the page to render itself. */\nexport type DeviceVerifyInfo = {\n mode: DeviceUIMode;\n /** Absent for `passkey` mode, by design — see device_page.go. */\n user_code?: string;\n app_name: string;\n csrf_token: string;\n methods: {\n password: boolean;\n passkey: boolean;\n };\n};\n\n/** A second factor the verification page can take. */\nexport type DeviceSecondFactorMethod = 'totp' | 'recovery_codes';\n\nexport type DeviceVerifyStatus =\n /** Asking the server what to render. */\n | 'loading'\n /** No code yet — show the entry form. */\n | 'code_entry'\n /** Info in hand; awaiting the user. */\n | 'ready'\n /** A call is in flight. */\n | 'working'\n /** A first factor proven; the app wants a second before anything can be approved. */\n | 'second_factor'\n /** Identity proven, ticket held, not yet approved. */\n | 'signed_in'\n /** Approved. The terminal has its tokens. */\n | 'done'\n /** The mode is switched off. Terminal, and nothing approvable is rendered. */\n | 'refused'\n /** Terminal failure — bad/expired code, dead app. */\n | 'failed';\n\nexport type UseDeviceVerifyProps = {\n status: DeviceVerifyStatus;\n info: DeviceVerifyInfo | null;\n error: DeviceError | null;\n /** The email that authenticated, once one has. */\n email: string | null;\n /** Whether an approval ticket is held. */\n isAuthenticated: boolean;\n /** Whether a first-factor ticket is waiting for its second factor. */\n isSecondFactorPending: boolean;\n /** The second factors the server takes, once a sign-in owes one. */\n secondFactorMethods: DeviceSecondFactorMethod[];\n /** Re-run the info lookup for a code typed by hand. */\n submitCode: (code: string) => void;\n /** Prove identity with a password. Does NOT approve. */\n signInWithPassword: (email: string, password: string) => Promise<void>;\n /** Prove identity with a passkey. Does NOT approve. */\n signInWithPasskey: () => Promise<void>;\n /** Approve, using the ticket already held. */\n approve: () => Promise<void>;\n /** One tap: prove identity if needed, then approve. */\n confirmWithPassword: (email: string, password: string) => Promise<void>;\n /** Passkey ceremony then approve, with no tap in between. */\n confirmWithPasskey: () => Promise<void>;\n /**\n * Prove the second factor. Approves too when the act that asked for it was\n * an approval (consent's tap, the passkey mode); otherwise lands on signed_in.\n */\n submitSecondFactor: (method: DeviceSecondFactorMethod, code: string) => Promise<void>;\n /** Clear a recoverable error so the user can try again. */\n clearError: () => void;\n};\n\nconst DEVICE_ENDPOINTS = {\n info: '/oidc/device/info',\n authenticate: '/oidc/device/authenticate',\n approve: '/oidc/device/approve',\n passkeyStart: '/oidc/device/passkey/start',\n secondFactor: '/oidc/device/second-factor',\n} as const;\n\n/** What /oidc/device/authenticate answers with. */\ntype DeviceAuthenticateResponse = {\n approval_ticket: string;\n email?: string;\n /** The app requires a second factor; this ticket cannot approve until one is given. */\n second_factor_required?: boolean;\n second_factor_methods?: string[];\n};\n\nconst SECOND_FACTOR_METHODS: readonly DeviceSecondFactorMethod[] = ['totp', 'recovery_codes'];\n\n/** The factors the server offers that this page can take, in its order. */\nconst toSecondFactorMethods = (methods: string[] | undefined): DeviceSecondFactorMethod[] => {\n const known = (methods ?? []).filter((m): m is DeviceSecondFactorMethod =>\n SECOND_FACTOR_METHODS.includes(m as DeviceSecondFactorMethod),\n );\n return known.length > 0 ? known : ['totp'];\n};\n\n/** Read `user_code` off the URL — the QR encodes verification_uri_complete. */\nconst readUserCodeFromURL = (): string => new URLSearchParams(window.location.search).get('user_code') ?? '';\n\n/**\n * Parse a device endpoint's response, turning any failure into a DeviceApiError\n * that carries the server's stable `reason`.\n */\nconst parseDeviceResponse = async <T>(res: Response): Promise<T> => {\n const body: unknown = await res.json().catch(() => ({}));\n const data = (body ?? {}) as Record<string, unknown>;\n\n if (!res.ok) {\n throw new DeviceApiError({\n reason: typeof data.reason === 'string' ? data.reason : '',\n code: typeof data.error === 'string' ? data.error : '',\n status: res.status,\n description: typeof data.error_description === 'string' ? data.error_description : '',\n });\n }\n return data as T;\n};\n\nexport const useDeviceVerify = (): UseDeviceVerifyProps => {\n const [status, setStatus] = useState<DeviceVerifyStatus>('loading');\n const [info, setInfo] = useState<DeviceVerifyInfo | null>(null);\n const [error, setError] = useState<DeviceError | null>(null);\n const [email, setEmail] = useState<string | null>(null);\n const [userCode, setUserCode] = useState<string>(() => readUserCodeFromURL());\n\n /**\n * The approval ticket. A ref, not state: it is an authorization handle, so it\n * must be readable synchronously by the call that follows the one that earned\n * it. `confirmWithPassword` authenticates and approves back-to-back within a\n * single event; a state read there would still be null, and the approve would\n * be refused for no reason a user could understand.\n */\n const ticketRef = useRef<string | null>(null);\n\n /**\n * The first-factor ticket, while the app still wants a second. Kept apart\n * from ticketRef because it cannot approve, so isAuthenticated must not\n * claim a sign-in the approval would refuse.\n */\n const firstFactorTicketRef = useRef<string | null>(null);\n /** Whether the act that asked for the second factor was an approval. */\n const approveAfterSecondFactorRef = useRef(false);\n const [secondFactorMethods, setSecondFactorMethods] = useState<DeviceSecondFactorMethod[]>([]);\n\n /** Guards against setting state after unmount, and against double-fires. */\n const activeRef = useRef(true);\n useEffect(() => {\n activeRef.current = true;\n return () => {\n activeRef.current = false;\n };\n }, []);\n\n const csrf = info?.csrf_token ?? '';\n\n /**\n * Every back-channel POST: same-origin, JSON, the challenge's CSRF token, and\n * the user_code that scopes it.\n */\n const post = useCallback(\n async <T>(path: string, body: Record<string, unknown>): Promise<T> => {\n const res = await fetch(path, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'X-Passflow-CSRF': csrf,\n },\n body: JSON.stringify({ ...body, user_code: userCode }),\n });\n return parseDeviceResponse<T>(res);\n },\n [csrf, userCode],\n );\n\n /**\n * Record a failure: classified for the user, logged in full for us.\n *\n * This is the ONLY place a failure becomes user-visible, which is what makes\n * \"no technical string reaches the screen\" checkable rather than aspirational.\n */\n const fail = useCallback((err: unknown, terminal: DeviceVerifyStatus | null = null) => {\n const classified = classifyDeviceError(err);\n // The detail the user must never read, kept exactly where a developer will\n // look for it first.\n if (classified.detail) {\n console.error('[passflow] device verification:', classified.detail, err);\n }\n if (!activeRef.current) return;\n setError(classified);\n if (terminal) {\n setStatus(terminal);\n return;\n }\n setStatus(\n classified.type === 'mode_disabled'\n ? 'refused'\n : firstFactorTicketRef.current\n ? 'second_factor'\n : ticketRef.current\n ? 'signed_in'\n : 'ready',\n );\n }, []);\n\n // ── Load what to render ───────────────────────────────────────────────────\n const loadInfo = useCallback(async (code: string) => {\n if (!code) {\n setStatus('code_entry');\n setError(null);\n return;\n }\n setStatus('loading');\n setError(null);\n try {\n const res = await fetch(`${DEVICE_ENDPOINTS.info}?user_code=${encodeURIComponent(code)}`, {\n method: 'GET',\n credentials: 'same-origin',\n headers: { Accept: 'application/json' },\n });\n const data = await parseDeviceResponse<DeviceVerifyInfo>(res);\n if (!activeRef.current) return;\n setInfo(data);\n setStatus('ready');\n } catch (err) {\n const classified = classifyDeviceError(err);\n if (classified.detail) {\n console.error('[passflow] device verification:', classified.detail, err);\n }\n if (!activeRef.current) return;\n\n // `code_required` is not a failure — it is the code entry form.\n if (classified.type === 'code_required') {\n setError(null);\n setStatus('code_entry');\n return;\n }\n setError(classified);\n // A disabled mode gets its own terminal state so the page can render a\n // refusal with NOTHING approvable on it. A bad or dead code lands on the\n // entry form, where the remedy (type it again) actually lives.\n setStatus(classified.type === 'mode_disabled' ? 'refused' : 'failed');\n }\n }, []);\n\n useEffect(() => {\n void loadInfo(userCode);\n }, [loadInfo, userCode]);\n\n const submitCode = useCallback((code: string) => {\n setUserCode(code.trim());\n }, []);\n\n // ── Prove identity. Yields a ticket; approves nothing. ────────────────────\n /**\n * Hold the ticket an authentication earned. Returns true when the app wants\n * a second factor first, in which case the ticket cannot approve yet.\n */\n const holdTicket = useCallback((res: DeviceAuthenticateResponse): boolean => {\n if (res.second_factor_required) {\n firstFactorTicketRef.current = res.approval_ticket;\n ticketRef.current = null;\n if (activeRef.current) setSecondFactorMethods(toSecondFactorMethods(res.second_factor_methods));\n return true;\n }\n firstFactorTicketRef.current = null;\n ticketRef.current = res.approval_ticket;\n return false;\n }, []);\n\n const authenticatePassword = useCallback(\n async (emailValue: string, password: string): Promise<boolean> => {\n const res = await post<DeviceAuthenticateResponse>(DEVICE_ENDPOINTS.authenticate, {\n method: 'password',\n email: emailValue,\n password,\n });\n const owesSecondFactor = holdTicket(res);\n if (activeRef.current) setEmail(res.email ?? emailValue);\n return owesSecondFactor;\n },\n [post, holdTicket],\n );\n\n const authenticatePasskey = useCallback(async (): Promise<boolean> => {\n // Thrown as a DOMException so it travels the same road as every real\n // WebAuthn failure and lands on the same classified copy — rather than\n // becoming a second, parallel way for this page to describe a passkey\n // problem, which is how the copy drifts.\n if (typeof window === 'undefined' || !window.PublicKeyCredential) {\n throw new DOMException('this browser does not implement PublicKeyCredential', 'NotSupportedError');\n }\n\n const start = await post<{ passkey_challenge_id: string; publicKey: PublicKeyCredentialRequestOptionsJSON }>(\n DEVICE_ENDPOINTS.passkeyStart,\n {},\n );\n\n // The SDK's existing WebAuthn primitive, not a hand-rolled base64url dance.\n // @simplewebauthn/browser (v14, the same copy @passflow/core uses) takes the\n // server's JSON options as-is. Loaded on demand: only this branch needs it.\n const { startAuthentication } = await import('@simplewebauthn/browser');\n const assertion = await startAuthentication({ optionsJSON: start.publicKey });\n\n const res = await post<DeviceAuthenticateResponse>(DEVICE_ENDPOINTS.authenticate, {\n method: 'passkey',\n passkey_challenge_id: start.passkey_challenge_id,\n passkey_data: assertion,\n });\n const owesSecondFactor = holdTicket(res);\n if (activeRef.current) setEmail(res.email ?? null);\n return owesSecondFactor;\n }, [post, holdTicket]);\n\n // ── The act that releases tokens ──────────────────────────────────────────\n const approveWithTicket = useCallback(async (): Promise<void> => {\n await post(DEVICE_ENDPOINTS.approve, { approval_ticket: ticketRef.current });\n if (!activeRef.current) return;\n setStatus('done');\n }, [post]);\n\n const signInWithPassword = useCallback(\n async (emailValue: string, password: string) => {\n setStatus('working');\n setError(null);\n try {\n const owesSecondFactor = await authenticatePassword(emailValue, password);\n if (!activeRef.current) return;\n approveAfterSecondFactorRef.current = false;\n setStatus(owesSecondFactor ? 'second_factor' : 'signed_in');\n } catch (err) {\n fail(err);\n }\n },\n [authenticatePassword, fail],\n );\n\n const signInWithPasskey = useCallback(async () => {\n setStatus('working');\n setError(null);\n try {\n const owesSecondFactor = await authenticatePasskey();\n if (!activeRef.current) return;\n approveAfterSecondFactorRef.current = false;\n setStatus(owesSecondFactor ? 'second_factor' : 'signed_in');\n } catch (err) {\n fail(err);\n }\n }, [authenticatePasskey, fail]);\n\n const approve = useCallback(async () => {\n setStatus('working');\n setError(null);\n try {\n await approveWithTicket();\n } catch (err) {\n fail(err);\n }\n }, [approveWithTicket, fail]);\n\n /**\n * Mode 1's single tap: prove identity if we have not already, then approve.\n *\n * Two calls behind one button is the affordance; it is NOT a collapse of the\n * §5.4 check. The check is that a human read the code and chose to proceed,\n * and that is exactly what the tap is.\n */\n const confirmWithPassword = useCallback(\n async (emailValue: string, password: string) => {\n setStatus('working');\n setError(null);\n try {\n if (!ticketRef.current && (await authenticatePassword(emailValue, password))) {\n approveAfterSecondFactorRef.current = true;\n if (activeRef.current) setStatus('second_factor');\n return;\n }\n await approveWithTicket();\n } catch (err) {\n fail(err);\n }\n },\n [authenticatePassword, approveWithTicket, fail],\n );\n\n /**\n * Passkey then approve, with nothing in between.\n *\n * For Mode 3 this runs on load, with no user gesture, and both halves of that\n * are deliberate:\n * - WebAuthn L3's get() carries no transient-activation requirement (unlike\n * create()), so firing on load is legal. The phone's own biometric prompt\n * IS the interaction; a button first would add a step that protects nothing.\n * - No §5.4 confirm follows, because a passkey is origin-bound: the\n * authenticator scopes the assertion to this origin, so it cannot be\n * produced on an attacker's page or replayed to one. There is no phished\n * approval to catch and so nothing for the human to compare.\n */\n const confirmWithPasskey = useCallback(async () => {\n setStatus('working');\n setError(null);\n try {\n if (await authenticatePasskey()) {\n approveAfterSecondFactorRef.current = true;\n if (activeRef.current) setStatus('second_factor');\n return;\n }\n await approveWithTicket();\n } catch (err) {\n fail(err);\n }\n }, [authenticatePasskey, approveWithTicket, fail]);\n\n /**\n * The second factor, for a sign-in whose app requires one. The server checks\n * the code for the user the first ticket names and answers with a ticket\n * recording both factors, which is the one that can approve.\n *\n * It approves straight away when the act that asked for the factor was\n * itself an approval: consent's tap, or the passkey mode, which has none.\n */\n const submitSecondFactor = useCallback(\n async (method: DeviceSecondFactorMethod, code: string) => {\n setStatus('working');\n setError(null);\n try {\n const res = await post<{ approval_ticket: string }>(DEVICE_ENDPOINTS.secondFactor, {\n approval_ticket: firstFactorTicketRef.current,\n method,\n code,\n });\n ticketRef.current = res.approval_ticket;\n firstFactorTicketRef.current = null;\n if (approveAfterSecondFactorRef.current) {\n await approveWithTicket();\n return;\n }\n if (activeRef.current) setStatus('signed_in');\n } catch (err) {\n fail(err);\n }\n },\n [post, approveWithTicket, fail],\n );\n\n const clearError = useCallback(() => setError(null), []);\n\n return {\n status,\n info,\n error,\n email,\n isAuthenticated: ticketRef.current !== null,\n isSecondFactorPending: firstFactorTicketRef.current !== null,\n secondFactorMethods,\n submitCode,\n signInWithPassword,\n signInWithPasskey,\n approve,\n confirmWithPassword,\n confirmWithPasskey,\n submitSecondFactor,\n clearError,\n };\n};\n","import type { PassflowAuthorizationResponse } from '@passflow/core';\nimport { useCallback, useEffect, useReducer, useRef, useState } from 'react';\nimport type { EmailCodeStep } from '@/types';\nimport { emailCodeErrorMessage, emailCodeStepReducer, initialEmailCodeStepState, readEmailVerificationStep } from '@/utils';\nimport { usePassflow } from './use-passflow';\n\nexport type UseEmailCodeStepOptions = {\n /**\n * Repeats the request that produced the step (the same sign-up or sign-in body). Absent when the code cannot be\n * sent again, as after a password change: the reset link is spent.\n */\n resend?: () => Promise<unknown>;\n /** The step ended (cancelled, verified, or turned into a link): anything held only for resend can be dropped. */\n onRelease?: () => void;\n};\n\nexport type UseEmailCodeStep = {\n step: EmailCodeStep;\n /** Enters the step when `answer` is an email verification step; `false` (nothing changes) for any other answer. */\n enter: (answer: unknown) => boolean;\n /**\n * Posts the code. Resolves the session answer on success (the caller runs its post-auth path), `null` on a failure\n * (shown in `error`), when a verify is already in flight, or when the step was left meanwhile.\n */\n verify: (otp: string) => Promise<PassflowAuthorizationResponse | null>;\n /**\n * Sends a new code by repeating the original request. Resolves `null` normally (the step moves to the new code or\n * to the link); resolves the session answer in the rare case the repeated request signed the user in directly.\n */\n resend: () => Promise<PassflowAuthorizationResponse | null>;\n canResend: boolean;\n /** Leaves the step for the screen's own form. Ignored while a verify is in flight. */\n cancel: () => void;\n isVerifying: boolean;\n isResending: boolean;\n error: string | null;\n};\n\n/**\n * The emailed-code step of a sign-up, sign-in or password change: holds the step, posts the code with\n * `passflow.verifyEmailCode`, and resends by repeating the original request. An answer that arrives after the user\n * left the step (or after a newer step replaced it) is dropped.\n */\nexport const useEmailCodeStep = (options: UseEmailCodeStepOptions = {}): UseEmailCodeStep => {\n const passflow = usePassflow();\n const [state, dispatch] = useReducer(emailCodeStepReducer, initialEmailCodeStepState);\n const [isVerifying, setIsVerifying] = useState(false);\n const [isResending, setIsResending] = useState(false);\n\n // Bumped whenever the step is entered or left: an async answer from an older epoch is stale.\n const epochRef = useRef(0);\n const verifyingRef = useRef(false);\n const resendingRef = useRef(false);\n const stepRef = useRef<EmailCodeStep>(state.step);\n stepRef.current = state.step;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(\n () => () => {\n epochRef.current += 1;\n },\n [],\n );\n\n const enter = useCallback((answer: unknown): boolean => {\n const step = readEmailVerificationStep(answer);\n if (step === null) return false;\n epochRef.current += 1;\n verifyingRef.current = false;\n resendingRef.current = false;\n setIsVerifying(false);\n setIsResending(false);\n dispatch({ type: 'ENTER', step });\n if (step.kind === 'link') optionsRef.current.onRelease?.();\n return true;\n }, []);\n\n const verify = useCallback(\n async (otp: string): Promise<PassflowAuthorizationResponse | null> => {\n const step = stepRef.current;\n if (step.kind !== 'code' || verifyingRef.current) return null;\n const epoch = epochRef.current;\n verifyingRef.current = true;\n setIsVerifying(true);\n dispatch({ type: 'VERIFY_STARTED' });\n\n try {\n const answer = await passflow.verifyEmailCode({ challenge_id: step.challengeId, otp });\n if (epoch !== epochRef.current) return null;\n\n // Not expected from /auth/validate, but core passes it through: show the new step rather than sign in.\n const next = readEmailVerificationStep(answer);\n if (next !== null) {\n enter(answer);\n return null;\n }\n\n // Stays \"verifying\" until the screen leaves: the caller now runs its post-auth path.\n dispatch({ type: 'VERIFY_OK' });\n optionsRef.current.onRelease?.();\n return answer;\n } catch (error) {\n if (epoch !== epochRef.current) return null;\n console.error('[passflow] email code verification failed', error);\n verifyingRef.current = false;\n setIsVerifying(false);\n dispatch({ type: 'VERIFY_FAILED', message: emailCodeErrorMessage(error) });\n return null;\n }\n },\n [passflow, enter],\n );\n\n const resend = useCallback(async (): Promise<PassflowAuthorizationResponse | null> => {\n const repeat = optionsRef.current.resend;\n if (!repeat || stepRef.current.kind !== 'code' || verifyingRef.current || resendingRef.current) return null;\n const epoch = epochRef.current;\n resendingRef.current = true;\n setIsResending(true);\n\n try {\n const answer = await repeat();\n if (epoch !== epochRef.current) return null;\n const next = readEmailVerificationStep(answer);\n if (next?.kind === 'code') dispatch({ type: 'RESENT', challengeId: next.challengeId, message: next.message });\n else if (next?.kind === 'link') {\n dispatch({ type: 'LINK_SENT', message: next.message });\n optionsRef.current.onRelease?.();\n } else {\n // The repeated request signed the user in (the address was verified meanwhile).\n optionsRef.current.onRelease?.();\n return (answer ?? null) as PassflowAuthorizationResponse | null;\n }\n return null;\n } catch (error) {\n if (epoch !== epochRef.current) return null;\n console.error('[passflow] email code resend failed', error);\n dispatch({ type: 'RESEND_FAILED', message: emailCodeErrorMessage(error) });\n return null;\n } finally {\n if (epoch === epochRef.current) {\n resendingRef.current = false;\n setIsResending(false);\n }\n }\n }, []);\n\n const cancel = useCallback(() => {\n if (verifyingRef.current) return;\n const leaving = stepRef.current;\n epochRef.current += 1;\n resendingRef.current = false;\n setIsResending(false);\n dispatch({ type: 'CANCEL' });\n // A code step on a PKCE app holds a verifier for /auth/validate; the user gave up on it. This public call also\n // clears a pending second factor, which a code step never has.\n if (leaving.kind === 'code') passflow.twoFactor?.clearPartialAuthState();\n optionsRef.current.onRelease?.();\n }, [passflow]);\n\n return {\n step: state.step,\n enter,\n verify,\n resend,\n canResend: Boolean(options.resend) && state.step.kind === 'code',\n cancel,\n isVerifying,\n isResending,\n error: state.error,\n };\n};\n","import type { PassflowSendPasswordResetEmailPayload } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseForgotPasswordProps = () => {\n fetch: (payload: PassflowSendPasswordResetEmailPayload) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n reset: () => void;\n};\n\nexport const useForgotPassword: UseForgotPasswordProps = () => {\n const passflow = usePassflow();\n const [isError, setIsError] = useState(false);\n const [errorMessage, setErrorMessage] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (payload: PassflowSendPasswordResetEmailPayload): Promise<boolean> => {\n try {\n setIsLoading(true);\n await passflow.sendPasswordResetEmail(payload);\n setIsLoading(false);\n return true;\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n return false;\n }\n },\n [passflow.sendPasswordResetEmail],\n );\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n };\n\n return { fetch, isLoading, isError, error: errorMessage, reset } as const;\n};\n","import { useCallback, useState } from 'react';\nimport { invitationJoinErrorFrom } from '@/utils';\nimport { usePassflow } from './use-passflow';\n\nexport type UseJoinInviteProps = () => {\n fetch: (token: string) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\nexport const useJoinInvite: UseJoinInviteProps = () => {\n const passflow = usePassflow();\n const [errorMessage, setErrorMessage] = useState('');\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (token: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n\n try {\n await passflow.joinInvitation(token);\n return true;\n } catch (error) {\n console.error('[passflow] accepting invitation failed', error);\n setIsError(true);\n setErrorMessage(invitationJoinErrorFrom(error));\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow.joinInvitation],\n );\n\n return { fetch, isLoading, isError, error: errorMessage } as const;\n};\n","import type { LogOutOptions } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseLogoutProps = () => {\n /** After a hosted sign-in core leaves the page once signed out, so code after `await fetch()` may not run. */\n fetch: (options?: LogOutOptions) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\nexport const useLogout: UseLogoutProps = () => {\n const passflow = usePassflow();\n const [errorMessage, setErrorMessage] = useState('');\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (options?: LogOutOptions): Promise<boolean> => {\n try {\n setIsLoading(true);\n await passflow.logOut(options);\n setIsLoading(false);\n return true;\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n return false;\n }\n },\n [passflow],\n );\n\n return { fetch, isLoading, isError, error: errorMessage } as const;\n};\n","import qs from 'query-string';\nimport { useCallback, useContext } from 'react';\nimport { type NavigateFunction, type NavigateOptions, NavigationContext } from '@/context';\n\nexport type ReactRouterNavigateOptions = {\n pathname: string;\n search: string;\n replace?: boolean;\n};\n\nexport type TanstackRouterNavigateOptions = {\n to: string;\n search: Record<string, unknown>;\n replace?: boolean;\n};\n\nexport type WouterNavigateOptions = {\n to: string;\n search?: Record<string, unknown>;\n replace?: boolean;\n};\n\nexport type ReachRouterNavigateOptions = {\n to: string;\n search?: Record<string, unknown>;\n replace?: boolean;\n};\n\nconst parseSearch = (search: string): Record<string, string> => {\n if (!search) return {};\n const parsed = qs.parse(search.startsWith('?') ? search.slice(1) : search);\n return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));\n};\n\nexport const useNavigation = () => {\n const { navigate, setNavigate, router, twoFactorVerifyPath, setTwoFactorVerifyPath, signInPath, setSignInPath } =\n useContext(NavigationContext);\n\n const wrappedSetNavigate = useCallback(\n (\n newNavigate:\n | ((\n to:\n | NavigateOptions\n | string\n | ReactRouterNavigateOptions\n | TanstackRouterNavigateOptions\n | WouterNavigateOptions\n | ReachRouterNavigateOptions,\n ) => void)\n | null,\n ) => {\n if (!newNavigate) {\n setNavigate(null);\n return;\n }\n\n const wrappedNavigate = ((options: NavigateOptions) => {\n const { to, search = '', replace = false } = options;\n\n switch (router) {\n case 'react-router':\n newNavigate({\n pathname: to,\n search: search.startsWith('?') ? search : `?${search}`,\n replace,\n } as ReactRouterNavigateOptions);\n break;\n\n case 'tanstack-router':\n newNavigate({\n to,\n search: parseSearch(search),\n replace,\n } as TanstackRouterNavigateOptions);\n break;\n\n case 'wouter': {\n const searchParamWouter = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n newNavigate({ to: `${to}${searchParamWouter}`, replace } as WouterNavigateOptions);\n break;\n }\n\n default: {\n // default router\n const searchParamDefault = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n if (replace) {\n window.location.replace(`${to}${searchParamDefault}`);\n } else {\n window.location.href = `${to}${searchParamDefault}`;\n }\n }\n }\n }) as NavigateFunction;\n\n setNavigate(wrappedNavigate);\n },\n [setNavigate, router],\n );\n\n return {\n navigate,\n setNavigate: wrappedSetNavigate,\n router,\n twoFactorVerifyPath,\n setTwoFactorVerifyPath,\n signInPath,\n setSignInPath,\n };\n};\n","import { type RefObject, useEffect } from 'react';\n\nexport const useOutsideClick = <T extends HTMLElement>(ref: RefObject<T | null>, onClickOutside?: () => void) => {\n useEffect(() => {\n const handleClick = (event: MouseEvent) => {\n if (ref.current && !ref.current.contains(event.target as Node)) {\n if (onClickOutside) {\n onClickOutside();\n }\n }\n };\n\n document.addEventListener('click', handleClick, true);\n\n return () => {\n document.removeEventListener('click', handleClick, true);\n };\n }, [onClickOutside, ref]);\n};\n","import type { Passflow, PassflowEvent, PassflowEventPayload, PassflowSubscriber, Tokens } from '@passflow/core';\nimport { useSyncExternalStore } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport function usePassflowStore(events?: PassflowEvent[]) {\n const passflow = usePassflow();\n const passflowSnapshot = useSyncExternalStore(subscribe(passflow, events), getSnapshot(passflow), getServerSnapshot);\n return passflowSnapshot;\n}\n\n// wrapper around react's subscribe\nfunction subscribe(passflow: Passflow, event?: PassflowEvent[]): (onStoreChange: () => void) => () => void {\n return (onStoreChange: () => void): (() => void) => {\n const bscr = subscriber(onStoreChange);\n passflow.subscribe(bscr, event);\n return () => {\n passflow.unsubscribe(bscr);\n };\n };\n}\n\nfunction subscriber(onStoreChange: () => void): PassflowSubscriber {\n return {\n onAuthChange: <E extends PassflowEvent>(_eventType: E, _payload?: PassflowEventPayload[E]) => {\n onStoreChange();\n },\n };\n}\n\nfunction getSnapshot(passflow: Passflow): () => Tokens | undefined {\n return () => {\n return passflow.getCachedTokens();\n };\n}\n\n// The server has no session; hydration renders with this, then switches to the cached tokens.\nfunction getServerSnapshot(): Tokens | undefined {\n return undefined;\n}\n","import type { PassflowPasswordlessSignInCompletePayload, PassflowValidationResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { passwordlessCompleteErrorMessage } from '@/utils';\nimport { usePassflow } from './use-passflow';\n\nexport type UsePasswordlessCompleteProps = () => {\n fetch: (payload: PassflowPasswordlessSignInCompletePayload) => Promise<PassflowValidationResponse | null>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n reset: () => void;\n};\n\nexport const usePasswordlessComplete: UsePasswordlessCompleteProps = () => {\n const passflow = usePassflow();\n const [errorMessage, setErrorMessage] = useState('');\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n\n try {\n return await passflow.passwordlessSignInComplete(payload);\n } catch (error) {\n console.error('[passflow] passwordless verification failed', error);\n setIsError(true);\n setErrorMessage(passwordlessCompleteErrorMessage(error));\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n };\n\n return {\n fetch,\n isLoading,\n isError,\n error: errorMessage,\n reset,\n } as const;\n};\n","import type { PassflowFederatedAuthPayload, Providers } from '@passflow/core';\nimport { useContext } from 'react';\nimport { PassflowContext } from '@/context';\nimport type { FederatedLanding } from '@/types';\nimport { isValidUrl, readParentChallengeIdFromURL } from '@/utils';\nimport { handOffScopes } from '@/utils/hand-off';\nimport { usePassflow } from './use-passflow';\n\nconst getFullRedirectUrl = (redirectUrl?: string): string => {\n if (redirectUrl && isValidUrl(redirectUrl)) {\n return redirectUrl;\n }\n return redirectUrl ? `${window.location.origin}${redirectUrl.startsWith('/') ? '' : '/'}${redirectUrl}` : '';\n};\n\n/**\n * The login page itself as the federated landing: it keeps the code, exchanges it and forwards. No trailing slash and\n * nothing else in the query, because the server refuses anything but this exact shape, an empty `redirectto=` too.\n */\nconst getLoginPageLandingUrl = (appId: string, redirectUrl?: string): string => {\n const { origin, pathname } = window.location;\n const target = getFullRedirectUrl(redirectUrl);\n const redirectTo = target ? `&redirectto=${encodeURIComponent(target)}` : '';\n return `${origin}${pathname.replace(/\\/+$/, '') || '/'}?appid=${encodeURIComponent(appId)}${redirectTo}`;\n};\n\nconst withoutUndefined = <T extends Record<string, unknown>>(value: T): Partial<T> =>\n Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as Partial<T>;\n\nexport type UseProviderProps = (\n redirectUrl?: string,\n createTenant?: boolean,\n federatedLanding?: FederatedLanding,\n) => {\n federatedWithPopup: (provider: Providers, inviteToken?: string) => void;\n federatedWithRedirect: (provider: Providers, inviteToken?: string) => void;\n};\n\nexport const useProvider: UseProviderProps = (redirectUrl, createTenant, federatedLanding = 'app') => {\n const passflow = usePassflow();\n const context = useContext(PassflowContext);\n const appId = context?.state.appId;\n const landsOnLoginPage =\n federatedLanding === 'login-page' && Boolean(context?.state.appSettings?.pkce_enabled) && !readParentChallengeIdFromURL();\n\n // The app's mode as the sign-in form already loaded it: the start must not wait for a settings read. In Simple mode\n // the tokens go back to the app, so they get the scopes it asked for and its state. In SDK mode this sign-in only\n // starts the hosted session, which then issues the app its code, so it uses the sign-in scopes. Unknown is not Simple\n // for the state, which is echoed only in Simple mode.\n const handOff = context?.state.handOff;\n const pkceEnabled = context?.state.appSettings?.pkce_enabled;\n const scopes = handOff && pkceEnabled !== true ? handOffScopes(handOff) : context?.state.scopes;\n\n const payload = withoutUndefined({\n redirect_url: landsOnLoginPage && appId ? getLoginPageLandingUrl(appId, redirectUrl) : getFullRedirectUrl(redirectUrl),\n scopes,\n create_tenant: createTenant,\n state: pkceEnabled === false ? handOff?.state : undefined,\n parent_challenge_id: readParentChallengeIdFromURL(),\n });\n\n const federatedWithPopup = (provider: Providers, inviteToken?: string) =>\n passflow.federatedAuthWithPopup({ provider, invite_token: inviteToken, ...payload } as PassflowFederatedAuthPayload);\n const federatedWithRedirect = (provider: Providers, inviteToken?: string) =>\n passflow.federatedAuthWithRedirect({ provider, invite_token: inviteToken, ...payload } as PassflowFederatedAuthPayload);\n\n return {\n federatedWithPopup,\n federatedWithRedirect,\n };\n};\n","import { PassflowEvent, type PassflowEventPayload, type PassflowSubscriber } from '@passflow/core';\nimport { useEffect, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport interface UseRefreshStatusResult {\n /**\n * True inside a transient-failure episode: a token refresh failed for a reason that\n * does not end the session (network, 5xx) and core is retrying. The session is kept.\n */\n isFailing: boolean;\n /**\n * Epoch ms of the episode's first transient failure (`RefreshFailing.since`).\n */\n since: number | null;\n /**\n * Epoch ms of the pending retry, when core knows it (`RefreshFailing.nextRetryAt`).\n */\n nextRetryAt: number | null;\n}\n\nconst IDLE: UseRefreshStatusResult = { isFailing: false, since: null, nextRetryAt: null };\n\nconst EVENTS = [\n PassflowEvent.RefreshFailing,\n PassflowEvent.RefreshRecovered,\n PassflowEvent.SessionExpired,\n PassflowEvent.SignOut,\n PassflowEvent.SignIn,\n PassflowEvent.Register,\n];\n\n/**\n * Hook to show a \"connection trouble\" notice while token refresh is failing transiently.\n *\n * Set by `RefreshFailing`; cleared by `RefreshRecovered`, and by `SessionExpired`,\n * `SignOut`, `SignIn` and `Register`, which end or replace the session the episode\n * belonged to. A real end of the session is reported by `useSessionExpired`, not here.\n *\n * Core reports the episode only as events (there is no getter to read on mount), so a\n * component that mounts after `RefreshFailing` starts idle. Call the hook in a component\n * that lives for the whole app, near `PassflowProvider`.\n *\n * @example\n * ```tsx\n * function ConnectionNotice() {\n * const { isFailing } = useRefreshStatus();\n * return isFailing ? <Banner>Reconnecting...</Banner> : null;\n * }\n * ```\n */\nexport function useRefreshStatus(): UseRefreshStatusResult {\n const passflow = usePassflow();\n const [status, setStatus] = useState<UseRefreshStatusResult>(IDLE);\n\n useEffect(() => {\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.RefreshFailing) {\n const failing = payload as PassflowEventPayload[PassflowEvent.RefreshFailing] | undefined;\n setStatus({\n isFailing: true,\n since: failing?.since ?? null,\n nextRetryAt: failing?.nextRetryAt ?? null,\n });\n } else {\n setStatus(IDLE);\n }\n },\n };\n\n passflow.subscribe(subscriber, EVENTS);\n\n return () => {\n passflow.unsubscribe(subscriber);\n };\n }, [passflow]);\n\n return status;\n}\n","import { useCallback, useState } from 'react';\nimport { isPasswordSavedRateLimit, newPasswordErrorMessage } from '@/utils';\nimport { type UseEmailCodeStep, useEmailCodeStep } from './use-email-code-step';\nimport { usePassflow } from './use-passflow';\n\nexport type UseResetPasswordProps = () => {\n /**\n * Saves the new password. Pass the reset link's `token` when you have it: without it core looks for `?token=` in\n * the address bar, which a hash or memory router does not keep. Resolves `true` for a session, `false` on an error\n * or when the server asks for an emailed code first (`emailCode` then holds the step).\n */\n fetch: (newPassword: string, resetToken?: string) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n /**\n * The password was changed, but the emailed code that should follow was refused for now (429). Asking for the\n * password again would be wrong: the user should sign in with it later.\n */\n isPasswordSaved: boolean;\n reset: () => void;\n /** The emailed-code step a password change may answer with. No resend: the reset link is spent. */\n emailCode: UseEmailCodeStep;\n};\n\nexport const useResetPassword: UseResetPasswordProps = () => {\n const passflow = usePassflow();\n const [isError, setIsError] = useState(false);\n const [errorMessage, setErrorMessage] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const [isPasswordSaved, setIsPasswordSaved] = useState(false);\n const emailCode = useEmailCodeStep();\n\n const fetch = useCallback(\n async (newPassword: string, resetToken?: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n const answer = resetToken\n ? await passflow.resetPassword(newPassword, undefined, resetToken)\n : await passflow.resetPassword(newPassword);\n return !emailCode.enter(answer);\n } catch (e) {\n console.error('[passflow] password change failed', e);\n setIsError(true);\n setErrorMessage(newPasswordErrorMessage(e));\n setIsPasswordSaved(isPasswordSavedRateLimit(e));\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow.resetPassword, emailCode.enter],\n );\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n setIsPasswordSaved(false);\n };\n\n return { fetch, isLoading, isError, error: errorMessage, isPasswordSaved, reset, emailCode } as const;\n};\n","import { PassflowEvent, type PassflowSubscriber, type SessionExpiredReason } from '@passflow/core';\nimport { useEffect, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport interface UseSessionExpiredOptions {\n /**\n * Called when the session expires.\n * Use this to redirect to your login page.\n */\n onSessionExpired?: (reason: SessionExpiredReason) => void;\n}\n\nexport interface UseSessionExpiredResult {\n /**\n * True if the session has expired and user needs to re-authenticate.\n */\n isSessionExpired: boolean;\n /**\n * The reason why the session expired, if applicable.\n */\n expiredReason: SessionExpiredReason | null;\n /**\n * Reset the session expired state (e.g., after redirecting to login).\n */\n resetSessionExpired: () => void;\n}\n\n/**\n * Hook to handle session expiration events.\n *\n * Core emits SessionExpired only when the session has really ended: the last\n * auth strike (`'refresh_failed'`), no successor token pair in time\n * (`'successor_timeout'`), or another user's tokens in storage\n * (`'identity_changed'`). A transient refresh failure (network, 5xx) keeps the\n * session and is reported as RefreshFailing / RefreshRecovered instead; see\n * `useRefreshStatus`. This hook lets you react to the real end and redirect\n * users to your login page.\n *\n * @example\n * ```tsx\n * function App() {\n * const { isSessionExpired } = useSessionExpired({\n * onSessionExpired: (reason) => {\n * console.log('Session expired:', reason);\n * window.location.href = '/login';\n * },\n * });\n *\n * if (isSessionExpired) {\n * return <div>Redirecting to login...</div>;\n * }\n *\n * return <YourApp />;\n * }\n * ```\n */\nexport function useSessionExpired(options?: UseSessionExpiredOptions): UseSessionExpiredResult {\n const passflow = usePassflow();\n const [isSessionExpired, setIsSessionExpired] = useState(false);\n const [expiredReason, setExpiredReason] = useState<SessionExpiredReason | null>(null);\n\n useEffect(() => {\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.SessionExpired) {\n const reason = (payload as { reason?: SessionExpiredReason })?.reason ?? 'refresh_failed';\n setIsSessionExpired(true);\n setExpiredReason(reason);\n options?.onSessionExpired?.(reason);\n } else if (eventType === PassflowEvent.SignIn || eventType === PassflowEvent.Register) {\n // Reset on successful auth\n setIsSessionExpired(false);\n setExpiredReason(null);\n }\n },\n };\n\n passflow.subscribe(subscriber, [PassflowEvent.SessionExpired, PassflowEvent.SignIn, PassflowEvent.Register]);\n\n return () => {\n passflow.unsubscribe(subscriber);\n };\n }, [passflow, options?.onSessionExpired]);\n\n const resetSessionExpired = () => {\n setIsSessionExpired(false);\n setExpiredReason(null);\n };\n\n return {\n isSessionExpired,\n expiredReason,\n resetSessionExpired,\n };\n}\n","/* eslint-disable react/jsx-props-no-spreading */\nimport { forwardRef, type InputHTMLAttributes } from 'react';\nimport '@/styles/index.css';\nimport { cn } from '@/utils';\n\ntype TFieldText = InputHTMLAttributes<HTMLInputElement> & {\n id: string;\n isError?: boolean;\n className?: string;\n disabled?: boolean;\n};\n\nexport const FieldText = forwardRef<HTMLInputElement, TFieldText>(\n ({ id, isError = false, className = '', disabled = false, ...rest }, ref) => {\n const styles = {\n 'passflow-field--error': isError,\n };\n\n return (\n <input\n ref={ref}\n id={id}\n type='text'\n className={cn('passflow-field-input passflow-field--focused', styles, className)}\n disabled={disabled}\n {...rest}\n />\n );\n },\n);\n","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='6'%20fill='%23F3F5F7'/%3e%3cg%20clip-path='url(%23clip0_2691_4741)'%3e%3cpath%20d='M21.9999%2019.3334C20.5272%2019.3334%2019.3333%2020.5273%2019.3333%2022C19.3333%2023.4728%2020.5272%2024.6667%2021.9999%2024.6667C23.4727%2024.6667%2024.6666%2023.4728%2024.6666%2022C24.6666%2020.5273%2023.4727%2019.3334%2021.9999%2019.3334ZM21.9999%2019.3334H28.1133M16.6333%2018.04L19.6933%2023.3334M21.2533%2028.6267L24.3066%2023.3334M28.6666%2022C28.6666%2025.6819%2025.6818%2028.6667%2021.9999%2028.6667C18.318%2028.6667%2015.3333%2025.6819%2015.3333%2022C15.3333%2018.3181%2018.318%2015.3334%2021.9999%2015.3334C25.6818%2015.3334%2028.6666%2018.3181%2028.6666%2022Z'%20stroke='%237F7F7F'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2691_4741'%3e%3crect%20width='16'%20height='16'%20fill='white'%20transform='translate(14%2014)'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M4%206L8%2010L12%206H4Z'%20fill='%236B6F76'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M4%208L6.82843%2010.8284L12.4847%205.17155'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M10.6666%2010.6667L7.99993%208.00001M7.99993%208.00001L5.33325%205.33333M7.99993%208.00001L10.6666%205.33333M7.99993%208.00001L5.33325%2010.6667'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.00004%208.66667C8.36823%208.66667%208.66671%208.36819%208.66671%208C8.66671%207.63181%208.36823%207.33333%208.00004%207.33333C7.63185%207.33333%207.33337%207.63181%207.33337%208C7.33337%208.36819%207.63185%208.66667%208.00004%208.66667Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3cpath%20d='M8.00004%204C8.36823%204%208.66671%203.70152%208.66671%203.33333C8.66671%202.96514%208.36823%202.66667%208.00004%202.66667C7.63185%202.66667%207.33337%202.96514%207.33337%203.33333C7.33337%203.70152%207.63185%204%208.00004%204Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3cpath%20d='M8.00004%2013.3333C8.36823%2013.3333%208.66671%2013.0349%208.66671%2012.6667C8.66671%2012.2985%208.36823%2012%208.00004%2012C7.63185%2012%207.33337%2012.2985%207.33337%2012.6667C7.33337%2013.0349%207.63185%2013.3333%208.00004%2013.3333Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.6231%206.86026L9.13975%204.37687M2%2014L4.10117%2013.7665C4.35789%2013.738%204.48624%2013.7238%204.60622%2013.6849C4.71266%2013.6505%204.81395%2013.6018%204.90735%2013.5402C5.01263%2013.4708%205.10395%2013.3794%205.28659%2013.1968L13.4857%204.99772C14.1714%204.31195%2014.1714%203.2001%2013.4857%202.51433C12.7999%201.82856%2011.6881%201.82856%2011.0023%202.51433L2.80321%2010.7134C2.62056%2010.896%202.52924%2010.9874%202.45982%2011.0926C2.39823%2011.186%202.34955%2011.2873%202.31509%2011.3938C2.27625%2011.5138%202.26199%2011.6421%202.23346%2011.8988L2%2014Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M7.16196%203.39488C7.4329%203.35482%207.7124%203.33333%208.00028%203.33333C11.4036%203.33333%2013.6369%206.33656%2014.3871%207.52455C14.4779%207.66833%2014.5233%207.74023%2014.5488%207.85112C14.5678%207.93439%2014.5678%208.06578%2014.5487%208.14905C14.5233%208.25993%2014.4776%208.3323%2014.3861%208.47705C14.1862%208.79343%2013.8814%209.23807%2013.4777%209.7203M4.48288%204.47669C3.0415%205.45447%202.06297%206.81292%201.61407%207.52352C1.52286%207.66791%201.47725%207.74011%201.45183%207.85099C1.43273%207.93426%201.43272%208.06563%201.45181%208.14891C1.47722%208.25979%201.52262%208.33168%201.61342%208.47545C2.36369%209.66344%204.59694%2012.6667%208.00028%2012.6667C9.37255%2012.6667%2010.5546%2012.1784%2011.5259%2011.5177M2.00028%202L14.0003%2014M6.58606%206.58579C6.22413%206.94772%206.00028%207.44772%206.00028%208C6.00028%209.10457%206.89571%2010%208.00028%2010C8.55256%2010%209.05256%209.77614%209.41449%209.41421'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M1.61342%208.47545C1.52262%208.33169%201.47723%208.25981%201.45182%208.14895C1.43273%208.06567%201.43273%207.93434%201.45182%207.85106C1.47723%207.74019%201.52262%207.66831%201.61341%207.52455C2.36369%206.33656%204.59693%203.33334%208.00027%203.33334C11.4036%203.33334%2013.6369%206.33656%2014.3871%207.52455C14.4779%207.66831%2014.5233%207.74019%2014.5487%207.85106C14.5678%207.93434%2014.5678%208.06567%2014.5487%208.14895C14.5233%208.25981%2014.4779%208.33169%2014.3871%208.47545C13.6369%209.66344%2011.4036%2012.6667%208.00027%2012.6667C4.59693%2012.6667%202.36369%209.66344%201.61342%208.47545Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3cpath%20d='M8.00027%2010C9.10484%2010%2010.0003%209.10457%2010.0003%208C10.0003%206.89543%209.10484%206%208.00027%206C6.8957%206%206.00027%206.89543%206.00027%208C6.00027%209.10457%206.8957%2010%208.00027%2010Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.1111%206.1333C11.1111%205.81483%2010.9896%205.49636%2010.7466%205.25338C10.5037%205.01039%2010.1852%204.88889%209.86669%204.88889M9.86669%209.86667C11.9286%209.86667%2013.6%208.1952%2013.6%206.13333C13.6%204.07147%2011.9286%202.4%209.86669%202.4C7.80483%202.4%206.13336%204.07147%206.13336%206.13333C6.13336%206.30362%206.14476%206.47125%206.16684%206.63549C6.20316%206.90562%206.22131%207.04069%206.20909%207.12615C6.19636%207.21516%206.18015%207.26313%206.13627%207.34163C6.09416%207.41698%206.01993%207.4912%205.87148%207.63965L2.69162%2010.8195C2.584%2010.9271%202.53019%2010.9809%202.49171%2011.0437C2.4576%2011.0994%202.43246%2011.1601%202.41722%2011.2236C2.40002%2011.2952%202.40002%2011.3713%202.40002%2011.5235V12.6044C2.40002%2012.9529%202.40002%2013.1272%202.46784%2013.2603C2.5275%2013.3773%202.62269%2013.4725%202.73976%2013.5322C2.87286%2013.6%203.0471%2013.6%203.39558%2013.6H4.88891V12.3556H6.13336V11.1111H7.3778L8.36037%2010.1285C8.50882%209.98009%208.58305%209.90587%208.6584%209.86375C8.73689%209.81988%208.78486%209.80367%208.87388%209.79093C8.95933%209.77871%209.0944%209.79687%209.36453%209.83319C9.52878%209.85527%209.6964%209.86667%209.86669%209.86667Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='43'%20height='10'%20viewBox='0%200%2043%2010'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.91%209H5.346L5.236%207.988H3.674L3.564%209H0L2.178%200.53H6.732L8.91%209ZM4.158%203.665L4.037%204.721H4.873L4.752%203.665H4.158ZM16.6389%206.712C16.5215%207.482%2016.1145%208.087%2015.4179%208.527C14.7212%208.95967%2013.8082%209.176%2012.6789%209.176C11.5495%209.176%2010.6365%208.95967%209.93988%208.527C9.25054%208.09433%208.84354%207.49667%208.71888%206.734C8.68954%206.52867%208.66388%206.25367%208.64188%205.909C8.62721%205.557%208.61988%205.17933%208.61988%204.776C8.61988%204.38733%208.62721%204.028%208.64188%203.698C8.66388%203.36067%208.68954%203.09667%208.71888%202.906C8.84354%202.09933%209.25421%201.47233%209.95088%201.025C10.6475%200.577666%2011.5569%200.354%2012.6789%200.354C13.8082%200.354%2014.7212%200.577666%2015.4179%201.025C16.1145%201.465%2016.5215%202.07733%2016.6389%202.862C16.6682%203.05267%2016.6902%203.31667%2016.7049%203.654C16.7269%203.984%2016.7379%204.347%2016.7379%204.743C16.7379%205.161%2016.7269%205.54233%2016.7049%205.887C16.6902%206.23167%2016.6682%206.50667%2016.6389%206.712ZM12.9759%206.206V3.324C12.9759%203.126%2012.8769%203.027%2012.6789%203.027C12.4809%203.027%2012.3819%203.126%2012.3819%203.324V6.206C12.3819%206.404%2012.4809%206.503%2012.6789%206.503C12.8769%206.503%2012.9759%206.404%2012.9759%206.206ZM25.1574%206.712C25.0401%207.482%2024.6331%208.087%2023.9364%208.527C23.2398%208.95967%2022.3268%209.176%2021.1974%209.176C20.0681%209.176%2019.1551%208.95967%2018.4584%208.527C17.7691%208.09433%2017.3621%207.49667%2017.2374%206.734C17.2081%206.52867%2017.1824%206.25367%2017.1604%205.909C17.1458%205.557%2017.1384%205.17933%2017.1384%204.776C17.1384%204.38733%2017.1458%204.028%2017.1604%203.698C17.1824%203.36067%2017.2081%203.09667%2017.2374%202.906C17.3621%202.09933%2017.7728%201.47233%2018.4694%201.025C19.1661%200.577666%2020.0754%200.354%2021.1974%200.354C22.3268%200.354%2023.2398%200.577666%2023.9364%201.025C24.6331%201.465%2025.0401%202.07733%2025.1574%202.862C25.1868%203.05267%2025.2088%203.31667%2025.2234%203.654C25.2454%203.984%2025.2564%204.347%2025.2564%204.743C25.2564%205.161%2025.2454%205.54233%2025.2234%205.887C25.2088%206.23167%2025.1868%206.50667%2025.1574%206.712ZM21.4944%206.206V3.324C21.4944%203.126%2021.3954%203.027%2021.1974%203.027C20.9994%203.027%2020.9004%203.126%2020.9004%203.324V6.206C20.9004%206.404%2020.9994%206.503%2021.1974%206.503C21.3954%206.503%2021.4944%206.404%2021.4944%206.206ZM33.555%200.53V3.797H31.432V9H27.769V3.797H25.635V0.53H33.555ZM38.4495%202.906V0.53H42.0135V9H38.4495V6.272H37.5585V9H33.9945V0.53H37.5585V2.906H38.4495Z'%20fill='%236B6F76'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='8'%20fill='%231E1E1E'%20/%3e%3cpath%20d='M21.2532%2031H13.6932V12.52H24.9012C25.9252%2012.52%2026.8612%2012.72%2027.7092%2013.12C28.5732%2013.504%2029.2612%2014.184%2029.7732%2015.16C30.2852%2016.12%2030.5412%2017.456%2030.5412%2019.168C30.5412%2020.848%2030.2772%2022.184%2029.7492%2023.176C29.2212%2024.152%2028.5252%2024.856%2027.6612%2025.288C26.8132%2025.704%2025.8932%2025.912%2024.9012%2025.912H21.2532V31ZM23.1252%2018.592H20.8212V19.888H23.1972C23.3252%2019.888%2023.4612%2019.848%2023.6052%2019.768C23.7652%2019.688%2023.8452%2019.52%2023.8452%2019.264C23.8452%2018.992%2023.7572%2018.816%2023.5812%2018.736C23.4052%2018.64%2023.2532%2018.592%2023.1252%2018.592Z'%20fill='white'%20/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='8'%20fill='%23D85D5D'%20/%3e%3cpath%20d='M21.2532%2031H13.6932V12.52H24.9012C25.9252%2012.52%2026.8612%2012.72%2027.7092%2013.12C28.5732%2013.504%2029.2612%2014.184%2029.7732%2015.16C30.2852%2016.12%2030.5412%2017.456%2030.5412%2019.168C30.5412%2020.848%2030.2772%2022.184%2029.7492%2023.176C29.2212%2024.152%2028.5252%2024.856%2027.6612%2025.288C26.8132%2025.704%2025.8932%2025.912%2024.9012%2025.912H21.2532V31ZM23.1252%2018.592H20.8212V19.888H23.1972C23.3252%2019.888%2023.4612%2019.848%2023.6052%2019.768C23.7652%2019.688%2023.8452%2019.52%2023.8452%2019.264C23.8452%2018.992%2023.7572%2018.816%2023.5812%2018.736C23.4052%2018.64%2023.2532%2018.592%2023.1252%2018.592Z'%20fill='white'%20/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M1.33337%204.66666L6.77665%208.47696C7.21743%208.78551%207.43783%208.93978%207.67755%208.99954C7.8893%209.05232%208.11078%209.05232%208.32253%208.99954C8.56226%208.93978%208.78265%208.78551%209.22343%208.47696L14.6667%204.66666M4.53337%2013.3333H11.4667C12.5868%2013.3333%2013.1469%2013.3333%2013.5747%2013.1153C13.951%2012.9236%2014.257%2012.6176%2014.4487%2012.2413C14.6667%2011.8135%2014.6667%2011.2534%2014.6667%2010.1333V5.86666C14.6667%204.74656%2014.6667%204.18651%2014.4487%203.75868C14.257%203.38236%2013.951%203.0764%2013.5747%202.88465C13.1469%202.66666%2012.5868%202.66666%2011.4667%202.66666H4.53337C3.41327%202.66666%202.85322%202.66666%202.42539%202.88465C2.04907%203.0764%201.74311%203.38236%201.55136%203.75868C1.33337%204.18651%201.33337%204.74656%201.33337%205.86666V10.1333C1.33337%2011.2534%201.33337%2011.8135%201.55136%2012.2413C1.74311%2012.6176%202.04907%2012.9236%202.42539%2013.1153C2.85322%2013.3333%203.41327%2013.3333%204.53337%2013.3333Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='6'%20fill='%23F3F5F7'/%3e%3cg%20clip-path='url(%23clip0_2691_4730)'%3e%3cpath%20d='M20.8039%2020.4084V18.2344C20.8039%2017.9893%2021.0026%2017.7906%2021.2477%2017.7906H22.7785C23.0236%2017.7906%2023.2222%2017.9893%2023.2222%2018.2344V22.2139C23.2222%2022.2748%2023.1918%2022.3212%2023.1614%2022.3669L22.7785%2022.7498C22.6864%2022.8419%2022.6864%2022.9797%2022.7785%2023.0558L23.1614%2023.4386C23.1819%2023.4582%2023.198%2023.4821%2023.2086%2023.5085C23.2191%2023.5349%2023.2237%2023.5633%2023.2222%2023.5916V25.7648C23.2222%2025.8825%2023.1755%2025.9954%2023.0923%2026.0786C23.009%2026.1618%2022.8962%2026.2086%2022.7785%2026.2086H21.2477C21.13%2026.2086%2021.0171%2026.1618%2020.9339%2026.0786C20.8507%2025.9954%2020.8039%2025.8825%2020.8039%2025.7648V21.7853C20.8039%2021.7244%2020.8344%2021.678%2020.8648%2021.6323L21.2477%2021.2494C21.3398%2021.1573%2021.3398%2021.0195%2021.2477%2020.9434L20.8648%2020.5606C20.8443%2020.5411%2020.8282%2020.5174%2020.8177%2020.4911C20.8072%2020.4649%2020.8025%2020.4366%2020.8039%2020.4084ZM27.7064%2022C27.7064%2021.2503%2027.5587%2020.5079%2027.2718%2019.8153C26.9849%2019.1227%2026.5644%2018.4933%2026.0343%2017.9632C25.5042%2017.4331%2024.8748%2017.0126%2024.1822%2016.7257C23.4895%2016.4388%2022.7472%2016.2911%2021.9975%2016.2911C21.2478%2016.2911%2020.5054%2016.4388%2019.8128%2016.7257C19.1201%2017.0126%2018.4908%2017.4331%2017.9607%2017.9632C17.4305%2018.4933%2017.01%2019.1227%2016.7231%2019.8153C16.4362%2020.5079%2016.2886%2021.2503%2016.2886%2022C16.2886%2023.5141%2016.89%2024.9662%2017.9607%2026.0368C19.0313%2027.1074%2020.4834%2027.7089%2021.9975%2027.7089C23.5116%2027.7089%2024.9637%2027.1074%2026.0343%2026.0368C27.1049%2024.9662%2027.7064%2023.5141%2027.7064%2022ZM29.5127%2022C29.5127%2026.1477%2026.1452%2029.5%2022.0127%2029.5C17.865%2029.5%2014.5127%2026.1325%2014.5127%2022C14.5127%2017.8523%2017.8802%2014.5%2022.0127%2014.5C26.1452%2014.5%2029.5127%2017.8523%2029.5127%2022Z'%20fill='%237F7F7F'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2691_4730'%3e%3crect%20width='16'%20height='16'%20fill='white'%20transform='translate(14%2014)'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='6'%20fill='%23F3F5F7'/%3e%3cpath%20d='M25.3333%2020C25.3333%2019.6587%2025.2031%2019.3175%2024.9428%2019.0572C24.6825%2018.7968%2024.3412%2018.6667%2024%2018.6667M24%2024C26.2091%2024%2028%2022.2091%2028%2020C28%2017.7909%2026.2091%2016%2024%2016C21.7909%2016%2020%2017.7909%2020%2020C20%2020.1825%2020.0122%2020.3621%2020.0359%2020.538C20.0748%2020.8275%2020.0942%2020.9722%2020.0811%2021.0637C20.0675%2021.1591%2020.0501%2021.2105%2020.0031%2021.2946C19.958%2021.3753%2019.8785%2021.4549%2019.7194%2021.6139L16.3124%2025.0209C16.1971%2025.1362%2016.1395%2025.1939%2016.0982%2025.2611C16.0617%2025.3208%2016.0348%2025.3858%2016.0184%2025.4538C16%2025.5306%2016%2025.6121%2016%2025.7752V26.9333C16%2027.3067%2016%2027.4934%2016.0727%2027.636C16.1366%2027.7614%2016.2386%2027.8634%2016.364%2027.9273C16.5066%2028%2016.6933%2028%2017.0667%2028H18.6667V26.6667H20V25.3333H21.3333L22.3861%2024.2806C22.5451%2024.1215%2022.6247%2024.042%2022.7054%2023.9969C22.7895%2023.9499%2022.8409%2023.9325%2022.9363%2023.9189C23.0278%2023.9058%2023.1725%2023.9252%2023.462%2023.9641C23.6379%2023.9878%2023.8175%2024%2024%2024Z'%20stroke='%237F7F7F'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='17'%20height='16'%20viewBox='0%200%2017%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.49998%2011.6666H8.50665M5.96665%2014.6666H11.0333C11.78%2014.6666%2012.1534%2014.6666%2012.4386%2014.5213C12.6895%2014.3934%2012.8935%2014.1895%2013.0213%2013.9386C13.1666%2013.6534%2013.1666%2013.28%2013.1666%2012.5333V3.46659C13.1666%202.71985%2013.1666%202.34648%2013.0213%202.06126C12.8935%201.81038%2012.6895%201.60641%2012.4386%201.47858C12.1534%201.33325%2011.78%201.33325%2011.0333%201.33325H5.96665C5.21991%201.33325%204.84654%201.33325%204.56133%201.47858C4.31044%201.60641%204.10647%201.81038%203.97864%202.06126C3.83331%202.34648%203.83331%202.71985%203.83331%203.46659V12.5333C3.83331%2013.28%203.83331%2013.6534%203.97864%2013.9386C4.10647%2014.1895%204.31044%2014.3934%204.56133%2014.5213C4.84654%2014.6666%205.21991%2014.6666%205.96665%2014.6666ZM8.83331%2011.6666C8.83331%2011.8507%208.68407%2011.9999%208.49998%2011.9999C8.31588%2011.9999%208.16665%2011.8507%208.16665%2011.6666C8.16665%2011.4825%208.31588%2011.3333%208.49998%2011.3333C8.68407%2011.3333%208.83331%2011.4825%208.83331%2011.6666Z'%20stroke='%237F7F7F'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M14%2014L11.1%2011.1M12.6667%207.33333C12.6667%2010.2789%2010.2789%2012.6667%207.33333%2012.6667C4.38781%2012.6667%202%2010.2789%202%207.33333C2%204.38781%204.38781%202%207.33333%202C10.2789%202%2012.6667%204.38781%2012.6667%207.33333Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M6%202H10M2%204H14M12.6667%204L12.1991%2011.0129C12.129%2012.065%2012.0939%2012.5911%2011.8667%2012.99C11.6666%2013.3412%2011.3648%2013.6235%2011.0011%2013.7998C10.588%2014%2010.0607%2014%209.00623%2014H6.99377C5.93927%2014%205.41202%2014%204.99889%2013.7998C4.63517%2013.6235%204.33339%2013.3412%204.13332%2012.99C3.90607%2012.5911%203.871%2012.065%203.80086%2011.0129L3.33333%204M6.66667%207V10.3333M9.33333%207V10.3333'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_823)'%3e%3cpath%20d='M7.99992%205.33334V8M7.99992%2010.6667H8.00659M14.6666%208C14.6666%2011.6819%2011.6818%2014.6667%207.99992%2014.6667C4.31802%2014.6667%201.33325%2011.6819%201.33325%208C1.33325%204.3181%204.31802%201.33334%207.99992%201.33334C11.6818%201.33334%2014.6666%204.3181%2014.6666%208Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2502_823'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M13.6167%204.77308C13.5312%204.83608%2012.0218%205.64397%2012.0218%207.44037C12.0218%209.51818%2013.9425%2010.2533%2014%2010.2715C13.9912%2010.3162%2013.6948%2011.2781%2012.9873%2012.2583C12.3564%2013.1207%2011.6976%2013.9818%2010.6952%2013.9818C9.69291%2013.9818%209.43498%2013.4287%208.27784%2013.4287C7.15021%2013.4287%206.74928%2014%205.83245%2014C4.9156%2014%204.27588%2013.2019%203.54034%2012.2218C2.68836%2011.0709%202%209.28291%202%207.58597C2%204.86409%203.86316%203.42054%205.69684%203.42054C6.67116%203.42054%207.48335%204.02821%208.09508%204.02821C8.67726%204.02821%209.58531%203.38414%2010.6937%203.38414C11.1139%203.38414%2012.6233%203.42054%2013.6167%204.77308ZM10.1676%202.23182C10.6259%201.71517%2010.9503%200.998298%2010.9503%200.281428C10.9503%200.182018%2010.9414%200.0812084%2010.9223%200C10.1764%200.0266027%209.28899%200.471848%208.75398%201.0613C8.33385%201.51495%207.94176%202.23182%207.94176%202.95849C7.94176%203.06771%207.96092%203.17691%207.9698%203.21192C8.01697%203.22032%208.09361%203.23012%208.17025%203.23012C8.83946%203.23012%209.68112%202.80448%2010.1676%202.23182Z'%20fill='black'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M5.14981%207.46537C4.94085%207.24181%204.61205%207.2541%204.47223%207.54219L1.03899%2014.4048C1.00767%2014.4674%200.992879%2014.5369%200.996019%2014.6068C0.999159%2014.6768%201.02013%2014.7447%201.05693%2014.8042C1.09373%2014.8637%201.14514%2014.9128%201.20627%2014.9469C1.26741%2014.9809%201.33623%2014.9987%201.4062%2014.9987H6.18693C6.26393%2015.0002%206.33969%2014.9792%206.40492%2014.9382C6.47014%2014.8973%206.52201%2014.8382%206.55414%2014.7682C7.58512%2012.641%206.96054%209.39978%205.14981%207.46537Z'%20fill='url(%23paint0_linear_2502_832)'/%3e%3cpath%20d='M7.66883%201.22039C5.74824%204.2626%205.875%207.63208%207.14029%2010.1611L9.44499%2014.7705C9.47857%2014.8394%209.53076%2014.8975%209.59567%2014.9382C9.66057%2014.979%209.73558%2015.0007%209.81221%2015.001H14.5929C14.6629%2015.001%2014.7317%2014.9832%2014.7929%2014.9492C14.854%2014.9151%2014.9054%2014.866%2014.9422%2014.8065C14.979%2014.747%2015%2014.6791%2015.0031%2014.6092C15.0063%2014.5393%2014.9915%2014.4697%2014.9601%2014.4071C14.9601%2014.4071%208.52849%201.53844%208.37023%201.21808C8.22196%200.929997%207.85474%200.923851%207.66883%201.22039Z'%20fill='%232681FF'/%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_2502_832'%20x1='7.03199'%20y1='8.52553'%20x2='3.40822'%20y2='14.802'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%230052CC'/%3e%3cstop%20offset='0.92'%20stop-color='%232684FF'/%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_831)'%3e%3cpath%20d='M0.519254%200.768994C0.44444%200.768029%200.370321%200.783452%200.302102%200.814182C0.233882%200.84491%200.173216%200.890198%200.124362%200.94687C0.0755086%201.00354%200.0396522%201.07021%200.0193102%201.14222C-0.00103186%201.21422%20-0.00536625%201.28981%200.00661131%201.36366L2.18278%2014.5745C2.2099%2014.7362%202.2931%2014.883%202.41779%2014.9894C2.54249%2015.0959%202.70068%2015.155%202.8646%2015.1563H13.3046C13.4274%2015.1579%2013.5468%2015.1153%2013.6409%2015.0362C13.735%2014.9572%2013.7976%2014.847%2013.8172%2014.7257L15.9934%201.36622C16.0054%201.29237%2016.001%201.21678%2015.9807%201.14478C15.9603%201.07278%2015.9245%201.0061%2015.8756%200.94943C15.8268%200.892766%2015.7661%200.84747%2015.6979%200.816742C15.6297%200.786016%2015.5556%200.770592%2015.4807%200.771557L0.519254%200.768994ZM9.68272%2010.317H6.35057L5.44832%205.60322H10.4902L9.68272%2010.317Z'%20fill='%232684FF'/%3e%3cpath%20d='M15.3013%205.60321H10.4902L9.68272%2010.3169H6.35055L2.41602%2014.9871C2.54072%2015.0949%202.69972%2015.1549%202.86458%2015.1563H13.3071C13.43%2015.1579%2013.5494%2015.1153%2013.6434%2015.0362C13.7375%2014.9572%2013.8001%2014.847%2013.8198%2014.7257L15.3013%205.60321Z'%20fill='url(%23paint0_linear_2502_831)'/%3e%3c/g%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_2502_831'%20x1='16.4138'%20y1='6.92327'%20x2='8.46264'%20y2='13.1288'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20offset='0.18'%20stop-color='%230052CC'/%3e%3cstop%20offset='1'%20stop-color='%232684FF'/%3e%3c/linearGradient%3e%3cclipPath%20id='clip0_2502_831'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_836)'%3e%3cpath%20d='M13.5535%202.79193C12.5178%202.30734%2011.4104%201.95517%2010.2526%201.75464C10.1104%202.01171%209.94432%202.35748%209.82976%202.63254C8.59904%202.44745%207.37956%202.44745%206.17144%202.63254C6.05693%202.35748%205.88704%202.01171%205.74358%201.75464C4.58454%201.95517%203.47584%202.30864%202.44013%202.79449C0.351095%205.95129%20-0.215207%209.02968%200.0679444%2012.0644C1.4535%2013.099%202.79627%2013.7276%204.11638%2014.139C4.44233%2013.6903%204.73302%2013.2134%204.98345%2012.7109C4.5065%2012.5297%204.04969%2012.306%203.61805%2012.0464C3.73256%2011.9615%203.84457%2011.8729%203.95278%2011.7816C6.58546%2013.013%209.44592%2013.013%2012.0471%2011.7816C12.1566%2011.8729%2012.2686%2011.9615%2012.3819%2012.0464C11.949%2012.3073%2011.491%2012.531%2011.014%2012.7122C11.2644%2013.2134%2011.5538%2013.6916%2011.881%2014.1402C13.2024%2013.7289%2014.5464%2013.1004%2015.932%2012.0644C16.2642%208.5464%2015.3645%205.49628%2013.5535%202.79193ZM5.34212%2010.1981C4.55182%2010.1981%203.9037%209.46024%203.9037%208.56184C3.9037%207.66337%204.53798%206.92429%205.34212%206.92429C6.14628%206.92429%206.79438%207.66207%206.78054%208.56184C6.78178%209.46024%206.14628%2010.1981%205.34212%2010.1981ZM10.6578%2010.1981C9.86752%2010.1981%209.21944%209.46024%209.21944%208.56184C9.21944%207.66337%209.85368%206.92429%2010.6578%206.92429C11.462%206.92429%2012.1101%207.66207%2012.0962%208.56184C12.0962%209.46024%2011.462%2010.1981%2010.6578%2010.1981Z'%20fill='%235865F2'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2502_836'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.01032%204.15504L4.00518%206.71006L8.01032%209.26513L4.00518%2011.8201L0%209.25129L4.00518%206.69625L0%204.15504L4.00518%201.60001L8.01032%204.15504ZM3.98446%2012.6418L7.98964%2010.0868L11.9948%2012.6418L7.98964%2015.1969L3.98446%2012.6418ZM8.01032%209.25129L12.0155%206.69625L8.01032%204.15504L11.9948%201.60001L16%204.15504L11.9948%206.71006L16%209.26513L11.9948%2011.8201L8.01032%209.25129Z'%20fill='%230061FF'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8%2015C11.866%2015%2015%2011.866%2015%207.99997C15%204.13401%2011.866%201%208%201C4.134%201%201%204.13401%201%207.99997C1%2011.866%204.134%2015%208%2015Z'%20fill='%231977F3'/%3e%3cpath%20d='M10.6065%2010.1416L10.9172%208.16548H8.97241V6.88336C8.97241%206.34321%209.24363%205.81556%2010.1154%205.81556H11V4.1336C11%204.1336%2010.1973%204%209.43%204C7.82844%204%206.78107%204.94574%206.78107%206.65942V8.16548H5V10.1416H6.78107V14.9174C7.13809%2014.9721%207.50398%2015%207.87671%2015C8.24951%2015%208.6154%2014.9712%208.97241%2014.9174V10.1416H10.6065Z'%20fill='white'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M7.97914%201C4.11986%201%201%204.20833%201%208.17748C1%2011.3502%202.999%2014.0359%205.77214%2014.9864C6.11886%2015.0579%206.24586%2014.832%206.24586%2014.642C6.24586%2014.4756%206.23443%2013.9052%206.23443%2013.311C4.293%2013.7388%203.88871%2012.4554%203.88871%2012.4554C3.57671%2011.6235%203.11443%2011.4097%203.11443%2011.4097C2.479%2010.97%203.16071%2010.97%203.16071%2010.97C3.86557%2011.0176%204.23543%2011.7068%204.23543%2011.7068C4.85929%2012.8%205.86457%2012.4911%206.269%2012.3009C6.32671%2011.8375%206.51171%2011.5166%206.70814%2011.3384C5.15971%2011.172%203.53057%2010.5541%203.53057%207.79715C3.53057%207.01285%203.80771%206.37119%204.24686%205.87215C4.17757%205.69394%203.93486%204.95704%204.31629%203.97077C4.31629%203.97077%204.90557%203.7806%206.23429%204.70752C6.80316%204.55041%207.38982%204.47049%207.97914%204.46981C8.56843%204.46981%209.16914%204.55308%209.72386%204.70752C11.0527%203.7806%2011.642%203.97077%2011.642%203.97077C12.0234%204.95704%2011.7806%205.69394%2011.7113%205.87215C12.162%206.37119%2012.4277%207.01285%2012.4277%207.79715C12.4277%2010.5541%2010.7986%2011.1601%209.23857%2011.3384C9.49286%2011.5642%209.71229%2011.9919%209.71229%2012.6693C9.71229%2013.6318%209.70086%2014.4043%209.70086%2014.6418C9.70086%2014.832%209.828%2015.0579%2010.1746%2014.9866C12.9477%2014.0358%2014.9467%2011.3502%2014.9467%208.17748C14.9581%204.20833%2011.8269%201%207.97914%201Z'%20fill='%2324292F'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_834)'%3e%3cpath%20d='M7.99957%2015.3683L10.9471%206.30157H5.05627L7.99957%2015.3683Z'%20fill='%23E24329'/%3e%3cpath%20d='M0.92752%206.30157L0.0299048%209.05617C-0.0513217%209.30625%200.0363974%209.58242%200.25079%209.73834L7.99948%2015.3683L0.92752%206.30157Z'%20fill='%23FCA326'/%3e%3cpath%20d='M0.92749%206.30164H5.05611L3.27927%200.841173C3.18833%200.561813%202.792%200.561813%202.69779%200.841173L0.92749%206.30164Z'%20fill='%23E24329'/%3e%3cpath%20d='M15.0757%206.30157L15.9701%209.05617C16.0513%209.30625%2015.9636%209.58242%2015.7492%209.73834L7.99939%2015.3683L15.0757%206.30157Z'%20fill='%23FCA326'/%3e%3cpath%20d='M15.0757%206.30164H10.947L12.7206%200.841173C12.8116%200.561813%2013.2079%200.561813%2013.3021%200.841173L15.0757%206.30164Z'%20fill='%23E24329'/%3e%3cpath%20d='M7.99939%2015.3683L10.947%206.30157H15.0757L7.99939%2015.3683Z'%20fill='%23FC6D26'/%3e%3cpath%20d='M7.9994%2015.3683L0.92749%206.30157H5.05611L7.9994%2015.3683Z'%20fill='%23FC6D26'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2502_834'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M14.7%208.15554C14.7%207.57997%2014.6533%207.15997%2014.5523%206.72443H7.97998V9.32218H11.8377C11.76%209.96777%2011.34%2010.94%2010.4066%2011.5933L10.3936%2011.6803L12.4716%2013.2901L12.6155%2013.3045C13.9378%2012.0834%2014.7%2010.2867%2014.7%208.15554Z'%20fill='%234285F4'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M7.98022%2015C9.87019%2015%2011.4568%2014.3778%2012.6158%2013.3045L10.4069%2011.5933C9.81576%2012.0055%209.02242%2012.2933%207.98022%2012.2933C6.12911%2012.2933%204.558%2011.0722%203.99793%209.38446L3.91586%209.39143L1.75507%2011.0637L1.72681%2011.1422C2.87791%2013.4289%205.2424%2015%207.98022%2015Z'%20fill='%2334A853'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M3.9977%209.38448C3.84994%208.94893%203.76439%208.48223%203.76439%208.00002C3.76439%207.51778%203.8499%207.05111%203.98993%206.61557L3.98602%206.52279L1.79819%204.82367L1.72662%204.85773C1.25218%205.80664%200.97998%206.87219%200.97998%207.99998C0.97998%209.12777%201.25223%2010.1933%201.72662%2011.1422L3.99774%209.38443'%20fill='%23FBBC04'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M7.98022%203.70662C9.29466%203.70662%2010.1813%204.27442%2010.6869%204.7489L12.6625%202.82C11.4492%201.69221%209.87019%201%207.98022%201C5.2424%201%202.87795%202.5711%201.72681%204.85776L3.99016%206.6156C4.558%204.92782%206.12911%203.70666%207.98022%203.70666'%20fill='%23EA4335'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.013%205.51301V3.9479C11.4349%203.74999%2011.7057%203.32811%2011.7083%202.86197V2.82551C11.7083%202.15884%2011.1667%201.61978%2010.5026%201.61978H10.4661C9.79948%201.61978%209.26042%202.15884%209.26042%202.82551V2.86197C9.26302%203.32811%209.53385%203.74999%209.95573%203.9479V5.51301C9.35937%205.60415%208.79948%205.85155%208.33073%206.22915L4.03646%202.8828C4.06771%202.77343%204.08333%202.65884%204.08594%202.54426C4.08594%201.79426%203.47917%201.18488%202.72917%201.18488C1.97917%201.18228%201.36979%201.78905%201.36719%202.53905C1.36719%203.29165%201.97396%203.90103%202.72396%203.90103C2.96094%203.90103%203.1901%203.83593%203.39323%203.71874L7.6224%207.0104C6.84635%208.18488%206.86719%209.71353%207.67448%2010.8672L6.38802%2012.1536C6.28646%2012.1198%206.17708%2012.1042%206.06771%2012.1016C5.45313%2012.1016%204.95313%2012.6016%204.95313%2013.2187C4.95313%2013.8333%205.45313%2014.3333%206.06771%2014.3333C6.6849%2014.3333%207.1849%2013.8333%207.1849%2013.2187C7.18229%2013.1094%207.16406%2013%207.13281%2012.8958L8.40365%2011.625C9.54167%2012.5%2011.1016%2012.5755%2012.3177%2011.8125C13.5339%2011.0521%2014.1484%209.61457%2013.8568%208.20832C13.5651%206.80468%2012.4297%205.72915%2011.013%205.51301ZM10.4844%2010.6641C9.84375%2010.6797%209.24479%2010.3489%208.92187%209.79686C8.59635%209.24478%208.59635%208.56249%208.92187%208.0104C9.24479%207.45832%209.84375%207.12759%2010.4844%207.14322C11.4323%207.17707%2012.1823%207.95572%2012.1823%208.90363C12.1849%209.84895%2011.4349%2010.6276%2010.487%2010.6614'%20fill='%23FF7A59'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cmask%20id='mask0_2502_833'%20style='mask-type:luminance'%20maskUnits='userSpaceOnUse'%20x='1'%20y='1'%20width='14'%20height='14'%3e%3cpath%20d='M15%201H1V15H15V1Z'%20fill='white'/%3e%3c/mask%3e%3cg%20mask='url(%23mask0_2502_833)'%3e%3cpath%20d='M1.17156%209.61322C1.14041%209.48043%201.2986%209.39678%201.39505%209.49324L6.50679%2014.6049C6.60323%2014.7014%206.5196%2014.8596%206.38681%2014.8284C3.80721%2014.2233%201.77669%2012.1928%201.17156%209.61322ZM1.00026%207.56447C0.997795%207.60414%201.01271%207.64286%201.0408%207.67096L8.32907%2014.9592C8.35714%2014.9873%208.39585%2015.0022%208.43554%2014.9997C8.7672%2014.9791%209.09263%2014.9353%209.41029%2014.8701C9.51732%2014.8481%209.55449%2014.7166%209.47721%2014.6394L1.36063%206.52279C1.28337%206.44552%201.15187%206.48271%201.12989%206.58974C1.06466%206.90734%201.02092%207.23279%201.00026%207.56447ZM1.58953%205.15876C1.56622%205.21109%201.57809%205.27224%201.6186%205.31276L10.6872%2014.3814C10.7278%2014.4219%2010.7889%2014.4338%2010.8412%2014.4105C11.0913%2014.2991%2011.3336%2014.1735%2011.5672%2014.0347C11.6445%2013.9888%2011.6565%2013.8826%2011.5929%2013.819L2.18099%204.40714C2.11742%204.34356%202.01121%204.35549%201.96529%204.43279C1.8265%204.66636%201.70091%204.9087%201.58953%205.15876ZM2.77222%203.53036C2.7204%203.47855%202.7172%203.39544%202.76602%203.34079C4.04913%201.9043%205.9156%201%207.99327%201C11.863%201%2015%204.13702%2015%208.00672C15%2010.0844%2014.0957%2011.9509%2012.6592%2013.234C12.6046%2013.2828%2012.5214%2013.2796%2012.4696%2013.2278L2.77222%203.53036Z'%20fill='url(%23paint0_linear_2502_833)'/%3e%3c/g%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_2502_833'%20x1='8'%20y1='1'%20x2='8'%20y2='15'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%235C6BF1'/%3e%3cstop%20offset='1'%20stop-color='%23283188'/%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M12.9289%2012.9289H10.8545V9.68033C10.8545%208.90563%2010.8407%207.90839%209.77562%207.90839C8.69517%207.90839%208.52983%208.7524%208.52983%209.62391V12.9287H6.45547V6.24817H8.44688V7.16113H8.47481C8.88025%206.46785%209.63695%206.05224%2010.4396%206.08204C12.5421%206.08204%2012.9297%207.46497%2012.9297%209.2641L12.9289%2012.9289ZM4.11485%205.33497C3.45446%205.33497%202.91079%204.79161%202.91079%204.1312C2.91079%203.47081%203.45421%202.92738%204.1146%202.92738C4.77493%202.92738%205.31829%203.47068%205.31841%204.13096C5.31841%204.79123%204.77512%205.33491%204.11485%205.33497ZM5.15203%2012.9289H3.07549V6.24817H5.15203V12.9289ZM13.963%201.00097H2.03305C1.47303%200.994641%201.00683%201.45002%201%202.01004V13.9897C1.00658%2014.55%201.47272%2015.0059%202.03305%2014.9999H13.963C14.5247%2015.007%2014.9925%2014.5511%2015%2013.9897V2.00923C14.9925%201.44802%2014.5241%200.992699%2013.963%201.00009V1.00097Z'%20fill='%230A66C2'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M1%201H15V15H1V1Z'%20fill='%23F3F3F3'/%3e%3cpath%20d='M2%202H8V8H2V2Z'%20fill='%23F35325'/%3e%3cpath%20d='M8%202H14V8H8V2Z'%20fill='%2381BC06'/%3e%3cpath%20d='M2%208H8V14H2V8Z'%20fill='%2305A6F0'/%3e%3cpath%20d='M8%208H14V14H8V8Z'%20fill='%23FFBA08'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M2.33281%201.60396L10.0795%201.03183C11.031%200.95016%2011.2756%201.00523%2011.8738%201.44016L14.3467%203.18223C14.7546%203.48183%2014.8904%203.5635%2014.8904%203.8897V13.4438C14.8904%2014.0425%2014.6729%2014.3967%2013.9118%2014.4509L4.91582%2014.9955C4.34462%2015.0225%204.07255%2014.9409%203.77341%2014.5596L1.95248%2012.1917C1.62581%2011.7559%201.49048%2011.4297%201.49048%2011.0484V2.55596C1.49048%202.06643%201.70795%201.65809%202.33281%201.60396Z'%20fill='white'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M10.0795%201.03183L2.33281%201.60396C1.70795%201.65809%201.49048%202.06643%201.49048%202.55596V11.0484C1.49048%2011.4297%201.62581%2011.7559%201.95248%2012.1917L3.77341%2014.5596C4.07255%2014.9409%204.34462%2015.0225%204.91582%2014.9955L13.9118%2014.4509C14.6724%2014.3967%2014.8904%2014.0425%2014.8904%2013.4438V3.8897C14.8904%203.5803%2014.7681%203.49116%2014.4083%203.22703C14.3876%203.21212%2014.3669%203.19718%2014.3462%203.18223L11.8738%201.44016C11.2756%201.00523%2011.031%200.95016%2010.0795%201.03183ZM5.11929%203.73336C4.38475%203.78283%204.21815%203.79403%203.80095%203.45476L2.74021%202.61103C2.63241%202.50183%202.68654%202.36556%202.95814%202.33849L10.4052%201.79436C11.0306%201.73976%2011.3563%201.95769%2011.6008%202.14809L12.8781%203.07349C12.9327%203.10103%2013.0685%203.26389%2012.9052%203.26389L5.21449%203.72683L5.11929%203.73336ZM4.26295%2013.3621V5.25144C4.26295%204.89724%204.37168%204.7339%204.69742%204.70637L13.5305%204.1893C13.8301%204.16223%2013.9654%204.35263%2013.9654%204.70637V12.7629C13.9654%2013.1171%2013.9108%2013.4167%2013.4218%2013.4438L4.96902%2013.9338C4.47995%2013.9609%204.26295%2013.798%204.26295%2013.3621ZM12.607%205.68637C12.6611%205.93137%2012.607%206.17637%2012.362%206.20437L11.9546%206.2851V12.2734C11.6008%2012.4638%2011.2751%2012.5725%2011.003%2012.5725C10.5681%2012.5725%2010.4593%2012.4363%2010.1336%2012.0284L7.46942%207.83677V11.8921L8.31224%2012.083C8.31224%2012.083%208.31224%2012.573%207.63229%2012.573L5.75769%2012.6817C5.70309%2012.5725%205.75769%2012.3005%205.94762%2012.2463L6.43716%2012.1105V6.7485L5.75769%206.69344C5.70309%206.44844%205.83889%206.0947%206.21969%206.06717L8.23104%205.93184L11.003%2010.1776V6.42137L10.2965%206.34017C10.2419%206.0401%2010.4593%205.82217%2010.7309%205.79557L12.607%205.68637Z'%20fill='black'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.94137%209.84695C3.94137%2010.6564%203.28013%2011.3176%202.47069%2011.3176C1.66124%2011.3176%201%2010.6564%201%209.84695C1%209.03747%201.66124%208.37625%202.47069%208.37625H3.94137V9.84695Z'%20fill='%23E01E5A'/%3e%3cpath%20d='M4.68237%209.84695C4.68237%209.03747%205.34361%208.37625%206.15306%208.37625C6.9625%208.37625%207.62374%209.03747%207.62374%209.84695V13.5293C7.62374%2014.3388%206.9625%2015%206.15306%2015C5.34361%2015%204.68237%2014.3388%204.68237%2013.5293V9.84695Z'%20fill='%23E01E5A'/%3e%3cpath%20d='M6.15306%203.94137C5.34361%203.94137%204.68237%203.28013%204.68237%202.47069C4.68237%201.66124%205.34361%201%206.15306%201C6.9625%201%207.62374%201.66124%207.62374%202.47069V3.94137H6.15306Z'%20fill='%2336C5F0'/%3e%3cpath%20d='M6.15309%204.68237C6.96254%204.68237%207.62378%205.34361%207.62378%206.15306C7.62378%206.9625%206.96254%207.62374%206.15309%207.62374H2.47069C1.66124%207.62374%201%206.9625%201%206.15306C1%205.34361%201.66124%204.68237%202.47069%204.68237H6.15309Z'%20fill='%2336C5F0'/%3e%3cpath%20d='M12.0585%206.15306C12.0585%205.34361%2012.7197%204.68237%2013.5291%204.68237C14.3386%204.68237%2014.9998%205.34361%2014.9998%206.15306C14.9998%206.9625%2014.3386%207.62374%2013.5291%207.62374H12.0585V6.15306Z'%20fill='%232EB67D'/%3e%3cpath%20d='M11.3176%206.15309C11.3176%206.96254%2010.6563%207.62378%209.84685%207.62378C9.03744%207.62378%208.37622%206.96254%208.37622%206.15309V2.47069C8.37622%201.66124%209.03744%201%209.84685%201C10.6563%201%2011.3176%201.66124%2011.3176%202.47069V6.15309Z'%20fill='%232EB67D'/%3e%3cpath%20d='M9.84685%2012.0586C10.6563%2012.0586%2011.3176%2012.7199%2011.3176%2013.5293C11.3176%2014.3388%2010.6563%2015%209.84685%2015C9.03744%2015%208.37622%2014.3388%208.37622%2013.5293V12.0586H9.84685Z'%20fill='%23ECB22E'/%3e%3cpath%20d='M9.84685%2011.3176C9.03744%2011.3176%208.37622%2010.6564%208.37622%209.84695C8.37622%209.03747%209.03744%208.37625%209.84685%208.37625H13.5293C14.3388%208.37625%2015%209.03747%2015%209.84695C15%2010.6564%2014.3388%2011.3176%2013.5293%2011.3176H9.84685Z'%20fill='%23ECB22E'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M6.60974%205.91839V5.33278C6.40646%205.30058%206.20114%205.28293%205.99535%205.27998C4.00296%205.27577%202.23902%206.56688%201.64074%208.46732C1.04245%2010.3678%201.74866%2012.4365%203.38415%2013.5744C2.15905%2012.2633%201.81888%2010.3546%202.51559%208.70096C3.21229%207.0473%204.81576%205.95753%206.60974%205.91839Z'%20fill='%2325F4EE'/%3e%3cpath%20d='M6.72004%2012.552C7.834%2012.5505%208.74966%2011.6729%208.79844%2010.56V0.6288H10.6128C10.5758%200.421288%2010.5581%200.210783%2010.56%200H8.07844V9.9216C8.03716%2011.0402%207.11934%2011.9262%206.00004%2011.928C5.66555%2011.9252%205.33652%2011.8429%205.04004%2011.688C5.42976%2012.2279%206.05416%2012.5491%206.72004%2012.552Z'%20fill='%2325F4EE'/%3e%3cpath%20d='M14.0014%203.9984V3.4464C13.3337%203.44663%2012.6808%203.24959%2012.1246%202.88C12.6122%203.44675%2013.271%203.83934%2014.0014%203.9984Z'%20fill='%2325F4EE'/%3e%3cpath%20d='M12.125%202.87999C11.5772%202.25615%2011.2752%201.45422%2011.2754%200.623993H10.613C10.786%201.55168%2011.3327%202.36746%2012.125%202.87999Z'%20fill='%23FE2C55'/%3e%3cpath%20d='M5.99519%207.7616C5.03925%207.76652%204.20933%208.42142%203.98229%209.34998C3.75525%2010.2786%204.18936%2011.2426%205.03519%2011.688C4.57688%2011.0552%204.51214%2010.219%204.86761%209.5232C5.22308%208.82744%205.9387%208.3898%206.71999%208.3904C6.92831%208.39298%207.13519%208.42532%207.33439%208.4864V5.9616C7.13099%205.93112%206.92567%205.91509%206.71999%205.9136H6.60959V7.8336C6.40937%207.7799%206.20243%207.75566%205.99519%207.7616Z'%20fill='%23FE2C55'/%3e%3cpath%20d='M14.0015%203.99841V5.91841C12.7654%205.91603%2011.5613%205.52475%2010.5599%204.80001V9.84481C10.5546%2012.3621%208.51245%2014.4%205.99511%2014.4C5.06025%2014.4017%204.1479%2014.1132%203.38391%2013.5744C4.6589%2014.9457%206.64315%2015.3971%208.38585%2014.7123C10.1285%2014.0275%2011.2747%2012.346%2011.2751%2010.4736V5.44321C12.2799%206.16321%2013.4854%206.54937%2014.7215%206.54721V4.07521C14.4795%204.07445%2014.2382%204.04871%2014.0015%203.99841Z'%20fill='%23FE2C55'/%3e%3cpath%20d='M10.56%209.8448V4.79999C11.5645%205.52056%2012.7702%205.9068%2014.0064%205.90399V3.98399C13.2761%203.82977%2012.6157%203.4423%2012.1248%202.87999C11.3324%202.36746%2010.7857%201.55168%2010.6128%200.623993H8.7984V10.56C8.7621%2011.4464%208.16834%2012.2126%207.31904%2012.4691C6.46968%2012.7255%205.55115%2012.4159%205.03038%2011.6976C4.18454%2011.2522%203.75043%2010.2882%203.97747%209.35958C4.20452%208.43102%205.03444%207.77612%205.99038%207.7712C6.19878%207.77306%206.40578%207.8054%206.6048%207.8672V5.94719C4.80073%205.97776%203.18515%207.07136%202.48647%208.73486C1.78778%2010.3984%202.13799%2012.3176%203.37918%2013.6272C4.1507%2014.1482%205.06437%2014.4181%205.99518%2014.4C8.5125%2014.4%2010.5547%2012.3621%2010.56%209.8448Z'%20fill='black'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M14%207.94593L11.75%2010.1081H9.5L7.53124%2012V10.1081H5V2H14V7.94593Z'%20fill='white'/%3e%3cpath%20d='M4.70834%201L2%203.67857V13.3215H5.25V16L7.95833%2013.3215H10.125L15%208.5V1H4.70834ZM13.9166%207.96428L11.75%2010.1072H9.5833L7.6875%2011.9822V10.1072H5.25V2.07143H13.9166V7.96428Z'%20fill='%239146FF'/%3e%3cpath%20d='M12%204H11V7H12V4Z'%20fill='%239146FF'/%3e%3cpath%20d='M9%204H8V7H9V4Z'%20fill='%239146FF'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M9.14163%206.50461L13.6089%201H12.5503L8.67137%205.77958L5.57328%201H2L6.68492%208.22757L2%2014H3.05866L7.15491%208.9526L10.4267%2014H14L9.14137%206.50461H9.14163ZM7.69165%208.29124L7.21697%207.57154L3.44011%201.84479H5.06615L8.11412%206.46646L8.5888%207.18616L12.5508%2013.1936H10.9248L7.69165%208.29152V8.29124Z'%20fill='black'%20stroke='black'%20stroke-width='0.5'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cmask%20id='mask0_2502_830'%20style='mask-type:luminance'%20maskUnits='userSpaceOnUse'%20x='1'%20y='1'%20width='14'%20height='14'%3e%3cpath%20d='M15%201H1V15H15V1Z'%20fill='white'/%3e%3c/mask%3e%3cg%20mask='url(%23mask0_2502_830)'%3e%3cpath%20d='M7.99994%2014.9733C11.8512%2014.9733%2014.9732%2011.8513%2014.9732%207.99997C14.9732%204.14873%2011.8512%201.02667%207.99994%201.02667C4.14867%201.02667%201.02661%204.14873%201.02661%207.99997C1.02661%2011.8513%204.14867%2014.9733%207.99994%2014.9733Z'%20fill='%231AB4D7'/%3e%3cpath%20d='M4.36467%207.97988L5.55473%206.78688C5.59418%206.74667%205.61619%206.69343%205.61619%206.63697C5.61619%206.5193%205.52054%206.42374%205.40287%206.42374C5.34555%206.42374%205.29181%206.44621%205.2513%206.48723L4.06231%207.67564L2.86801%206.48544C2.82765%206.44566%202.77418%206.42374%202.71748%206.42374C2.59995%206.42374%202.50427%206.51925%202.50427%206.6368C2.50427%206.69415%202.52716%206.74796%202.56825%206.7885L3.75814%207.97822L2.56887%209.16973C2.52707%209.21089%202.50427%209.26479%202.50427%209.3224C2.50427%209.44007%202.59995%209.53548%202.71748%209.53548C2.77428%209.53548%202.8278%209.51343%202.86801%209.47325L4.06046%208.28241L5.24838%209.46891C5.29051%209.51245%205.34487%209.53562%205.40287%209.53562C5.52042%209.53562%205.61608%209.44007%205.61608%209.3224C5.61608%209.26563%205.59409%209.21229%205.55406%209.17211L4.36467%207.97988Z'%20fill='white'/%3e%3cpath%20d='M11.4393%207.97953C11.4393%208.19316%2011.6131%208.36697%2011.827%208.36697C12.0404%208.36697%2012.2142%208.19316%2012.2142%207.97953C12.2142%207.76582%2012.0404%207.59204%2011.827%207.59204C11.6131%207.59204%2011.4393%207.76582%2011.4393%207.97953Z'%20fill='white'/%3e%3cpath%20d='M10.7045%207.97969C10.7045%207.36096%2011.2078%206.85753%2011.8266%206.85753C12.4451%206.85753%2012.9485%207.36096%2012.9485%207.97969C12.9485%208.59828%2012.4451%209.10151%2011.8266%209.10151C11.2078%209.10151%2010.7045%208.59828%2010.7045%207.97969ZM10.2631%207.97969C10.2631%208.84167%2010.9645%209.543%2011.8266%209.543C12.6887%209.543%2013.3905%208.84167%2013.3905%207.97969C13.3905%207.11757%2012.6887%206.41608%2011.8266%206.41608C10.9645%206.41608%2010.2631%207.11757%2010.2631%207.97969Z'%20fill='white'/%3e%3cpath%20d='M10.152%206.44279L10.0864%206.4426C9.88947%206.4426%209.69956%206.50471%209.54094%206.62696C9.52001%206.5313%209.43447%206.45933%209.33269%206.45933C9.21544%206.45933%209.1215%206.55325%209.12122%206.67071L9.12192%209.3041C9.12227%209.42135%209.21789%209.51662%209.33514%209.51662C9.45246%209.51662%209.54808%209.42135%209.54836%209.30382L9.54843%207.68463C9.54843%207.14496%209.59778%206.927%2010.0601%206.86923C10.1028%206.86392%2010.1494%206.86475%2010.1494%206.86475C10.276%206.86041%2010.3659%206.77348%2010.3659%206.656C10.3659%206.53844%2010.2699%206.44279%2010.152%206.44279Z'%20fill='white'/%3e%3cpath%20d='M6.05791%207.72227C6.05791%207.71643%206.05836%207.71035%206.05864%207.70435C6.18243%207.215%206.62563%206.85287%207.15344%206.85287C7.68764%206.85287%208.13489%207.2239%208.25235%207.72227H6.05791ZM8.689%207.682C8.59709%207.24697%208.35895%206.88964%207.99626%206.66016C7.46613%206.32358%206.76607%206.3422%206.25401%206.70635C5.83632%207.00349%205.59521%207.48958%205.59521%207.9903C5.59521%208.11586%205.61035%208.24256%205.64186%208.3673C5.79957%208.98778%206.33294%209.45741%206.96885%209.53525C7.15754%209.55814%207.34122%209.54715%207.53141%209.49794C7.69485%209.45818%207.85299%209.39189%207.99871%209.29851C8.14993%209.20128%208.27628%209.07304%208.39864%208.9196C8.40116%208.9168%208.40361%208.91428%208.40613%208.91134C8.49104%208.80599%208.47529%208.65619%208.38198%208.58465C8.30323%208.52438%208.17107%208.49988%208.06712%208.63309C8.04472%208.66487%208.0198%208.69763%207.99238%208.73039C7.90969%208.82181%207.80712%208.91029%207.6842%208.97896C7.52779%209.06254%207.34955%209.11028%207.16006%209.11133C6.53986%209.1044%206.20799%208.67152%206.08993%208.36254C6.06932%208.30479%206.05342%208.24494%206.04234%208.18334C6.0409%208.17179%206.03983%208.16066%206.0394%208.15044C6.16763%208.15044%208.26501%208.15009%208.26501%208.15009C8.57014%208.14365%208.73436%207.92828%208.689%207.682Z'%20fill='white'/%3e%3c/g%3e%3c/svg%3e\"","import type { CSSProperties } from 'react';\nimport { cn } from '@/utils';\nimport { CountryFlag } from '../country-flag';\nimport '@/styles/index.css';\nimport './style.css';\n\nimport browserChrome from '@/assets/icons/general/browser-chrome.svg';\nimport caretDown from '@/assets/icons/general/caret-down.svg';\nimport check from '@/assets/icons/general/check.svg';\nimport close from '@/assets/icons/general/close.svg';\nimport dotsVertical from '@/assets/icons/general/dots-vertical.svg';\nimport edit from '@/assets/icons/general/edit.svg';\nimport eyeOff from '@/assets/icons/general/eye-off.svg';\nimport eyeOn from '@/assets/icons/general/eye-on.svg';\nimport key from '@/assets/icons/general/key.svg';\nimport label from '@/assets/icons/general/label.svg';\nimport logo from '@/assets/icons/general/logo.svg';\nimport logoRed from '@/assets/icons/general/logo-red.svg';\nimport mail from '@/assets/icons/general/mail.svg';\nimport onePassword from '@/assets/icons/general/one-password.svg';\nimport passkey from '@/assets/icons/general/passkey.svg';\nimport phone from '@/assets/icons/general/phone.svg';\nimport search from '@/assets/icons/general/search.svg';\nimport trash from '@/assets/icons/general/trash.svg';\nimport warning from '@/assets/icons/general/warning.svg';\nimport apple from '@/assets/icons/providers/apple.svg';\nimport atlassian from '@/assets/icons/providers/atlassian.svg';\nimport bitbucket from '@/assets/icons/providers/bitbucket.svg';\nimport discord from '@/assets/icons/providers/discord.svg';\nimport dropbox from '@/assets/icons/providers/dropbox.svg';\nimport facebook from '@/assets/icons/providers/facebook.svg';\nimport github from '@/assets/icons/providers/github.svg';\nimport gitlab from '@/assets/icons/providers/gitlab.svg';\nimport google from '@/assets/icons/providers/google.svg';\nimport hubspot from '@/assets/icons/providers/hubspot.svg';\nimport linear from '@/assets/icons/providers/linear.svg';\nimport linkedin from '@/assets/icons/providers/linkedin.svg';\nimport microsoft from '@/assets/icons/providers/microsoft.svg';\nimport notion from '@/assets/icons/providers/notion.svg';\nimport slack from '@/assets/icons/providers/slack.svg';\nimport tiktok from '@/assets/icons/providers/tiktok.svg';\nimport twitch from '@/assets/icons/providers/twitch.svg';\nimport twitter from '@/assets/icons/providers/twitter.svg';\nimport xero from '@/assets/icons/providers/xero.svg';\n\ntype TIcon = {\n type: 'general' | 'providers' | 'flags';\n id: string;\n size: 'small' | 'medium' | 'big' | 'large';\n className?: string;\n decorative?: boolean;\n matchTextColor?: boolean;\n};\n\ntype IconMaskStyle = CSSProperties & {\n '--passflow-icon-mask': string;\n};\n\nexport const Icon = ({ type, id, size, className = '', decorative = false, matchTextColor = false }: TIcon) => {\n const styles = {\n 'passflow-icon--small': size === 'small',\n 'passflow-icon--medium': size === 'medium',\n 'passflow-icon--big': size === 'big',\n 'passflow-icon--large': size === 'large',\n };\n\n const icons: Record<'providers' | 'general', Record<string, string>> = {\n general: {\n logo,\n 'logo-red': logoRed,\n warning,\n mail,\n edit,\n 'eye-on': eyeOn,\n 'eye-off': eyeOff,\n search,\n 'caret-down': caretDown,\n label,\n close,\n check,\n key,\n phone,\n 'one-password': onePassword,\n 'browser-chrome': browserChrome,\n passkey,\n 'dots-vertical': dotsVertical,\n trash,\n },\n providers: {\n google,\n gitlab,\n apple,\n atlassian,\n bitbucket,\n discord,\n dropbox,\n facebook,\n github,\n hubspot,\n linear,\n linkedin,\n linledin: linkedin,\n microsoft,\n notion,\n slack,\n tiktok,\n twitch,\n twitter,\n xero,\n },\n };\n\n if (matchTextColor && type === 'general') {\n const style: IconMaskStyle = {\n '--passflow-icon-mask': `url(\"${icons.general[id]}\")`,\n };\n\n return (\n <span\n className={cn('passflow-icon passflow-icon--match-text', styles, className)}\n style={style}\n role={decorative ? undefined : 'img'}\n aria-label={decorative ? undefined : id}\n aria-hidden={decorative || undefined}\n />\n );\n }\n\n if (type !== 'flags') {\n return <img className={cn('passflow-icon', styles, className)} src={icons[type][id]} alt={decorative ? '' : id} />;\n }\n\n return (\n <div className={cn('passflow-icon', styles, className)}>\n <CountryFlag iso2={id} />\n </div>\n );\n};\n","import type { FC, PropsWithChildren } from 'react';\nimport { useEffect, useRef } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport type { LoginScreenNotice as LoginScreenNoticeProps } from './types';\nimport './login-screen.css';\n\n/** `error` is the default; `info` is a neutral note that is not announced as an alert. */\nexport const LoginAlert: FC<{ message?: string | null; id?: string; tone?: 'error' | 'info' }> = ({\n message,\n id,\n tone = 'error',\n}) => {\n if (!message) return null;\n\n if (tone === 'info') {\n return (\n <div id={id} className='passflow-login-screen-note' role='status'>\n {message}\n </div>\n );\n }\n\n return (\n <div id={id} className='passflow-form-error' role='alert'>\n <Icon size='small' id='warning' type='general' className='icon-warning' decorative />\n <span className='passflow-form-error-text'>{message}</span>\n </div>\n );\n};\n\n/** For a code input locked while a request is in flight: gives focus back when the request ends. */\nexport const useFocusAfterBusy = (busy: boolean) => {\n const inputRef = useRef<HTMLInputElement>(null);\n const wasBusy = useRef(busy);\n\n useEffect(() => {\n if (wasBusy.current && !busy) inputRef.current?.focus();\n wasBusy.current = busy;\n }, [busy]);\n\n return inputRef;\n};\n\nexport const LoginDivider: FC<{ label: string }> = ({ label }) => (\n <div className='passflow-form-divider' aria-hidden='true'>\n <div className='passflow-form-divider__line-left' />\n <span className='passflow-form-divider__text'>{label}</span>\n <div className='passflow-form-divider__line-right' />\n </div>\n);\n\nexport const LoginActionStack: FC<PropsWithChildren> = ({ children }) => (\n <div className='passflow-login-screen-actions'>{children}</div>\n);\n\nexport const LoginProgress: FC<{ message: string; onCancel?: () => void }> = ({ message, onCancel }) => {\n const status = (\n <div className='passflow-login-screen-status' role='status' aria-live='polite'>\n <div className='passflow-login-screen-spinner passflow-login-screen-spinner--small' aria-hidden='true' />\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>{message}</p>\n </div>\n );\n if (!onCancel) return status;\n return (\n <div className='passflow-login-screen-progress'>\n {status}\n <Button size='small' variant='link' type='button' onClick={onCancel}>\n Cancel\n </Button>\n </div>\n );\n};\n\nexport const LoginScreenNotice: FC<LoginScreenNoticeProps> = ({ code, appName, message, codeTestId, appNameTestId }) => (\n <div className='passflow-login-screen-notice' role='note'>\n {code ? (\n <div className='passflow-login-screen-code' data-testid={codeTestId}>\n {code}\n </div>\n ) : null}\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n <span className='passflow-login-screen-app-name' data-testid={appNameTestId}>\n {appName}\n </span>{' '}\n {message}\n </p>\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useState } from 'react';\nimport { Button } from '../button';\nimport { FieldText } from '../fields/field-text';\nimport { LoginAlert, LoginProgress } from './shared';\nimport type { LoginCodeEntryState } from './types';\n\nexport const LoginCodeEntry: FC<LoginCodeEntryState> = ({\n label = 'Code',\n initialCode = '',\n error,\n busy = false,\n submitLabel = 'Continue',\n testId,\n onSubmit,\n}) => {\n const [code, setCode] = useState(initialCode);\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const normalizedCode = code.trim();\n if (normalizedCode) onSubmit(normalizedCode);\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container'>\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label htmlFor='device-user-code' className='passflow-field-label'>\n {label}\n </label>\n </div>\n <FieldText\n id='device-user-code'\n name='user_code'\n type='text'\n autoCapitalize='characters'\n autoComplete='off'\n autoCorrect='off'\n spellCheck={false}\n inputMode='text'\n className='passflow-login-screen-code-input'\n value={code}\n disabled={busy}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? 'device-user-code-error' : undefined}\n isError={Boolean(error)}\n onChange={(event) => setCode(event.target.value)}\n />\n </div>\n <LoginAlert id='device-user-code-error' message={error} />\n </div>\n {busy ? <LoginProgress message='Checking the code…' /> : null}\n <Button size='big' variant='primary' type='submit' disabled={busy || code.trim().length === 0}>\n {busy ? 'Checking…' : submitLabel}\n </Button>\n </form>\n );\n};\n","import { type ChangeEvent, type FC, useId } from 'react';\nimport { cn } from '@/utils';\n\ntype TSwitch = {\n label: string;\n checked: boolean;\n disabled?: boolean;\n /**\n * Overrides the generated input id. Only needed when something outside this\n * component has to point at the input (`aria-describedby`, a test hook, a\n * label rendered elsewhere).\n *\n * The default is a `useId()` value rather than a constant, because a constant\n * breaks the moment a screen renders more than one Switch: duplicate DOM ids\n * are invalid, and every `<label htmlFor>` would resolve to the FIRST input,\n * so clicking row three would toggle row one. The consent screen renders one\n * Switch per requested scope, so this is load-bearing, not hygiene.\n */\n id?: string;\n onChange: (event: ChangeEvent<HTMLInputElement>) => void;\n};\n\nexport const Switch: FC<TSwitch> = ({ label, checked, disabled = false, id, onChange }) => {\n const generatedId = useId();\n const inputId = id ?? generatedId;\n\n return (\n <label className={cn('passflow-switch-wrapper', { 'passflow-switch-wrapper--disabled': disabled })} htmlFor={inputId}>\n <span className='passflow-switch-label'>{label}</span>\n <input\n id={inputId}\n type='checkbox'\n className='passflow-switch-input'\n checked={checked}\n disabled={disabled}\n onChange={onChange}\n />\n <div className='passflow-switch-track' />\n </label>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Switch } from '../switch';\nimport { LoginAlert, LoginProgress, LoginScreenNotice } from './shared';\nimport type { LoginConsentState } from './types';\n\n/**\n * The OIDC consent screen: which scopes an application is asking for, and the\n * two decisions a user can make about them.\n *\n * Every scope starts granted and can be switched off individually — the Allow\n * button submits the subset that is still on, so \"Allow\" never grants more than\n * what is visible on screen. Deny is a peer of Allow, not a hidden link: a\n * consent screen where refusing is harder than accepting is a dark pattern.\n * For the same reason neither button takes initial focus: a bare Enter on a\n * freshly loaded screen must not grant every requested scope.\n */\nexport const LoginConsent: FC<LoginConsentState> = ({\n appName,\n scopes,\n prompt = 'wants to access your account.',\n busy = false,\n error,\n allowLabel = 'Allow',\n denyLabel = 'Deny',\n busyLabel = 'Submitting…',\n testId,\n allowTestId,\n denyTestId,\n appNameTestId,\n onToggleScope,\n onAllow,\n onDeny,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <LoginScreenNotice appName={appName} message={prompt} appNameTestId={appNameTestId} />\n\n <div className='passflow-form-container'>\n <LoginAlert message={error} />\n\n {scopes.length ? (\n <ul className='passflow-consent-scopes'>\n {scopes.map((item) => (\n <li key={item.scope} className='passflow-consent-scope' data-testid={`consent-scope-${item.scope}`}>\n <Switch label={item.label} checked={item.granted} disabled={busy} onChange={() => onToggleScope(item.scope)} />\n {item.description ? <p className='passflow-consent-scope-description'>{item.description}</p> : null}\n </li>\n ))}\n </ul>\n ) : (\n <p className='passflow-login-screen-hint'>This application is not requesting access to any of your data.</p>\n )}\n </div>\n\n {busy ? <LoginProgress message={busyLabel} /> : null}\n\n <div className='passflow-consent-actions'>\n <Button size='big' variant='primary' type='button' data-testid={allowTestId} disabled={busy} onClick={onAllow}>\n {allowLabel}\n </Button>\n <Button size='big' variant='outlined' type='button' data-testid={denyTestId} disabled={busy} onClick={onDeny}>\n {denyLabel}\n </Button>\n </div>\n </div>\n);\n","/* eslint-disable react/jsx-props-no-spreading */\nimport type { FC, MouseEvent, PropsWithChildren } from 'react';\nimport { useNavigation } from '@/hooks';\nimport '@/styles/index.css';\n\ntype LinkProps = PropsWithChildren<{\n to: string;\n search?: string;\n replace?: boolean;\n className?: string;\n onClick?: (e: MouseEvent<HTMLAnchorElement>) => void;\n}>;\n\nexport const Link: FC<LinkProps> = ({ to, search, replace = false, children, className, onClick, ...props }) => {\n const { navigate } = useNavigation();\n\n const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n\n if (onClick) {\n onClick(e);\n }\n\n navigate({ to, search, replace });\n };\n\n const getHref = (): string => {\n const searchParam = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n return `${to}${searchParam}`;\n };\n\n return (\n <a href={getHref()} onClick={handleClick} className={className} {...props}>\n {children}\n </a>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport '@/styles/index.css';\nimport type { Providers } from '@passflow/core';\nimport { cn } from '@/utils';\n\ntype TProvidersBox = {\n providers: Providers[];\n onClick: (provider: Providers) => void;\n className?: string;\n};\n\nexport const ProvidersBox: FC<TProvidersBox> = ({ providers, onClick, className = '' }) => {\n const styles = {\n 'passflow-providers-box--grid': providers.length > 1,\n };\n\n return (\n <div className={cn('passflow-providers-box', styles, className)}>\n {providers.map((provider) => (\n <Button\n onClick={() => onClick(provider)}\n size='big'\n variant='provider'\n type='button'\n key={provider}\n withIcon\n className='passflow-provider-item'\n >\n <Icon size='small' type='providers' id={provider} decorative={providers.length <= 2} />\n {providers.length <= 2 && <p className='passflow-provider-text'>{provider}</p>}\n </Button>\n ))}\n </div>\n );\n};\n","import { phone } from 'phone';\nimport type { FC } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { Controller, useForm } from 'react-hook-form';\nimport type { DefaultMethod } from '@/types';\nimport { cn, emailRegex, passwordValidation } from '@/utils';\nimport { Button } from '../button';\nimport { FieldPassword } from '../fields/field-password';\nimport { FieldPhone } from '../fields/field-phone';\nimport { FieldText } from '../fields/field-text';\nimport { Icon } from '../icon';\nimport { Link } from '../link';\nimport { ProvidersBox } from '../providers-box';\nimport { Switch } from '../switch';\nimport { LoginActionStack, LoginAlert, LoginDivider, LoginProgress, LoginScreenNotice } from './shared';\nimport type { LoginCredentialsState, LoginCredentialsValues } from './types';\n\ntype LoginFormValues = {\n email_or_username: string;\n phone: string;\n password: string;\n};\n\nconst initialValues: LoginFormValues = {\n email_or_username: '',\n phone: '',\n password: '',\n};\n\nconst getDefaultMethod = (state: LoginCredentialsState): DefaultMethod | null => {\n if (state.initialMethod !== undefined && state.methods.identities.some((method) => method.id === state.initialMethod)) {\n return state.initialMethod;\n }\n return state.methods.identities[0]?.id ?? null;\n};\n\nexport const LoginCredentials: FC<LoginCredentialsState> = (state) => {\n const { methods } = state;\n const computedDefaultMethod = getDefaultMethod(state);\n const [defaultMethod, setDefaultMethod] = useState<DefaultMethod | null>(computedDefaultMethod);\n const [passkeyOnly, setPasskeyOnly] = useState(Boolean(state.forcePasskey));\n const previousComputedMethod = useRef(computedDefaultMethod);\n const previousForcePasskey = useRef(Boolean(state.forcePasskey));\n const {\n control,\n getValues,\n reset,\n trigger,\n watch,\n formState: { errors, isDirty, isValid, isSubmitted, touchedFields },\n handleSubmit,\n } = useForm<LoginFormValues>({\n defaultValues: initialValues,\n mode: 'onChange',\n });\n\n useEffect(() => {\n if (previousComputedMethod.current === computedDefaultMethod) return;\n previousComputedMethod.current = computedDefaultMethod;\n setDefaultMethod(computedDefaultMethod);\n reset(initialValues);\n }, [computedDefaultMethod, reset]);\n\n useEffect(() => {\n const nextForcePasskey = Boolean(state.forcePasskey);\n if (previousForcePasskey.current === nextForcePasskey) return;\n previousForcePasskey.current = nextForcePasskey;\n setPasskeyOnly(nextForcePasskey);\n }, [state.forcePasskey]);\n\n const currentIdentity = methods.identities.find((method) => method.id === defaultMethod);\n const hasPassword = Boolean(currentIdentity?.password);\n const hasPasswordless = Boolean(currentIdentity?.passwordlessLabel);\n const hasPasskey = methods.passkey;\n const hasIdentity = Boolean(currentIdentity);\n const showCredentialFields = !passkeyOnly && hasIdentity;\n const showStandalonePasskey = hasPasskey && (passkeyOnly || !hasIdentity);\n const hasCredentialActions = hasPassword || hasPasswordless || hasPasskey;\n const controlsDisabled = Boolean(state.busy || state.disabled);\n const errorScope = state.error?.scope;\n const hasIdentityError = errorScope === 'identity' || errorScope === 'credentials';\n const hasPasswordError = errorScope === 'password' || errorScope === 'credentials';\n const isNewPassword = state.credentialPurpose === 'sign-up';\n // The identity is checked on every keystroke so the submit button can enable, but a half-typed address is not an\n // error yet: its message waits until the user leaves the field or submits.\n const identityError = touchedFields.email_or_username || isSubmitted ? errors.email_or_username : undefined;\n\n const validatePassword = (value: string) => {\n if (!isNewPassword) return true;\n\n try {\n passwordValidation(state.passwordPolicy).validateSync(value);\n return true;\n } catch (error) {\n const validationError = error as { errors?: string[] };\n return validationError.errors?.join(', ') ?? 'Password does not meet the requirements';\n }\n };\n\n const toCredentials = (values: LoginFormValues): LoginCredentialsValues => ({\n method: defaultMethod,\n emailOrUsername: values.email_or_username,\n phone: values.phone,\n password: values.password,\n });\n\n const handleReset = () => {\n reset(initialValues);\n state.onReset?.();\n };\n\n const handleMethodChange = (method: DefaultMethod) => {\n setDefaultMethod(method);\n handleReset();\n };\n\n const handlePasskeyExperienceChange = (checked: boolean) => {\n setPasskeyOnly(checked);\n handleReset();\n };\n\n const submitCurrentMethod = handleSubmit((values) => {\n if (hasPassword) {\n state.onPassword?.(toCredentials(values));\n return;\n }\n if (hasPasswordless) state.onPasswordless?.(toCredentials(values));\n });\n\n const submitPasswordless = async () => {\n if (!defaultMethod || !state.onPasswordless) return;\n const identityField = defaultMethod === 'phone' ? 'phone' : 'email_or_username';\n if (!(await trigger(identityField))) return;\n state.onPasswordless(toCredentials(getValues()));\n };\n const selectedIdentityValue = defaultMethod === 'phone' ? watch('phone') : watch('email_or_username');\n const alternateIdentity = methods.identities.find((method) => method.id !== defaultMethod);\n const formAlert =\n state.error?.startAgain && state.onStartAgain ? (\n <div className='passflow-login-screen-alert-row'>\n <LoginAlert message={state.error.message} />\n <Button size='small' variant='link' type='button' disabled={controlsDisabled} onClick={state.onStartAgain}>\n Start again\n </Button>\n </div>\n ) : (\n <LoginAlert message={state.error?.message} />\n );\n\n return (\n <>\n {state.notice ? <LoginScreenNotice {...state.notice} /> : null}\n {state.allowPasskeyToggle && hasPasskey && hasIdentity && (hasPassword || hasPasswordless) ? (\n <div className='passflow-form-switch'>\n <Switch\n label='Passwordless experience'\n checked={passkeyOnly}\n disabled={controlsDisabled}\n onChange={(event) => handlePasskeyExperienceChange(event.target.checked)}\n />\n </div>\n ) : null}\n <form\n className='passflow-form'\n data-testid={state.testId}\n aria-busy={controlsDisabled && Boolean(state.busy)}\n onSubmit={submitCurrentMethod}\n >\n {state.busy ? <LoginProgress message={state.primaryLabel ?? 'Signing in…'} onCancel={state.onCancel} /> : null}\n {showCredentialFields ? (\n <>\n <div className='passflow-form-container'>\n {defaultMethod === 'email_or_username' ? (\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label\n htmlFor='email_or_username'\n className={cn('passflow-field-label', {\n 'passflow-field-label--error': hasIdentityError || Boolean(identityError),\n })}\n >\n {currentIdentity?.label}\n </label>\n {alternateIdentity ? (\n <Button\n size='small'\n variant='clean'\n type='button'\n className='passflow-field-label-button'\n disabled={controlsDisabled}\n onClick={() => handleMethodChange(alternateIdentity.id)}\n >\n {alternateIdentity.selectLabel}\n </Button>\n ) : null}\n </div>\n <Controller\n name='email_or_username'\n control={control}\n rules={{\n required: currentIdentity?.requiredMessage ?? 'Identity is required',\n ...(currentIdentity?.format === 'email'\n ? { pattern: { value: emailRegex, message: 'Invalid email' } }\n : undefined),\n }}\n render={({ field }) => (\n <FieldText\n {...field}\n id='email_or_username'\n type={currentIdentity?.format === 'email' ? 'email' : 'text'}\n autoComplete={currentIdentity?.format === 'email' ? 'email' : 'username'}\n aria-invalid={Boolean(identityError)}\n aria-describedby={identityError ? 'email_or_username-error' : undefined}\n isError={hasIdentityError || Boolean(identityError)}\n disabled={controlsDisabled}\n />\n )}\n />\n {identityError?.message ? <LoginAlert id='email_or_username-error' message={identityError.message} /> : null}\n </div>\n ) : null}\n\n {defaultMethod === 'phone' ? (\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label\n htmlFor='phone'\n className={cn('passflow-field-label', {\n 'passflow-field-label--error': hasIdentityError || Boolean(errors.phone),\n })}\n >\n Phone number\n </label>\n {alternateIdentity ? (\n <Button\n size='small'\n variant='clean'\n type='button'\n className='passflow-field-label-button'\n disabled={controlsDisabled}\n onClick={() => handleMethodChange(alternateIdentity.id)}\n >\n {alternateIdentity.selectLabel}\n </Button>\n ) : null}\n </div>\n <Controller\n name='phone'\n control={control}\n rules={{\n required: 'Phone number is required',\n validate: (value) => phone(value).isValid || 'Invalid phone number',\n }}\n render={({ field }) => (\n <FieldPhone\n id='phone'\n name='phone'\n onChange={field.onChange}\n aria-describedby={errors.phone ? 'phone-error' : undefined}\n isError={hasIdentityError || Boolean(errors.phone)}\n disabled={controlsDisabled}\n ref={null}\n />\n )}\n />\n {errors.phone?.message ? <LoginAlert id='phone-error' message={errors.phone.message} /> : null}\n </div>\n ) : null}\n\n {hasPassword ? (\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label\n htmlFor='password'\n className={cn('passflow-field-label', {\n 'passflow-field-label--error': hasPasswordError || Boolean(errors.password),\n })}\n >\n Password\n </label>\n {state.forgotPassword ? (\n <Link\n to={state.forgotPassword.to}\n search={state.forgotPassword.getSearch?.(defaultMethod)}\n className='passflow-field-label-button'\n >\n Forgot Password?\n </Link>\n ) : null}\n </div>\n <Controller\n name='password'\n control={control}\n rules={{ required: 'Password is required', validate: validatePassword }}\n render={({ field }) => (\n <FieldPassword\n {...field}\n id='password'\n name='password'\n aria-invalid={Boolean(errors.password)}\n aria-describedby={errors.password && !isNewPassword ? 'password-error' : undefined}\n isError={hasPasswordError || Boolean(errors.password)}\n passwordPolicy={state.passwordPolicy}\n withMessages={isNewPassword}\n validationErrors={\n isNewPassword && errors.password?.message ? errors.password.message.split(', ') : undefined\n }\n autoComplete={isNewPassword ? 'new-password' : 'current-password'}\n disabled={controlsDisabled}\n />\n )}\n />\n {!isNewPassword && errors.password?.message ? (\n <LoginAlert id='password-error' message={errors.password.message} />\n ) : null}\n </div>\n ) : null}\n\n {formAlert}\n </div>\n\n <LoginActionStack>\n {hasPassword && state.onPassword ? (\n <Button\n size='big'\n variant='primary'\n type='submit'\n disabled={controlsDisabled || !isDirty || !isValid}\n className='passflow-button-signin'\n data-testid={state.primaryTestId}\n >\n {state.primaryLabel ?? 'Sign In'}\n </Button>\n ) : null}\n {hasPasswordless && state.onPasswordless ? (\n <Button\n size='big'\n variant={hasPassword ? 'outlined' : 'primary'}\n type='button'\n className={cn('passflow-button-passwordless', {\n 'passflow-button-passwordless--active': hasPassword,\n })}\n disabled={controlsDisabled || selectedIdentityValue.trim().length === 0}\n onClick={() => void submitPasswordless()}\n >\n {state.passwordlessLabelPrefix ?? 'Sign In with'} {currentIdentity?.passwordlessLabel}\n </Button>\n ) : null}\n {hasPasskey && state.onPasskey ? (\n <Button\n size='big'\n variant='dark'\n type='button'\n className='passflow-button-passkey'\n withIcon\n disabled={controlsDisabled}\n onClick={state.onPasskey}\n >\n <Icon\n id='key'\n size='small'\n type='general'\n className='passflow-button-passkey-icon'\n decorative\n matchTextColor\n />\n {state.passkeyLabel ?? 'Sign In with a Passkey'}\n </Button>\n ) : null}\n </LoginActionStack>\n </>\n ) : null}\n\n {showStandalonePasskey ? (\n <>\n {formAlert}\n {state.onPasskey ? (\n <LoginActionStack>\n <Button\n size='big'\n variant='dark'\n type='button'\n className='passflow-button-passkey'\n withIcon\n disabled={controlsDisabled}\n onClick={state.onPasskey}\n >\n <Icon\n id='key'\n size='small'\n type='general'\n className='passflow-button-passkey-icon'\n decorative\n matchTextColor\n />\n {state.passkeyLabel ?? 'Sign In with a Passkey'}\n </Button>\n </LoginActionStack>\n ) : null}\n </>\n ) : null}\n\n {state.footer ? (\n <div className={cn('passflow-form-actions', { 'passflow-form-actions--top-space': hasCredentialActions })}>\n <p className='passflow-dont-have-account'>\n {state.footer.prompt}{' '}\n <Link to={state.footer.to} search={state.footer.search} className='passflow-link'>\n {state.footer.label}\n </Link>\n </p>\n </div>\n ) : null}\n\n {methods.providers.length > 0 && state.onProvider ? (\n <div className='passflow-form-providers'>\n {hasCredentialActions ? <LoginDivider label='Or continue with' /> : null}\n <ProvidersBox providers={methods.providers} onClick={state.onProvider} />\n </div>\n ) : null}\n </form>\n </>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginAlert, LoginProgress, LoginScreenNotice } from './shared';\nimport type { LoginDeviceApprovalState } from './types';\n\nexport const LoginDeviceApproval: FC<LoginDeviceApprovalState> = ({\n appName,\n code,\n identity,\n busy = false,\n error,\n actionLabel = 'Approve this device',\n busyLabel = 'Approving…',\n testId,\n actionTestId,\n codeTestId,\n appNameTestId,\n onApprove,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <LoginScreenNotice\n code={code}\n appName={appName}\n message='requested this sign-in. Confirm that the code matches your terminal.'\n codeTestId={codeTestId}\n appNameTestId={appNameTestId}\n />\n <div className='passflow-form-container passflow-login-screen-centered'>\n <div className='passflow-login-screen-success' role='status' aria-live='polite'>\n <Icon size='small' id='check' type='general' className='icon-success' decorative />\n <p className='passflow-login-screen-text'>\n {identity ? (\n <>\n Signed in as <strong className='passflow-login-screen-app-name'>{identity}</strong>.\n </>\n ) : (\n 'Signed in successfully.'\n )}\n </p>\n </div>\n <p className='passflow-login-screen-hint'>Approve this request to finish signing in on the device.</p>\n <LoginAlert message={error} />\n </div>\n {busy ? <LoginProgress message={busyLabel} /> : null}\n <Button\n size='big'\n variant='primary'\n type='button'\n autoFocus={!busy}\n data-testid={actionTestId}\n disabled={busy}\n onClick={onApprove}\n >\n {busy ? busyLabel : actionLabel}\n </Button>\n </div>\n);\n","import type { FC } from 'react';\nimport './visually-hidden.css';\n\nexport type VisuallyHiddenProps = {\n /** Referenced by a control's `aria-labelledby` or `aria-describedby`. */\n id: string;\n /** The text read by assistive technology. Plain text only. */\n children: string;\n};\n\n/**\n * Text that screen readers announce and sighted users do not see.\n *\n * For a control whose purpose the screen already shows another way, for\n * example a row of code boxes under a \"We sent a code\" subtitle, so it still\n * has an accessible name. Prefer pointing the control at visible text when\n * the screen has some.\n */\nexport const VisuallyHidden: FC<VisuallyHiddenProps> = ({ id, children }) => (\n <span id={id} className='passflow-visually-hidden'>\n {children}\n </span>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { Button } from '../button';\nimport { FieldOtp, type FieldOtpState } from '../fields/field-otp';\nimport { VisuallyHidden } from '../visually-hidden';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginEmailCodeResend, LoginEmailCodeState } from './types';\n\nconst PROMPT_ID = 'email-code-prompt';\nconst INPUT_ID = 'email-code';\nconst ERROR_ID = 'email-code-error';\nconst RESEND_HINT_ID = 'email-code-resend-hint';\nconst DEFAULT_LENGTH = 6;\nconst DEFAULT_COOLDOWN_SECONDS = 30;\n\ntype EmailCodeResendButtonProps = LoginEmailCodeResend & {\n /** Locked by the step itself, while a verify is in flight. */\n locked: boolean;\n};\n\n/**\n * Resend, with its own cooldown. The countdown is drawn in the label but hidden\n * from assistive technology, so the name stays `Resend code` and is not re-read\n * every second. While it counts down, the button is `aria-disabled`: it keeps\n * focus after a press instead of dropping the keyboard user.\n *\n * The step remounts it (`key`) when `restartKey` changes, which restarts the\n * cooldown for a code the server sent again.\n */\nexport const EmailCodeResendButton: FC<EmailCodeResendButtonProps> = ({\n cooldownSeconds = DEFAULT_COOLDOWN_SECONDS,\n busy = false,\n label = 'Resend code',\n locked,\n onResend,\n}) => {\n const [remaining, setRemaining] = useState(cooldownSeconds);\n\n useEffect(() => {\n if (remaining <= 0) return undefined;\n const timer = setTimeout(() => setRemaining((seconds) => seconds - 1), 1000);\n return () => clearTimeout(timer);\n }, [remaining]);\n\n const coolingDown = remaining > 0;\n const unavailable = coolingDown || busy || locked;\n\n const handleResend = () => {\n if (unavailable) return;\n setRemaining(cooldownSeconds);\n onResend();\n };\n\n return (\n <>\n <Button\n size='big'\n variant='clean'\n type='button'\n aria-disabled={unavailable}\n aria-describedby={coolingDown ? RESEND_HINT_ID : undefined}\n onClick={handleResend}\n >\n {busy ? 'Sending…' : label}\n {coolingDown && !busy ? <span aria-hidden='true'>{`\\u00A0(${remaining})`}</span> : null}\n </Button>\n {coolingDown ? (\n <VisuallyHidden id={RESEND_HINT_ID}>A new code can be requested when the countdown ends.</VisuallyHidden>\n ) : null}\n </>\n );\n};\n\n/**\n * The emailed verification code step: the server's prompt names a row of code\n * boxes; six digits submit by themselves. A failed verify or a resend clears the\n * typed code. While a verify is in flight the code, Resend and the way back are\n * locked, and focus returns to the code when it ends.\n */\nexport const LoginEmailCode: FC<LoginEmailCodeState> = ({\n message,\n length = DEFAULT_LENGTH,\n error,\n busy = false,\n submitLabel = 'Verify',\n resend,\n secondaryAction,\n testId,\n onSubmit,\n}) => {\n const [code, setCode] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n const wasBusy = useRef(busy);\n\n // A verify or resend that ended with an error clears the code, so the user types\n // the next one into empty boxes. Compared during render, not in an effect, so the\n // stale code is never drawn next to the error.\n const [seenOutcome, setSeenOutcome] = useState({ busy, error });\n if (seenOutcome.busy !== busy || seenOutcome.error !== error) {\n setSeenOutcome({ busy, error });\n if (!busy && error) setCode('');\n }\n\n // A new code was sent: the old one is no longer worth keeping.\n const restartKey = resend?.restartKey;\n const [seenRestartKey, setSeenRestartKey] = useState(restartKey);\n if (seenRestartKey !== restartKey) {\n setSeenRestartKey(restartKey);\n setCode('');\n }\n\n // The locked input loses focus; give it back once the verify ends.\n useEffect(() => {\n if (wasBusy.current && !busy) inputRef.current?.focus();\n wasBusy.current = busy;\n }, [busy]);\n\n const submit = (value: string) => {\n if (busy || value.length !== length) return;\n onSubmit(value);\n };\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submit(code);\n };\n\n const fieldState: FieldOtpState = busy ? 'disabled' : error ? 'error' : 'default';\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <p id={PROMPT_ID} className='passflow-login-screen-text passflow-login-screen-centered-text'>\n {message}\n </p>\n <FieldOtp\n ref={inputRef}\n id={INPUT_ID}\n name='otp'\n length={length}\n value={code}\n onChange={setCode}\n onComplete={submit}\n charset='numeric'\n state={fieldState}\n labelledBy={PROMPT_ID}\n describedBy={error ? ERROR_ID : undefined}\n autoFocus\n />\n <LoginAlert id={ERROR_ID} message={error} />\n </div>\n {busy ? <LoginProgress message='Checking the code…' /> : null}\n <LoginActionStack>\n <Button size='big' variant='primary' type='submit' disabled={busy || code.length !== length}>\n {busy ? 'Verifying…' : submitLabel}\n </Button>\n {resend ? (\n <EmailCodeResendButton\n key={restartKey}\n {...resend}\n locked={busy}\n onResend={() => {\n setCode('');\n resend.onResend();\n }}\n />\n ) : null}\n {secondaryAction ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={secondaryAction.onClick}>\n {secondaryAction.label}\n </Button>\n ) : null}\n </LoginActionStack>\n </form>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport type { LoginGeneralErrorState } from './types';\n\nexport const LoginGeneralError: FC<LoginGeneralErrorState> = ({\n message,\n detail = 'Go back to start again.',\n actionLabel = 'Go back',\n testId,\n onAction,\n}) => (\n <div className='passflow-error-container' data-testid={testId}>\n <div className='passflow-error-container-text-wrapper' role='alert' aria-live='assertive'>\n {message ? <h1 className='passflow-error-container-text'>{message}</h1> : null}\n <p className='passflow-error-container-text-secondary'>{detail}</p>\n </div>\n <Button size='big' type='button' variant='primary' onClick={onAction} className='passflow-button-go-back-error'>\n {actionLabel}\n </Button>\n </div>\n);\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginInvitationState } from './types';\n\nexport const LoginInvitation: FC<LoginInvitationState> = ({\n identity,\n inviterName,\n busy = false,\n error,\n acceptLabel = 'Accept invitation',\n busyLabel = 'Accepting invitation…',\n switchAccountLabel = 'Switch account',\n createAccountLabel = 'Create a new account',\n testId,\n acceptTestId,\n onAccept,\n onSwitchAccount,\n onCreateAccount,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n {inviterName ? (\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n <strong className='passflow-login-screen-app-name'>{inviterName}</strong> sent this invitation.\n </p>\n ) : null}\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n {identity ? (\n <>\n You&apos;re signed in as <strong className='passflow-login-screen-app-name'>{identity}</strong>.\n </>\n ) : (\n 'You’re already signed in.'\n )}\n </p>\n <p className='passflow-login-screen-hint'>Continue with this account, or switch accounts?</p>\n <LoginAlert message={error} />\n </div>\n {busy ? <LoginProgress message={busyLabel} /> : null}\n <LoginActionStack>\n <Button\n size='big'\n variant='primary'\n type='button'\n autoFocus={!busy}\n data-testid={acceptTestId}\n disabled={busy}\n onClick={onAccept}\n >\n {busy ? busyLabel : acceptLabel}\n </Button>\n <Button size='big' variant='outlined' type='button' disabled={busy} onClick={onSwitchAccount}>\n {switchAccountLabel}\n </Button>\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={onCreateAccount}>\n {createAccountLabel}\n </Button>\n </LoginActionStack>\n </div>\n);\n","import type { FC } from 'react';\nimport { Controller, useForm } from 'react-hook-form';\nimport { cn, passwordValidation } from '@/utils';\nimport { Button } from '../button';\nimport { FieldPassword } from '../fields/field-password';\nimport { LoginAlert, LoginProgress } from './shared';\nimport type { LoginNewPasswordState } from './types';\n\ntype NewPasswordValues = { password: string };\n\nconst ERROR_ID = 'new-password-error';\nconst VALIDATION_ERROR_ID = 'new-password-validation-error';\n\n/**\n * Choosing a new password, checked against the app's password policy as it is\n * typed: for a reset, or to finish an account started by email. The field keeps\n * `id=\"password\"`, and the button the `passflow-button-reset-password` class, so an\n * app's custom CSS still finds them.\n */\nexport const LoginNewPassword: FC<LoginNewPasswordState> = ({\n passwordPolicy,\n label = 'New password',\n hint = 'Enter your new password below.',\n error,\n busy = false,\n submitLabel = 'Save new password',\n testId,\n onSubmit,\n}) => {\n const {\n control,\n handleSubmit,\n formState: { errors, isDirty, isValid },\n } = useForm<NewPasswordValues>({\n defaultValues: { password: '' },\n mode: 'onChange',\n });\n\n const validatePassword = (value: string) => {\n try {\n passwordValidation(passwordPolicy).validateSync(value);\n return true;\n } catch (validationError) {\n const { errors: messages } = validationError as { errors?: string[] };\n return messages?.join(', ') ?? 'Password does not meet the requirements';\n }\n };\n\n const submit = handleSubmit((values) => {\n if (!busy) onSubmit(values.password);\n });\n\n const validationMessage = errors.password?.message;\n // With a policy, FieldPassword lists what is missing; without one, say it in an alert.\n const showValidationAlert = !passwordPolicy && Boolean(validationMessage);\n const describedBy = [error ? ERROR_ID : null, showValidationAlert ? VALIDATION_ERROR_ID : null].filter(Boolean).join(' ');\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={submit}>\n {hint ? <p className='passflow-login-screen-hint'>{hint}</p> : null}\n <div className='passflow-form-container'>\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label htmlFor='password' className={cn('passflow-field-label', { 'passflow-field-label--error': Boolean(error) })}>\n {label}\n </label>\n </div>\n <Controller\n name='password'\n control={control}\n rules={{ required: 'Password is required', validate: validatePassword }}\n render={({ field }) => (\n <FieldPassword\n {...field}\n id='password'\n name='password'\n autoComplete='new-password'\n aria-invalid={Boolean(error) || Boolean(validationMessage)}\n aria-describedby={describedBy || undefined}\n isError={Boolean(error)}\n passwordPolicy={passwordPolicy}\n withMessages\n validationErrors={validationMessage ? validationMessage.split(', ') : undefined}\n disabled={busy}\n />\n )}\n />\n {showValidationAlert ? <LoginAlert id={VALIDATION_ERROR_ID} message={validationMessage} /> : null}\n </div>\n <LoginAlert id={ERROR_ID} message={error} />\n </div>\n {busy ? <LoginProgress message='Saving your password…' /> : null}\n <Button\n size='big'\n variant='primary'\n type='submit'\n disabled={busy || !isDirty || !isValid}\n className='passflow-button-reset-password'\n >\n {busy ? 'Saving…' : submitLabel}\n </Button>\n </form>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginAlert } from './shared';\nimport type { LoginPasskeyProgressState } from './types';\n\nexport const LoginPasskeyProgress: FC<LoginPasskeyProgressState> = ({\n working,\n message,\n actionLabel = 'Continue with a passkey',\n error,\n recoverable = false,\n retryLabel = 'Try again',\n testId,\n onAction,\n onRetry,\n}) => (\n <div className='passflow-form' data-testid={testId}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <div className='passflow-login-screen-status' role='status'>\n {working ? <div className='passflow-login-screen-spinner' aria-hidden='true' /> : null}\n <p className='passflow-login-screen-text'>{message}</p>\n </div>\n <LoginAlert message={error} />\n </div>\n {!working && onAction ? (\n <Button size='big' variant='dark' type='button' className='passflow-button-passkey' withIcon onClick={onAction}>\n <Icon id='key' size='small' type='general' className='icon-white passflow-button-passkey-icon' decorative />\n {actionLabel}\n </Button>\n ) : !working && error && recoverable && onRetry ? (\n <Button size='big' variant='dark' type='button' className='passflow-button-passkey' withIcon onClick={onRetry}>\n <Icon id='key' size='small' type='general' className='icon-white passflow-button-passkey-icon' decorative />\n {retryLabel}\n </Button>\n ) : null}\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { Button } from '../button';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginPasswordlessApprovalFormState, LoginPasswordlessApprovalState } from './types';\n\n/**\n * Approving a sign-in started on any device, in one click. The request details are shown, and the two answers are\n * equally prominent. While an answer is in flight both are locked.\n */\nconst LoginPasswordlessApprovalForm: FC<LoginPasswordlessApprovalFormState> = ({\n appName,\n browser,\n os,\n location,\n requestedAt,\n error,\n busy = false,\n testId,\n onApprove,\n onDeny,\n}) => {\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!busy) onApprove();\n };\n\n const details = [\n { label: 'Application', value: appName },\n { label: 'Browser', value: browser },\n { label: 'Operating system', value: os },\n { label: 'Location', value: location },\n { label: 'Time', value: requestedAt },\n ];\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <dl className='passflow-login-screen-details'>\n {details.map(({ label, value }) =>\n value ? (\n <div key={label} className='passflow-login-screen-details-row'>\n <dt className='passflow-login-screen-details-label'>{label}</dt>\n <dd className='passflow-login-screen-details-value'>{value}</dd>\n </div>\n ) : null,\n )}\n </dl>\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n Choose Sign in only if you just started signing in. If you didn't, choose This wasn't me.\n </p>\n <LoginAlert message={error} />\n </div>\n {busy ? <LoginProgress message='Sending your answer…' /> : null}\n <LoginActionStack>\n <Button size='big' variant='primary' type='submit' disabled={busy}>\n Sign in\n </Button>\n <Button size='big' variant='warning' type='button' disabled={busy} onClick={onDeny}>\n This wasn't me\n </Button>\n </LoginActionStack>\n </form>\n );\n};\n\nexport const LoginPasswordlessApproval: FC<LoginPasswordlessApprovalState> = (state) =>\n state.loading ? (\n <div className='passflow-form'>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <LoginProgress message='Loading the sign-in request…' />\n </div>\n </div>\n ) : (\n <LoginPasswordlessApprovalForm {...state} />\n );\n","import type { FC } from 'react';\nimport { EmailCodeResendButton } from './email-code';\nimport { LoginActionStack, LoginAlert } from './shared';\nimport type { LoginPasswordlessWaitingState } from './types';\n\nexport const LoginPasswordlessWaiting: FC<LoginPasswordlessWaitingState> = ({ error, resend, testId }) => (\n <div className='passflow-form' data-testid={testId}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <div className='passflow-login-screen-notice' role='status'>\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n Open the link we sent on any device and choose Sign in.\n </p>\n </div>\n <LoginAlert message={error} />\n </div>\n {resend ? (\n <LoginActionStack>\n <EmailCodeResendButton key={resend.restartKey} label='Resend email' {...resend} locked={false} />\n </LoginActionStack>\n ) : null}\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useState } from 'react';\nimport { Button } from '../button';\nimport { FieldText } from '../fields/field-text';\nimport { LoginAlert, LoginProgress } from './shared';\nimport type { LoginSecondFactorMethod, LoginSecondFactorState } from './types';\n\n/** The words for each factor, matching the sign-in's own two-factor screens. */\nconst METHOD_COPY: Record<LoginSecondFactorMethod, { label: string; hint: string; switchLabel: string }> = {\n totp: {\n label: 'Authenticator code',\n hint: 'Enter the code from your authenticator app.',\n switchLabel: 'Use authenticator app',\n },\n recovery_codes: {\n label: 'Recovery code',\n hint: 'Enter one of your recovery codes.',\n switchLabel: 'Use recovery code',\n },\n};\n\nexport const LoginSecondFactor: FC<LoginSecondFactorState> = ({\n methods,\n identity,\n busy = false,\n error,\n submitLabel = 'Verify',\n testId,\n onSubmit,\n onMethodChange,\n}) => {\n const [method, setMethod] = useState<LoginSecondFactorMethod>(methods[0] ?? 'totp');\n const [code, setCode] = useState('');\n const alternate = methods.find((m) => m !== method);\n const copy = METHOD_COPY[method];\n const isTOTP = method === 'totp';\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const normalizedCode = code.trim();\n if (normalizedCode) onSubmit(method, normalizedCode);\n };\n\n const switchTo = (next: LoginSecondFactorMethod) => {\n setMethod(next);\n setCode('');\n onMethodChange?.();\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container'>\n {identity ? (\n <p className='passflow-login-screen-hint'>\n Signed in as <strong className='passflow-login-screen-app-name'>{identity}</strong>.\n </p>\n ) : null}\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label htmlFor='second-factor-code' className='passflow-field-label'>\n {copy.label}\n </label>\n {alternate ? (\n <Button\n size='small'\n variant='clean'\n type='button'\n className='passflow-field-label-button'\n disabled={busy}\n onClick={() => switchTo(alternate)}\n >\n {METHOD_COPY[alternate].switchLabel}\n </Button>\n ) : null}\n </div>\n <FieldText\n id='second-factor-code'\n name={isTOTP ? 'otp' : 'recovery_code'}\n type='text'\n autoComplete={isTOTP ? 'one-time-code' : 'off'}\n autoCapitalize={isTOTP ? 'off' : 'characters'}\n autoCorrect='off'\n spellCheck={false}\n inputMode={isTOTP ? 'numeric' : 'text'}\n autoFocus\n className='passflow-login-screen-code-input'\n value={code}\n disabled={busy}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? 'second-factor-code-error' : 'second-factor-code-hint'}\n isError={Boolean(error)}\n onChange={(event) => setCode(event.target.value)}\n />\n <p id='second-factor-code-hint' className='passflow-login-screen-hint'>\n {copy.hint}\n </p>\n </div>\n <LoginAlert id='second-factor-code-error' message={error} />\n </div>\n {busy ? <LoginProgress message='Checking the code…' /> : null}\n <Button size='big' variant='primary' type='submit' disabled={busy || code.trim().length === 0}>\n {busy ? 'Checking…' : submitLabel}\n </Button>\n </form>\n );\n};\n","import type { FC, PropsWithChildren } from 'react';\nimport { cn } from '@/utils';\nimport { Icon } from '../icon';\nimport '@/styles/index.css';\nimport './login-screen.css';\n\nexport type LoginScreenShellProps = PropsWithChildren & {\n iconId?: string;\n title?: string;\n subtitle?: string;\n className?: string;\n customCss?: string;\n customLogo?: string;\n customLogoAlt?: string;\n removeBranding?: boolean;\n};\n\nexport const LoginScreenShell: FC<LoginScreenShellProps> = ({\n iconId = 'logo',\n title = '',\n subtitle = '',\n className = '',\n children,\n customCss,\n customLogo,\n customLogoAlt = 'Application logo',\n removeBranding = false,\n}) => (\n <div id='passflow-wrapper' className='passflow-wrapper'>\n {/*\n * The app's custom CSS (login theme `custom_css`), rendered inline as the\n * last layer so it overrides the kit's styles. Only when there is some.\n */}\n {customCss ? (\n <style className='psfw-custom-styles' data-passflow-style-layer='custom'>\n {customCss}\n </style>\n ) : null}\n <main className={cn('passflow-form-main-wrapper', className)}>\n <div className='passflow-form-main-container'>\n {customLogo ? (\n <img src={customLogo} alt={customLogoAlt} className='passflow-form-main-container-logo' />\n ) : (\n <Icon id={iconId} size='large' type='general' decorative />\n )}\n {title ? (\n <div className='passflow-form-header'>\n <h1 className='passflow-form-title'>{title}</h1>\n {subtitle ? <span className='passflow-form-subtitle'>{subtitle}</span> : null}\n </div>\n ) : null}\n </div>\n {children}\n </main>\n {!removeBranding ? (\n <footer className='passflow-branding'>\n <p className='passflow-branding-text'>\n Secured by <span className='passflow-branding-text-secondary passflow-secondary-font'>PASSFLOW</span>\n </p>\n </footer>\n ) : null}\n </div>\n);\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginStatusState } from './types';\n\nexport const LoginStatus: FC<LoginStatusState> = ({\n tone,\n message,\n detail,\n error,\n recoverable = false,\n retryLabel = 'Try again',\n testId,\n onRetry,\n primaryAction,\n secondaryAction,\n}) => {\n const busy = primaryAction?.busy ?? false;\n const canRetry = !primaryAction && tone === 'error' && recoverable && Boolean(onRetry);\n\n return (\n <div className='passflow-form' data-testid={testId} aria-busy={busy || undefined}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n {tone === 'working' ? (\n <LoginProgress message={message} />\n ) : tone === 'success' ? (\n <div className='passflow-login-screen-success' role='status'>\n <Icon size='small' id='check' type='general' className='icon-success' decorative />\n <span className='passflow-login-screen-success-text'>{message}</span>\n </div>\n ) : tone === 'info' ? (\n <div className='passflow-login-screen-info' role='status'>\n <Icon size='big' id='mail' type='general' className='passflow-login-screen-info-icon' matchTextColor decorative />\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>{message}</p>\n </div>\n ) : (\n <LoginAlert message={message} />\n )}\n {detail ? <p className='passflow-login-screen-hint'>{detail}</p> : null}\n <LoginAlert message={error} />\n </div>\n {primaryAction || canRetry || secondaryAction ? (\n <LoginActionStack>\n {primaryAction ? (\n <Button size='big' variant='primary' type='button' disabled={busy} onClick={primaryAction.onClick}>\n {primaryAction.label}\n </Button>\n ) : canRetry ? (\n <Button size='big' variant='primary' type='button' onClick={onRetry}>\n {retryLabel}\n </Button>\n ) : null}\n {secondaryAction ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={secondaryAction.onClick}>\n {secondaryAction.label}\n </Button>\n ) : null}\n </LoginActionStack>\n ) : null}\n </div>\n );\n};\n","import type { FC, FormEvent } from 'react';\nimport { useId } from 'react';\nimport { cn } from '@/utils';\nimport { Button } from '../button';\nimport { FieldOtp } from '../fields/field-otp';\nimport { FieldText } from '../fields/field-text';\nimport { Switch } from '../switch';\nimport { LoginActionStack, LoginAlert, useFocusAfterBusy } from './shared';\nimport type { LoginTwoFactorCodeState } from './types';\n\n/**\n * Asking for a second factor at sign-in: authenticator boxes or a recovery code field, with the trust switch above\n * them when the state offers it. The screen owns no code: a submit on the last digit belongs to the caller's\n * `onCodeChange`.\n */\nexport const LoginTwoFactorCode: FC<LoginTwoFactorCodeState> = ({\n factor,\n label,\n code,\n trustDevice,\n busy = false,\n canSubmit,\n locked = false,\n alert,\n submitLabel,\n busyLabel,\n alternate,\n secondaryAction,\n autoFocus = false,\n testId,\n onCodeChange,\n onSubmit,\n}) => {\n const inputId = useId();\n const alertId = `${inputId}-alert`;\n const inputRef = useFocusAfterBusy(busy);\n const disabled = busy || locked;\n const isError = alert?.tone === 'error';\n const describedBy = alert ? alertId : undefined;\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (canSubmit && !disabled) onSubmit();\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container'>\n {/* Above the code: the code can submit itself on its last digit. */}\n {trustDevice ? (\n <div className='passflow-form-field'>\n <Switch\n label={trustDevice.label}\n checked={trustDevice.checked}\n disabled={disabled}\n onChange={(event) => trustDevice.onChange(event.target.checked)}\n />\n </div>\n ) : null}\n {factor.type === 'totp' ? (\n <div className='passflow-verify-otp-wrapper'>\n <FieldOtp\n ref={inputRef}\n id={inputId}\n name='code'\n length={factor.digits}\n value={code}\n onChange={onCodeChange}\n state={disabled ? 'disabled' : isError ? 'error' : 'default'}\n label={label}\n describedBy={describedBy}\n autoFocus={autoFocus && !disabled}\n />\n </div>\n ) : (\n <div className='passflow-form-field'>\n <label htmlFor={inputId} className={cn('passflow-field-label', isError && 'passflow-field-label--error')}>\n {label}\n </label>\n <FieldText\n ref={inputRef}\n id={inputId}\n name='recovery_code'\n autoCapitalize='characters'\n autoComplete='off'\n autoCorrect='off'\n spellCheck={false}\n placeholder={factor.placeholder}\n className='passflow-login-screen-code-input'\n value={code}\n disabled={disabled}\n autoFocus={autoFocus && !disabled}\n aria-invalid={isError}\n aria-describedby={describedBy}\n isError={isError}\n onChange={(event) => onCodeChange(event.target.value)}\n />\n </div>\n )}\n <LoginAlert id={alertId} message={alert?.message} tone={alert?.tone} />\n </div>\n {!locked || secondaryAction ? (\n <LoginActionStack>\n {locked ? null : (\n <Button size='big' variant='primary' type='submit' disabled={busy || !canSubmit}>\n {busy ? busyLabel : submitLabel}\n </Button>\n )}\n {secondaryAction ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={secondaryAction.onClick}>\n {secondaryAction.label}\n </Button>\n ) : null}\n </LoginActionStack>\n ) : null}\n {alternate && !locked ? (\n <div className='passflow-form-actions'>\n <p className='passflow-dont-have-account'>\n {alternate.prompt}{' '}\n <Button size='small' variant='link' type='button' disabled={busy} onClick={alternate.onClick}>\n {alternate.label}\n </Button>\n </p>\n </div>\n ) : null}\n </form>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginActionStack, LoginAlert } from './shared';\nimport type { LoginTwoFactorRecoveryCodesState } from './types';\n\n/** The recovery codes, shown once. They stay on screen through a failed `onContinue`, so they are not lost. */\nexport const LoginTwoFactorRecoveryCodes: FC<LoginTwoFactorRecoveryCodesState> = ({\n warning,\n codes,\n copyLabel,\n continueLabel,\n busyLabel,\n busy = false,\n error,\n testId,\n onCopy,\n onContinue,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <div className='passflow-form-container'>\n <div className='passflow-2fa-warning' role='note'>\n <Icon size='small' id='warning' type='general' className='icon-warning' decorative />\n <span className='passflow-2fa-warning-text'>{warning}</span>\n </div>\n <ul className='passflow-2fa-recovery-codes'>\n {codes.map((code) => (\n <li key={code}>\n <code className='passflow-2fa-recovery-code'>{code}</code>\n </li>\n ))}\n </ul>\n <LoginAlert message={error} />\n </div>\n <LoginActionStack>\n <Button size='big' variant='secondary' type='button' onClick={onCopy}>\n {copyLabel}\n </Button>\n <Button size='big' variant='primary' type='button' disabled={busy} onClick={onContinue}>\n {busy ? busyLabel : continueLabel}\n </Button>\n </LoginActionStack>\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useId, useState } from 'react';\nimport { Button } from '../button';\nimport { FieldOtp } from '../fields/field-otp';\nimport { LoginActionStack, LoginAlert, useFocusAfterBusy } from './shared';\nimport type {\n LoginScreenAction,\n LoginTwoFactorSetupCodeState,\n LoginTwoFactorSetupStartState,\n LoginTwoFactorSetupState,\n} from './types';\n\nconst SecondaryAction: FC<{ action?: LoginScreenAction; busy: boolean }> = ({ action, busy }) =>\n action ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={action.onClick}>\n {action.label}\n </Button>\n ) : null;\n\nconst LoginTwoFactorSetupStart: FC<LoginTwoFactorSetupStartState> = ({\n startLabel,\n busyLabel,\n busy = false,\n error,\n secondaryAction,\n testId,\n onStart,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n {error ? (\n <div className='passflow-form-container passflow-login-screen-centered'>\n <LoginAlert message={error} />\n </div>\n ) : null}\n <LoginActionStack>\n <Button size='big' variant='primary' type='button' disabled={busy} onClick={onStart}>\n {busy ? busyLabel : startLabel}\n </Button>\n <SecondaryAction action={secondaryAction} busy={busy} />\n </LoginActionStack>\n </div>\n);\n\n/** The caller shows a new secret by passing it: `LoginTwoFactorSetup` remounts this step, so the typed code clears. */\nconst LoginTwoFactorSetupCode: FC<LoginTwoFactorSetupCodeState> = ({\n qrCode,\n qrAlt,\n secret,\n secretLabel,\n showSecretLabel,\n hideSecretLabel,\n digits,\n codeLabel,\n submitLabel,\n busyLabel,\n busy = false,\n alert,\n secondaryAction,\n testId,\n onSubmit,\n}) => {\n const [code, setCode] = useState('');\n const [secretShown, setSecretShown] = useState(false);\n const inputId = useId();\n const alertId = `${inputId}-alert`;\n const inputRef = useFocusAfterBusy(busy);\n const canSubmit = code.length === digits;\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (canSubmit && !busy) onSubmit(code);\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n {qrCode ? (\n <>\n <div className='passflow-2fa-qr-container'>\n <img src={`data:image/png;base64,${qrCode}`} alt={qrAlt} className='passflow-2fa-qr-image' />\n </div>\n <p className='passflow-login-screen-hint'>\n <Button size='small' variant='link' type='button' onClick={() => setSecretShown((shown) => !shown)}>\n {secretShown ? hideSecretLabel : showSecretLabel}\n </Button>\n </p>\n </>\n ) : null}\n {secretShown || !qrCode ? (\n <div className='passflow-2fa-secret'>\n <p className='passflow-login-screen-hint'>{secretLabel}</p>\n <code className='passflow-2fa-secret-code'>{secret}</code>\n </div>\n ) : null}\n <FieldOtp\n ref={inputRef}\n id={inputId}\n name='code'\n length={digits}\n value={code}\n onChange={setCode}\n state={busy ? 'disabled' : alert?.tone === 'error' ? 'error' : 'default'}\n label={codeLabel}\n describedBy={alert ? alertId : undefined}\n autoFocus={!busy}\n />\n <LoginAlert id={alertId} message={alert?.message} tone={alert?.tone} />\n </div>\n <LoginActionStack>\n <Button size='big' variant='primary' type='submit' disabled={busy || !canSubmit}>\n {busy ? busyLabel : submitLabel}\n </Button>\n <SecondaryAction action={secondaryAction} busy={busy} />\n </LoginActionStack>\n </form>\n );\n};\n\nexport const LoginTwoFactorSetup: FC<LoginTwoFactorSetupState> = (state) =>\n state.step === 'start' ? <LoginTwoFactorSetupStart {...state} /> : <LoginTwoFactorSetupCode key={state.secret} {...state} />;\n","import type { FC } from 'react';\nimport { LoginCodeEntry } from './code-entry';\nimport { LoginConsent } from './consent';\nimport { LoginCredentials } from './credentials';\nimport { LoginDeviceApproval } from './device-approval';\nimport { LoginEmailCode } from './email-code';\nimport { LoginGeneralError } from './general-error';\nimport { LoginInvitation } from './invitation';\nimport { LoginNewPassword } from './new-password';\nimport { LoginPasskeyProgress } from './passkey-progress';\nimport { LoginPasswordlessApproval } from './passwordless-approval';\nimport { LoginPasswordlessWaiting } from './passwordless-waiting';\nimport { LoginSecondFactor } from './second-factor';\nimport { LoginScreenShell } from './shell';\nimport { LoginStatus } from './status';\nimport { LoginTwoFactorCode } from './two-factor-code';\nimport { LoginTwoFactorRecoveryCodes } from './two-factor-recovery-codes';\nimport { LoginTwoFactorSetup } from './two-factor-setup';\nimport type { LoginScreenProps } from './types';\n\nexport const LoginScreen: FC<LoginScreenProps> = ({ chrome, state }) => {\n const content = (() => {\n switch (state.kind) {\n case 'credentials':\n return <LoginCredentials {...state} />;\n case 'code-entry':\n return <LoginCodeEntry {...state} />;\n case 'email-code':\n return <LoginEmailCode {...state} />;\n case 'passwordless-waiting':\n return <LoginPasswordlessWaiting {...state} />;\n case 'passwordless-approval':\n return <LoginPasswordlessApproval {...state} />;\n case 'new-password':\n return <LoginNewPassword {...state} />;\n case 'passkey-progress':\n return <LoginPasskeyProgress {...state} />;\n case 'device-approval':\n return <LoginDeviceApproval {...state} />;\n case 'second-factor':\n return <LoginSecondFactor {...state} />;\n case 'two-factor-code':\n return <LoginTwoFactorCode {...state} />;\n case 'two-factor-setup':\n return <LoginTwoFactorSetup {...state} />;\n case 'two-factor-recovery-codes':\n return <LoginTwoFactorRecoveryCodes {...state} />;\n case 'invitation':\n return <LoginInvitation {...state} />;\n case 'general-error':\n return <LoginGeneralError {...state} />;\n case 'consent':\n return <LoginConsent {...state} />;\n case 'status':\n return <LoginStatus {...state} />;\n }\n })();\n const isError = state.kind === 'general-error' || (state.kind === 'status' && state.tone === 'error');\n const className =\n state.kind === 'general-error'\n ? 'passflow-error-wrapper'\n : chrome.variant === 'sign-in'\n ? 'passflow-signin-wrapper'\n : chrome.variant === 'reset-password'\n ? 'passflow-reset-password-wrapper'\n : undefined;\n\n return (\n <LoginScreenShell\n iconId={isError ? 'logo-red' : 'logo'}\n title={chrome.title}\n subtitle={chrome.subtitle}\n className={className}\n customCss={chrome.customCss}\n customLogo={chrome.customLogo}\n customLogoAlt={chrome.customLogoAlt}\n removeBranding={chrome.removeBranding}\n >\n {content}\n </LoginScreenShell>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport type { UpgradeDialogFactor, UpgradeFactorType } from './types';\n\ntype UpgradeFactorListProps = {\n factors: readonly UpgradeDialogFactor[];\n selected: UpgradeFactorType;\n disabled?: boolean;\n label?: string;\n onSelect: (factor: UpgradeFactorType) => void;\n};\n\n/**\n * The \"use another way\" alternatives. Selecting one reports the user's choice;\n * it never navigates.\n *\n * Each row is `Button variant='option'`: the two-line geometry and the pressed\n * look belong to that variant in the button library, not to this list. The list\n * contributes layout only.\n */\nexport const UpgradeFactorList: FC<UpgradeFactorListProps> = ({\n factors,\n selected,\n disabled = false,\n label = 'Other verification methods',\n onSelect,\n}) => (\n <ul className='passflow-upgrade-dialog__alternatives' aria-label={label}>\n {factors.map((factor) => (\n <li key={factor.type} className='passflow-upgrade-dialog__alternative'>\n <Button\n size='big'\n variant='option'\n type='button'\n disabled={disabled}\n pressed={factor.type === selected}\n description={factor.hint}\n data-testid={`upgrade-dialog-factor-${factor.type}`}\n onClick={() => onSelect(factor.type)}\n >\n {factor.label}\n </Button>\n </li>\n ))}\n </ul>\n);\n","import { type FC, type FormEvent, useRef, useState } from 'react';\nimport { Button } from '../button';\nimport { FieldText } from '../fields/field-text';\nimport { LoginAlert } from '../login-screen';\nimport { UpgradeFactorList } from './factor-list';\nimport type { UpgradeDialogChallengeState, UpgradeFactorType } from './types';\n\nconst CODE_FIELD_ID = 'passflow-upgrade-code';\nconst CODE_ERROR_ID = 'passflow-upgrade-code-error';\n\n/**\n * The collecting view: the suggested factor, its input affordance, the\n * alternatives toggle, and the two terminal controls.\n *\n * Selection is reported through `onSelectFactor` before `onSubmit` ever fires —\n * architecture §13.2's late-join boundary is factor selection, not submission,\n * so the controller must learn of the choice while the user is still typing.\n */\nexport const UpgradeChallengeView: FC<UpgradeDialogChallengeState> = ({\n factors,\n selected,\n busy = false,\n error,\n showAlternatives = false,\n submitLabel = 'Verify',\n cancelLabel = 'Cancel',\n alternativesLabel = 'Use another way',\n testId,\n onSelectFactor,\n onToggleAlternatives,\n onSubmit,\n onCancel,\n}) => {\n const [code, setCode] = useState('');\n const reported = useRef<UpgradeFactorType | null>(null);\n\n const active = factors.find((factor) => factor.type === selected) ?? factors[0];\n // The code contract travels WITH the factor (§H12): length, charset and\n // autofill are the factor's own statement, never this component's guess. A\n // six-character cap applied to every factor truncated a 12-character recovery\n // code into a guaranteed rejection.\n const codeContract = active?.input === 'code' ? active.code : undefined;\n const needsCode = codeContract !== undefined;\n const hasAlternatives = factors.length > 1;\n\n const report = (factor: UpgradeFactorType) => {\n if (reported.current === factor) return;\n reported.current = factor;\n onSelectFactor(factor);\n };\n\n const choose = (factor: UpgradeFactorType) => {\n setCode('');\n report(factor);\n };\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!active) return;\n const trimmed = code.trim();\n if (needsCode && trimmed.length === 0) return;\n report(active.type);\n onSubmit(needsCode ? trimmed : undefined);\n };\n\n return (\n <form className='passflow-upgrade-dialog__form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit} noValidate>\n {active ? (\n <div className='passflow-upgrade-dialog__factor'>\n <span className='passflow-upgrade-dialog__factor-label'>{active.label}</span>\n {active.hint ? <span className='passflow-upgrade-dialog__factor-hint'>{active.hint}</span> : null}\n </div>\n ) : null}\n\n {codeContract ? (\n <div className='passflow-upgrade-dialog__field'>\n <label htmlFor={CODE_FIELD_ID} className='passflow-field-label'>\n Verification code\n </label>\n <FieldText\n id={CODE_FIELD_ID}\n name='upgrade_code'\n type='text'\n inputMode={codeContract.inputMode}\n autoComplete={codeContract.autoComplete}\n autoCorrect='off'\n autoCapitalize={codeContract.autoCapitalize}\n spellCheck={false}\n maxLength={codeContract.maxLength}\n value={code}\n disabled={busy}\n isError={Boolean(error)}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? CODE_ERROR_ID : undefined}\n data-testid='upgrade-dialog-code'\n onChange={(event) => setCode(event.target.value)}\n />\n </div>\n ) : null}\n\n <LoginAlert id={CODE_ERROR_ID} message={error} />\n\n <div className='passflow-upgrade-dialog__actions'>\n <Button\n size='big'\n variant='primary'\n type='submit'\n disabled={busy || !active || (needsCode && code.trim().length === 0)}\n data-testid='upgrade-dialog-submit'\n >\n {busy ? 'Verifying…' : submitLabel}\n </Button>\n {hasAlternatives ? (\n <Button\n size='big'\n variant='clean'\n type='button'\n disabled={busy}\n aria-expanded={showAlternatives}\n data-testid='upgrade-dialog-alternatives'\n onClick={onToggleAlternatives}\n >\n {alternativesLabel}\n </Button>\n ) : null}\n {showAlternatives && hasAlternatives ? (\n <UpgradeFactorList factors={factors} selected={selected} disabled={busy} onSelect={choose} />\n ) : null}\n <Button size='big' variant='clean' type='button' data-testid='upgrade-dialog-cancel' onClick={onCancel}>\n {cancelLabel}\n </Button>\n </div>\n </form>\n );\n};\n","/**\n * Pure mapping from the controller's prompt request plus local UI state to the\n * dialog's rendering union. No React, no DOM, no styling — architecture §10.2\n * classifies this as non-visual state mapping, which is why it is the one file\n * in this folder a Vitest spec may cover.\n *\n * The inputs are declared structurally — `UpgradePromptSnapshot` is the shape of\n * `UpgradePromptRequest` that the dialog actually reads — but the one judgement\n * that is NOT structural is which kind of failure an error is: that belongs to\n * `@passflow/core`, which raises the errors, and is imported from it.\n */\n\nimport { classifyUpgradeError, type UpgradeErrorKind } from '@passflow/core';\nimport type {\n AssuranceBar,\n UpgradeDialogFactor,\n UpgradeDialogState,\n UpgradeFactorCodeContract,\n UpgradeFactorInput,\n UpgradeFactorType,\n} from './types';\n\nexport type UpgradeChallengeSnapshot = {\n requiredLevel?: number;\n acrValues?: string;\n maxAge?: number;\n};\n\nexport type UpgradeFactorSnapshot = {\n type: UpgradeFactorType;\n input: UpgradeFactorInput;\n};\n\nexport type UpgradePromptSnapshot = {\n challenge: UpgradeChallengeSnapshot;\n /** Already ranked by `selectFactors`; index 0 is the suggested factor. */\n factors: readonly UpgradeFactorSnapshot[];\n previousError?: unknown;\n};\n\nexport type UpgradeDialogLabels = Partial<Record<UpgradeFactorType, { label: string; hint?: string }>>;\n\n/** How the flight ended, as the controller's outcome summary reports it (§13.4). */\nexport type UpgradeDialogOutcome =\n | { kind: 'elevated' }\n | { kind: 'insufficient'; obtained: AssuranceBar; required: AssuranceBar }\n | { kind: 'cancelled' }\n | { kind: 'failed'; error: unknown };\n\nexport type UpgradeDialogUiState = {\n selected?: UpgradeFactorType | null;\n busy?: boolean;\n showAlternatives?: boolean;\n};\n\nexport type UpgradeDialogHandlers = {\n onSelectFactor: (factor: UpgradeFactorType) => void;\n onToggleAlternatives: () => void;\n onSubmit: (code?: string) => void;\n onCancel: () => void;\n onDismiss: () => void;\n onRetry?: () => void;\n /** Sends the user to sign in again, from a state that offers it. */\n onSignIn?: () => void;\n};\n\nexport type ToDialogStateInput = {\n prompt: UpgradePromptSnapshot | null;\n outcome?: UpgradeDialogOutcome;\n ui?: UpgradeDialogUiState;\n labels?: UpgradeDialogLabels;\n handlers: UpgradeDialogHandlers;\n testId?: string;\n};\n\n/**\n * How an elevation failure reads to the user. `rejected` is the retryable\n * wrong-answer case, which keeps the dialog open on the challenge.\n */\nexport type UpgradeDialogErrorKind =\n | 'rejected'\n | 'cancelled'\n | 'exhausted'\n | 'unsatisfiable'\n | 'unavailable'\n | 'transport'\n | 'insufficient'\n | 'session-changed'\n | 'rate-limited'\n | 'sign-in-required';\n\nexport const DEFAULT_FACTOR_LABELS: Record<UpgradeFactorType, { label: string; hint?: string }> = {\n totp: { label: 'Authenticator app', hint: 'Enter the code from your authenticator app' },\n passkey: { label: 'Passkey', hint: 'Confirm with your device' },\n recovery_codes: { label: 'Recovery code', hint: 'Enter one of your single-use recovery codes' },\n email_otp: { label: 'Email code', hint: 'Enter the code we emailed you' },\n sms_otp: { label: 'SMS code', hint: 'Enter the code we texted you' },\n};\n\nconst CHALLENGE_REASON = 'This action needs extra verification';\n\n/** No factor of this account reaches the bar. A fresh sign-in would not either, so nothing offers one. */\nexport const UPGRADE_UNSATISFIABLE_DETAIL =\n \"This account can't reach the security level this app asks for. Add a passkey on this device, or contact the app.\";\n\nconst countOf = (count: number, unit: string): string => `${count} ${unit}${count === 1 ? '' : 's'}`;\n\n/**\n * A wait in seconds in the largest unit it reaches once rounded up: `90` is \"2 minutes\", and `3599`, which rounds up\n * to 60 minutes, is \"1 hour\".\n */\nconst waitDuration = (seconds: number): string => {\n if (seconds < 60) return countOf(seconds, 'second');\n const minutes = Math.ceil(seconds / 60);\n if (minutes < 60) return countOf(minutes, 'minute');\n const hours = Math.ceil(seconds / 3600);\n if (hours < 24) return countOf(hours, 'hour');\n return countOf(Math.ceil(seconds / 86400), 'day');\n};\n\n/** What the rate limit asks for: the wait, when the server named one, else its own text. */\nexport const upgradeRateLimitedMessage = (retryAfter: number | undefined, serverText: string | undefined): string =>\n retryAfter !== undefined\n ? `Too many attempts. Try again in ${waitDuration(retryAfter)}.`\n : (serverText ?? 'Too many attempts. Try again later.');\n\n/** A six-digit numeric one-time code — the two OTP transports. */\nconst OTP_CODE_CONTRACT: UpgradeFactorCodeContract = Object.freeze({\n maxLength: 6,\n inputMode: 'numeric',\n autoComplete: 'one-time-code',\n autoCapitalize: 'off',\n});\n\n/** An authenticator code: six or eight digits, so the cap is eight and a six-digit code simply types shorter. */\nconst TOTP_CODE_CONTRACT: UpgradeFactorCodeContract = Object.freeze({ ...OTP_CODE_CONTRACT, maxLength: 8 });\n\n/**\n * Per-factor code contracts, keyed by the factor type, which is the only thing\n * about a factor the protocol guarantees.\n *\n * `recovery_codes` is the reason this table exists. The server generates them\n * at `DefaultRecoveryCodeLength` (12) from a 32-character alphanumeric charset,\n * 8 codes by default, and accepts a configured length anywhere in 10..16, so the cap is the server's\n * MAXIMUM — capping at the default would reject a valid code on a deployment\n * that raised it, and capping at six (the old single hardcoded number) rejected\n * every code on every deployment. A shorter configured code simply types\n * shorter; a cap can only ever do harm by being too small.\n *\n * `null` means the factor collects nothing typed: its proof comes from the\n * ceremony, so there is no field and no contract to state.\n */\nexport const UPGRADE_FACTOR_CODE_CONTRACTS: Readonly<{\n totp: UpgradeFactorCodeContract;\n email_otp: UpgradeFactorCodeContract;\n sms_otp: UpgradeFactorCodeContract;\n recovery_codes: UpgradeFactorCodeContract;\n passkey: null;\n}> = Object.freeze({\n totp: TOTP_CODE_CONTRACT,\n email_otp: OTP_CODE_CONTRACT,\n sms_otp: OTP_CODE_CONTRACT,\n recovery_codes: Object.freeze({\n maxLength: 16,\n inputMode: 'text',\n autoComplete: 'off',\n autoCapitalize: 'characters',\n }),\n passkey: null,\n});\n\n/**\n * The contract for a factor that collects a typed answer. A `'code'` factor the\n * table has no entry for falls back to the OTP shape rather than to no cap at\n * all, so an unknown future code factor is merely sub-optimal, never broken.\n */\nconst codeContractFor = (type: UpgradeFactorType): UpgradeFactorCodeContract =>\n UPGRADE_FACTOR_CODE_CONTRACTS[type] ?? OTP_CODE_CONTRACT;\n\n/** Index 0 stays index 0: `selectFactors` already ranked the list, and ranking is not filtering. */\nexport const toDialogFactors = (\n factors: readonly UpgradeFactorSnapshot[],\n labels?: UpgradeDialogLabels,\n): UpgradeDialogFactor[] =>\n factors.map((factor) => {\n const fallback = DEFAULT_FACTOR_LABELS[factor.type];\n const override = labels?.[factor.type];\n const base = {\n type: factor.type,\n label: override?.label ?? fallback.label,\n hint: override?.hint ?? fallback.hint,\n };\n return factor.input === 'code'\n ? { ...base, input: 'code' as const, code: codeContractFor(factor.type) }\n : { ...base, input: 'none' as const };\n });\n\nconst readString = (value: unknown): string | undefined => (typeof value === 'string' && value ? value : undefined);\n\nconst readRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n\n/**\n * Every kind `@passflow/core` can classify, mapped to the panel the user sees.\n *\n * **The table routes by `kind`, never by `code`, and its totality is the\n * point.** Every classified transport failure carries the same fixed literal\n * `code === 'upgrade_transport'`, so routing by `code` would swallow the kinds\n * with their own route: a mistyped code (`wrong_code`, retryable) would land on\n * a terminal panel. Routing by `kind` through a `Record<UpgradeErrorKind, …>`\n * needs no catch-all and makes a missing route a TYPE error: a new kind added\n * to core cannot compile here until someone decides where it goes.\n *\n * `attempts_exhausted` is terminal. It is the controller's local attempt\n * budget being spent, so the challenge the server holds will never be accepted\n * again; routing it with the retryable kinds would re-prompt forever. It shares\n * the `exhausted` panel with the server's own `challenge_too_many_attempts`,\n * which settles the challenge the same way.\n */\nconst DIALOG_KIND_BY_UPGRADE_KIND: Readonly<Record<UpgradeErrorKind, UpgradeDialogErrorKind>> = Object.freeze({\n // Retryable: the user answers again, the prompt stays open (§3.3, §13.3).\n wrong_code: 'rejected',\n challenge_spent: 'rejected',\n not_registered: 'rejected',\n prepare_not_required: 'rejected',\n // Terminal.\n exhausted: 'exhausted',\n attempts_exhausted: 'exhausted',\n rate_limited: 'rate-limited',\n unavailable: 'unavailable',\n session_changed: 'session-changed',\n fatal: 'transport',\n protocol: 'transport',\n network: 'transport',\n});\n\nconst isUpgradeErrorKind = (value: string | undefined): value is UpgradeErrorKind =>\n value !== undefined && Object.hasOwn(DIALOG_KIND_BY_UPGRADE_KIND, value);\n\n/**\n * Whether the value carries enough HTTP fact for core's classifier to say\n * anything at all. Without one of these, `classifyUpgradeError` would read the\n * value as a network failure, so a stray non-protocol object would be reported\n * to the user as a transport outcome it has no evidence for.\n */\nconst hasTransportFacts = (record: Record<string, unknown>): boolean =>\n typeof record.status === 'number' || typeof record.id === 'string' || readRecord(record.response) !== undefined;\n\n/**\n * The kind, as core determines it. The dialog states no kinds of its own.\n *\n * The already-tagged `kind` is read FIRST, and that order is load-bearing:\n * `classifyUpgradeError` passes a `UpgradeTransportError` through by\n * `instanceof`, which fails across a duplicated bundle or a structured clone,\n * and re-classifying an already-classified error by its bare status re-buckets\n * a `wrong_code` 401 into `session_changed`. The string is validated against\n * the route table, so a kind core does not know still falls through to the\n * classifier.\n */\nconst upgradeKindOf = (error: unknown, record: Record<string, unknown>): UpgradeErrorKind | undefined => {\n const tagged = readString(record.kind);\n if (isUpgradeErrorKind(tagged)) return tagged;\n if (!hasTransportFacts(record)) return undefined;\n // `'refresh'` is the commit round: the dialog only ever sees a failure that\n // already travelled through a flight, and the one round-dependent id\n // (`token.invalid`) means a session change there, which is the terminal\n // reading and the safe one for an un-tagged error.\n return classifyUpgradeError(error, 'refresh').kind;\n};\n\n/**\n * How a failure reads to the user, as the dialog's own vocabulary.\n *\n * Named `dialogOutcomeFromError`, not `classifyUpgradeError`: that name belongs\n * to `@passflow/core`, and holding it here shadowed core's symbol in the\n * package's own star exports, which made the real classifier unreachable to\n * consumers. This function decides nothing about what the error IS — core's\n * classifier does — only which panel that kind is shown on.\n *\n * The dedicated error classes are matched before the kind table because they\n * are not transport failures at all: they carry no `kind`, and core's\n * classifier has nothing to say about them.\n */\nexport const dialogOutcomeFromError = (error: unknown): UpgradeDialogErrorKind => {\n const record = readRecord(error);\n if (!record) return 'rejected';\n const code = readString(record.code);\n const name = readString(record.name);\n\n if (code === 'upgrade_cancelled' || name === 'UpgradeCancelledError' || record.cancelled === true) return 'cancelled';\n if (code === 'upgrade_sign_in_required' || name === 'UpgradeSignInRequiredError') return 'sign-in-required';\n if (code === 'upgrade_unsatisfiable' || name === 'UpgradeUnsatisfiableError') return 'unsatisfiable';\n if (code === 'upgrade_unavailable' || name === 'UpgradeUnavailableError') return 'unavailable';\n if (code === 'upgrade_exhausted' || name === 'UpgradeExhaustedError') return 'exhausted';\n if (code === 'upgrade_insufficient' || name === 'UpgradeInsufficientError') return 'insufficient';\n if (code === 'upgrade_session_changed' || name === 'UpgradeSessionChangedError') return 'session-changed';\n\n const kind = upgradeKindOf(error, record);\n // Nothing identifiable: keep the prompt open rather than inventing a terminal\n // outcome. The controller's attempt budget bounds the re-prompting.\n return kind === undefined ? 'rejected' : DIALOG_KIND_BY_UPGRADE_KIND[kind];\n};\n\nexport const readAssuranceBar = (value: unknown): AssuranceBar | undefined => {\n const record = readRecord(value);\n if (!record) return undefined;\n const bar: AssuranceBar = {};\n if (typeof record.acrValues === 'string') bar.acrValues = record.acrValues;\n if (typeof record.level === 'number') bar.level = record.level;\n if (typeof record.maxAge === 'number') bar.maxAge = record.maxAge;\n return bar.acrValues === undefined && bar.level === undefined && bar.maxAge === undefined ? undefined : bar;\n};\n\n/** Human wording for a bar, on whichever axis it constrains. */\nexport const describeAssuranceBar = (bar?: AssuranceBar): string => {\n if (!bar) return 'an unknown level';\n const parts: string[] = [];\n if (bar.level !== undefined) parts.push(`AAL${bar.level}`);\n else if (bar.acrValues) parts.push(`acr ${bar.acrValues}`);\n if (bar.maxAge !== undefined) parts.push(`verified within ${bar.maxAge}s`);\n return parts.length > 0 ? parts.join(', ') : 'an unknown level';\n};\n\nconst challengeBar = (challenge: UpgradeChallengeSnapshot): AssuranceBar | undefined =>\n readAssuranceBar({\n acrValues: challenge.acrValues,\n level: challenge.requiredLevel,\n maxAge: challenge.maxAge,\n });\n\nconst errorMessage = (error: unknown, fallback: string): string => {\n const record = readRecord(error);\n return readString(record?.message) ?? fallback;\n};\n\nconst terminalFromError = (input: ToDialogStateInput, error: unknown): UpgradeDialogState => {\n const { handlers, testId } = input;\n switch (dialogOutcomeFromError(error)) {\n case 'cancelled':\n return {\n kind: 'cancelled',\n message: 'Verification cancelled',\n detail: 'The action that needed extra verification was not completed.',\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'exhausted':\n return {\n kind: 'exhausted',\n message: 'Too many attempts',\n detail: errorMessage(error, 'No attempts are left for this verification. Start the action again to retry.'),\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'unsatisfiable':\n return {\n kind: 'unsatisfiable',\n message: 'No usable verification method',\n detail: UPGRADE_UNSATISFIABLE_DETAIL,\n required: input.prompt ? challengeBar(input.prompt.challenge) : undefined,\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'rate-limited': {\n const record = readRecord(error);\n const retryAfter = typeof record?.retryAfter === 'number' ? record.retryAfter : undefined;\n return {\n kind: 'exhausted',\n message: upgradeRateLimitedMessage(retryAfter, readString(record?.message)),\n testId,\n onDismiss: handlers.onDismiss,\n };\n }\n case 'sign-in-required':\n // `UpgradeProvider` shows no dialog for it: it sends the user to sign in.\n return {\n kind: 'cancelled',\n message: 'Sign in again to continue',\n detail: 'Only a fresh sign-in can verify this action.',\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'unavailable':\n return {\n kind: 'unavailable',\n message: 'Verification is unavailable',\n detail: errorMessage(error, 'This deployment cannot raise your assurance level right now.'),\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'session-changed':\n return {\n kind: 'cancelled',\n message: 'Verification stopped',\n detail: errorMessage(error, 'Your session changed while verifying, so the request was abandoned.'),\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'insufficient': {\n const record = readRecord(error);\n return {\n kind: 'insufficient',\n message: errorMessage(error, 'Verified, but not enough for this action'),\n obtained: readAssuranceBar(record?.obtained) ?? {},\n required: readAssuranceBar(record?.required) ?? {},\n testId,\n onSignIn: handlers.onSignIn,\n onDismiss: handlers.onDismiss,\n };\n }\n default:\n return {\n kind: 'transport',\n message: 'Verification could not be completed',\n detail: errorMessage(error, 'The verification request failed before it reached the server.'),\n retryable: readRecord(error)?.retryable === true,\n testId,\n onRetry: handlers.onRetry,\n onDismiss: handlers.onDismiss,\n };\n }\n};\n\n/**\n * The single projection. A terminal `outcome` always wins over an open prompt;\n * an empty offered factor list is the `no usable factor` outcome; a `busy`\n * ceremony with no code to type is `working`; everything else is the challenge.\n */\nexport const toDialogState = (input: ToDialogStateInput): UpgradeDialogState => {\n const { prompt, outcome, ui, labels, handlers, testId } = input;\n\n if (outcome) {\n switch (outcome.kind) {\n case 'elevated':\n return {\n kind: 'success',\n message: 'Verification complete',\n detail: 'Your request is continuing.',\n testId,\n // The happy path must clear itself: §13.4's \"reports success and\n // closes\". Without this the modal's focus trap covers the app after\n // every elevation.\n onDismiss: handlers.onDismiss,\n };\n case 'insufficient':\n return {\n kind: 'insufficient',\n message: `Verified to ${describeAssuranceBar(outcome.obtained)}; this action requires ${describeAssuranceBar(outcome.required)}`,\n obtained: outcome.obtained,\n required: outcome.required,\n detail: 'The elevation succeeded but the action was challenged again. Nothing was completed.',\n testId,\n onSignIn: handlers.onSignIn,\n onDismiss: handlers.onDismiss,\n };\n case 'cancelled':\n return {\n kind: 'cancelled',\n message: 'Verification cancelled',\n detail: 'The action that needed extra verification was not completed.',\n testId,\n onDismiss: handlers.onDismiss,\n };\n default:\n return terminalFromError(input, outcome.error);\n }\n }\n\n if (!prompt) {\n return {\n kind: 'working',\n message: 'Preparing verification…',\n testId,\n onCancel: handlers.onCancel,\n };\n }\n\n const previousKind = prompt.previousError === undefined ? undefined : dialogOutcomeFromError(prompt.previousError);\n if (previousKind !== undefined && previousKind !== 'rejected') {\n return terminalFromError(input, prompt.previousError);\n }\n\n const factors = toDialogFactors(prompt.factors, labels);\n const required = challengeBar(prompt.challenge);\n const suggested = factors[0];\n\n if (suggested === undefined) {\n return {\n kind: 'unsatisfiable',\n message: 'No usable verification method',\n detail: UPGRADE_UNSATISFIABLE_DETAIL,\n required,\n testId,\n onDismiss: handlers.onDismiss,\n };\n }\n\n const selected = factors.find((factor) => factor.type === ui?.selected)?.type ?? suggested.type;\n const active = factors.find((factor) => factor.type === selected);\n const busy = ui?.busy === true;\n\n if (busy && active?.input === 'none') {\n return {\n kind: 'working',\n message: 'Waiting for your passkey…',\n detail: 'Follow the prompt from your device to confirm it is you.',\n testId,\n onCancel: handlers.onCancel,\n };\n }\n\n return {\n kind: 'challenge',\n factors,\n selected,\n reason: CHALLENGE_REASON,\n busy,\n error: previousKind === 'rejected' ? errorMessage(prompt.previousError, 'That code was not accepted. Try again.') : null,\n showAlternatives: ui?.showAlternatives === true,\n testId,\n onSelectFactor: handlers.onSelectFactor,\n onToggleAlternatives: handlers.onToggleAlternatives,\n onSubmit: handlers.onSubmit,\n onCancel: handlers.onCancel,\n };\n};\n\n/**\n * What Escape and an overlay click mean in each state. Cancellation must reach\n * the controller or the caller's promise hangs (§8.1), so this is never a bare\n * close; `success` has nothing to cancel, so it closes instead of cancelling —\n * returning `undefined` there made Escape and the overlay inert on the one\n * state every user reaches.\n */\nexport const upgradeDialogDismissHandler = (state: UpgradeDialogState): (() => void) | undefined => {\n switch (state.kind) {\n case 'challenge':\n return state.onCancel;\n case 'working':\n return state.onCancel;\n default:\n return state.onDismiss;\n }\n};\n","import type { FC } from 'react';\nimport { cn } from '@/utils';\nimport './spinner.css';\n\nexport type SpinnerSize = 'small' | 'medium';\n\nexport type SpinnerProps = {\n /** `small` sits inline beside a line of text; `medium` stands alone. */\n size?: SpinnerSize;\n /**\n * The accessible name. Omit it when a sibling already announces the busy\n * state — the ring is then decorative and hidden from assistive technology,\n * which is what a status region with its own live text wants.\n */\n label?: string;\n};\n\n/**\n * The indeterminate activity ring.\n *\n * It exists as a primitive so its diameter and stroke live in one place rather\n * than in each consuming component's stylesheet. The upgrade dialog uses it;\n * the login screen still draws its own identical ring in\n * `login-screen.css` and should be migrated onto this when that file is next\n * touched.\n */\nexport const Spinner: FC<SpinnerProps> = ({ size = 'medium', label }) => (\n <span\n className={cn('passflow-spinner', { 'passflow-spinner--small': size === 'small' })}\n role={label === undefined ? undefined : 'status'}\n aria-label={label}\n aria-hidden={label === undefined ? true : undefined}\n />\n);\n","import { type FC, useEffect } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { Spinner } from '../spinner';\nimport { describeAssuranceBar } from './state-mapping';\nimport type { AssuranceBar, UpgradeDialogState } from './types';\n\n/** Every state that is not the collecting challenge. */\nexport type UpgradeStatusState = Exclude<UpgradeDialogState, { kind: 'challenge' }>;\n\ntype Tone = 'working' | 'success' | 'problem' | 'neutral';\n\nconst TONE: Record<UpgradeStatusState['kind'], Tone> = {\n working: 'working',\n success: 'success',\n insufficient: 'problem',\n unsatisfiable: 'problem',\n unavailable: 'problem',\n exhausted: 'problem',\n transport: 'problem',\n cancelled: 'neutral',\n};\n\n/**\n * How long `success` stays on screen before it closes itself (§13.4: \"reports\n * success and closes\"). Long enough to be read, short enough that the app is\n * never held behind a modal the user cannot see a reason for.\n */\nexport const UPGRADE_SUCCESS_AUTO_CLOSE_MS = 1800;\n\nconst BarRow: FC<{ term: string; bar: AssuranceBar }> = ({ term, bar }) => (\n <div className='passflow-upgrade-dialog__bar'>\n <span className='passflow-upgrade-dialog__bar-term'>{term}</span>\n <span className='passflow-upgrade-dialog__bar-value'>{describeAssuranceBar(bar)}</span>\n </div>\n);\n\n/**\n * The non-collecting views: `working`, `success` and the six terminal outcomes\n * of §13.3's settlement table.\n *\n * `insufficient` is deliberately rendered in the problem tone with both bars\n * shown: the elevation succeeded and the action still did not, and the dialog\n * must not report success when the replay was re-challenged (§13.4).\n *\n * `success` owns its own exit: a Done control and an auto-close timer, both\n * calling the state's `onDismiss`. The affordance lives here rather than in the\n * provider because a modal that cannot be closed is a property of this\n * component, and the Storybook story for the state has to show the way out.\n */\nexport const UpgradeStatus: FC<UpgradeStatusState> = (state) => {\n const tone = TONE[state.kind];\n const { detail } = state;\n\n const autoClose = state.kind === 'success' ? (state.autoCloseMs ?? UPGRADE_SUCCESS_AUTO_CLOSE_MS) : 0;\n const autoDismiss = state.kind === 'success' ? state.onDismiss : undefined;\n\n useEffect(() => {\n if (autoDismiss === undefined || autoClose <= 0) return;\n const timer = setTimeout(autoDismiss, autoClose);\n return () => clearTimeout(timer);\n }, [autoClose, autoDismiss]);\n\n return (\n <div className='passflow-upgrade-dialog__status' data-testid={state.testId} data-upgrade-state={state.kind}>\n <div\n className={`passflow-upgrade-dialog__status-head passflow-upgrade-dialog__status-head--${tone}`}\n role={tone === 'problem' ? 'alert' : 'status'}\n aria-live={tone === 'problem' ? 'assertive' : 'polite'}\n >\n {tone === 'working' ? <Spinner size='small' /> : null}\n {tone === 'success' ? <Icon size='small' id='check' type='general' className='icon-success' decorative /> : null}\n {tone === 'problem' ? <Icon size='small' id='warning' type='general' className='icon-warning' decorative /> : null}\n <span className='passflow-upgrade-dialog__status-message'>{state.message}</span>\n </div>\n\n {detail ? <p className='passflow-upgrade-dialog__status-detail'>{detail}</p> : null}\n\n {state.kind === 'insufficient' ? (\n <div className='passflow-upgrade-dialog__bars' data-testid='upgrade-dialog-bars'>\n <BarRow term='Verified' bar={state.obtained} />\n <BarRow term='Required' bar={state.required} />\n </div>\n ) : null}\n\n {state.kind === 'unsatisfiable' && state.required ? (\n <div className='passflow-upgrade-dialog__bars' data-testid='upgrade-dialog-bars'>\n <BarRow term='Required' bar={state.required} />\n </div>\n ) : null}\n\n <div className='passflow-upgrade-dialog__actions'>\n {state.kind === 'insufficient' && state.onSignIn ? (\n <Button size='big' variant='primary' type='button' data-testid='upgrade-dialog-sign-in' onClick={state.onSignIn}>\n {state.signInLabel ?? 'Sign in again'}\n </Button>\n ) : null}\n {state.kind === 'transport' && state.retryable && state.onRetry ? (\n <Button size='big' variant='primary' type='button' data-testid='upgrade-dialog-retry' onClick={state.onRetry}>\n {state.retryLabel ?? 'Try again'}\n </Button>\n ) : null}\n {state.kind === 'working' && state.onCancel ? (\n <Button size='big' variant='clean' type='button' data-testid='upgrade-dialog-cancel' onClick={state.onCancel}>\n Cancel\n </Button>\n ) : null}\n {state.kind !== 'working' ? (\n <Button size='big' variant='clean' type='button' data-testid='upgrade-dialog-dismiss' onClick={state.onDismiss}>\n {state.dismissLabel ?? (state.kind === 'success' ? 'Done' : 'Close')}\n </Button>\n ) : null}\n </div>\n </div>\n );\n};\n","import type { FC } from 'react';\nimport { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../dialog';\nimport { UpgradeChallengeView } from './challenge';\nimport { upgradeDialogDismissHandler } from './state-mapping';\nimport { UpgradeStatus } from './status';\nimport type { UpgradeDialogProps } from './types';\nimport './upgrade-dialog.css';\n\nconst DESCRIPTION_ID = 'passflow-upgrade-dialog-description';\n\n/**\n * The assurance-upgrade modal. A switch over `state.kind`, modelled on\n * `LoginScreen`: one discriminated union, one view per state, no transitions of\n * its own.\n *\n * Escape and an overlay click route to the state's cancel or dismiss callback,\n * never to a bare close — cancellation must reach the controller or the\n * caller's promise never settles (§8.1).\n */\nexport const UpgradeDialog: FC<UpgradeDialogProps> = ({ open, title = 'Extra verification required', state }) => {\n const dismiss = upgradeDialogDismissHandler(state);\n const description = state.kind === 'challenge' ? state.reason : undefined;\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) dismiss?.();\n }}\n >\n <DialogContent\n className='passflow-upgrade-dialog'\n data-testid='upgrade-dialog'\n aria-describedby={description ? DESCRIPTION_ID : undefined}\n >\n <DialogHeader className='passflow-upgrade-dialog__header'>\n <DialogTitle>{title}</DialogTitle>\n {description ? <DialogDescription id={DESCRIPTION_ID}>{description}</DialogDescription> : null}\n </DialogHeader>\n {state.kind === 'challenge' ? <UpgradeChallengeView {...state} /> : <UpgradeStatus {...state} />}\n </DialogContent>\n </Dialog>\n );\n};\n","/**\n * `UpgradeProvider` — the React side of the assurance-upgrade flow (§8.3).\n *\n * It owns the controller (through `passflow.upgrade`, or the `facade` it is\n * given), bridges the\n * promise-returning `UpgradePromptHandler` to React state, and mounts the\n * dialog from `src/components/ui/upgrade-dialog`. It selects a state and maps\n * domain data onto that component's props; it renders no UI of its own and\n * styles nothing, per the project's component-library boundary.\n *\n * Three properties fall out of the shipped controller, and they are why this\n * is small:\n *\n * 1. **The wrong-code loop needs no plumbing.** The controller catches the\n * recoverable failure, sets `previousError` and calls `prompt()` again, so\n * the provider simply receives a new request and the dialog re-renders with\n * the error, still open.\n * 2. **Attempt budgeting needs no plumbing.** `maxAttempts` bounds the loop in\n * the controller and then fails the flight, which arrives here as the\n * `exhausted` terminal state.\n * 3. **Passkey has no code field.** `factors[i].input === 'none'` submits with\n * no code and the dialog shows `working` while the platform authenticator\n * runs.\n *\n * **The anti-leak rule is the single most important line in this file.** On\n * unmount, on teardown and on a session change, the pending prompt is resolved\n * `{ type: 'cancel' }`. A dangling `resolve` is an Observer leak wearing a\n * promise: the controller awaits forever, the elevation never settles, and\n * every request that joined the single flight hangs.\n *\n * **The session-change reset.** A challenge is server-bound to the session, so\n * an abandoned flight must never elevate a NEW session. The core discards its\n * controller on `SignIn` / `SignOut`; this provider discards its view of it in\n * the same breath, and the waiter that was mid-flight settles as\n * `session changed`, which the hook reports as `idle` — nothing that did not\n * happen is reported as though it had. The hosted step-up\n * (`passflow.hostedUpgrade`) is bound to the hosted session cookie instead, so\n * the instance's `SignIn` / `SignOut` leave its prompt open.\n */\n\nimport {\n type AssuranceBar,\n PassflowEvent,\n type PassflowSubscriber,\n type ReplayPolicy,\n requiredAcrLevel,\n type UpgradeChallenge,\n type UpgradeDiagnosticSink,\n type UpgradeFacade,\n type UpgradeFactor,\n type UpgradeFactorType,\n type UpgradeFlightSummary,\n type UpgradePromptHandler,\n type UpgradePromptResult,\n type UpgradeReplayInfo,\n type Waiter,\n} from '@passflow/core';\nimport { type FC, type ReactElement, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { UpgradeDialogLabels, UpgradeDialogOutcome, UpgradeDialogProps } from '@/components/ui/upgrade-dialog';\nimport { dialogOutcomeFromError, readAssuranceBar, toDialogState, UpgradeDialog } from '@/components/ui/upgrade-dialog';\nimport {\n UpgradeContext,\n type UpgradeContextValue,\n type UpgradeElevateOptions,\n type UpgradeErrorStatusKind,\n type UpgradeHookState,\n type UpgradePromptView,\n type UpgradeSettledState,\n} from '@/context/upgrade-context';\nimport { useIsomorphicLayoutEffect } from '@/hooks/use-isomorphic-layout-effect';\nimport { usePassflow } from '@/hooks/use-passflow';\nimport { registerUpgradeAuthInstance, upgradeAuthInstance } from '@/utils/upgrade-auth';\n\nexport type UpgradeProviderProps = {\n children?: ReactNode;\n /** Default `true`. `false` installs nothing and leaves the hook inert. */\n enabled?: boolean;\n /**\n * The upgrade facade to install and elevate through. Defaults to\n * `passflow.upgrade`. The hosted login passes `passflow.hostedUpgrade`, which\n * proves factors against the hosted session cookie instead of stored tokens.\n */\n facade?: UpgradeFacade;\n /**\n * Where the customer's own API is — domain 2 (§13.5). Nothing outside this\n * and Passflow's own API is ever observed, and there is no allow-all opt-in.\n */\n backend?: string | string[];\n /**\n * Patches `globalThis.fetch` through the core's registry. **Off by default**,\n * and a different decision from enabling the UI: one prop for both would\n * bundle \"show me the verification prompt\" with \"patch the global\", and only\n * the second has the blast radius.\n */\n interceptFetch?: boolean;\n /** Requires the RFC 9470 channel. The body is then never read for a challenge. */\n requireChallengeChannel?: 'header';\n /** NARROWING ONLY: `false` excludes an admitted URL; `true` cannot widen. */\n shouldIntercept?: (url: string) => boolean;\n replay?: ReplayPolicy;\n /** The fetch surface's only cancellation option. Default `'resolve-original'`. */\n onCancel?: 'resolve-original' | 'reject';\n onUpgradeDiagnostic?: UpgradeDiagnosticSink;\n factors?: readonly UpgradeFactor[];\n maxAttempts?: number;\n relyingPartyId?: string;\n /** Per-factor wording for the dialog. */\n labels?: UpgradeDialogLabels;\n title?: string;\n /**\n * Where a step-up that only a fresh sign-in can meet sends the user, and the \"Sign in again\" action of an\n * insufficient one. Called once, with the dialog closed; nothing is retried. Default: `passflow.authRedirect()`.\n */\n onSignInRequired?: () => void;\n /**\n * Who shows how a failed step-up ended. `'dialog'` (default): the dialog's own panels, and sign-in required calls\n * `onSignInRequired`. `'caller'`: the dialog closes and the caller of `elevate` shows it from the rejection, as the\n * hosted login page does.\n */\n failures?: 'dialog' | 'caller';\n /**\n * FR5's render-prop override. It receives the **exact** props the built-in\n * dialog would render — a typed, constrained override with no `className` or\n * `style` leak.\n *\n * It carries the same obligations as the built-in dialog, the selection\n * signal included: the `challenge` state's `onSelectFactor` must be called\n * when the user picks a factor, because that is the only thing that reports\n * §13.2's selection boundary to the controller. An override that never calls\n * it leaves the controller `collecting` for the whole ceremony, so a late\n * join re-ranks mid-entry — degraded, not silent.\n */\n renderDialog?: (props: UpgradeDialogProps) => ReactElement | null;\n};\n\ntype PendingResolve = ((result: UpgradePromptResult) => void) | undefined;\n\n/** §13.3's settlement table, hook column, for a flight that produced no proof. */\nconst errorStateOf = (error: Error): UpgradeSettledState => {\n switch (dialogOutcomeFromError(error)) {\n case 'cancelled':\n case 'session-changed':\n // Cancellation is not a status (§13.3): it is `elevate()` resolving null.\n return { status: 'idle' };\n case 'insufficient':\n return {\n status: 'insufficient',\n obtained: readAssuranceBar((error as { obtained?: unknown }).obtained) ?? {},\n required: readAssuranceBar((error as { required?: unknown }).required) ?? {},\n };\n case 'exhausted':\n return { status: 'error', kind: 'exhausted', error };\n case 'unsatisfiable':\n return { status: 'error', kind: 'unsatisfiable', error };\n case 'unavailable':\n return { status: 'error', kind: 'unavailable', error };\n case 'rate-limited':\n return { status: 'error', kind: 'rate_limited', error };\n case 'sign-in-required':\n return { status: 'error', kind: 'sign_in_required', error };\n default:\n return { status: 'error', kind: 'transport' satisfies UpgradeErrorStatusKind, error };\n }\n};\n\nconst summaryError = (summary: UpgradeFlightSummary): Error =>\n summary.error ??\n (summary.proof.status === 'failed' ? summary.proof.reason : undefined) ??\n new Error('The verification flight failed without reporting a reason.');\n\n/** One terminal state per flight, taken from the controller's summary (§13.4). */\nconst summaryToState = (summary: UpgradeFlightSummary): UpgradeSettledState => {\n if (summary.terminal === 'success') return { status: 'success' };\n if (summary.terminal === 'insufficient') {\n return {\n status: 'insufficient',\n obtained: summary.insufficient?.obtained ?? {},\n required: summary.insufficient?.required ?? {},\n };\n }\n return errorStateOf(summaryError(summary));\n};\n\nconst summaryToOutcome = (summary: UpgradeFlightSummary): UpgradeDialogOutcome => {\n if (summary.terminal === 'success') return { kind: 'elevated' };\n if (summary.terminal === 'insufficient') {\n return {\n kind: 'insufficient',\n obtained: summary.insufficient?.obtained ?? {},\n required: summary.insufficient?.required ?? {},\n };\n }\n return { kind: 'failed', error: summaryError(summary) };\n};\n\nconst asError = (value: unknown): Error => (value instanceof Error ? value : new Error(String(value)));\n\nconst statedBar = (options?: UpgradeElevateOptions): AssuranceBar | undefined => {\n if (options === undefined) return undefined;\n const bar = readAssuranceBar({\n acrValues: options.acrValues,\n level: requiredAcrLevel(options.acrValues),\n maxAge: options.maxAge,\n });\n return bar;\n};\n\n/**\n * The imperative seam's challenge. A caller asking for a bar states it here;\n * the parsing of `acrValues` is the core's `requiredAcrLevel`, never a second\n * reading of the ACR list.\n */\nconst imperativeChallenge = (options?: UpgradeElevateOptions): UpgradeChallenge => ({\n acrValues: options?.acrValues,\n requiredLevel: requiredAcrLevel(options?.acrValues),\n maxAge: options?.maxAge,\n status: 403,\n channels: [],\n});\n\n/**\n * Value identity for `factors`, so a fresh array literal with the same factors\n * does not tear down and reinstall the interceptors (H13).\n *\n * The factor TYPE is the identity: everything else on an `UpgradeFactor` is the\n * `assert` implementation, and the registry is keyed by type. A caller who\n * swaps one type's implementation for another keeps the installed one until the\n * type list itself changes — the same trade the `backend` join already makes,\n * and the alternative is an unconditional reinstall on every render.\n */\nconst factorsSignature = (factors?: readonly UpgradeFactor[]): string =>\n factors === undefined ? '\\u0000default' : factors.map((factor) => factor.type).join('\\u0000');\n\n/**\n * Value identity for `replay` (H13). The policy is a union, so each arm gets\n * its own comparable signature:\n *\n * - a mode string compares as itself;\n * - a limits object compares by its two fields;\n * - a PREDICATE compares as the constant `fn`, because a function's identity is\n * never stable across renders. The current closure is reached through a ref\n * and called by a stable proxy, which is the same pattern `shouldIntercept`\n * and `onUpgradeDiagnostic` already use here.\n */\nconst replaySignature = (replay?: ReplayPolicy): string => {\n if (replay === undefined) return 'none';\n if (typeof replay === 'string') return `mode:${replay}`;\n if (typeof replay === 'function') return 'fn';\n return `limits:${replay.maxBodyBytes ?? ''}:${replay.allowStreamingBody ?? ''}`;\n};\n\nexport const UpgradeProvider: FC<UpgradeProviderProps> = ({\n children,\n enabled = true,\n facade,\n backend,\n interceptFetch = false,\n requireChallengeChannel,\n shouldIntercept,\n replay,\n onCancel,\n onUpgradeDiagnostic,\n factors,\n maxAttempts,\n relyingPartyId,\n labels,\n title,\n onSignInRequired,\n failures = 'dialog',\n renderDialog,\n}) => {\n const passflow = usePassflow();\n const upgradeFacade = facade ?? passflow.upgrade;\n\n const [prompt, setPrompt] = useState<UpgradePromptView | null>(null);\n const [state, setState] = useState<UpgradeHookState>({ status: 'idle' });\n const [selectedFactor, setSelectedFactor] = useState<UpgradeFactorType | null>(null);\n const [busy, setBusy] = useState(false);\n const [showAlternatives, setShowAlternatives] = useState(false);\n const [outcome, setOutcome] = useState<UpgradeDialogOutcome | undefined>(undefined);\n const [installed, setInstalled] = useState(false);\n\n /** The open prompt's resolver. Cleared the instant it is used — H3's \"once\". */\n const resolveRef = useRef<PendingResolve>(undefined);\n /** The open request, so the selection signal reaches the controller. */\n const requestRef = useRef<Parameters<UpgradePromptHandler>[0] | null>(null);\n /** Whether this prompt already reported a selection (§13.2 T3 fires once). */\n const reportedSelectionRef = useRef(false);\n /** Set by `cancel()`: the user closed the dialog, so no terminal panel is shown. */\n const userCancelledRef = useRef(false);\n /**\n * H11 — cancellation is STICKY for the rest of the flight.\n *\n * After a submit the prompt's resolver is already spent, so `cancel()` has\n * nothing to answer and the cancellation was simply lost: the flight ran on,\n * and the controller re-prompted the user it had just been told to stop\n * asking. The intent is recorded here and answered at the first boundary the\n * controller offers — its next `prompt()` call — which settles the flight as\n * `UpgradeCancelledError` and so puts every surface on §13.3's asymmetric\n * contract (fetch resolves the untouched 401/403, axios and the imperative\n * seam reject, `useUpgrade().elevate` resolves `null`). Cleared when the\n * flight settles, so it can never leak into the next one.\n *\n * It cannot abort a request already on the wire: the core exposes no abort\n * channel for a round in progress, and inventing one here would be a second\n * lifecycle authority beside the controller (§13.2).\n */\n const cancelRequestedRef = useRef(false);\n\n // Callback props are read through refs so that re-rendering with a new inline\n // closure never tears down and reinstalls the interceptors.\n const shouldInterceptRef = useRef(shouldIntercept);\n const diagnosticRef = useRef(onUpgradeDiagnostic);\n shouldInterceptRef.current = shouldIntercept;\n diagnosticRef.current = onUpgradeDiagnostic;\n\n const signInRef = useRef<() => void>(() => undefined);\n signInRef.current = onSignInRequired ?? (() => void passflow.authRedirect().catch(() => undefined));\n const failuresRef = useRef(failures);\n failuresRef.current = failures;\n\n // H13: `factors` and `replay` are compared by VALUE in the install effect's\n // dependencies (see `factorsSignature` / `replaySignature`) and read through\n // these refs, so an inline array or an inline predicate no longer reinstalls\n // the interceptors on every render. `onCancel` needs neither: it is a string\n // union, so it already compares by value.\n const factorsRef = useRef(factors);\n const replayRef = useRef(replay);\n factorsRef.current = factors;\n replayRef.current = replay;\n\n /**\n * The stable stand-in for a caller-supplied replay PREDICATE. The non-function\n * arms are passed through untouched; this is only ever installed when the\n * policy is a function, and a change of arm changes the signature and\n * reinstalls, which is why the fallback is unreachable rather than a decision.\n */\n const replayPredicate = useCallback((info: UpgradeReplayInfo): boolean => {\n const policy = replayRef.current;\n return typeof policy === 'function' ? policy(info) : true;\n }, []);\n\n /** Resolves a pending prompt exactly once. The anti-leak primitive. */\n const settlePrompt = useCallback((result: UpgradePromptResult): boolean => {\n const resolve = resolveRef.current;\n if (resolve === undefined) return false;\n resolveRef.current = undefined;\n resolve(result);\n return true;\n }, []);\n\n const clearPromptView = useCallback(() => {\n requestRef.current = null;\n reportedSelectionRef.current = false;\n setPrompt(null);\n setSelectedFactor(null);\n setShowAlternatives(false);\n setBusy(false);\n }, []);\n\n const promptHandler = useCallback<UpgradePromptHandler>(\n (request) =>\n new Promise<UpgradePromptResult>((resolve) => {\n // H11: the user cancelled after submitting and the controller came back\n // for another answer. Answer the cancellation instead of re-opening a\n // dialog they already closed.\n if (cancelRequestedRef.current) {\n resolve({ type: 'cancel' });\n return;\n }\n\n // Branch 2's channel (§13.2 T2): the controller pushes a raised bar and\n // a re-ranked list into the OPEN prompt, which updates without\n // resolving. Subscribed synchronously, before anything is awaited.\n request.onRequirementRaised = (next) => {\n setPrompt({ challenge: next.challenge, factors: next.factors, previousError: request.previousError });\n setState({ status: 'challenged', challenge: next.challenge, factors: next.factors.map((f) => f.type) });\n };\n\n resolveRef.current = resolve;\n requestRef.current = request;\n reportedSelectionRef.current = false;\n userCancelledRef.current = false;\n setOutcome(undefined);\n setSelectedFactor(null);\n setShowAlternatives(false);\n setBusy(false);\n setPrompt({ challenge: request.challenge, factors: request.factors, previousError: request.previousError });\n setState({\n status: 'challenged',\n challenge: request.challenge,\n factors: request.factors.map((factor) => factor.type),\n });\n }),\n [],\n );\n\n const handleFlightSettled = useCallback(\n (summary: UpgradeFlightSummary) => {\n cancelRequestedRef.current = false;\n setState(summaryToState(summary));\n clearPromptView();\n const signInRequired =\n summary.terminal === 'failed' && dialogOutcomeFromError(summaryError(summary)) === 'sign-in-required';\n // Cleared here as well as when a prompt opens: a flight can settle without ever prompting, and a cancel from an\n // earlier flight must not hide its outcome.\n const userCancelled = userCancelledRef.current;\n userCancelledRef.current = false;\n if (userCancelled || (failuresRef.current === 'caller' && summary.terminal !== 'success')) {\n setOutcome(undefined);\n } else if (signInRequired) {\n setOutcome(undefined);\n signInRef.current();\n } else {\n setOutcome(summaryToOutcome(summary));\n }\n },\n [clearPromptView],\n );\n\n // A layout effect, so the facade is enabled in the commit that brings it. The hosted login elevates through the\n // facade from an awaited network answer, which can run between a commit and its passive effects; a facade that is\n // not enabled yet rejects that elevation as unavailable.\n useIsomorphicLayoutEffect(() => {\n if (!enabled) {\n setInstalled(false);\n return;\n }\n\n const teardown = upgradeFacade.enable({\n prompt: promptHandler,\n backend,\n interceptFetch,\n requireChallengeChannel,\n shouldIntercept: shouldIntercept === undefined ? undefined : (url) => shouldInterceptRef.current?.(url) !== false,\n replay: typeof replayRef.current === 'function' ? replayPredicate : replayRef.current,\n onCancel,\n onUpgradeDiagnostic: onUpgradeDiagnostic === undefined ? undefined : (d) => diagnosticRef.current?.(d),\n factors: factorsRef.current,\n maxAttempts,\n relyingPartyId,\n onFlightSettled: handleFlightSettled,\n });\n setInstalled(true);\n\n return () => {\n // The anti-leak rule: never leave the controller awaiting an answer.\n settlePrompt({ type: 'cancel' });\n teardown();\n setInstalled(false);\n };\n // `backend` is compared by value so a fresh array literal does not reinstall.\n }, [\n upgradeFacade,\n enabled,\n Array.isArray(backend) ? backend.join('\\u0000') : backend,\n interceptFetch,\n requireChallengeChannel,\n shouldIntercept === undefined,\n onUpgradeDiagnostic === undefined,\n // H13: compared by value, never by identity — an inline policy object, an\n // inline predicate or a fresh factor array must not reinstall.\n replaySignature(replay),\n replayPredicate,\n onCancel,\n factorsSignature(factors),\n maxAttempts,\n relyingPartyId,\n promptHandler,\n handleFlightSettled,\n settlePrompt,\n ]);\n\n /**\n * Publishes this provider's instance to the free-function adapters, twice,\n * for two different reasons — and both are load-bearing.\n *\n * **The render-phase write** exists because React runs a child's effects\n * before the parent's in the same commit, so the documented\n * `useEffect(() => attachAuth(api), [])` in a child would otherwise reach\n * `requireInstance` with nothing registered and throw — and a throw inside an\n * effect unmounts the tree. Publishing in render makes attach order\n * irrelevant. It is guarded and idempotent, so a re-render or a discarded\n * Strict-Mode render changes nothing.\n *\n * **The effect re-registers and releases through the same call**, so the pair\n * is symmetric: `registerUpgradeAuthInstance` returns the release for its own\n * registration, and that release is deferred by a microtask and cancelled by\n * any registration in the meantime (see `utils/upgrade-auth`). React Strict\n * Mode mounts, unmounts and remounts effects in development, and a cleanup\n * that released immediately would leave the registry empty for the remount —\n * render does not run again, and the child-before-parent effect order holds\n * on the remount pass as well, so the re-registration here cannot be early\n * enough on its own. Measured, not assumed: with an immediate release the\n * remounting child's `attachAuth` throws.\n *\n * A ref cannot be the publication channel, which is why this is not the ref\n * shape: the free functions are bare module imports called by code that never\n * sees this component's context or refs, so the module-level registry is the\n * only channel children can read.\n */\n if (upgradeAuthInstance() !== passflow) registerUpgradeAuthInstance(passflow);\n useEffect(() => registerUpgradeAuthInstance(passflow), [passflow]);\n\n /**\n * The session-change reset. The core discards its controller here; the view\n * of it must go with it, or a dialog from the old session would collect an\n * answer that can only elevate the new one.\n *\n * Not for the hosted step-up: it elevates the hosted session cookie, which a\n * sign-in or sign-out of the instance's stored tokens leaves as it was.\n */\n const elevatesHostedSession = upgradeFacade === passflow.hostedUpgrade;\n useEffect(() => {\n if (elevatesHostedSession) return;\n const subscriber: PassflowSubscriber = {\n onAuthChange: () => {\n cancelRequestedRef.current = false;\n settlePrompt({ type: 'cancel' });\n clearPromptView();\n setOutcome(undefined);\n setState({ status: 'idle' });\n },\n };\n const events = [PassflowEvent.SignIn, PassflowEvent.SignOut];\n passflow.subscribe(subscriber, events);\n return () => passflow.unsubscribe(subscriber, events);\n }, [passflow, elevatesHostedSession, settlePrompt, clearPromptView]);\n\n const selectFactor = useCallback((factor: UpgradeFactorType) => {\n setSelectedFactor(factor);\n // §13.2 T3: the selection boundary, reported before any answer is\n // submitted. `selected` is defined off this call and off nothing else.\n requestRef.current?.onFactorSelected(factor);\n reportedSelectionRef.current = true;\n }, []);\n\n const submit = useCallback(\n (code?: string) => {\n const request = requestRef.current;\n if (request === null || resolveRef.current === undefined) return;\n const factor = selectedFactor ?? request.factors[0]?.type;\n if (factor === undefined) return;\n if (!reportedSelectionRef.current) {\n // A submit that skipped the picker still selected a factor — the\n // suggested one — and the controller must hear it before the ceremony.\n request.onFactorSelected(factor);\n reportedSelectionRef.current = true;\n }\n setBusy(true);\n setState({ status: 'submitting' });\n settlePrompt({ type: 'submit', factor, code });\n },\n [selectedFactor, settlePrompt],\n );\n\n const cancel = useCallback(() => {\n userCancelledRef.current = true;\n cancelRequestedRef.current = true;\n if (!settlePrompt({ type: 'cancel' })) {\n // Nothing was pending: either a terminal panel is on screen, or an answer\n // is in flight. Close it either way — the sticky flag answers the\n // controller's next prompt, and leaving a busy dialog open would ask the\n // user to wait for a flight they have abandoned.\n setOutcome(undefined);\n }\n clearPromptView();\n setState({ status: 'idle' });\n }, [settlePrompt, clearPromptView]);\n\n const dismiss = useCallback(() => {\n setOutcome(undefined);\n }, []);\n\n const signInAgain = useCallback(() => {\n setOutcome(undefined);\n signInRef.current();\n }, []);\n\n const toggleAlternatives = useCallback(() => {\n setShowAlternatives((shown) => !shown);\n }, []);\n\n const elevate = useCallback(\n async (options?: UpgradeElevateOptions): Promise<UpgradeSettledState | null> => {\n const requested = statedBar(options);\n const waiter: Waiter = requested === undefined ? { kind: 'imperative' } : { kind: 'imperative', requested };\n try {\n await upgradeFacade.elevate(imperativeChallenge(options), waiter);\n return { status: 'success' };\n } catch (error) {\n // The one surface where cancellation resolves `null`: there the\n // cancellation IS the whole value (§13.3).\n if (dialogOutcomeFromError(error) === 'cancelled') return null;\n return errorStateOf(asError(error));\n }\n },\n [upgradeFacade],\n );\n\n const value = useMemo<UpgradeContextValue>(\n () => ({\n enabled: enabled && installed,\n state,\n prompt,\n selectedFactor,\n selectFactor,\n submit,\n cancel,\n dismiss,\n elevate,\n }),\n [enabled, installed, state, prompt, selectedFactor, selectFactor, submit, cancel, dismiss, elevate],\n );\n\n const dialogState = toDialogState({\n prompt:\n prompt === null ? null : { challenge: prompt.challenge, factors: prompt.factors, previousError: prompt.previousError },\n outcome,\n ui: { selected: selectedFactor, busy, showAlternatives },\n labels,\n handlers: {\n onSelectFactor: selectFactor,\n onToggleAlternatives: toggleAlternatives,\n onSubmit: submit,\n onCancel: cancel,\n onDismiss: dismiss,\n onSignIn: signInAgain,\n },\n });\n\n const dialogProps: UpgradeDialogProps = {\n open: prompt !== null || outcome !== undefined,\n title,\n state: dialogState,\n };\n\n return (\n <UpgradeContext.Provider value={value}>\n {children}\n {/* Mounted after `children` so it overlays them. */}\n {renderDialog === undefined ? <UpgradeDialog {...dialogProps} /> : renderDialog(dialogProps)}\n </UpgradeContext.Provider>\n );\n};\n","import type { Passflow } from '@passflow/core';\nimport { useEffect, useRef } from 'react';\n\ntype Disposable = Pick<Passflow, 'dispose'>;\n\ntype PendingDispose = {\n instance: Disposable;\n timer: ReturnType<typeof setTimeout>;\n};\n\n/**\n * Disposes a Passflow instance once it is replaced (a new `useMemo` value) or the\n * provider unmounts. Each instance owns refresh timers, a BroadcastChannel and Web\n * Locks; one left undisposed keeps acting as an extra tab.\n *\n * Why the dispose is deferred: React StrictMode runs effect cleanup and setup again\n * for the same instance in one commit, while `useMemo` keeps that instance live. An\n * immediate dispose in cleanup would kill the instance the app keeps using, and core\n * forbids using an instance after `dispose()`. So cleanup only schedules the dispose\n * (`setTimeout(0)`); a setup that sees the same instance cancels it. A different\n * instance or a real unmount leaves the timer to fire.\n */\nexport function useDisposeOnReplace(instance: Disposable): void {\n const pending = useRef<PendingDispose | null>(null);\n\n useEffect(() => {\n const scheduled = pending.current;\n if (scheduled) {\n if (scheduled.instance === instance) clearTimeout(scheduled.timer);\n pending.current = null;\n }\n\n return () => {\n const timer = setTimeout(() => instance.dispose(), 0);\n pending.current = { instance, timer };\n };\n }, [instance]);\n}\n","import {\n type ErrorPayload,\n FETCH_PRIORITY_OIDC,\n Passflow,\n type PassflowConfig,\n PassflowEvent,\n type PassflowEventPayload,\n type PassflowSubscriber,\n parseUpgradeChallenge,\n registerFetchMiddleware,\n} from '@passflow/core';\nimport React, { type FC, type ReactNode, useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { UpgradeProvider, type UpgradeProviderProps } from '@/components/provider/upgrade-provider';\nimport { useDisposeOnReplace } from '@/components/provider/use-dispose-on-replace';\nimport { ContinuingStatus } from '@/components/ui/continuing-status';\nimport { LoginScreen } from '@/components/ui/login-screen';\nimport {\n dialogOutcomeFromError,\n UPGRADE_UNSATISFIABLE_DETAIL,\n upgradeRateLimitedMessage,\n} from '@/components/ui/upgrade-dialog/state-mapping';\nimport {\n AuthProvider,\n addressBarSearch,\n defaultNavigate,\n type FederatedLandingOutcome,\n type HandOff,\n initialState,\n type NavigateFunction,\n NavigationContext,\n PassflowContext,\n type PassflowState,\n passflowReducer,\n type RouterType,\n routes,\n} from '@/context';\nimport { useHydrated } from '@/hooks/use-hydrated';\nimport { passwordlessSignInFailedMessage } from '@/utils/auth-error';\nimport { submitFormPost } from '@/utils/form-post';\nimport { signInSearch, twoFactorTokenAppId, urlCarriesAccessToken, urlCarriesTwoFactorToken } from '@/utils/second-factor';\nimport { readParentChallengeIdFromURL } from '@/utils/url-params';\nimport '@/styles/index.css';\n\nexport { readParentChallengeIdFromURL };\n\n/** A hosted sign-in return this tab refused, such as one whose state is not its sign-in. */\nconst SignInReturnFailed: FC<{ onSignInAgain: () => void }> = ({ onSignInAgain }) => (\n <LoginScreen\n chrome={{ title: 'We could not sign you in' }}\n state={{\n kind: 'status',\n tone: 'error',\n message: passwordlessSignInFailedMessage,\n testId: 'sign-in-return-failed',\n primaryAction: { label: 'Sign in again', onClick: onSignInAgain },\n }}\n />\n);\n\n/** A hosted session the exchange could not step up, with why: the page shows it instead of the sign-in form. */\nconst StepUpFailed: FC<{ message: string; testId: string }> = ({ message, testId }) => (\n <LoginScreen chrome={{ title: 'Extra verification required' }} state={{ kind: 'status', tone: 'error', message, testId }} />\n);\n\n/**\n * The assurance-upgrade options a consumer may set on `PassflowProvider`.\n *\n * `children`, `enabled` and `backend` are owned by `PassflowProvider` itself:\n * `backend` is a top-level prop (§13.5 — \"where your API is\" is the headline\n * act, not a nested detail) and `enabled` is derived from `upgrade`/`backend`\n * below, so there is exactly one source for each.\n */\nexport type PassflowUpgradeOptions = Omit<UpgradeProviderProps, 'children' | 'enabled' | 'backend' | 'failures'>;\n\ntype PassflowProviderProps = PassflowConfig & {\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n keyStoragePrefix?: PassflowConfig['keyStoragePrefix'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n tokenExchange?: PassflowConfig['tokenExchange'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n platform?: PassflowConfig['platform'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n refreshCoordination?: PassflowConfig['refreshCoordination'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n refreshStrikes?: PassflowConfig['refreshStrikes'];\n children: ReactNode;\n navigate?: NavigateFunction;\n router?: RouterType;\n /**\n * Where the customer's own API is — domain 2 of §13.5's two-domain\n * interception model. Nothing outside this and Passflow's own API is ever\n * observed, and there is no allow-all opt-in. `string | string[]`, an origin\n * or a same-origin path prefix (`'/api'`).\n */\n backend?: string | string[];\n /**\n * Automatic assurance upgrade (step-up). `undefined` ⇒ **off**, so no\n * existing consumer changes behaviour on upgrade. `true` ⇒ on with\n * defaults; an object ⇒ on with those options; `false` ⇒ off even when\n * `backend` is declared.\n *\n * Declaring `backend` also turns it on: naming where your API is has no\n * other meaning, and §13.5's acceptance configuration is `backend` plus one\n * attached client. The global `window.fetch` patch is a separate, explicit\n * act (`upgrade={{ interceptFetch: true }}`) and stays off by default.\n */\n upgrade?: boolean | PassflowUpgradeOptions;\n /**\n * Where to send a sign-in that lands on this page owing its second factor:\n * a federated redirect on a non-PKCE app comes back with `#tfa_token=` and\n * no tokens. A mounted `PassflowFlow` registers its own (prefixed) route,\n * which wins; set this when the landing page renders no flow, or the flow\n * is mounted elsewhere. Defaults to `routes.two_factor_verify.path`.\n */\n twoFactorVerifyPath?: string;\n /**\n * For the hosted login: the scopes and `state` the app that sent the user here asked for. They decide what goes\n * back to the app after sign-in; unset `scopes` are filled from the app's configuration, else `openid profile id`.\n * Read once, when the provider mounts. Leave unset when the flow is embedded in the app itself.\n */\n handOff?: HandOff;\n};\n\n/**\n * Passflow auth-endpoint regex used by the OIDC interceptor below.\n * Matches every endpoint that takes credentials + an optional\n * parent_challenge_id so the SDK can inject the parent on outbound\n * POSTs and follow `redirect_url` on responses.\n *\n * The set is canonical with the server's AuthFlow dispatcher; if a\n * new credential endpoint lands server-side, it must be added here.\n *\n * - /auth/login — password login\n * - /auth/register — password sign-up\n * - /auth/passwordless/start|complete — OTP / magic-link; the status and\n * approval calls take no parent\n * - /auth/passkey/* — passkey registration/auth\n * - /auth/2fa/* — second-factor verify\n * - /auth/validate — emailed sign-up / sign-in code\n * - /auth/federated/start — federated start (callback is server)\n * - /auth/session/exchange — RFC 8693-style session exchange\n * (ADR-2; activated on Leg 2 of\n * OIDC two-step flows)\n */\nexport const AUTH_ENDPOINT_PATTERN =\n /\\/auth\\/(login|register|passwordless\\/(start|complete)|passkey|2fa|validate|session\\/exchange)\\b|\\/auth\\/federated\\/start\\b/;\n\n/**\n * The passwordless status poll. Under a parent, the approved answer is `{ redirect_url }`, which the interceptor\n * follows. It is follow-only: the poll takes no parent, so its request body is never rewritten.\n */\nexport const PASSWORDLESS_STATUS_PATTERN = /\\/auth\\/passwordless\\/status\\b/;\n\n// Captured at module evaluation — before React mounts and before any\n// consumer-side router can rewrite the URL. The provider's mount-time\n// read stays primary (a consumer could mount the SDK long after boot,\n// on a different URL); this is the fallback that makes the OIDC opt-in\n// immune to mount-vs-navigation timing. Observed in the field: the\n// OIDF conformance login intermittently proceeded as a plain\n// first-party login (tokens in the response, no redirect_url) because\n// the whole OIDC layer keyed off a single mount-time read.\nconst bootParentChallengeId = readParentChallengeIdFromURL();\n\n/**\n * The RFC 8628 device verification page (`/oidc/device`) is the ONE auth surface\n * that must never silently exchange an existing session. A device grant is\n * approved only through the explicit authenticate → user_code confirmation →\n * approve path (see `useDeviceVerify` + src/web/oidc/device_verify.go). Letting\n * the exchange-on-mount probe solve a device parent would approve a grant with\n * no §5.4 code check — the STORM-2372 device-code phishing attack. The server\n * now refuses this at `/auth/session/exchange` too; this is the client half of\n * the same guard, so the probe never even fires here.\n */\nconst isDeviceVerificationURL = (): boolean => typeof window !== 'undefined' && window.location.pathname === '/oidc/device';\n\n/**\n * Set once the OIDC interceptor has started following a server-issued\n * `redirect_url`. Module-level on purpose: it is read by the credential forms,\n * which are siblings of the provider rather than children of a context it could\n * publish through, and its lifetime is exactly one page — the navigation it\n * records is what ends that page.\n */\nlet oidcRedirectFollowed = false;\n\n/**\n * Has the OIDC interceptor already taken ownership of the post-login navigation?\n *\n * A credential form MUST NOT navigate after a successful login when this is\n * true. Two navigations do not queue — the second cancels the first, and the\n * first is the one that completes the OIDC flow:\n *\n * 1. The interceptor calls `window.location.assign(redirect_url)` to hand the\n * authorization code back to the RP (a CLI's `127.0.0.1:<port>/callback`,\n * a web RP's `redirect_uri`, …).\n * 2. `window.location.assign` does not halt script execution, so the form's\n * success handler keeps running and sets `window.location.href` to the\n * app's default post-login page.\n * 3. The browser drops the in-flight request from (1) and goes to (2).\n *\n * Whether (1) has already been delivered when (2) lands is pure scheduling, so\n * this presents as a flake rather than a clean break. Measured against the CLI\n * loopback flow (RFC 8252 §7.3): roughly a third of real browser sign-ins had\n * the GET to the CLI's loopback port aborted mid-flight, and the CLI then sat\n * waiting for a callback that had already been cancelled until it timed out.\n */\nexport const hasFollowedOIDCRedirect = (): boolean => oidcRedirectFollowed;\n\n/**\n * Install the global OIDC AuthFlow interceptor on `fetch` and\n * `XMLHttpRequest`. The interceptor:\n *\n * 1. Injects `parent_challenge_id` on every Passflow auth POST\n * body (when one is present on the SDK's host URL).\n * 2. Watches Passflow auth responses for a JSON answer and executes\n * it: `{ redirect_url: \"...\" }` is followed with\n * `window.location.assign(redirect_url)`, and\n * `{ form_post: { action, fields } }` is submitted as a hidden POST\n * form (OIDC response_mode=form_post).\n *\n * Why both fetch and XHR: `@passflow/core` uses axios, which on the\n * browser delegates to XMLHttpRequest. Other consumer code (and the\n * SDK's own `/oidc/requests/{id}` GET) uses fetch. Patching both\n * keeps the interceptor uniform.\n *\n * No-op when `parent_challenge_id` is absent from the URL.\n *\n * Implementation note: previously this hook lived in the bundled\n * login-app at `login-app/src/App.tsx::useAuthFlowInterceptor`.\n * Moved into the SDK so any Passflow consumer that mounts\n * `<PassflowProvider>` gets full OIDC RP integration automatically.\n */\nconst useOIDCInterceptor = (parentChallengeId: string | undefined): void => {\n useEffect(() => {\n if (!parentChallengeId || typeof window === 'undefined') {\n return;\n }\n\n const isAuthURL = (url: string): boolean => AUTH_ENDPOINT_PATTERN.test(url);\n const followsAnswer = (url: string): boolean => isAuthURL(url) || PASSWORDLESS_STATUS_PATTERN.test(url);\n\n const injectParentChallenge = (raw: string | null | undefined): string | undefined => {\n if (!raw) return undefined;\n try {\n const obj = JSON.parse(raw) as Record<string, unknown>;\n if ('parent_challenge_id' in obj) return undefined;\n obj.parent_challenge_id = parentChallengeId;\n return JSON.stringify(obj);\n } catch {\n return undefined;\n }\n };\n\n const followRedirectURL = (raw: string | null | undefined): void => {\n if (!raw) return;\n try {\n const obj = JSON.parse(raw) as {\n redirect_url?: unknown;\n form_post?: { action?: unknown; fields?: unknown } | null;\n };\n // Claim the navigation BEFORE starting it. `assign` and `submit` do not\n // stop JavaScript: the credential form's own success handler runs right\n // after this and would otherwise navigate on top of us. See\n // `hasFollowedOIDCRedirect` for why that is fatal, not cosmetic.\n const formPost = obj.form_post;\n if (\n typeof formPost === 'object' &&\n formPost !== null &&\n typeof formPost.action === 'string' &&\n formPost.action &&\n typeof formPost.fields === 'object' &&\n formPost.fields !== null\n ) {\n // response_mode=form_post: the RP takes the code as a POST body.\n oidcRedirectFollowed = true;\n submitFormPost(formPost.action, formPost.fields as Record<string, string>);\n return;\n }\n if (typeof obj.redirect_url === 'string' && obj.redirect_url) {\n oidcRedirectFollowed = true;\n window.location.assign(obj.redirect_url);\n }\n } catch {\n // Non-JSON — ignore.\n }\n };\n\n // fetch() interceptor (covers code paths that use the platform fetch API).\n //\n // Installed through the core's fetch registry rather than by assigning\n // `window.fetch` here. Two features that each capture and restore the\n // global compose as `A(B(native))`, and whichever cleanup runs first\n // restores a fetch that predates the other patch — so one interceptor\n // disappears non-deterministically (architecture §13.5, \"the OIDC\n // collision: 'untouched' is withdrawn\"). The registry owns the single\n // patch, reference-counts it, and never restores over a foreign patch.\n //\n // Priority matters behaviourally: OIDC is the OUTER layer\n // (`FETCH_PRIORITY_OIDC` = 10, outside `FETCH_PRIORITY_UPGRADE` = 20) so it\n // still observes the response the caller actually receives — including a\n // replayed one — which is what it reads `redirect_url` from. The logic\n // below is unchanged from the hand-rolled patch: `next` stands exactly\n // where the captured `originalFetch` stood.\n const unregisterFetchMiddleware = registerFetchMiddleware(\n async (next, input, init) => {\n let url = '';\n if (typeof input === 'string') url = input;\n else if (input instanceof URL) url = input.toString();\n else if (input instanceof Request) url = input.url;\n\n const method = init?.method?.toUpperCase() ?? 'GET';\n let outInit = init;\n if (method === 'POST' && isAuthURL(url) && typeof init?.body === 'string') {\n const rewritten = injectParentChallenge(init.body);\n if (rewritten !== undefined) outInit = { ...init, body: rewritten };\n }\n\n const response = await next(input, outInit);\n\n if (response.ok && followsAnswer(url)) {\n try {\n const cloned = response.clone();\n const text = await cloned.text();\n followRedirectURL(text);\n } catch {\n // ignore\n }\n }\n\n return response;\n },\n { priority: FETCH_PRIORITY_OIDC, name: 'passflow-oidc-authflow' },\n );\n\n // XMLHttpRequest interceptor — `@passflow/core` uses axios, which in\n // the browser uses XHR under the hood. The fetch interceptor above\n // does NOT catch those calls.\n const OriginalXHROpen = XMLHttpRequest.prototype.open;\n const OriginalXHRSend = XMLHttpRequest.prototype.send;\n\n // `isAuth` gates the parent injection; `follows` gates following `redirect_url` in the answer.\n type XHRTracker = { method?: string; url?: string; isAuth?: boolean; follows?: boolean };\n const tracker = new WeakMap<XMLHttpRequest, XHRTracker>();\n\n XMLHttpRequest.prototype.open = function (\n this: XMLHttpRequest,\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ): void {\n const urlStr = typeof url === 'string' ? url : url.toString();\n tracker.set(this, {\n method: method?.toUpperCase(),\n url: urlStr,\n isAuth: isAuthURL(urlStr),\n follows: followsAnswer(urlStr),\n });\n this.addEventListener('load', () => {\n const meta = tracker.get(this);\n if (!meta?.follows) return;\n if (this.status >= 200 && this.status < 300) {\n // Server returns 200 + JSON body { redirect_url } or\n // { form_post: { action, fields } } when an AuthFlow parent\n // (OIDC, federated) needs the SPA to navigate.\n followRedirectURL(typeof this.responseText === 'string' ? this.responseText : null);\n }\n });\n // @ts-expect-error spread into open's varargs signature\n OriginalXHROpen.call(this, method, url, ...rest);\n };\n\n XMLHttpRequest.prototype.send = function (this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null): void {\n const meta = tracker.get(this);\n let outBody: Document | XMLHttpRequestBodyInit | null | undefined = body;\n if (meta?.isAuth && meta.method === 'POST' && typeof body === 'string') {\n const rewritten = injectParentChallenge(body);\n if (rewritten !== undefined) outBody = rewritten;\n }\n OriginalXHRSend.call(this, outBody as Document | XMLHttpRequestBodyInit | null);\n };\n\n return () => {\n // Fetch teardown is the registry's: it removes the one patch on the last\n // registration's removal and declines to restore over a stranger's patch.\n // Nothing here captures or restores `window.fetch`.\n unregisterFetchMiddleware();\n XMLHttpRequest.prototype.open = OriginalXHROpen;\n XMLHttpRequest.prototype.send = OriginalXHRSend;\n };\n }, [parentChallengeId]);\n};\n\n/**\n * Parent-challenge metadata returned by GET /oidc/requests/{id}.\n * Subset used by the SDK's exchange-on-mount probe.\n */\ntype ParentChallengeMeta = {\n request_id: string;\n app_name?: string;\n client_id?: string;\n redirect_uri?: string;\n state?: string;\n response_mode?: string;\n // The OIDC directives the parent carries. `prompt=login` and `max_age` are\n // enforced by the server at /auth/session/exchange, which answers 403 when\n // the hosted session does not satisfy them; `prompt=none` is the SDK's to\n // honour, because only the SDK can decide not to render a form.\n oidc_prompt_login?: boolean;\n oidc_prompt_none?: boolean;\n max_age?: number;\n};\n\n/**\n * Where the exchange-on-mount probe stands.\n *\n * - `idle`: nothing attempted yet (no parent, or the app id is unknown).\n * - `exchanging`: the exchange is in flight, or it answered and the browser is\n * on its way back to the relying party.\n * - `upgrade_required`: the hosted session needs a step-up before it can be\n * exchanged, and the step-up dialog is open.\n * - `fallback_to_login`: no usable hosted session; the sign-in form renders.\n * - `unsatisfiable`: no factor of this account reaches the level; the page says so, with no form.\n * - `rate_limited`: the step-up hit the server's rate limit; the page says how long to wait, with no form.\n */\ntype ExchangeState = 'idle' | 'exchanging' | 'upgrade_required' | 'fallback_to_login' | 'unsatisfiable' | 'rate_limited';\n\n/** An OIDC error sent back to the relying party instead of rendering a form. */\ntype RelyingPartyError = 'login_required' | 'interaction_required' | 'unmet_authentication_requirements';\n\nconst relyingPartyErrorDescriptions: Record<RelyingPartyError, string> = {\n login_required: 'user is not authenticated',\n interaction_required: 'user interaction is required',\n unmet_authentication_requirements: 'the authentication requirements could not be met',\n};\n\n/**\n * Sends an OIDC error to the parent's `redirect_uri`, in the parent's\n * `response_mode`: a hidden POST form for `form_post`, a query-string\n * navigation otherwise. Returns false when the metadata has no `redirect_uri`\n * (its fetch failed), leaving the caller to render the form.\n */\nconst answerRelyingParty = (meta: ParentChallengeMeta | undefined, error: RelyingPartyError): boolean => {\n if (!meta?.redirect_uri) return false;\n const fields: Record<string, string> = { error, error_description: relyingPartyErrorDescriptions[error] };\n if (meta.state) fields.state = meta.state;\n if (meta.response_mode === 'form_post') {\n submitFormPost(meta.redirect_uri, fields);\n return true;\n }\n const dest = new URL(meta.redirect_uri);\n for (const [key, value] of Object.entries(fields)) dest.searchParams.set(key, value);\n window.location.assign(dest.toString());\n return true;\n};\n\n/**\n * Does a 200 from the exchange carry an answer the OIDC interceptor executes\n * (`redirect_url` or `form_post`)? The interceptor is the sole owner of that\n * navigation: it reads the response before this hook does, and a second\n * navigation from here would re-present the single-use authorization code.\n */\nconst carriesAnswer = async (res: Response): Promise<boolean> => {\n try {\n const body = (await res.json()) as { redirect_url?: unknown; form_post?: unknown };\n return Boolean(body.redirect_url) || Boolean(body.form_post);\n } catch {\n return false;\n }\n};\n\nconst readBody = async (res: Response): Promise<unknown> => {\n try {\n return await res.json();\n } catch {\n return undefined;\n }\n};\n\n/**\n * Exchange-on-mount: when a parent challenge is on the URL, ask\n * /auth/session/exchange whether the hosted session cookie can answer it\n * without a sign-in form. The request carries the cookie only\n * (`credentials: 'include'`), never stored tokens; the server is the sole judge\n * of the session, including `prompt=login` and `max_age`.\n *\n * The answers:\n *\n * - 200 `{ redirect_url }` or `{ form_post }` → the OIDC interceptor executes\n * it; the hook stays `exchanging` so no form flashes while the page leaves.\n * A 200 with neither renders the form.\n * - 401 / 400 → no usable hosted session: the form, or `login_required` to\n * the relying party under `prompt=none`.\n * - 403 → the session falls short. Under `prompt=none` that is\n * `interaction_required` to the relying party. Otherwise the body is read\n * with core's `parseUpgradeChallenge`, `available_factors` and\n * `sign_in_required` included:\n * - `sign_in_required: true`, or a body naming neither `acr_values` nor\n * `max_age` → the form, with no step-up.\n * - Otherwise the step-up dialog opens through `passflow.hostedUpgrade`\n * (`upgrade_required`), offering exactly the server's factors.\n * - Step-up succeeds → exactly one more exchange. A 200 answer completes;\n * a 401 renders the form; anything else sends\n * `unmet_authentication_requirements` to the relying party.\n * - Step-up ends in sign-in required (an older server's empty\n * `available_factors`) or insufficient → the form.\n * - Unsatisfiable (no factor of this account reaches the level) →\n * `unsatisfiable`: the page says why. No form, since a fresh sign-in\n * would not meet it either, and nothing goes to the relying party.\n * - Rate limited → `rate_limited`: the page says how long to wait.\n * - Cancelled or any other failure → when the refusal named `acr_values`\n * the relying party gets `unmet_authentication_requirements`; when it\n * named only `max_age`, the form renders so the user can sign in again.\n * - Any other status, or a network error → the form.\n *\n * An error for the relying party needs the parent's `redirect_uri`; without\n * it the form renders instead.\n */\nconst useSessionExchangeOnMount = (\n parentChallengeId: string | undefined,\n landedWithTwoFactorToken: boolean,\n // Read at call time: the provider replaces its instance while the exchange runs, and only the current one steps up.\n currentPassflow: () => Passflow,\n baseUrl: string | undefined,\n appId: string | undefined,\n): { exchangeState: ExchangeState; parentMeta?: ParentChallengeMeta; stepUpFailure?: string } => {\n const [exchangeState, setExchangeState] = useState<ExchangeState>('idle');\n const [stepUpFailure, setStepUpFailure] = useState<string | undefined>(undefined);\n const [parentMeta, setParentMeta] = useState<ParentChallengeMeta | undefined>(undefined);\n const attemptedRef = useRef(false);\n\n useEffect(() => {\n // A landing that owes its second factor finishes that sign-in: the 2FA screen, not an exchange of another session.\n if (!parentChallengeId || landedWithTwoFactorToken || attemptedRef.current) {\n return;\n }\n // Never auto-exchange on the device verification page — that would approve\n // a device grant with no user_code check (see isDeviceVerificationURL).\n if (isDeviceVerificationURL()) {\n return;\n }\n // Wait until appId has been discovered before attempting the\n // exchange — otherwise the request 400s on \"Application ID is\n // missing from request\".\n if (!appId) {\n return;\n }\n attemptedRef.current = true;\n\n const base = baseUrl ?? '';\n\n const exchange = (): Promise<Response> =>\n fetch(`${base}/auth/session/exchange`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n // App middleware reads X-Passflow-ClientID; without it the\n // request gets 400 \"Application ID is missing from request\".\n 'X-Passflow-ClientID': appId,\n },\n body: JSON.stringify({ parent_challenge_id: parentChallengeId }),\n });\n\n const run = async () => {\n // The parent's metadata: where an error for the relying party goes\n // (`redirect_uri`, `state`, `response_mode`), whether it asked for\n // `prompt=none`, and the app name for the continuing status.\n let meta: ParentChallengeMeta | undefined;\n try {\n const res = await fetch(`${base}/oidc/requests/${encodeURIComponent(parentChallengeId)}`);\n if (res.ok) {\n meta = (await res.json()) as ParentChallengeMeta;\n setParentMeta(meta);\n }\n } catch {\n // Network error fetching the parent: no relying-party answer is\n // possible, but the exchange still decides between leaving and the form.\n }\n\n const showForm = () => setExchangeState('fallback_to_login');\n const answerOrShowForm = (error: RelyingPartyError) => {\n if (!answerRelyingParty(meta, error)) showForm();\n };\n\n setExchangeState('exchanging');\n try {\n const res = await exchange();\n if (res.ok) {\n if (!(await carriesAnswer(res))) showForm();\n return;\n }\n if (res.status === 401 || res.status === 400) {\n if (meta?.oidc_prompt_none) answerOrShowForm('login_required');\n else showForm();\n return;\n }\n if (res.status !== 403) {\n showForm();\n return;\n }\n if (meta?.oidc_prompt_none) {\n answerOrShowForm('interaction_required');\n return;\n }\n\n const challenge = parseUpgradeChallenge(403, (name) => res.headers.get(name), await readBody(res));\n if (\n !challenge ||\n challenge.signInRequired === true ||\n (challenge.acrValues === undefined && challenge.maxAge === undefined)\n ) {\n showForm();\n return;\n }\n\n setExchangeState('upgrade_required');\n try {\n await currentPassflow().hostedUpgrade.elevate(challenge, { kind: 'imperative' });\n } catch (error) {\n const outcome = dialogOutcomeFromError(error);\n if (outcome === 'sign-in-required' || outcome === 'insufficient') {\n showForm();\n } else if (outcome === 'unsatisfiable') {\n setStepUpFailure(UPGRADE_UNSATISFIABLE_DETAIL);\n setExchangeState('unsatisfiable');\n } else if (outcome === 'rate-limited') {\n const { retryAfter, message } = error as { retryAfter?: number; message?: string };\n setStepUpFailure(upgradeRateLimitedMessage(retryAfter, message || undefined));\n setExchangeState('rate_limited');\n } else if (challenge.acrValues !== undefined) {\n answerOrShowForm('unmet_authentication_requirements');\n } else {\n showForm();\n }\n return;\n }\n\n setExchangeState('exchanging');\n const retry = await exchange();\n if (retry.ok) {\n if (!(await carriesAnswer(retry))) showForm();\n return;\n }\n if (retry.status === 401) {\n showForm();\n return;\n }\n answerOrShowForm('unmet_authentication_requirements');\n } catch {\n showForm();\n }\n };\n\n void run();\n }, [parentChallengeId, baseUrl, appId]);\n\n return { exchangeState, parentMeta, stepUpFailure };\n};\n\n/**\n * Context surface exposed to children so the SDK's own components\n * (or consumer code) can read the OIDC parent-challenge state.\n */\nexport type OIDCExchangeContextValue = {\n parentChallengeId?: string;\n parentMeta?: ParentChallengeMeta;\n exchangeState: ExchangeState;\n};\n\n/**\n * Sends a landing that owes its second factor to the 2FA screen.\n *\n * A federated sign-in on a non-PKCE app comes back to its redirect URL with\n * the 2FA token in the fragment and no tokens. Core adopts it as it is\n * constructed (`parseQueryParams`, on by default) and strips the fragment;\n * with that off, the token is adopted here through `handleTokensRedirect()`.\n *\n * The navigation runs one render after mount, not in the mount effect: the\n * flow's router and its 2FA route register themselves in their own mount\n * effects, which run before this one, and their state lands in the next\n * render. Navigating at mount would go through the default full-page\n * navigation to the unprefixed route. App-id discovery would hold the flow back\n * the same way, so a `#tfa_token=` landing on the hosted login never runs it: the\n * app comes from the token. That app goes onto the URL here, where the hosted login\n * reads it after a reload.\n *\n * A PKCE federated landing (`?code=&user_state=`) is taken here too, from an\n * effect: the instance is built during render, and StrictMode throws one away\n * without running its effects, so core must not take the landing in its\n * constructor. So is the landing of a hosted sign-in in SDK mode (`?code=&state=`,\n * started by `authRedirect()` in this tab), which core takes after the federated\n * one. Taking either can end in that same 2FA navigation; returned is how it\n * ended otherwise, and a refused landing is `'failed'`.\n *\n * Under an OIDC parent the 2FA landing goes on even with a stored session: the\n * parent's sign-in is the one owing the factor.\n *\n * Tokens in the URL (`access_token=`) are taken from an effect for the same\n * reason, and only once the app id is known: core verifies them against it in\n * the background, and an instance with no app id would reject and strip them.\n * The outcome arrives as `SignIn` with source `tokens-in-url`, or as `Error`\n * with operation `tokens.from-url`, after which the sign-in form shows.\n */\nconst useSecondFactorLanding = (\n landedWithTwoFactorToken: boolean,\n passflow: Passflow,\n navigate: NavigateFunction,\n twoFactorVerifyPath: string,\n appIdFromToken: string | undefined,\n takeTokensFromUrl: boolean,\n isDiscoveringAppId: boolean,\n parentChallengeId: string | undefined,\n): { federatedLandingOutcome?: FederatedLandingOutcome; signInReturnFailed: boolean } => {\n const [pending, setPending] = useState(false);\n const [federatedLandingOutcome, setFederatedLandingOutcome] = useState<FederatedLandingOutcome>();\n const [signInReturnFailed, setSignInReturnFailed] = useState(false);\n\n const takenRef = useRef(false);\n const currentPassflowRef = useRef(passflow);\n currentPassflowRef.current = passflow;\n\n // Deps `[passflow]`: under app-id discovery the first instance has no app id\n // and leaves the landing to the next one. The ref makes StrictMode's replay a\n // no-op. No cleanup on purpose: settings can replace the instance while its\n // exchange runs, and the events still fire on the store of the one that took\n // the landing. The listener removes itself on its first outcome.\n useEffect(() => {\n if (takenRef.current) return;\n\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.TwoFactorRequired) {\n passflow.unsubscribe(subscriber);\n setPending(true);\n } else if (eventType === PassflowEvent.Error) {\n const operation = (payload as ErrorPayload | undefined)?.operation;\n if (operation !== 'federated.redirect' && operation !== 'oidc.redirect') return;\n passflow.unsubscribe(subscriber);\n setFederatedLandingOutcome('failed');\n // Core reports a refused hosted sign-in return only as this event: the provider shows it.\n if (operation === 'oidc.redirect') setSignInReturnFailed(true);\n } else if (eventType === PassflowEvent.SignIn) {\n const signIn = payload as PassflowEventPayload[PassflowEvent.SignIn] | undefined;\n if (signIn?.source !== 'federated-landing' && signIn?.source !== 'oidc-landing') return;\n passflow.unsubscribe(subscriber);\n // A replaced instance's session start is a no-op, and the current one\n // read storage before these tokens existed.\n const current = currentPassflowRef.current;\n if (current !== passflow && signIn.tokens) current.setTokens(signIn.tokens);\n setFederatedLandingOutcome('signed-in');\n }\n },\n };\n\n passflow.subscribe(subscriber, [PassflowEvent.TwoFactorRequired, PassflowEvent.SignIn, PassflowEvent.Error]);\n if (passflow.completeFederatedLanding()) takenRef.current = true;\n else passflow.unsubscribe(subscriber);\n }, [passflow]);\n\n // Same shape as the federated landing above: once, on the instance that has\n // the app id (or the last one, if discovery failed), with no cleanup.\n const tokensTakenRef = useRef(false);\n useEffect(() => {\n if (!takeTokensFromUrl || isDiscoveringAppId || tokensTakenRef.current) return;\n tokensTakenRef.current = true;\n\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.Error) {\n if ((payload as ErrorPayload | undefined)?.operation !== 'tokens.from-url') return;\n passflow.unsubscribe(subscriber);\n } else if (eventType === PassflowEvent.SignIn) {\n const signIn = payload as PassflowEventPayload[PassflowEvent.SignIn] | undefined;\n if (signIn?.source !== 'tokens-in-url') return;\n passflow.unsubscribe(subscriber);\n const current = currentPassflowRef.current;\n if (current !== passflow && signIn.tokens) current.setTokens(signIn.tokens);\n setFederatedLandingOutcome('tokens-in-url');\n }\n },\n };\n\n passflow.subscribe(subscriber, [PassflowEvent.SignIn, PassflowEvent.Error]);\n passflow.handleTokensRedirect();\n }, [passflow, takeTokensFromUrl, isDiscoveringAppId]);\n\n // Once, on mount — the landing is a property of the page load. A hydrated page waits for the render after\n // hydration: the flow mounts its routes only then, and the navigation must come one render after them.\n const hydrated = useHydrated();\n const landingTakenRef = useRef(false);\n useEffect(() => {\n if (!hydrated || landingTakenRef.current) return;\n landingTakenRef.current = true;\n if (!landedWithTwoFactorToken) return;\n // A signed-in user owes no factor: a `#tfa_token=` link is not theirs to answer. Under an OIDC parent it is the\n // parent's sign-in that owes it.\n if (passflow.isAuthenticated() && !parentChallengeId) return;\n if (!passflow.isTwoFactorVerificationRequired()) passflow.handleTokensRedirect();\n if (passflow.isTwoFactorVerificationRequired()) setPending(true);\n }, [hydrated]);\n\n useEffect(() => {\n if (!pending) return;\n setPending(false);\n const search = new URLSearchParams(signInSearch(addressBarSearch.read()));\n if (appIdFromToken) search.set('appid', appIdFromToken);\n navigate({ to: twoFactorVerifyPath, search: search.toString() || undefined, replace: true });\n }, [pending, navigate, twoFactorVerifyPath, appIdFromToken]);\n\n return { federatedLandingOutcome, signInReturnFailed };\n};\n\nexport const OIDCExchangeContext = React.createContext<OIDCExchangeContextValue>({\n exchangeState: 'idle',\n});\n\nexport const PassflowProvider: FC<PassflowProviderProps> = ({\n children,\n navigate: initialNavigate,\n router = 'default',\n backend,\n upgrade,\n twoFactorVerifyPath,\n // `backend` and `upgrade` are destructured out on purpose: they are\n // interception policy, not client-wide configuration, and §13.5 keeps them\n // off `PassflowConfig` — which is what `config` is spread into below.\n ...config\n}) => {\n // Read before core is constructed: core adopts `#tfa_token=` and strips it.\n const [appIdFromToken] = useState(() => (config.appId ? undefined : twoFactorTokenAppId(config.url)));\n\n // If appId is not provided, set isDiscoveringAppId to true to signal\n // that auto-discovery should happen (prevents showing error before discovery)\n const needsDiscovery = !config.appId && !appIdFromToken;\n\n const [state, dispatch] = useReducer(passflowReducer, {\n ...initialState,\n ...config,\n appId: config.appId || appIdFromToken,\n isDiscoveringAppId: needsDiscovery,\n });\n\n // A new `appId` prop is another app: the instance below is rebuilt for it and reads only that app's tokens.\n // Everything the old app's settings wrote goes back to the props or the initial state, so the new app's settings\n // are fetched and fill it again.\n const appIdPropRef = useRef(config.appId);\n const [mountHandOff] = useState(config.handOff);\n useEffect(() => {\n if (!config.appId || config.appId === appIdPropRef.current) return;\n appIdPropRef.current = config.appId;\n dispatch({\n type: 'SET_PASSFLOW_STATE',\n payload: {\n appId: config.appId,\n appSettings: initialState.appSettings,\n passwordPolicy: initialState.passwordPolicy,\n hasSettingsError: initialState.hasSettingsError,\n scopes: config.scopes,\n createTenantForNewUser: config.createTenantForNewUser,\n handOff: mountHandOff,\n },\n });\n }, [config.appId]);\n\n const [navigate, setNavigate] = useState<NavigateFunction>(() => {\n if (initialNavigate) {\n return initialNavigate;\n }\n return defaultNavigate;\n });\n\n // Read before core is constructed: core adopts `#tfa_token=` and strips it.\n const [landedWithTwoFactorToken] = useState(urlCarriesTwoFactorToken);\n const [landedWithAccessToken] = useState(urlCarriesAccessToken);\n const takeTokensFromUrl = landedWithAccessToken && config.parseQueryParams !== false;\n\n // Read once, at mount, like every other prop that seeds the reducer.\n const [fixedConfig] = useState<PassflowConfig>(() => ({\n keyStoragePrefix: config.keyStoragePrefix,\n tokenExchange: config.tokenExchange,\n platform: config.platform,\n refreshCoordination: config.refreshCoordination,\n refreshStrikes: config.refreshStrikes,\n }));\n\n // OIDC AuthFlow integration: the interceptor injects\n // parent_challenge_id on outbound auth POSTs + follows\n // server-returned redirect_url; the exchange-on-mount probe decides\n // whether to render login form vs auto-exchange. See ADR-2.\n const parentChallengeId = useMemo(() => readParentChallengeIdFromURL() ?? bootParentChallengeId, []);\n useOIDCInterceptor(parentChallengeId);\n // Assigned below in every render, before any effect reads it.\n const passflowRef = useRef<Passflow | undefined>(undefined);\n const currentPassflow = useCallback(() => passflowRef.current as Passflow, []);\n const { exchangeState, parentMeta, stepUpFailure } = useSessionExchangeOnMount(\n parentChallengeId,\n landedWithTwoFactorToken,\n currentPassflow,\n config.url,\n state.appId,\n );\n\n // The fields core reads. While the step-up dialog is open they stay as they were: the dialog is the current\n // instance's hosted step-up, and replacing the instance would cancel it. What arrived meanwhile, such as the app's\n // settings, applies once the dialog closes.\n const liveInstanceConfig = {\n url: state.url,\n appId: state.appId,\n scopes: state.scopes,\n createTenantForNewUser: state.createTenantForNewUser,\n parseQueryParams: state.parseQueryParams,\n };\n const instanceConfigRef = useRef(liveInstanceConfig);\n if (exchangeState !== 'upgrade_required') instanceConfigRef.current = liveInstanceConfig;\n const instanceConfig = instanceConfigRef.current;\n\n // Rebuilt only when a field core reads changes. Settings arriving, discovery ending or an equal scopes array keep\n // the instance, and with it core's cached settings read.\n const scopesKey = instanceConfig.scopes?.join(' ');\n const passflow = useMemo(\n () =>\n new Passflow({\n ...fixedConfig,\n ...instanceConfig,\n parseQueryParams: landedWithAccessToken ? false : instanceConfig.parseQueryParams,\n deferFederatedLanding: true,\n }),\n [\n fixedConfig,\n instanceConfig.url,\n instanceConfig.appId,\n scopesKey,\n instanceConfig.createTenantForNewUser,\n instanceConfig.parseQueryParams,\n landedWithAccessToken,\n ],\n );\n passflowRef.current = passflow;\n useDisposeOnReplace(passflow);\n\n // Auto-discover appId from /settings endpoint if not provided\n const discoveryAttemptedRef = useRef(false);\n useEffect(() => {\n if (needsDiscovery && !discoveryAttemptedRef.current && state.isDiscoveringAppId) {\n discoveryAttemptedRef.current = true;\n\n const discoverAppId = async () => {\n // Try relative path first (works with dev server proxy and same-origin production)\n // Then fall back to absolute URL if configured\n const urlsToTry = ['/settings'];\n if (config.url) {\n urlsToTry.push(`${config.url}/settings`);\n }\n\n for (const url of urlsToTry) {\n try {\n const response = await fetch(url);\n if (response.ok) {\n const settings = await response.json();\n const discoveredAppId = settings.login_app?.app_id || settings.appId;\n\n if (discoveredAppId) {\n passflow.setAppId(discoveredAppId);\n // Only what discovery found: a field it did not find keeps whatever is in the state now.\n const discovered: Partial<PassflowState> = { appId: discoveredAppId, isDiscoveringAppId: false };\n const scopes = settings.login_app?.scopes || settings.scopes;\n // Under a hand-off the sign-in scopes follow the hand-off scopes rule, applied by the reducer.\n if (state.handOff) dispatch({ type: 'SET_FOUND_SCOPES', found: scopes });\n else if (scopes) discovered.scopes = scopes;\n const createTenant = settings.login_app?.create_tenant_for_new_user ?? settings.createTenantForNewUser;\n if (createTenant !== undefined) discovered.createTenantForNewUser = createTenant;\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: discovered });\n return;\n }\n }\n } catch (error) {}\n }\n\n // All URLs failed\n console.warn('Failed to discover appId from /settings');\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { isDiscoveringAppId: false } });\n };\n\n void discoverAppId();\n }\n }, [needsDiscovery, state.isDiscoveringAppId, config.url, passflow]);\n\n const passflowValue = useMemo(() => ({ state, dispatch, passflow }), [state, passflow]);\n\n const handleSetNavigate = useCallback((newNavigate: NavigateFunction | null) => {\n setNavigate(() => newNavigate || defaultNavigate);\n }, []);\n\n const [flowTwoFactorVerifyPath, setFlowTwoFactorVerifyPath] = useState<string | null>(null);\n const resolvedTwoFactorVerifyPath = flowTwoFactorVerifyPath ?? twoFactorVerifyPath ?? routes.two_factor_verify.path;\n const [flowSignInPath, setFlowSignInPath] = useState<string | null>(null);\n const { federatedLandingOutcome, signInReturnFailed } = useSecondFactorLanding(\n landedWithTwoFactorToken,\n passflow,\n navigate,\n resolvedTwoFactorVerifyPath,\n appIdFromToken,\n takeTokensFromUrl,\n state.isDiscoveringAppId === true,\n parentChallengeId,\n );\n\n const navigationValue = useMemo(\n () => ({\n navigate,\n setNavigate: handleSetNavigate,\n router,\n twoFactorVerifyPath: resolvedTwoFactorVerifyPath,\n setTwoFactorVerifyPath: setFlowTwoFactorVerifyPath,\n signInPath: flowSignInPath ?? routes.signin.path,\n setSignInPath: setFlowSignInPath,\n federatedLandingOutcome,\n }),\n [navigate, handleSetNavigate, router, resolvedTwoFactorVerifyPath, flowSignInPath, federatedLandingOutcome],\n );\n\n const oidcExchangeValue = useMemo<OIDCExchangeContextValue>(\n () => ({ parentChallengeId, parentMeta, exchangeState }),\n [parentChallengeId, parentMeta, exchangeState],\n );\n\n // `undefined` ⇒ off, so no existing consumer changes behaviour. `false`\n // forces it off even when a `backend` is declared; declaring a `backend` is\n // itself an opt-in, since naming where your API is has no other meaning.\n //\n // Under a parent challenge (the hosted login) it is on, through\n // `passflow.hostedUpgrade`: the exchange-on-mount probe steps the hosted\n // session up through that facade. The facade is chosen once, from mount, and\n // the global fetch is never patched there — the exchange reads its own 403.\n const hosted = parentChallengeId !== undefined;\n const upgradeEnabled = upgrade === false ? false : upgrade !== undefined || backend !== undefined || hosted;\n const upgradeOptions = useMemo<PassflowUpgradeOptions>(\n () => (typeof upgrade === 'object' && upgrade !== null ? upgrade : {}),\n [upgrade],\n );\n // A step-up only a fresh sign-in can meet: the app's own sign-in route when a mounted flow registered one, else the\n // hosted login. The hosted login page itself shows its sign-in form from the exchange instead.\n const signInForStepUp = useCallback(() => {\n if (flowSignInPath) navigate({ to: flowSignInPath });\n else void passflow.authRedirect().catch(() => undefined);\n }, [flowSignInPath, navigate, passflow]);\n\n // Render the continuing status while the exchange is in flight or the\n // step-up dialog is open over it. Once it resolves (either via navigation\n // or by falling through), children mount as normal.\n const showContinuing = exchangeState === 'exchanging' || exchangeState === 'upgrade_required';\n return (\n <PassflowContext.Provider value={passflowValue}>\n <NavigationContext.Provider value={navigationValue}>\n <OIDCExchangeContext.Provider value={oidcExchangeValue}>\n <AuthProvider>\n {/* Mounted outside the exchange branch so a state change does not\n tear down and reinstall the upgrade interceptors. */}\n <UpgradeProvider\n {...upgradeOptions}\n facade={hosted ? passflow.hostedUpgrade : undefined}\n interceptFetch={hosted ? false : upgradeOptions.interceptFetch}\n onSignInRequired={upgradeOptions.onSignInRequired ?? signInForStepUp}\n failures={hosted ? 'caller' : 'dialog'}\n enabled={upgradeEnabled}\n backend={backend}\n >\n {signInReturnFailed ? (\n <SignInReturnFailed onSignInAgain={() => void passflow.authRedirect().catch(() => undefined)} />\n ) : (exchangeState === 'unsatisfiable' || exchangeState === 'rate_limited') && stepUpFailure ? (\n <StepUpFailed message={stepUpFailure} testId={`exchange-${exchangeState.replace('_', '-')}`} />\n ) : showContinuing ? (\n <ContinuingStatus appName={parentMeta?.app_name} />\n ) : (\n children\n )}\n </UpgradeProvider>\n </AuthProvider>\n </OIDCExchangeContext.Provider>\n </NavigationContext.Provider>\n </PassflowContext.Provider>\n );\n};\n","import { SERVICE_UNAVAILABLE_ERROR_ID } from '@passflow/core';\nimport { useContext, useRef, useState } from 'react';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport { PassflowContext } from '@/context';\nimport { getUrlWithTokens, isSameOriginPath, isSignInPage } from '@/utils';\nimport { useNavigation } from './use-navigation';\nimport { usePassflow } from './use-passflow';\n\nconst REDIRECT_NOT_REGISTERED = 'error.app.redirect.url.not.registered';\n\nexport type SignInEnding = 'none' | 'checking' | 'signed-in' | 'refused' | 'unavailable' | 'service-unavailable';\n\n/**\n * How every sign-in ends once the user holds tokens, in this order:\n * 1. With no target, or a target that is the sign-in page itself, the user stays and is told they are signed in.\n * 2. A path on this page's origin is a plain navigation. It carries no tokens.\n * 3. Anything else is left for. A target that came with the request (a prop, the URL, a token or a response) is\n * validated by the server first and the user goes to the address it returns. If the server refuses, fails, or\n * Passflow cannot be reached at all, nothing is sent: `ending` says which, and `retry` asks again. The app's own\n * default redirect is its operator's configuration and is not checked. The source decides, not the value.\n * 4. Tokens go in the URL only for an app in Simple mode; in SDK mode the user goes to the address with nothing, and\n * the app's SDK starts the sign-in. If the app's mode cannot be read, nothing is sent and `ending` is\n * `unavailable`.\n */\nexport const useSignInEnding = () => {\n const passflow = usePassflow();\n const handOff = useContext(PassflowContext)?.state.handOff;\n const { navigate, signInPath } = useNavigation();\n const [ending, setEnding] = useState<SignInEnding>('none');\n // The external ending last started, for `retry`: a requested target is checked again, the app default is not.\n const lastEnding = useRef<{ target: string; checked: boolean } | null>(null);\n // A screen that starts its request on mount holds this render's closure, from before the flow registered its path.\n const latestSignInPath = useRef(signInPath);\n latestSignInPath.current = signInPath;\n\n const handOver = async (address: string) => {\n setEnding('checking');\n let pkceEnabled: boolean | undefined;\n try {\n pkceEnabled = (await passflow.getAppSettings())?.pkce_enabled;\n } catch {\n setEnding('unavailable');\n return;\n }\n // Only a mode positively known to be Simple gets tokens in the URL.\n window.location.href = pkceEnabled === false ? await getUrlWithTokens(passflow, address, 'hash', handOff) : address;\n };\n\n const leaveFor = async (target: string) => {\n setEnding('checking');\n let address: string;\n try {\n address = await passflow.checkRedirectUrl(target);\n } catch (error) {\n const id = (error as { id?: string } | undefined)?.id;\n if (id === REDIRECT_NOT_REGISTERED) setEnding('refused');\n else if (id === SERVICE_UNAVAILABLE_ERROR_ID) setEnding('service-unavailable');\n else setEnding('unavailable');\n return;\n }\n await handOver(address);\n };\n\n const finishSignIn = async (requested?: string | null, appDefault?: string | null) => {\n // An OIDC parent's redirect is already under way: a second navigation would break it.\n if (hasFollowedOIDCRedirect()) return;\n const target = requested || appDefault;\n if (!target || isSignInPage(target, latestSignInPath.current)) {\n setEnding('signed-in');\n } else if (isSameOriginPath(target)) {\n navigate({ to: target });\n } else if (requested) {\n lastEnding.current = { target: requested, checked: true };\n await leaveFor(requested);\n } else {\n lastEnding.current = { target, checked: false };\n await handOver(target);\n }\n };\n\n const retry = () => {\n const last = lastEnding.current;\n if (!last) return;\n void (last.checked ? leaveFor(last.target) : handOver(last.target));\n };\n\n return { ending, retry, finishSignIn };\n};\n","import type {\n PassflowPasskeyAuthenticateStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignInPayload,\n} from '@passflow/core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { AuthOperation, AuthUiError } from '@/types';\nimport {\n authErrorFor,\n authErrorFrom,\n passwordChangeRequiredErrorId,\n passwordChangeRequiredMessage,\n serverErrorIdFrom,\n serverMessageFor,\n} from '@/utils';\nimport { type UseEmailCodeStep, useEmailCodeStep } from './use-email-code-step';\nimport { usePassflow } from './use-passflow';\n\n/**\n * How a password or passkey sign-in ended. `'two-factor-required'` means core holds a pending sign-in that still owes\n * a second factor: there is no session yet.\n */\nexport type SignInOutcome = 'signed-in' | 'two-factor-required';\n\nexport type UseSignInOptions = {\n /**\n * Called when the server refuses the sign-in until the password is changed. `fetch` then resolves `false` and sets\n * no form error; send the user to the password reset. `notice` is the server's message for the user. Without this\n * option, the same message shows as the form error.\n */\n onPasswordChangeRequired?: (notice: string) => void;\n};\n\nexport type UseSignInProps = (options?: UseSignInOptions) => {\n /**\n * Resolves a {@link SignInOutcome} for a password or passkey sign-in, the server's answer for a passwordless one,\n * and `false` when the request failed, was superseded, or entered the emailed-code step.\n */\n fetch: (\n payload: PassflowPasskeyAuthenticateStartPayload | PassflowSignInPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ) => Promise<false | SignInOutcome | PassflowPasswordlessResponse>;\n isLoading: boolean;\n isError: boolean;\n error: AuthUiError | null;\n reset: () => void;\n /** Abandons the passkey request in flight: the form returns with a cancelled error, and this hook ignores the request's late result. core may still finish a sign-in that completes later. */\n cancelPasskey: () => void;\n /** The sign-in method whose request is in flight, `null` when none is. */\n pendingOperation: AuthOperation | null;\n /**\n * The emailed-code step. A password request the server answers with a code (or a link) enters it, and `fetch`\n * resolves `false`: there is no session yet.\n */\n emailCode: UseEmailCodeStep;\n};\n\nexport const useSignIn: UseSignInProps = ({ onPasswordChangeRequired } = {}) => {\n const passflow = usePassflow();\n const onPasswordChangeRequiredRef = useRef(onPasswordChangeRequired);\n onPasswordChangeRequiredRef.current = onPasswordChangeRequired;\n // The password request is kept only to repeat it for \"Resend code\"; never rendered, logged or stored.\n const lastPasswordPayloadRef = useRef<PassflowSignInPayload | null>(null);\n const resendPasswordRequest = useCallback(async () => {\n const payload = lastPasswordPayloadRef.current;\n if (!payload) throw new Error('Nothing to resend');\n return passflow.signIn(payload);\n }, [passflow]);\n const emailCode = useEmailCodeStep({\n resend: resendPasswordRequest,\n onRelease: () => {\n lastPasswordPayloadRef.current = null;\n },\n });\n\n useEffect(\n () => () => {\n lastPasswordPayloadRef.current = null;\n },\n [],\n );\n const [error, setError] = useState<AuthUiError | null>(null);\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [pendingOperation, setPendingOperation] = useState<AuthOperation | null>(null);\n const attemptRef = useRef(0);\n\n const fetch = useCallback(\n async (\n payload: PassflowPasskeyAuthenticateStartPayload | PassflowSignInPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ): Promise<false | SignInOutcome | PassflowPasswordlessResponse> => {\n attemptRef.current += 1;\n const attempt = attemptRef.current;\n const isCurrent = () => attempt === attemptRef.current;\n setIsLoading(true);\n setPendingOperation(type);\n setIsError(false);\n setError(null);\n\n try {\n if (type === 'password') {\n const answer = await passflow.signIn(payload as PassflowSignInPayload);\n if (!isCurrent()) return false;\n // Held before entering: a link answer releases it at once, a code answer keeps it for resend.\n lastPasswordPayloadRef.current = payload as PassflowSignInPayload;\n if (emailCode.enter(answer)) return false;\n lastPasswordPayloadRef.current = null;\n } else if (type === 'passkey') {\n await passflow.passkeyAuthenticate(payload as PassflowPasskeyAuthenticateStartPayload);\n } else {\n const answer = await passflow.passwordlessSignIn(payload as PassflowPasswordlessSignInPayload);\n return isCurrent() ? answer : false;\n }\n if (!isCurrent()) return false;\n return passflow.isTwoFactorVerificationRequired() ? 'two-factor-required' : 'signed-in';\n } catch (error) {\n if (!isCurrent()) return false;\n const handlePasswordChange = onPasswordChangeRequiredRef.current;\n if (handlePasswordChange && serverErrorIdFrom(error) === passwordChangeRequiredErrorId) {\n handlePasswordChange(serverMessageFor(error) ?? passwordChangeRequiredMessage);\n return false;\n }\n console.error(`[passflow] ${type} sign-in failed`, error);\n setIsError(true);\n setError(authErrorFrom(error, 'sign-in', type));\n return false;\n } finally {\n if (isCurrent()) {\n setIsLoading(false);\n setPendingOperation(null);\n }\n }\n },\n [\n passflow.passkeyAuthenticate,\n passflow.passwordlessSignIn,\n passflow.signIn,\n passflow.isTwoFactorVerificationRequired,\n emailCode.enter,\n ],\n );\n\n const reset = () => {\n setIsError(false);\n setError(null);\n setIsLoading(false);\n setPendingOperation(null);\n };\n\n const cancelPasskey = useCallback(() => {\n attemptRef.current += 1;\n setIsLoading(false);\n setPendingOperation(null);\n setIsError(true);\n setError({ message: 'Passkey sign-in was cancelled.', scope: authErrorFor('sign-in', 'passkey').scope });\n }, []);\n\n return { fetch, isLoading, isError, error, reset, cancelPasskey, pendingOperation, emailCode } as const;\n};\n","import type {\n PassflowPasskeyRegisterStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignUpPayload,\n} from '@passflow/core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { AuthOperation, AuthUiError } from '@/types';\nimport { authErrorFrom } from '@/utils';\nimport { type UseEmailCodeStep, useEmailCodeStep } from './use-email-code-step';\nimport { usePassflow } from './use-passflow';\nimport type { SignInOutcome } from './use-signin';\n\nexport type UseSignUpProps = () => {\n /**\n * Resolves a {@link SignInOutcome} for a password or passkey sign-up, the server's answer for a passwordless one,\n * and `false` when the request failed or entered the emailed-code step.\n */\n fetch: (\n payload: PassflowPasskeyRegisterStartPayload | PassflowSignUpPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ) => Promise<false | SignInOutcome | PassflowPasswordlessResponse>;\n isLoading: boolean;\n isError: boolean;\n error: AuthUiError | null;\n reset: () => void;\n /**\n * The emailed-code step. A password request the server answers with a code (or a link) enters it, and `fetch`\n * resolves `false`: there is no session yet.\n */\n emailCode: UseEmailCodeStep;\n};\n\nexport const useSignUp: UseSignUpProps = () => {\n const passflow = usePassflow();\n // The password request is kept only to repeat it for \"Resend code\"; never rendered, logged or stored.\n const lastPasswordPayloadRef = useRef<PassflowSignUpPayload | null>(null);\n const resendPasswordRequest = useCallback(async () => {\n const payload = lastPasswordPayloadRef.current;\n if (!payload) throw new Error('Nothing to resend');\n return passflow.signUp(payload);\n }, [passflow]);\n const emailCode = useEmailCodeStep({\n resend: resendPasswordRequest,\n onRelease: () => {\n lastPasswordPayloadRef.current = null;\n },\n });\n\n useEffect(\n () => () => {\n lastPasswordPayloadRef.current = null;\n },\n [],\n );\n const [isError, setIsError] = useState(false);\n const [error, setError] = useState<AuthUiError | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (\n payload: PassflowPasskeyRegisterStartPayload | PassflowSignUpPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ): Promise<false | SignInOutcome | PassflowPasswordlessResponse> => {\n setIsLoading(true);\n setIsError(false);\n setError(null);\n const cleanup = () => setIsLoading(false);\n\n try {\n if (type === 'password') {\n const answer = await passflow.signUp(payload as PassflowSignUpPayload);\n // Held before entering: a link answer releases it at once, a code answer keeps it for resend.\n lastPasswordPayloadRef.current = payload as PassflowSignUpPayload;\n if (emailCode.enter(answer)) return false;\n lastPasswordPayloadRef.current = null;\n } else if (type === 'passkey') {\n await passflow.passkeyRegister(payload as PassflowPasskeyRegisterStartPayload);\n } else {\n const passwordlessResponse = await passflow.passwordlessSignIn(payload as PassflowPasswordlessSignInPayload);\n cleanup();\n return passwordlessResponse;\n }\n cleanup();\n return passflow.isTwoFactorVerificationRequired() ? 'two-factor-required' : 'signed-in';\n } catch (error) {\n console.error(`[passflow] ${type} sign-up failed`, error);\n setIsError(true);\n setError(authErrorFrom(error, 'sign-up', type));\n cleanup();\n return false;\n } finally {\n cleanup();\n }\n },\n [\n passflow.signUp,\n passflow.passkeyRegister,\n passflow.passwordlessSignIn,\n passflow.isTwoFactorVerificationRequired,\n emailCode.enter,\n ],\n );\n\n const reset = () => {\n setIsError(false);\n setError(null);\n setIsLoading(false);\n };\n\n return { fetch, isLoading, isError, error, reset, emailCode } as const;\n};\n","import type { TwoFactorTrustedDevice } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTrustedDevicesProps = () => {\n /** The devices the signed-in user trusted to skip the second factor on this app. */\n data: TwoFactorTrustedDevice[];\n refetch: () => Promise<TwoFactorTrustedDevice[] | null>;\n /**\n * Revokes one device; its next sign-in asks for the second factor again.\n * On success the device leaves `data` without a refetch.\n *\n * @returns true when the server revoked it\n */\n revoke: (deviceId: string) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n errorMessage: string;\n};\n\n/**\n * Hook to list and revoke the signed-in user's trusted devices\n */\nexport const useTrustedDevices: UseTrustedDevicesProps = () => {\n const passflow = usePassflow();\n const [data, setData] = useState<TwoFactorTrustedDevice[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [errorMessage, setErrorMessage] = useState<string>('');\n\n const fail = useCallback((e: unknown) => {\n setIsError(true);\n setErrorMessage((e as Error).message);\n }, []);\n\n const fetch = useCallback(async (): Promise<TwoFactorTrustedDevice[] | null> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n const devices = await passflow.getTrustedDevices();\n setData(devices);\n return devices;\n } catch (e) {\n fail(e);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [passflow, fail]);\n\n const revoke = useCallback(\n async (deviceId: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n await passflow.revokeTrustedDevice(deviceId);\n setData((devices) => devices.filter((device) => device.id !== deviceId));\n return true;\n } catch (e) {\n fail(e);\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, fail],\n );\n\n useIsomorphicLayoutEffect(() => {\n void fetch();\n }, [fetch]);\n\n return {\n data,\n refetch: fetch,\n revoke,\n isLoading,\n isError,\n errorMessage,\n };\n};\n","import type { TwoFactorChallengeResponse, TwoFactorMethod, TwoFactorVerifyResponseV2 } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorChallengeReturn = {\n challenge: TwoFactorChallengeResponse | null;\n isLoading: boolean;\n error: Error | null;\n requestChallenge: (firstFactorMethod?: string) => Promise<void>;\n verify: (response: string, trustDevice?: boolean) => Promise<TwoFactorVerifyResponseV2 | null>;\n switchMethod: (method: TwoFactorMethod) => Promise<void>;\n selectedMethod: TwoFactorMethod | null;\n reset: () => void;\n};\n\n/**\n * Hook to manage the v2 two-factor challenge flow with multi-method support\n */\nexport const useTwoFactorChallenge = (): UseTwoFactorChallengeReturn => {\n const passflow = usePassflow();\n const [challenge, setChallenge] = useState<TwoFactorChallengeResponse | null>(null);\n const [selectedMethod, setSelectedMethod] = useState<TwoFactorMethod | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const requestChallenge = useCallback(\n async (firstFactorMethod?: string): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const response = await passflow.twoFactor.requestChallenge({\n first_factor_method: firstFactorMethod,\n });\n setChallenge(response);\n setSelectedMethod(response.method);\n } catch (e) {\n setError(e as Error);\n setChallenge(null);\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const verify = useCallback(\n async (response: string, trustDevice = false): Promise<TwoFactorVerifyResponseV2 | null> => {\n if (!challenge?.challenge_id) {\n setError(new Error('No active challenge session'));\n return null;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result = await passflow.twoFactor.verifyV2({\n challenge_id: challenge.challenge_id,\n method: selectedMethod || challenge.method,\n response,\n trust_device: trustDevice,\n });\n return result;\n } catch (e) {\n setError(e as Error);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, challenge, selectedMethod],\n );\n\n const switchMethod = useCallback(\n async (method: TwoFactorMethod): Promise<void> => {\n if (!challenge?.challenge_id) {\n setError(new Error('No active challenge session'));\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const response = await passflow.twoFactor.switchToAlternative({\n challenge_id: challenge.challenge_id,\n method,\n });\n setChallenge(response);\n setSelectedMethod(method);\n } catch (e) {\n setError(e as Error);\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, challenge],\n );\n\n const reset = useCallback(() => {\n setChallenge(null);\n setSelectedMethod(null);\n setError(null);\n setIsLoading(false);\n }, []);\n\n return {\n challenge,\n isLoading,\n error,\n requestChallenge,\n verify,\n switchMethod,\n selectedMethod,\n reset,\n };\n};\n","import type { TwoFactorRegenerateResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorManageProps = () => {\n recoveryCodes: string[];\n disable: (code: string) => Promise<boolean>;\n regenerateCodes: (code: string) => Promise<TwoFactorRegenerateResponse | null>;\n reset: () => void;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\n/**\n * Hook to manage 2FA (disable, regenerate codes)\n */\nexport const useTwoFactorManage: UseTwoFactorManageProps = () => {\n const passflow = usePassflow();\n const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [error, setError] = useState<string>('');\n\n const disable = useCallback(\n async (code: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n await passflow.disableTwoFactor(code);\n return true;\n } catch (e) {\n setIsError(true);\n const err = e as Error;\n setError(err.message);\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const regenerateCodes = useCallback(\n async (code: string): Promise<TwoFactorRegenerateResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n const response = await passflow.regenerateTwoFactorRecoveryCodes(code);\n setRecoveryCodes(response.recovery_codes);\n return response;\n } catch (e) {\n setIsError(true);\n const err = e as Error;\n setError(err.message);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const reset = useCallback(() => {\n setRecoveryCodes([]);\n setIsError(false);\n setError('');\n }, []);\n\n return {\n recoveryCodes,\n disable,\n regenerateCodes,\n reset,\n isLoading,\n isError,\n error,\n };\n};\n","import type { RegisteredTwoFactorMethod, TwoFactorMethod } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorMethodsReturn = {\n availableMethods: TwoFactorMethod[];\n registeredMethods: RegisteredTwoFactorMethod[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n removeMethod: (methodId: string) => Promise<void>;\n};\n\n/**\n * Hook to manage two-factor authentication methods\n */\nexport const useTwoFactorMethods = (): UseTwoFactorMethodsReturn => {\n const passflow = usePassflow();\n const [availableMethods, setAvailableMethods] = useState<TwoFactorMethod[]>([]);\n const [registeredMethods, setRegisteredMethods] = useState<RegisteredTwoFactorMethod[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async (): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const methods = await passflow.twoFactor.getRegisteredMethods();\n setRegisteredMethods(methods);\n\n // Extract available methods from registered methods\n const available = methods.map((m) => m.method);\n setAvailableMethods(available);\n } catch (e) {\n setError(e as Error);\n setRegisteredMethods([]);\n setAvailableMethods([]);\n } finally {\n setIsLoading(false);\n }\n }, [passflow]);\n\n const removeMethod = useCallback(\n async (methodId: string): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n // Call remove method API (needs to be implemented in @passflow/core)\n // For now, this is a placeholder\n await passflow.twoFactor.removeMethod?.(methodId);\n\n // Refresh the methods list after removal\n await refresh();\n } catch (e) {\n setError(e as Error);\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, refresh],\n );\n\n return {\n availableMethods,\n registeredMethods,\n isLoading,\n error,\n refresh,\n removeMethod,\n };\n};\n","import type { TwoFactorConfirmResponse, TwoFactorSetupResponse } from '@passflow/core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { enrollmentFailureFrom, twoFactorRateLimitedMessage, twoFactorWrongCodeMessage } from '@/utils/auth-error';\nimport { useHydrated } from './use-hydrated';\nimport { usePassflow } from './use-passflow';\n\n/** `checking` reads whether a signed-in user is enrolled; `enrolled` is a user with two-factor authentication on. */\nexport type TwoFactorSetupStep = 'checking' | 'idle' | 'setup' | 'complete' | 'enrolled';\n\nexport type UseTwoFactorSetupProps = () => {\n setupData: TwoFactorSetupResponse | null;\n recoveryCodes: string[];\n step: TwoFactorSetupStep;\n beginSetup: () => Promise<TwoFactorSetupResponse | null>;\n confirmSetup: (code: string) => Promise<TwoFactorConfirmResponse | null>;\n reset: () => void;\n /** The user saved the codes, or there were none: the step becomes `enrolled`. */\n finish: () => void;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\n/** A rate limit on the link page's confirm is a 400 with an id, so the status alone cannot tell. */\nconst setupErrorMessage = (e: unknown): string => {\n const failure = enrollmentFailureFrom(e);\n if (failure === 'rate_limited') return twoFactorRateLimitedMessage;\n if (failure === 'wrong_code') return twoFactorWrongCodeMessage;\n return (e as Error).message;\n};\n\n/**\n * Hook to handle 2FA setup flow (enable 2FA)\n */\nexport const useTwoFactorSetup: UseTwoFactorSetupProps = () => {\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const [setupData, setSetupData] = useState<TwoFactorSetupResponse | null>(null);\n const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [error, setError] = useState<string>('');\n // Signed out, as in a setup link or a sign-in waiting on its second factor, there is no status to read.\n const [step, setStep] = useState<TwoFactorSetupStep>(() => (passflow.isAuthenticated() ? 'checking' : 'idle'));\n\n const checkedRef = useRef(false);\n useEffect(() => {\n if (step !== 'checking' || checkedRef.current) return;\n checkedRef.current = true;\n const read = async () => {\n let enabled = false;\n try {\n enabled = (await passflow.getTwoFactorStatus()).enabled;\n } catch {\n // Unread, the user can still start: the server refuses a second enrolment.\n }\n setStep((current) => (current === 'checking' ? (enabled ? 'enrolled' : 'idle') : current));\n };\n void read();\n }, [passflow, step]);\n\n const beginSetup = useCallback(async (): Promise<TwoFactorSetupResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n const response = await passflow.beginTwoFactorSetup();\n setSetupData(response);\n setStep('setup');\n return response;\n } catch (e) {\n setIsError(true);\n setError(setupErrorMessage(e));\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [passflow]);\n\n const confirmSetup = useCallback(\n async (code: string): Promise<TwoFactorConfirmResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n const response = await passflow.confirmTwoFactorSetup(code);\n // The answer may carry no codes: an empty list, null or no field.\n setRecoveryCodes(response.recovery_codes ?? []);\n setStep('complete');\n return response;\n } catch (e) {\n setIsError(true);\n setError(setupErrorMessage(e));\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const reset = useCallback(() => {\n setSetupData(null);\n setRecoveryCodes([]);\n setIsError(false);\n setError('');\n setStep('idle');\n }, []);\n\n const finish = useCallback(() => setStep('enrolled'), []);\n\n return {\n setupData,\n recoveryCodes,\n // Hydration renders what the signed-out server rendered.\n step: hydrated ? step : 'idle',\n beginSetup,\n confirmSetup,\n reset,\n finish,\n isLoading,\n isError,\n error,\n };\n};\n","import type { TwoFactorSetupMagicLinkError, TwoFactorSetupMagicLinkErrorCode } from '@passflow/core';\nimport { useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { PassflowContext } from '@/context';\nimport { usePassflow } from './use-passflow';\n\nconst knownErrorCodes: readonly TwoFactorSetupMagicLinkErrorCode[] = [\n 'INVALID_TOKEN',\n 'EXPIRED_TOKEN',\n 'REVOKED_TOKEN',\n 'ALREADY_USED',\n 'RATE_LIMITED',\n 'SERVER_ERROR',\n];\n\n/**\n * Return type for useTwoFactorSetupMagicLink hook\n */\nexport type UseTwoFactorSetupMagicLinkReturn = {\n /** True during validation */\n isLoading: boolean;\n /** True during retry attempt */\n isRetrying: boolean;\n /** True if token validated successfully */\n isValidated: boolean;\n /** Error details if validation failed */\n error: TwoFactorSetupMagicLinkError | null;\n /** Session token if validated */\n sessionToken: string | null;\n /** User ID if validated */\n userId: string | null;\n /** App ID if validated (may be null) */\n appId: string | null;\n /** Session expiration in seconds */\n expiresIn: number | null;\n /** Manual retry function for transient errors */\n retry: () => Promise<void>;\n};\n\n/**\n * Hook to validate magic link token for 2FA setup\n *\n * This hook:\n * - Validates once per token on mount (StrictMode included), after app id discovery ends: the session lives in memory\n * on the Passflow instance, and discovery replaces the instance\n * - Provides loading, error, and success states\n * - Allows manual retry for transient failures\n * - Cleans up conditionally on unmount (only if validation failed or not validated)\n *\n * Usage:\n * ```tsx\n * const { isLoading, isValidated, error, retry } = useTwoFactorSetupMagicLink(token);\n *\n * if (isLoading) return <Loading />;\n * if (error) return <ErrorUI error={error} onRetry={retry} />;\n * if (isValidated) return <TwoFactorSetupForm />;\n * ```\n */\nexport const useTwoFactorSetupMagicLink = (token: string): UseTwoFactorSetupMagicLinkReturn => {\n const passflow = usePassflow();\n const isDiscovering = useContext(PassflowContext)?.state.isDiscoveringAppId ?? false;\n\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [isRetrying, setIsRetrying] = useState<boolean>(false);\n const [isValidated, setIsValidated] = useState<boolean>(false);\n const [error, setError] = useState<TwoFactorSetupMagicLinkError | null>(null);\n const [sessionToken, setSessionToken] = useState<string | null>(null);\n const [userId, setUserId] = useState<string | null>(null);\n const [appId, setAppId] = useState<string | null>(null);\n const [expiresIn, setExpiresIn] = useState<number | null>(null);\n\n // The token the mount effect already validated: its guard, and only its guard.\n const validatedOnMount = useRef<string | null>(null);\n\n // Ref to track if we should clear session on unmount\n const shouldClearOnUnmount = useRef<boolean>(true);\n\n const validateToken = useCallback(async () => {\n try {\n const response = await passflow.validateTwoFactorSetupMagicLink(token);\n\n if (response.success && response.sessionToken && response.userId) {\n // Cleared only here: a retry keeps its error screen, with the busy button, until the answer comes.\n setError(null);\n setSessionToken(response.sessionToken);\n setUserId(response.userId);\n setAppId(response.appId ?? null);\n setExpiresIn(response.expiresIn ?? null);\n setIsValidated(true);\n // Don't clear session on unmount if validation succeeded\n shouldClearOnUnmount.current = false;\n } else if (response.error) {\n // Core copies a raw 429's body `error` into `code`, and only that path gives an unknown code.\n setError(knownErrorCodes.includes(response.error.code) ? response.error : { ...response.error, code: 'RATE_LIMITED' });\n setIsValidated(false);\n shouldClearOnUnmount.current = true;\n }\n } catch (err) {\n // Unexpected error (shouldn't happen - SDK catches errors)\n setError({\n code: 'SERVER_ERROR',\n message: err instanceof Error ? err.message : 'An unexpected error occurred',\n });\n setIsValidated(false);\n shouldClearOnUnmount.current = true;\n } finally {\n setIsLoading(false);\n setIsRetrying(false);\n }\n }, [token, passflow]);\n\n /**\n * Manual retry for transient errors: it skips the mount guard\n */\n const retry = useCallback(async () => {\n setIsRetrying(true);\n await validateToken();\n }, [validateToken]);\n\n /**\n * Validate on mount or when token changes\n */\n useEffect(() => {\n if (!token) {\n setError({\n code: 'INVALID_TOKEN',\n message: 'No token provided',\n });\n setIsLoading(false);\n return;\n }\n\n if (isDiscovering || validatedOnMount.current === token) return;\n validatedOnMount.current = token;\n setIsLoading(true);\n void validateToken();\n }, [token, isDiscovering, validateToken]);\n\n /**\n * Cleanup on unmount - conditional based on validation state\n * Per review feedback: Only clear if validation failed or user navigated away before validation\n */\n useEffect(() => {\n return () => {\n // Only clear magic link session if validation failed or wasn't validated\n // If isValidated=true, let the form handle session clearing after confirm\n if (shouldClearOnUnmount.current) {\n passflow.clearMagicLinkSession();\n }\n };\n }, [passflow]);\n\n return {\n isLoading,\n isRetrying,\n isValidated,\n error,\n sessionToken,\n userId,\n appId,\n expiresIn,\n retry,\n };\n};\n","import type { TwoFactorStatusResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorStatusProps = () => {\n data: TwoFactorStatusResponse | null;\n refetch: () => Promise<TwoFactorStatusResponse | null>;\n isLoading: boolean;\n isError: boolean;\n errorMessage: string;\n};\n\n/**\n * Hook to get the current 2FA enrollment status\n */\nexport const useTwoFactorStatus: UseTwoFactorStatusProps = () => {\n const passflow = usePassflow();\n const [data, setData] = useState<TwoFactorStatusResponse | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [errorMessage, setErrorMessage] = useState<string>('');\n\n const fetch = useCallback(async (): Promise<TwoFactorStatusResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n const response = await passflow.getTwoFactorStatus();\n setData(response);\n return response;\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [passflow]);\n\n useIsomorphicLayoutEffect(() => {\n void fetch();\n }, [fetch]);\n\n return {\n data,\n refetch: fetch,\n isLoading,\n isError,\n errorMessage,\n };\n};\n","import type { TwoFactorCompletionOptions, TwoFactorRecoveryResponse, TwoFactorVerifyResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport type { TwoFactorError, TwoFactorErrorType } from '@/types/two-factor-errors';\nimport { classifyTwoFactorError } from '@/utils/classify-two-factor-error';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorVerifyProps = () => {\n isVerificationRequired: () => boolean;\n /** `options.trustDevice` asks the server to trust this device for later sign-ins. */\n verify: (code: string, options?: TwoFactorCompletionOptions) => Promise<TwoFactorVerifyResponse | null>;\n /** `options.trustDevice` asks the server to trust this device for later sign-ins. */\n useRecoveryCode: (code: string, options?: TwoFactorCompletionOptions) => Promise<TwoFactorRecoveryResponse | null>;\n reset: () => void;\n isLoading: boolean;\n isError: boolean;\n error: string;\n errorType: TwoFactorErrorType | null;\n errorDetails: TwoFactorError | null;\n};\n\n/**\n * Hook to verify 2FA code during login with error classification\n */\nexport const useTwoFactorVerify: UseTwoFactorVerifyProps = () => {\n const passflow = usePassflow();\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [error, setError] = useState<string>('');\n const [errorType, setErrorType] = useState<TwoFactorErrorType | null>(null);\n const [errorDetails, setErrorDetails] = useState<TwoFactorError | null>(null);\n\n const isVerificationRequired = useCallback((): boolean => {\n return passflow.isTwoFactorVerificationRequired();\n }, [passflow]);\n\n const handleError = useCallback((e: unknown) => {\n const classified = classifyTwoFactorError(e);\n\n setIsError(true);\n setError(classified.message);\n setErrorType(classified.type);\n setErrorDetails(classified);\n }, []);\n\n const verify = useCallback(\n async (code: string, options?: TwoFactorCompletionOptions): Promise<TwoFactorVerifyResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n setErrorType(null);\n setErrorDetails(null);\n\n try {\n const response = await passflow.verifyTwoFactor(code, options);\n return response;\n } catch (e) {\n handleError(e);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, handleError],\n );\n\n const useRecoveryCode = useCallback(\n async (code: string, options?: TwoFactorCompletionOptions): Promise<TwoFactorRecoveryResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n setErrorType(null);\n setErrorDetails(null);\n\n try {\n const response = await passflow.useTwoFactorRecoveryCode(code, options);\n return response;\n } catch (e) {\n handleError(e);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, handleError],\n );\n\n const reset = useCallback(() => {\n setIsError(false);\n setError('');\n setErrorType(null);\n setErrorDetails(null);\n }, []);\n\n return {\n isVerificationRequired,\n verify,\n useRecoveryCode,\n reset,\n isLoading,\n isError,\n error,\n errorType,\n errorDetails,\n };\n};\n","/**\n * `useUpgrade` — the read side of the assurance-upgrade flow (§8.2, §13.3).\n *\n * It **reads `UpgradeContext` and installs nothing**. Installation belongs to\n * `UpgradeProvider` and only to it: two hooks each installing a prompt handler\n * would open two prompts and defeat single-flight.\n *\n * Outside an `UpgradeProvider` it returns `status: 'idle'` with no-op actions\n * rather than throwing (§9.5 H8).\n */\n\nimport type { AssuranceBar, UpgradeChallenge, UpgradeFactor, UpgradeFactorType } from '@passflow/core';\nimport { useContext, useMemo } from 'react';\nimport {\n INERT_UPGRADE_CONTEXT,\n UpgradeContext,\n type UpgradeContextValue,\n type UpgradeElevateOptions,\n type UpgradeErrorStatusKind,\n type UpgradeHookState,\n type UpgradePromptView,\n type UpgradeSettledState,\n} from '@/context/upgrade-context';\n\nexport type UseUpgradeResult = {\n /** True when an `UpgradeProvider` installed a prompt handler. */\n enabled: boolean;\n /** The whole state, as the discriminated union (§13.5's `UpgradeHookState`). */\n state: UpgradeHookState;\n /** The discriminant, for the common `status === 'challenged'` read. */\n status: UpgradeHookState['status'];\n /** What the server demanded — the MERGED requirement when challenges joined. */\n challenge: UpgradeChallenge | null;\n /** Usable factors, already ranked; index 0 is the suggested one. */\n factors: readonly UpgradeFactor[];\n /** The ranked factor types, which is what `UpgradeHookState.challenged` carries. */\n factorTypes: readonly UpgradeFactorType[];\n selectedFactor: UpgradeFactorType | null;\n /**\n * Elevated, and still not enough: the replay was re-challenged (§13.4).\n * Non-null **only** in the `insufficient` state, and it never coexists with\n * `status === 'success'` — this must not read as success.\n */\n insufficient: { obtained: AssuranceBar; required: AssuranceBar } | null;\n /** The terminal failure, in the `error` state only. */\n error: Error | null;\n /** Which failure class, in the `error` state only. */\n errorKind: UpgradeErrorStatusKind | null;\n /** The previous attempt's failure while the prompt is re-shown (a wrong code). */\n previousError: Error | null;\n /** True while a ceremony is on the wire. */\n busy: boolean;\n /** The factor-selection signal — §13.2's late-join boundary (T3). */\n selectFactor: (factor: UpgradeFactorType) => void;\n submit: (code?: string) => void;\n cancel: () => void;\n dismiss: () => void;\n /** Resolves `null` on cancellation; otherwise the flight's terminal state. */\n elevate: (options?: UpgradeElevateOptions) => Promise<UpgradeSettledState | null>;\n};\n\nconst EMPTY_FACTORS: readonly UpgradeFactor[] = [];\n\nconst readPromptFactors = (prompt: UpgradePromptView | null): readonly UpgradeFactor[] =>\n prompt === null ? EMPTY_FACTORS : prompt.factors;\n\nexport const useUpgrade = (): UseUpgradeResult => {\n const context: UpgradeContextValue = useContext(UpgradeContext) ?? INERT_UPGRADE_CONTEXT;\n const { enabled, state, prompt, selectedFactor, selectFactor, submit, cancel, dismiss, elevate } = context;\n\n return useMemo<UseUpgradeResult>(() => {\n const factors = readPromptFactors(prompt);\n\n return {\n enabled,\n state,\n status: state.status,\n challenge: state.status === 'challenged' ? state.challenge : (prompt?.challenge ?? null),\n factors,\n factorTypes: state.status === 'challenged' ? state.factors : factors.map((factor) => factor.type),\n selectedFactor,\n insufficient: state.status === 'insufficient' ? { obtained: state.obtained, required: state.required } : null,\n error: state.status === 'error' ? state.error : null,\n errorKind: state.status === 'error' ? state.kind : null,\n previousError: prompt?.previousError ?? null,\n busy: state.status === 'submitting',\n selectFactor,\n submit,\n cancel,\n dismiss,\n elevate,\n };\n }, [enabled, state, prompt, selectedFactor, selectFactor, submit, cancel, dismiss, elevate]);\n};\n","import { type ParsedTokens, type Passflow, PassflowEvent, type PassflowSubscriber } from '@passflow/core';\nimport { useEffect, useState } from 'react';\nimport { useHydrated } from './use-hydrated';\nimport { usePassflow } from './use-passflow';\n\n/** The signed-in user, from the tokens. Every field is absent when no one is signed in. */\nexport type PassflowUser = {\n /** The user id, the tokens' `sub`. */\n id?: string;\n email?: string;\n phone?: string;\n};\n\nconst USER_EVENTS = [\n PassflowEvent.SignIn,\n PassflowEvent.Register,\n PassflowEvent.Refresh,\n PassflowEvent.SignOut,\n PassflowEvent.SessionExpired,\n];\n\nconst claim = (tokens: ParsedTokens, read: (token: NonNullable<ParsedTokens['id_token']>) => string | undefined) => {\n const fromId = tokens.id_token ? read(tokens.id_token) : undefined;\n return fromId || (tokens.access_token ? read(tokens.access_token) : undefined) || undefined;\n};\n\n// The hosted code flow puts `email` in the access token and the embedded flow in the id token, so the id token is read\n// first and the access token fills what it lacks.\nconst readUser = (passflow: Passflow): PassflowUser => {\n const tokens = passflow.isAuthenticated() ? passflow.getParsedTokens() : undefined;\n if (!tokens) return {};\n return {\n id: claim(tokens, (token) => token.sub),\n email: claim(tokens, (token) => token.email),\n phone: claim(tokens, (token) => token.phonenumber),\n };\n};\n\nconst signedOut: PassflowUser = {};\n\nconst sameUser = (a: PassflowUser, b: PassflowUser) => a.id === b.id && a.email === b.email && a.phone === b.phone;\n\n/** The signed-in user's id, email and phone. Re-renders on sign-in, sign-up, refresh, sign-out and session expiry. */\nexport const useUser = (): PassflowUser => {\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const [user, setUser] = useState<PassflowUser>(() => readUser(passflow));\n\n useEffect(() => {\n const update = () => {\n const next = readUser(passflow);\n setUser((current) => (sameUser(current, next) ? current : next));\n };\n // The session may have changed between the first render and this subscription.\n update();\n const subscriber: PassflowSubscriber = { onAuthChange: update };\n passflow.subscribe(subscriber, USER_EVENTS);\n return () => passflow.unsubscribe(subscriber, USER_EVENTS);\n }, [passflow]);\n\n return hydrated ? user : signedOut;\n};\n","import type { PassflowUserPasskey } from '@passflow/core';\nimport { useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseUserPasskeysProps = () => {\n data: PassflowUserPasskey[];\n createUserPasskey: (relaingPartyId: string) => Promise<void>;\n editUserPasskey: (newName: string, passkeyId: string) => Promise<void>;\n deleteUserPasskey: (passkeyId: string) => Promise<void>;\n isLoading: boolean;\n isError: boolean;\n errorMessage: string;\n};\n\nexport const useUserPasskeys: UseUserPasskeysProps = () => {\n const passflow = usePassflow();\n const [data, setData] = useState<PassflowUserPasskey[]>([]);\n const [isError, setIsError] = useState<boolean>(false);\n const [errorMessage, setErrorMessage] = useState<string>('');\n const [isLoading, setIsLoading] = useState<boolean>(false);\n\n useIsomorphicLayoutEffect(() => {\n const fetch = async (): Promise<void> => {\n setIsLoading(true);\n try {\n const response = await passflow.getUserPasskeys();\n setData(response as unknown as PassflowUserPasskey[]);\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n void fetch();\n }, [passflow]);\n\n const createUserPasskey = async (\n relyingPartyId: string,\n passkeyUsername?: string,\n passkeyDisplayName?: string,\n ): Promise<void> => {\n setIsLoading(true);\n try {\n await passflow.addUserPasskey({ relyingPartyId, passkeyUsername, passkeyDisplayName });\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n const editUserPasskey = async (newName: string, passkeyId: string): Promise<void> => {\n setIsLoading(true);\n try {\n const editUserPasskeyStatus = await passflow.renameUserPasskey(newName, passkeyId);\n if (editUserPasskeyStatus) {\n const userPasskeys = await passflow.getUserPasskeys();\n setData(userPasskeys as unknown as PassflowUserPasskey[]);\n }\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n const deleteUserPasskey = async (passkeyId: string): Promise<void> => {\n setIsLoading(true);\n try {\n const deleteUserPasskeyStatus = await passflow.deleteUserPasskey(passkeyId);\n if (deleteUserPasskeyStatus) {\n const userPasskeys = await passflow.getUserPasskeys();\n setData(userPasskeys as unknown as PassflowUserPasskey[]);\n }\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n return {\n data,\n createUserPasskey,\n editUserPasskey,\n deleteUserPasskey,\n isLoading,\n isError,\n errorMessage,\n };\n};\n","import { getCountryForTimezone } from 'countries-and-timezones';\nimport {\n type ChangeEvent,\n type FC,\n type InputHTMLAttributes,\n type KeyboardEvent,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { type CountryIso2, defaultCountries, parseCountry, usePhoneInput } from 'react-international-phone';\nimport { useOutsideClick } from '@/hooks';\nimport { cn } from '@/utils';\nimport { Button, CountryFlag, Icon } from '..';\n\nimport '@/styles/index.css';\nimport 'react-international-phone/style.css';\n\ntype TFieldPhone = InputHTMLAttributes<HTMLInputElement> & {\n id: string;\n onChange: (event: ChangeEvent<HTMLInputElement>) => void;\n isError?: boolean;\n className?: string;\n // eslint-disable-next-line react/no-unused-prop-types\n ref?: null;\n};\n\nexport const FieldPhone: FC<TFieldPhone> = ({\n id,\n name,\n onChange,\n isError = false,\n className = '',\n disabled = false,\n value,\n ...inputProps\n}) => {\n // The number the field opens with; after that the input owns what is typed.\n const [startingValue] = useState(typeof value === 'string' ? value : '');\n const [show, setShow] = useState(false);\n const [filterValue, setFilterValue] = useState('');\n const [isFocused, setIsFocused] = useState(false);\n const refWrapper = useRef<HTMLDivElement>(null);\n const searchInputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (show) searchInputRef.current?.focus();\n }, [show]);\n\n useOutsideClick(refWrapper, () => {\n setShow(false);\n setFilterValue('');\n });\n\n const userTZ = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const userCountry = getCountryForTimezone(userTZ);\n // Set while a country switch is in flight: the hook resets the number to the new dial code, and the form must hear\n // about it. Typed changes already reach the form through the input's own change event.\n const countrySwitchRef = useRef(false);\n const { inputValue, country, setCountry, handlePhoneValueChange, inputRef } = usePhoneInput({\n defaultCountry: userCountry?.id.toLocaleLowerCase() || 'us',\n value: startingValue,\n onChange: ({ inputValue: nextValue }) => {\n if (!countrySwitchRef.current) return;\n countrySwitchRef.current = false;\n // The tel input is not mounted while the country list is open, so the change is reported without it.\n onChange({ target: { name, value: nextValue } } as ChangeEvent<HTMLInputElement>);\n },\n });\n\n const handlePhoneChange = (event: ChangeEvent<HTMLInputElement>) => {\n countrySwitchRef.current = false;\n handlePhoneValueChange(event);\n onChange(event);\n };\n\n const filteredCountries = useMemo(\n () =>\n defaultCountries.filter((defCountry) => {\n const { name: countryName } = parseCountry(defCountry);\n return countryName.toLowerCase().includes(filterValue.toLowerCase());\n }),\n [filterValue],\n );\n\n const preferredCountries = useMemo(\n () =>\n defaultCountries.filter((defCountry) => {\n const { iso2 } = parseCountry(defCountry);\n return iso2 === userCountry?.id.toLocaleLowerCase();\n }),\n [userCountry?.id],\n );\n\n const allCountries = useMemo(() => {\n if (filterValue) return filteredCountries;\n const preferredIso = new Set(preferredCountries.map((defCountry) => parseCountry(defCountry).iso2));\n return filteredCountries.filter((defCountry) => !preferredIso.has(parseCountry(defCountry).iso2));\n }, [filterValue, filteredCountries, preferredCountries]);\n\n const restoreCountryButtonFocus = () => {\n refWrapper.current?.querySelector<HTMLButtonElement>('.passflow-button-show-country')?.focus();\n };\n\n const handleShow = () => setShow(true);\n\n const handleClose = (restoreFocus = false) => {\n setShow(false);\n setFilterValue('');\n if (restoreFocus) restoreCountryButtonFocus();\n };\n\n const handleChangeCountry = (iso2: CountryIso2) => {\n countrySwitchRef.current = true;\n setCountry(iso2);\n handleClose(true);\n };\n\n const handleOptionKeyDown = (event: KeyboardEvent<HTMLDivElement>, iso2: CountryIso2) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n handleChangeCountry(iso2);\n return;\n }\n\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;\n event.preventDefault();\n const options = Array.from(refWrapper.current?.querySelectorAll<HTMLElement>('[role=\"option\"]') ?? []);\n const currentIndex = options.indexOf(event.currentTarget);\n const nextIndex =\n event.key === 'ArrowDown' ? Math.min(currentIndex + 1, options.length - 1) : Math.max(currentIndex - 1, 0);\n options[nextIndex]?.focus();\n };\n\n const renderCountry = (defCountry: (typeof defaultCountries)[number]) => {\n const { name: countryName, dialCode, iso2 } = parseCountry(defCountry);\n return (\n <div\n key={iso2}\n role='option'\n aria-selected={iso2 === country.iso2}\n tabIndex={0}\n title={countryName}\n onClick={() => handleChangeCountry(iso2)}\n onKeyDown={(event) => handleOptionKeyDown(event, iso2)}\n className='passflow-country-search-item'\n >\n <CountryFlag iso2={iso2} className='passflow-country-search-flag' />\n <span className='passflow-country-search-name'>{countryName}</span>\n <span className='passflow-country-search-code'>+{dialCode}</span>\n </div>\n );\n };\n\n return (\n <div\n ref={refWrapper}\n className={cn(\n 'passflow-field-phone-wrapper',\n { 'passflow-field-phone-wrapper--focus': isFocused, 'passflow-field-phone-wrapper--error': isError },\n className,\n )}\n >\n <Button\n type='button'\n variant='clean'\n onClick={() => (show ? handleClose(true) : handleShow())}\n size='big'\n className='passflow-button-show-country'\n disabled={disabled}\n aria-label={`Select country, current ${country.iso2.toUpperCase()}`}\n aria-haspopup='listbox'\n aria-expanded={show}\n aria-controls='passflow-country-options'\n >\n <CountryFlag iso2={country.iso2} />\n <Icon type='general' id='caret-down' size='small' />\n </Button>\n\n {!show ? (\n <input\n {...inputProps}\n id={id}\n name={name}\n ref={inputRef}\n type='tel'\n value={inputValue}\n disabled={disabled}\n aria-invalid={isError}\n onChange={handlePhoneChange}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n className='passflow-field-phone-input'\n />\n ) : (\n <div className='passflow-field-country-search-wrapper'>\n <input\n ref={searchInputRef}\n role='combobox'\n aria-label='Search countries'\n aria-expanded='true'\n aria-controls='passflow-country-options'\n aria-autocomplete='list'\n value={filterValue}\n onChange={(event) => setFilterValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Escape') handleClose(true);\n if (event.key === 'ArrowDown') {\n event.preventDefault();\n refWrapper.current?.querySelector<HTMLElement>('[role=\"option\"]')?.focus();\n }\n }}\n className='passflow-field-country-search'\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n placeholder='Search for a country'\n />\n <div className='passflow-field-country-search-icon'>\n <Icon type='general' id='search' size='small' />\n </div>\n </div>\n )}\n\n <div\n id='passflow-country-options'\n role='listbox'\n tabIndex={-1}\n aria-label='Countries'\n aria-hidden={!show}\n className={cn('passflow-country-search-wrapper', {\n 'passflow-country-search-wrapper--show': show,\n 'passflow-country-search-wrapper--hidden': !show,\n 'passflow-country-search-wrapper--without-preferred': !!filterValue || preferredCountries.length === 0,\n })}\n >\n {filteredCountries.length > 0 ? (\n <>\n <div role='presentation' aria-hidden='true' className='passflow-country-search-sticky-top' />\n {!filterValue && preferredCountries.length > 0 ? (\n <>\n {preferredCountries.map(renderCountry)}\n <div role='presentation' className='passflow-country-search-divider'>\n All countries\n </div>\n </>\n ) : null}\n {allCountries.map(renderCountry)}\n <div role='presentation' aria-hidden='true' className='passflow-country-search-sticky-bottom' />\n </>\n ) : (\n <div role='presentation' className='passflow-country-search-no-matches'>\n No matches\n </div>\n )}\n </div>\n </div>\n );\n};\n","/**\n * Reads a host app's shadcn/ui colour variables for `appearance=\"shadcn\"`.\n *\n * shadcn themes come in two formats. Older themes store a bare HSL triplet\n * (`--primary: 222.2 47.4% 11.2%`) that the app wraps as `hsl(var(--primary))`;\n * Tailwind v4 themes store a complete colour (`oklch(0.205 0 0)`, a hex, …)\n * used as `var(--primary)`. CSS cannot tell the two apart, so the value is read\n * in script and handed to the stylesheet as a `--passflow-login-button-*`\n * custom property. A missing variable sets nothing and the stylesheet's\n * `--passflow-*` fallback applies.\n */\n\nconst HSL_TRIPLET = /^[+-]?[\\d.]+(deg|rad|grad|turn)?\\s+[+-]?[\\d.]+%\\s+[+-]?[\\d.]+%(\\s*\\/\\s*[+-]?[\\d.]+%?)?$/;\n\n/** A shadcn colour variable's value as a CSS colour, or `undefined` when the variable is missing. */\nexport const toCssColor = (raw: string): string | undefined => {\n const value = raw.trim();\n if (!value) return undefined;\n return HSL_TRIPLET.test(value) ? `hsl(${value})` : value;\n};\n\nconst COLOR_VARIABLES = {\n '--primary': '--passflow-login-button-background',\n '--primary-foreground': '--passflow-login-button-foreground',\n '--ring': '--passflow-login-button-ring',\n} as const;\n\nexport type ShadcnThemeProperties = Partial<Record<(typeof COLOR_VARIABLES)[keyof typeof COLOR_VARIABLES], string>>;\n\n/** The login button custom properties for the shadcn colour variables that reach `element`. */\nexport const readShadcnTheme = (element: Element): ShadcnThemeProperties => {\n const style = getComputedStyle(element);\n const properties: ShadcnThemeProperties = {};\n for (const [source, target] of Object.entries(COLOR_VARIABLES) as [\n keyof typeof COLOR_VARIABLES,\n (typeof COLOR_VARIABLES)[keyof typeof COLOR_VARIABLES],\n ][]) {\n const color = toCssColor(style.getPropertyValue(source));\n if (color) properties[target] = color;\n }\n return properties;\n};\n","import type { RefObject } from 'react';\nimport { useIsomorphicLayoutEffect } from '@/hooks/use-isomorphic-layout-effect';\nimport { readShadcnTheme } from './shadcn-theme';\n\n/** The attributes a shadcn app switches its theme with, on `<html>` or `<body>`. */\nconst THEME_ATTRIBUTES = ['class', 'style', 'data-theme'];\n\n/**\n * Sets the host's shadcn colours on `ref`'s element as the custom properties\n * its stylesheet reads, and sets them again when the theme switches: a class,\n * style or `data-theme` change on `<html>` or `<body>`, or a change of\n * `prefers-color-scheme`. Does nothing while `enabled` is false.\n */\nexport const useShadcnTheme = (ref: RefObject<HTMLElement | null>, enabled: boolean): void => {\n // A layout effect so the host's colours are in place before the first paint.\n useIsomorphicLayoutEffect(() => {\n const element = ref.current;\n if (!enabled || !element) return;\n\n let applied: string[] = [];\n const clear = () => {\n for (const name of applied) element.style.removeProperty(name);\n };\n const apply = () => {\n clear();\n const theme = readShadcnTheme(element);\n applied = Object.keys(theme);\n for (const [name, value] of Object.entries(theme)) element.style.setProperty(name, value);\n };\n apply();\n\n const observer = new MutationObserver(apply);\n for (const target of [document.documentElement, document.body]) {\n observer.observe(target, { attributes: true, attributeFilter: THEME_ATTRIBUTES });\n }\n const colorScheme = window.matchMedia?.('(prefers-color-scheme: dark)');\n colorScheme?.addEventListener('change', apply);\n\n return () => {\n observer.disconnect();\n colorScheme?.removeEventListener('change', apply);\n clear();\n };\n }, [ref, enabled]);\n};\n","import { cloneElement, type FC, type MouseEvent, type ReactElement, type ReactNode, useId, useRef } from 'react';\nimport { cn } from '@/utils';\nimport '@/styles/index.css';\nimport { VisuallyHidden } from '../visually-hidden';\nimport { useShadcnTheme } from './use-shadcn-theme';\nimport './login-button.css';\n\n/**\n * `passflow` is the Passflow look. `shadcn` takes the colours, radius, focus\n * ring and font from the host app's shadcn/ui variables (`--primary`,\n * `--primary-foreground`, `--radius`, `--ring`, `--font-sans`), in either the\n * HSL-triplet or the complete-colour format, and falls back to the Passflow\n * tokens for any that are missing.\n */\nexport type LoginButtonAppearance = 'passflow' | 'shadcn';\n\n/** `signing-out` is the signed-in button while the sign-out is in flight: disabled and busy. */\nexport type LoginButtonViewState = 'signed-out' | 'signed-in' | 'signing-out';\n\nexport type LoginButtonViewProps = {\n state: LoginButtonViewState;\n /** The visible content of the default button. Ignored when `children` is given. */\n label: ReactNode;\n /** Read by assistive technology after the name while signed in, since clicking signs out. */\n signOutDescription?: string;\n appearance?: LoginButtonAppearance;\n /** The sign-in or sign-out. Not called when a wrapped child's own `onClick` calls `preventDefault()`. */\n onClick: () => void;\n /**\n * The app's own element to use as the button instead of the default one. It\n * is cloned with a click handler and otherwise left as it is: its props,\n * content and look are its own, and no label is injected. While signing out\n * it also gets `disabled` and `aria-busy`; when idle those stay as the app\n * passed them.\n */\n children?: ReactElement;\n};\n\ntype ClickableProps = { onClick?: (event?: MouseEvent<HTMLElement>) => void };\ntype ChildProps = ClickableProps & { disabled?: boolean; 'aria-busy'?: boolean };\n\n/**\n * The sign-in / sign-out button. It renders a state and calls `onClick`; the\n * `LoginButton` runtime component decides the state and does the sign-in or\n * sign-out.\n */\nexport const LoginButtonView: FC<LoginButtonViewProps> = ({\n state,\n label,\n signOutDescription = 'Sign out',\n appearance = 'passflow',\n onClick,\n children,\n}) => {\n const buttonRef = useRef<HTMLButtonElement>(null);\n const descriptionId = useId();\n useShadcnTheme(buttonRef, appearance === 'shadcn' && !children);\n\n const busy = state === 'signing-out';\n\n if (children) {\n const own = (children.props as ClickableProps).onClick;\n return cloneElement(children as ReactElement<ChildProps>, {\n // Some UI libraries call `onClick()` with no event; then there is nothing to have been prevented.\n onClick: (event?: MouseEvent<HTMLElement>) => {\n own?.(event);\n if (!event?.defaultPrevented) onClick();\n },\n // Set only while busy, so an idle child keeps its own `disabled` and `aria-busy`.\n ...(busy ? { disabled: true, 'aria-busy': true } : {}),\n });\n }\n\n const signedIn = state !== 'signed-out';\n\n // The description is a sibling, not a child: inside the button it would join the button's name.\n return (\n <>\n <button\n ref={buttonRef}\n type='button'\n className={cn('passflow-login-button', {\n 'passflow-login-button--shadcn': appearance === 'shadcn',\n })}\n disabled={busy}\n aria-busy={busy || undefined}\n aria-describedby={signedIn ? descriptionId : undefined}\n onClick={onClick}\n >\n {label}\n </button>\n {signedIn ? <VisuallyHidden id={descriptionId}>{signOutDescription}</VisuallyHidden> : null}\n </>\n );\n};\n","import * as PopoverPrimitive from '@radix-ui/react-popover';\nimport { type ComponentPropsWithoutRef, type ElementRef, forwardRef } from 'react';\nimport { cn } from '@/utils';\n\nconst Popover = PopoverPrimitive.Root;\n\nconst PopoverTrigger = PopoverPrimitive.Trigger;\n\nconst PopoverAnchor = PopoverPrimitive.Anchor;\n\nconst PopoverContent = forwardRef<\n ElementRef<typeof PopoverPrimitive.Content>,\n ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n ref={ref}\n align={align}\n sideOffset={sideOffset}\n className={cn('passflow-popover-content', className)}\n {...props}\n />\n </PopoverPrimitive.Portal>\n));\nPopoverContent.displayName = PopoverPrimitive.Content.displayName;\n\nexport { Popover, PopoverAnchor, PopoverContent, PopoverTrigger };\n","/* eslint-disable react/jsx-props-no-spreading */\nimport type { ComponentType, FC } from 'react';\nimport { useHydrated } from '@/hooks/use-hydrated';\n\n/**\n * Renders `Component` only once the page has hydrated. The URL and the session exist only in the browser, so a screen\n * that reads either during render renders nothing on the server and in the hydration render, and its content from\n * the next render. A render that is not a hydration shows the screen at once.\n */\nexport const withHydration = <P extends object>(Component: ComponentType<P>): FC<P> => {\n const Hydrated: FC<P> = (props) => {\n const hydrated = useHydrated();\n if (!hydrated) return null;\n return <Component {...props} />;\n };\n Hydrated.displayName = Component.displayName ?? Component.name;\n return Hydrated;\n};\n","import type { LoginScreenProps } from '@/components/ui';\nimport type { UseConsentProps } from '@/hooks/use-consent';\n\n/**\n * Maps consent state onto the shared LoginScreen. Pure — every visual decision\n * lives in LoginScreen, every protocol decision lives in useConsent, and this\n * file is only the translation between them.\n */\nexport const getConsentLoginScreenProps = (consent: UseConsentProps): LoginScreenProps | null => {\n if (consent.status === 'loading') return null;\n\n if (consent.status === 'invalid') {\n return {\n chrome: {\n title: consent.error?.message ?? 'Consent request unavailable',\n },\n state: {\n kind: 'general-error',\n message: consent.error?.message,\n detail: consent.error?.description,\n actionLabel: 'Back to login',\n testId: 'consent-invalid',\n onAction: () => {\n window.location.href = '/web';\n },\n },\n };\n }\n\n if (consent.status === 'redirecting') {\n return {\n chrome: {\n title: 'Taking you back',\n subtitle: `Returning you to ${consent.info?.app_name || 'the application'}.`,\n },\n state: {\n kind: 'status',\n tone: 'success',\n message: 'Decision recorded',\n detail: 'You can close this page if it does not continue on its own.',\n testId: 'consent-redirecting',\n },\n };\n }\n\n const info = consent.info;\n if (!info) return null;\n\n const appName = info.app_name || info.client_id;\n const busy = consent.status === 'working';\n\n return {\n chrome: {\n title: `Allow ${appName} to access your account?`,\n subtitle: 'Choose what this application may use, then allow or deny.',\n // The app's own logo replaces the Passflow mark, which is what makes this\n // read as \"THIS app is asking\" rather than a generic Passflow screen.\n customLogo: info.app_logo_url || undefined,\n customLogoAlt: `${appName} logo`,\n },\n state: {\n kind: 'consent',\n appName,\n scopes: info.requested_scopes.map((scope) => {\n const meta = consent.scopeMetadata(scope);\n return {\n scope,\n label: meta.label || scope,\n description: meta.description || undefined,\n granted: consent.grantedScopes.includes(scope),\n };\n }),\n busy,\n error: consent.error?.message,\n allowLabel: 'Allow',\n denyLabel: 'Deny',\n busyLabel: 'Submitting…',\n testId: 'consent-screen',\n allowTestId: 'consent-allow',\n denyTestId: 'consent-deny',\n appNameTestId: 'consent-app-name',\n onToggleScope: consent.toggleScope,\n onAllow: () => void consent.allow(),\n onDeny: () => void consent.deny(),\n },\n };\n};\n","import type { FC } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useConsent } from '@/hooks/use-consent';\nimport { getConsentLoginScreenProps } from './screen';\n\n/**\n * OIDC consent controller, mounted by the host app on `/web/consent`.\n *\n * Standalone by design: it needs no PassflowProvider. The staged request is\n * addressed by `consent_challenge_id` on the URL and read with a same-origin\n * cookie, so there is no SDK client, no app settings lookup, and no token to\n * hold — which is also why mounting it inside the provider would be actively\n * wrong, since the provider's session-exchange probe would fire against a\n * challenge that is waiting for a human decision.\n */\nconst ConsentFlowScreen: FC = () => {\n const consent = useConsent();\n const screen = getConsentLoginScreenProps(consent);\n\n return screen ? <LoginScreen {...screen} /> : null;\n};\n\nexport const ConsentFlow = withHydration(ConsentFlowScreen);\n","import type { LoginMethodConfig, LoginScreenProps } from '@/components/ui';\nimport type { UseDeviceVerifyProps } from '@/hooks/use-device-verify';\nimport type { AuthUiError, DeviceError } from '@/types';\nimport { deviceErrorOfType } from '@/utils';\n\nconst getDeviceLoginMethods = (device: UseDeviceVerifyProps): LoginMethodConfig => ({\n identities: device.info?.methods.password\n ? [\n {\n id: 'email_or_username',\n label: 'Email',\n selectLabel: 'Use email',\n requiredMessage: 'Email is required',\n format: 'email',\n password: true,\n },\n ]\n : [],\n passkey: Boolean(device.info?.methods.passkey),\n providers: [],\n});\n\nconst toCredentialsError = (error: DeviceError | null): AuthUiError | null => {\n if (!error) return null;\n\n return {\n message: error.message,\n scope: error.type === 'bad_credentials' || error.type === 'missing_credentials' ? 'credentials' : 'form',\n };\n};\n\nconst deviceNotice = (device: UseDeviceVerifyProps) => {\n if (!device.info) return undefined;\n\n return {\n code: device.info.user_code,\n appName: device.info.app_name,\n message: \"requested this sign-in. Confirm that the code matches your terminal. If it doesn't, close this page.\",\n codeTestId: 'device-consent-user-code',\n appNameTestId: 'device-consent-app-name',\n };\n};\n\nexport const getDeviceLoginScreenProps = (device: UseDeviceVerifyProps): LoginScreenProps | null => {\n if (device.status === 'loading') return null;\n\n if (device.status === 'code_entry') {\n return {\n chrome: {\n title: 'Enter the code',\n subtitle: 'Type the code shown on your device.',\n },\n state: {\n kind: 'code-entry',\n error: device.error?.message,\n testId: 'device-code-entry',\n onSubmit: device.submitCode,\n },\n };\n }\n\n if (device.status === 'done') {\n return {\n chrome: {\n title: device.info?.app_name ? `You're signed in to ${device.info.app_name}` : \"You're signed in\",\n subtitle: \"Head back to your terminal — it's ready to go.\",\n },\n state: {\n kind: 'status',\n tone: 'success',\n message: 'This device is approved',\n detail: 'You can close this page.',\n testId: device.info?.mode === 'passkey' ? 'device-auto-passkey-done' : 'device-done',\n },\n };\n }\n\n if (device.status === 'refused') {\n const error = device.error ?? deviceErrorOfType('mode_disabled');\n return {\n chrome: {\n title: \"Sign-in isn't available this way\",\n },\n state: {\n kind: 'status',\n tone: 'disabled',\n message: error.message,\n detail: 'Nothing was approved, and nothing was sent to the device that showed you this code.',\n testId: 'device-mode-disabled',\n },\n };\n }\n\n if (device.status === 'failed') {\n const error = device.error ?? deviceErrorOfType('generic');\n return {\n chrome: {\n title: \"That didn't work\",\n },\n state: {\n kind: 'status',\n tone: 'error',\n message: error.message,\n recoverable: error.isRecoverable,\n testId: 'device-failed',\n onRetry: error.isRecoverable ? () => device.submitCode('') : undefined,\n },\n };\n }\n\n if (!device.info) return null;\n\n // Every mode asks for the second factor the same way, before its approval.\n if (device.status === 'second_factor' || (device.status === 'working' && device.isSecondFactorPending)) {\n return {\n chrome: {\n title: 'Two-Factor Authentication',\n subtitle: `One more step to approve ${device.info.app_name}.`,\n },\n state: {\n kind: 'second-factor',\n methods: device.secondFactorMethods,\n identity: device.email,\n busy: device.status === 'working',\n error: device.error?.message,\n testId: 'device-second-factor',\n onSubmit: (method, code) => void device.submitSecondFactor(method, code),\n onMethodChange: device.clearError,\n },\n };\n }\n\n if (device.info.mode === 'passkey') {\n const working = (device.status === 'ready' || device.status === 'working') && !device.error;\n return {\n chrome: {\n title: `Sign in to ${device.info.app_name}`,\n subtitle: 'Confirm with your passkey to finish this device sign-in.',\n },\n state: {\n kind: 'passkey-progress',\n working,\n message: device.error\n ? \"Passkey sign-in couldn't continue.\"\n : 'Waiting for your passkey — follow the prompt on your device.',\n error: device.error?.message,\n recoverable: device.error?.isRecoverable,\n testId: 'device-auto-passkey',\n onRetry: device.error?.isRecoverable ? () => void device.confirmWithPasskey() : undefined,\n },\n };\n }\n\n const busy = device.status === 'working';\n const authenticated = device.isAuthenticated || device.status === 'signed_in';\n const methods = getDeviceLoginMethods(device);\n const notice = deviceNotice(device);\n\n if (device.info.mode === 'full_login') {\n if (authenticated) {\n return {\n chrome: {\n title: `Approve sign-in to ${device.info.app_name}`,\n subtitle: 'Confirm that the code matches your terminal before approving.',\n },\n state: {\n kind: 'device-approval',\n appName: device.info.app_name,\n code: device.info.user_code,\n identity: device.email,\n busy,\n error: device.error?.message,\n testId: 'device-full-login-approval',\n actionTestId: 'device-confirm',\n codeTestId: 'device-consent-user-code',\n appNameTestId: 'device-consent-app-name',\n onApprove: () => void device.approve(),\n },\n };\n }\n\n return {\n chrome: {\n title: `Sign in to approve ${device.info.app_name}`,\n subtitle: 'Confirm the code, then sign in to continue.',\n variant: 'sign-in',\n },\n state: {\n kind: 'credentials',\n methods,\n passwordPolicy: null,\n notice,\n busy,\n error: toCredentialsError(device.error),\n primaryLabel: busy ? 'Signing in…' : 'Sign In',\n passkeyLabel: 'Sign In with a Passkey',\n testId: 'device-full-login',\n onPassword: (values) => void device.signInWithPassword(values.emailOrUsername, values.password),\n onPasskey: () => void device.signInWithPasskey(),\n },\n };\n }\n\n return {\n chrome: {\n title: `Approve sign-in to ${device.info.app_name}`,\n subtitle: 'Confirm the code, then sign in to approve this request.',\n variant: 'sign-in',\n },\n state: {\n kind: 'credentials',\n methods,\n passwordPolicy: null,\n notice,\n busy,\n error: toCredentialsError(device.error),\n primaryLabel: busy ? 'Approving…' : 'Approve',\n primaryTestId: 'device-confirm',\n passkeyLabel: 'Approve with a Passkey',\n testId: 'device-consent',\n onPassword: (values) => void device.confirmWithPassword(values.emailOrUsername, values.password),\n onPasskey: () => void device.confirmWithPasskey(),\n },\n };\n};\n","import type { FC } from 'react';\nimport { useEffect, useRef } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useDeviceVerify } from '@/hooks/use-device-verify';\nimport { getDeviceLoginScreenProps } from './screen';\n\n/**\n * RFC 8628 device verification controller.\n *\n * The server selects consent, full-login, or passkey mode. This component owns\n * the state transition and automatic passkey attempt; the Storybook-backed\n * LoginScreen owns every visual state.\n */\nconst DeviceVerifyFlowScreen: FC = () => {\n const device = useDeviceVerify();\n const attemptedPasskeyChallenge = useRef<string | null>(null);\n const { confirmWithPasskey } = device;\n const challengeKey = device.info?.csrf_token ?? null;\n const isAutomaticPasskeyReady = device.info?.mode === 'passkey' && device.status === 'ready' && !device.error;\n\n useEffect(() => {\n if (!isAutomaticPasskeyReady || !challengeKey || attemptedPasskeyChallenge.current === challengeKey) return;\n\n attemptedPasskeyChallenge.current = challengeKey;\n void confirmWithPasskey();\n }, [challengeKey, confirmWithPasskey, isAutomaticPasskeyReady]);\n\n const screen = getDeviceLoginScreenProps(device);\n return screen ? <LoginScreen {...screen} /> : null;\n};\n\nexport const DeviceVerifyFlow = withHydration(DeviceVerifyFlowScreen);\n","import type { TwoFactorSetupResponse } from '@passflow/core';\nimport type { LoginScreenAction, LoginScreenProps } from '@/components/ui';\n\nconst DEFAULT_DIGITS = 6;\n\ntype SetupScreenStatus = {\n busy: boolean;\n error?: string | null;\n};\n\ntype StartScreenProps = SetupScreenStatus & {\n secondaryAction?: LoginScreenAction;\n onStart: () => void;\n};\n\ntype CodeScreenProps = SetupScreenStatus & {\n data: TwoFactorSetupResponse;\n /** Used when the server named no digit count. */\n fallbackDigits?: number;\n /** Tells the user something without marking the code invalid. An `error` takes its place. */\n notice?: string;\n secondaryAction?: LoginScreenAction;\n onSubmit: (code: string) => void;\n};\n\ntype RecoveryCodesScreenProps = SetupScreenStatus & {\n codes: string[];\n onContinue: () => void;\n};\n\n/** Direct enrolment and the setup link page share these, so both look the same. */\nexport const getTwoFactorSetupStartScreen = ({\n busy,\n error,\n secondaryAction,\n onStart,\n}: StartScreenProps): LoginScreenProps => ({\n chrome: {\n title: 'Enable Two-Factor Authentication',\n subtitle: 'Add an extra layer of security to your account',\n },\n state: {\n kind: 'two-factor-setup',\n step: 'start',\n startLabel: 'Get Started',\n busyLabel: 'Loading...',\n busy,\n error,\n secondaryAction,\n testId: 'two-factor-setup-start',\n onStart,\n },\n});\n\n/** A user with two-factor authentication on: shown instead of the start step. */\nexport const getTwoFactorSetupEnrolledScreen = (): LoginScreenProps => ({\n chrome: { title: 'Two-Factor Authentication' },\n state: {\n kind: 'status',\n tone: 'success',\n message: 'Two-factor authentication is on for your account.',\n detail: 'You will be asked for a code from your authenticator app when you sign in.',\n testId: 'two-factor-setup-enrolled',\n },\n});\n\nexport const getTwoFactorSetupCodeScreen = ({\n data,\n fallbackDigits = DEFAULT_DIGITS,\n notice,\n busy,\n error,\n secondaryAction,\n onSubmit,\n}: CodeScreenProps): LoginScreenProps => {\n const digits = data.totp_digits ?? fallbackDigits;\n\n return {\n chrome: data.qr_code\n ? {\n title: 'Scan QR Code',\n subtitle: 'Scan this code with your authenticator app (Google Authenticator, Authy, etc.)',\n }\n : {\n title: 'Add Your Authenticator',\n subtitle: 'Add this key to your authenticator app (Google Authenticator, Authy, etc.)',\n },\n state: {\n kind: 'two-factor-setup',\n step: 'code',\n qrCode: data.qr_code,\n qrAlt: '2FA QR Code',\n secret: data.secret,\n secretLabel: 'Enter this key in your authenticator app.',\n showSecretLabel: \"Can't scan? Enter code manually\",\n hideSecretLabel: 'Hide manual code',\n digits,\n codeLabel: `Enter the ${digits}-digit code from your app to confirm:`,\n submitLabel: 'Confirm & Enable',\n busyLabel: 'Confirming...',\n busy,\n alert: error ? { message: error, tone: 'error' } : notice ? { message: notice, tone: 'info' } : undefined,\n secondaryAction,\n testId: 'two-factor-setup-code',\n onSubmit,\n },\n };\n};\n\nexport const getTwoFactorRecoveryCodesScreen = ({\n codes,\n busy,\n error,\n onContinue,\n}: RecoveryCodesScreenProps): LoginScreenProps => ({\n chrome: {\n title: 'Save Your Recovery Codes',\n subtitle: \"Store these codes in a safe place. You'll need them if you lose access to your authenticator.\",\n },\n state: {\n kind: 'two-factor-recovery-codes',\n warning: 'These codes will only be shown once. Make sure to save them!',\n codes,\n copyLabel: 'Copy to Clipboard',\n continueLabel: \"I've Saved These Codes\",\n busyLabel: 'Finishing sign-in...',\n busy,\n error,\n testId: 'two-factor-recovery-codes',\n onCopy: () => void navigator.clipboard.writeText(codes.join('\\n')),\n onContinue,\n },\n});\n","import { type FC, useEffect, useRef } from 'react';\nimport { LoginScreen, type LoginScreenAction } from '@/components/ui';\nimport { useTwoFactorSetup } from '@/hooks';\nimport { twoFactorBackToSignInLabel } from '@/utils';\nimport {\n getTwoFactorRecoveryCodesScreen,\n getTwoFactorSetupCodeScreen,\n getTwoFactorSetupEnrolledScreen,\n getTwoFactorSetupStartScreen,\n} from './setup-screen';\n\nimport '@/styles/index.css';\n\ntype TwoFactorSetupFormProps = {\n onComplete?: (recoveryCodes: string[]) => void;\n /** The way out of the first step only. */\n onCancel?: () => void;\n /** The way out of the first step and the code step, labelled Back to sign in. */\n onBackToSignIn?: () => void;\n numInputs?: number;\n};\n\nexport const TwoFactorSetupForm: FC<TwoFactorSetupFormProps> = ({ onComplete, onCancel, onBackToSignIn, numInputs }) => {\n const { setupData, recoveryCodes, step, beginSetup, confirmSetup, finish, isLoading, isError, error } = useTwoFactorSetup();\n const shownError = isError ? error : null;\n const backToSignIn: LoginScreenAction | undefined = onBackToSignIn\n ? { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn }\n : undefined;\n const cancel: LoginScreenAction | undefined = onCancel ? { label: 'Cancel', onClick: onCancel } : undefined;\n\n const handleComplete = () => {\n // A caller that gets `onComplete` owns the next step: its session may be gone, so the form stays on the codes.\n if (onComplete) onComplete(recoveryCodes);\n else finish();\n };\n\n // No codes to save: the codes screen is skipped.\n const skipsCodes = step === 'complete' && recoveryCodes.length === 0;\n const skipCodesRef = useRef(handleComplete);\n skipCodesRef.current = handleComplete;\n useEffect(() => {\n if (skipsCodes) skipCodesRef.current();\n }, [skipsCodes]);\n\n if (step === 'enrolled' || skipsCodes) return <LoginScreen {...getTwoFactorSetupEnrolledScreen()} />;\n\n if (step === 'idle' || step === 'checking') {\n return (\n <LoginScreen\n {...getTwoFactorSetupStartScreen({\n busy: isLoading || step === 'checking',\n error: shownError,\n secondaryAction: backToSignIn ?? cancel,\n onStart: () => void beginSetup(),\n })}\n />\n );\n }\n\n if (step === 'setup' && setupData) {\n return (\n <LoginScreen\n {...getTwoFactorSetupCodeScreen({\n data: setupData,\n fallbackDigits: numInputs,\n busy: isLoading,\n error: shownError,\n secondaryAction: backToSignIn,\n onSubmit: (code) => void confirmSetup(code),\n })}\n />\n );\n }\n\n if (step === 'complete') {\n return (\n <LoginScreen {...getTwoFactorRecoveryCodesScreen({ codes: recoveryCodes, busy: false, onContinue: handleComplete })} />\n );\n }\n\n return null;\n};\n","import type { FC } from 'react';\nimport { useEffect, useState } from 'react';\nimport { TwoFactorSetupForm } from '@/components/form/two-factor-setup';\nimport { routes } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useNavigation, usePassflow } from '@/hooks';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { TwoFactorLoopPrevention } from '@/utils';\n\nimport '@/styles/index.css';\n\nexport type TwoFactorSetupFlowProps = {\n successAuthRedirect?: SuccessAuthRedirect;\n twoFactorVerifyPath?: string;\n signInPath?: string;\n};\n\nconst TwoFactorSetupFlowScreen: FC<TwoFactorSetupFlowProps> = ({\n twoFactorVerifyPath = routes.two_factor_verify.path,\n signInPath = routes.signin.path,\n}) => {\n const [shouldBlockRender, setShouldBlockRender] = useState(false);\n const { navigate } = useNavigation();\n const passflow = usePassflow();\n\n // Handle initial verification requirement check\n // User must be in partial auth state (have tfa_token) to access setup\n useEffect(() => {\n if (!passflow.isTwoFactorVerificationRequired()) {\n // Not in partial auth state - redirect to sign-in\n if (TwoFactorLoopPrevention.canRedirect()) {\n TwoFactorLoopPrevention.incrementRedirect();\n navigate({ to: signInPath });\n setShouldBlockRender(true);\n } else {\n // Loop detected - let component handle gracefully\n setShouldBlockRender(false);\n }\n }\n }, [passflow, navigate, signInPath]);\n\n const handleSetupComplete = () => {\n // After setup is complete, redirect back to verify flow\n // User now has 2FA enabled and needs to verify with a code\n navigate({ to: twoFactorVerifyPath });\n };\n\n const handleCancel = () => {\n // User cancelled setup - reset loop prevention and go back to sign-in\n TwoFactorLoopPrevention.reset();\n navigate({ to: signInPath });\n };\n\n // Don't render if we're redirecting\n if (shouldBlockRender) {\n return null;\n }\n\n // Don't render if verification not required and no loop detected\n if (!passflow.isTwoFactorVerificationRequired() && TwoFactorLoopPrevention.canRedirect()) {\n return null;\n }\n\n return <TwoFactorSetupForm onComplete={handleSetupComplete} onCancel={handleCancel} />;\n};\n\nexport const TwoFactorSetupFlow = withHydration(TwoFactorSetupFlowScreen);\n","import type { FC } from 'react';\nimport { useEffect } from 'react';\nimport { TwoFactorSetupForm } from '@/components/form/two-factor-setup';\nimport { LoginScreen, type LoginStatusState } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { type UseTwoFactorSetupMagicLinkReturn, useNavigation, useTwoFactorSetupMagicLink } from '@/hooks';\nimport {\n signInSearch,\n twoFactorBackToSignInLabel,\n twoFactorLinkAlreadyUsedMessage,\n twoFactorRateLimitedMessage,\n twoFactorSignInLabel,\n} from '@/utils';\n\nimport '@/styles/index.css';\n\n/**\n * Error type for magic link validation\n */\ntype MagicLinkError = NonNullable<UseTwoFactorSetupMagicLinkReturn['error']>;\n\n/**\n * Props for TwoFactorSetupMagicLinkFlow component\n */\nexport type TwoFactorSetupMagicLinkFlowProps = {\n /**\n * The magic-link token. Leave it out and it is read from the URL: the path\n * segment after `/two-factor-setup-magic-link/` (or the same after `#`).\n */\n token?: string;\n /** Callback after successful setup */\n onSuccess?: () => void;\n /** Callback on validation error */\n onError?: (error: MagicLinkError) => void;\n /** Whether to redirect after setup (default: true) */\n redirectOnSuccess?: boolean;\n /** Path to sign-in page (default: /signin) */\n signInPath?: string;\n};\n\nconst MAGIC_LINK_SEGMENT = /\\/two-factor-setup-magic-link\\/([^/?#]+)/;\n\n/** The token in the current URL's path, or after `#` for hash routing; '' when there is none. */\nconst tokenFromUrl = (): string => {\n const found = MAGIC_LINK_SEGMENT.exec(window.location.pathname) ?? MAGIC_LINK_SEGMENT.exec(window.location.hash);\n if (!found?.[1]) return '';\n try {\n return decodeURIComponent(found[1]);\n } catch {\n return found[1];\n }\n};\n\nconst ERROR_SUBTITLES: Partial<Record<MagicLinkError['code'], string>> = {\n EXPIRED_TOKEN: 'This link has expired',\n INVALID_TOKEN: 'This link is invalid',\n REVOKED_TOKEN: 'This link has been revoked',\n SERVER_ERROR: 'Something went wrong',\n};\n\ntype ErrorStateOptions = {\n isRetrying: boolean;\n onRetry: () => void;\n onSignIn: () => void;\n};\n\nconst errorState = (error: MagicLinkError, { isRetrying, onRetry, onSignIn }: ErrorStateOptions): LoginStatusState => {\n const base = { kind: 'status', tone: 'error', testId: 'two-factor-link-error' } as const;\n const signIn = { label: twoFactorSignInLabel, onClick: onSignIn };\n const backToSignIn = { label: twoFactorBackToSignInLabel, onClick: onSignIn };\n\n switch (error.code) {\n case 'ALREADY_USED':\n return { ...base, message: twoFactorLinkAlreadyUsedMessage, primaryAction: signIn };\n case 'RATE_LIMITED':\n return { ...base, message: twoFactorRateLimitedMessage, primaryAction: signIn };\n case 'SERVER_ERROR':\n return {\n ...base,\n message: error.message,\n primaryAction: { label: isRetrying ? 'Retrying...' : 'Try Again', busy: isRetrying, onClick: onRetry },\n secondaryAction: backToSignIn,\n };\n default:\n return {\n ...base,\n message: error.message,\n detail: 'Please contact your administrator to request a new magic link.',\n secondaryAction: backToSignIn,\n };\n }\n};\n\n/**\n * Flow component for magic link 2FA setup\n *\n * This component:\n * 1. Takes the token from its `token` prop, or from the URL\n * 2. Validates token via useTwoFactorSetupMagicLink hook\n * 3. Shows loading state during validation\n * 4. Shows error UI if validation fails\n * 5. Renders TwoFactorSetupForm if validation succeeds\n * 6. Redirects to sign-in after successful setup\n *\n * Route: /two-factor-setup-magic-link/:token\n */\nconst TwoFactorSetupMagicLinkFlowScreen: FC<TwoFactorSetupMagicLinkFlowProps> = ({\n token: tokenProp,\n onSuccess,\n onError,\n redirectOnSuccess = true,\n signInPath = routes.signin.path,\n}) => {\n const token = tokenProp ?? tokenFromUrl();\n const { navigate } = useNavigation();\n const searchSource = useSearchSource();\n\n const { isLoading, isRetrying, isValidated, error, retry } = useTwoFactorSetupMagicLink(token);\n\n useEffect(() => {\n if (error) {\n onError?.(error);\n }\n }, [error, onError]);\n\n const goToSignIn = () => navigate({ to: signInPath, search: signInSearch(searchSource.read()) });\n\n const handleSetupComplete = () => {\n onSuccess?.();\n if (redirectOnSuccess) goToSignIn();\n };\n\n if (isLoading) {\n return (\n <LoginScreen\n chrome={{ title: 'Validating Magic Link', subtitle: 'Please wait while we verify your link...' }}\n state={{ kind: 'status', tone: 'working', message: 'Validating your magic link...', testId: 'two-factor-link-loading' }}\n />\n );\n }\n\n if (error) {\n return (\n <LoginScreen\n chrome={{ title: 'We could not open this link', subtitle: ERROR_SUBTITLES[error.code] }}\n state={errorState(error, { isRetrying, onRetry: () => void retry(), onSignIn: goToSignIn })}\n />\n );\n }\n\n if (isValidated) {\n return <TwoFactorSetupForm onComplete={handleSetupComplete} onBackToSignIn={goToSignIn} />;\n }\n\n // Fallback (should not reach here)\n return null;\n};\n\nexport const TwoFactorSetupMagicLinkFlow = withHydration(TwoFactorSetupMagicLinkFlowScreen);\n","import { SERVICE_UNAVAILABLE_MESSAGE } from '@passflow/core';\nimport type { FC } from 'react';\nimport { LoginScreen, type LoginScreenProps } from '@/components/ui';\nimport { useAppSettings } from '@/hooks';\nimport type { SignInEnding } from '@/hooks/use-sign-in-ending';\n\nexport const SIGNED_IN_MESSAGE = \"You're signed in\";\n\nconst COULD_NOT_FINISH = 'We could not finish your sign-in';\n\nconst screens: Record<\n Exclude<SignInEnding, 'none'>,\n (onRetry: () => void) => Pick<LoginScreenProps, 'state'> & { title: string }\n> = {\n checking: () => ({\n title: 'Finishing your sign-in',\n state: { kind: 'status', tone: 'working', message: 'One moment.', testId: 'sign-in-checking' },\n }),\n 'signed-in': () => ({\n title: SIGNED_IN_MESSAGE,\n state: { kind: 'status', tone: 'success', message: 'You can close this page.', testId: 'signed-in' },\n }),\n refused: () => ({\n title: COULD_NOT_FINISH,\n state: {\n kind: 'status',\n tone: 'error',\n message: 'This app does not allow the address it was asked to return to. Contact your administrator.',\n testId: 'sign-in-refused',\n },\n }),\n unavailable: (onRetry) => ({\n title: COULD_NOT_FINISH,\n state: {\n kind: 'status',\n tone: 'error',\n message: 'We could not check where to send you. Try again.',\n recoverable: true,\n retryLabel: 'Try again',\n onRetry,\n testId: 'sign-in-unavailable',\n },\n }),\n 'service-unavailable': (onRetry) => ({\n title: COULD_NOT_FINISH,\n state: {\n kind: 'status',\n tone: 'error',\n message: SERVICE_UNAVAILABLE_MESSAGE,\n recoverable: true,\n retryLabel: 'Try again',\n onRetry,\n testId: 'sign-in-service-unavailable',\n },\n }),\n};\n\n/** How a sign-in ended, when that is not a redirect. See `useSignInEnding`. */\nexport const SignInEndingScreen: FC<{ ending: Exclude<SignInEnding, 'none'>; onRetry: () => void }> = ({ ending, onRetry }) => {\n const { currentStyles, loginAppTheme } = useAppSettings();\n const { title, state } = screens[ending](onRetry);\n\n return (\n <LoginScreen\n chrome={{\n title,\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={state}\n />\n );\n};\n","import { type FC, useEffect, useRef, useState } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { useTwoFactorVerify } from '@/hooks';\nimport {\n getUserFriendlyErrorMessage,\n isTerminalTwoFactorError,\n twoFactorBackToSignInLabel,\n twoFactorWrongRecoveryCodeMessage,\n} from '@/utils';\n\nimport '@/styles/index.css';\n\ntype TwoFactorRecoveryFormProps = {\n onSuccess?: () => void;\n onBack?: () => void;\n /** The server ended the sign-in, or locked it for too many attempts. The form still shows why when this is not handled. */\n onEnded?: (type: 'expired' | 'rate_limited') => void;\n /** The way out once no further code can be taken. */\n onBackToSignIn?: () => void;\n title?: string;\n subtitle?: string;\n /** Label of the \"trust this device\" option, unticked by default. */\n trustDeviceLabel?: string;\n /** The server's `device_trust_available` for this sign-in. Only `false` hides the option; absent shows it. */\n deviceTrustAvailable?: boolean;\n};\n\n/** Only a ticked box asks for trust; an unticked one sends no option at all. */\nconst completionOptions = (trustDevice: boolean) => (trustDevice ? { trustDevice: true } : undefined);\n\nexport const TwoFactorRecoveryForm: FC<TwoFactorRecoveryFormProps> = ({\n onSuccess,\n onBack,\n onEnded,\n onBackToSignIn,\n title = 'Use Recovery Code',\n subtitle = 'Enter one of your recovery codes',\n trustDeviceLabel = 'Trust this device',\n deviceTrustAvailable,\n}) => {\n const [code, setCode] = useState('');\n const [trustDevice, setTrustDevice] = useState(false);\n const { useRecoveryCode: redeemRecoveryCode, isLoading, isError, errorDetails, reset } = useTwoFactorVerify();\n const errorType = errorDetails?.type;\n\n // Once per error, whatever the caller's callback identity does.\n const onEndedRef = useRef(onEnded);\n onEndedRef.current = onEnded;\n useEffect(() => {\n if (errorType === 'expired' || errorType === 'rate_limited') onEndedRef.current?.(errorType);\n }, [errorType]);\n\n const handleCodeChange = (value: string) => {\n reset();\n // Normalize: uppercase and remove spaces\n setCode(value.toUpperCase().replace(/\\s/g, ''));\n };\n\n const handleSubmit = async () => {\n const result = await redeemRecoveryCode(code, completionOptions(trustDevice));\n if (result) onSuccess?.();\n };\n\n const locked = isTerminalTwoFactorError(errorType);\n const errorMessage = errorDetails\n ? errorType === 'invalid_code'\n ? twoFactorWrongRecoveryCodeMessage\n : getUserFriendlyErrorMessage(errorDetails)\n : '';\n\n return (\n <LoginScreen\n chrome={{ title, subtitle }}\n state={{\n kind: 'two-factor-code',\n factor: { type: 'recovery', placeholder: 'XXXX-XXXX-XXXX' },\n label: 'Recovery Code',\n code,\n trustDevice:\n deviceTrustAvailable === false\n ? undefined\n : { label: trustDeviceLabel, checked: trustDevice, onChange: setTrustDevice },\n busy: isLoading,\n canSubmit: code.length >= 8,\n locked,\n alert:\n isError && errorDetails ? { message: errorMessage, tone: errorType === 'expired' ? 'info' : 'error' } : undefined,\n submitLabel: 'Verify',\n busyLabel: 'Verifying...',\n alternate: onBack ? { prompt: 'Have your device?', label: 'Use authenticator code', onClick: onBack } : undefined,\n secondaryAction: locked && onBackToSignIn ? { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn } : undefined,\n testId: 'two-factor-recovery',\n onCodeChange: handleCodeChange,\n onSubmit: () => void handleSubmit(),\n }}\n />\n );\n};\n","import { type FC, useEffect, useRef, useState } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { usePassflow, useTwoFactorVerify } from '@/hooks';\nimport { getUserFriendlyErrorMessage, isTerminalTwoFactorError, twoFactorBackToSignInLabel } from '@/utils';\n\nimport '@/styles/index.css';\n\ntype TwoFactorVerifyFormProps = {\n onSuccess?: () => void;\n onUseRecovery?: () => void;\n /** The server ended the sign-in, or locked it for too many attempts. The form still shows why when this is not handled. */\n onEnded?: (type: 'expired' | 'rate_limited') => void;\n /** The way out once no further code can be taken. */\n onBackToSignIn?: () => void;\n title?: string;\n subtitle?: string;\n numInputs?: number;\n shouldAutoFocus?: boolean;\n /** Label of the \"trust this device\" option, unticked by default. */\n trustDeviceLabel?: string;\n /** The server's `device_trust_available` for this sign-in. Only `false` hides the option; absent shows it. */\n deviceTrustAvailable?: boolean;\n};\n\n/** Only a ticked box asks for trust; an unticked one sends no option at all. */\nconst completionOptions = (trustDevice: boolean) => (trustDevice ? { trustDevice: true } : undefined);\n\nconst TwoFactorVerifyFormScreen: FC<TwoFactorVerifyFormProps> = ({\n onSuccess,\n onUseRecovery,\n onEnded,\n onBackToSignIn,\n title = 'Two-Factor Authentication',\n subtitle,\n numInputs,\n shouldAutoFocus = true,\n trustDeviceLabel = 'Trust this device',\n deviceTrustAvailable,\n}) => {\n const [code, setCode] = useState('');\n const [trustDevice, setTrustDevice] = useState(false);\n const passflow = usePassflow();\n const { verify, isLoading, isError, errorDetails, reset } = useTwoFactorVerify();\n const errorType = errorDetails?.type;\n\n // An explicit numInputs wins; otherwise core's digit count for the pending sign-in.\n const totpDigits = numInputs ?? passflow.getTotpDigits();\n\n // Compute subtitle dynamically based on totpDigits\n const computedSubtitle = subtitle ?? `Enter the ${totpDigits}-digit code from your authenticator app`;\n\n // Once per error, whatever the caller's callback identity does.\n const onEndedRef = useRef(onEnded);\n onEndedRef.current = onEnded;\n useEffect(() => {\n if (errorType === 'expired' || errorType === 'rate_limited') onEndedRef.current?.(errorType);\n }, [errorType]);\n\n const submit = async (value: string) => {\n const result = await verify(value, completionOptions(trustDevice));\n if (result) onSuccess?.();\n };\n\n // Auto-submit when code is complete\n const handleCodeChange = (value: string) => {\n reset();\n setCode(value);\n if (value.length === totpDigits) void submit(value);\n };\n\n const locked = isTerminalTwoFactorError(errorType);\n\n return (\n <LoginScreen\n chrome={{ title, subtitle: computedSubtitle }}\n state={{\n kind: 'two-factor-code',\n factor: { type: 'totp', digits: totpDigits },\n label: 'Verification code',\n code,\n trustDevice:\n deviceTrustAvailable === false\n ? undefined\n : { label: trustDeviceLabel, checked: trustDevice, onChange: setTrustDevice },\n busy: isLoading,\n canSubmit: code.length === totpDigits,\n locked,\n alert:\n isError && errorDetails\n ? { message: getUserFriendlyErrorMessage(errorDetails), tone: errorType === 'expired' ? 'info' : 'error' }\n : undefined,\n submitLabel: 'Verify',\n busyLabel: 'Verifying...',\n alternate: onUseRecovery\n ? { prompt: 'Lost your device?', label: 'Use recovery code', onClick: onUseRecovery }\n : undefined,\n secondaryAction: locked && onBackToSignIn ? { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn } : undefined,\n autoFocus: shouldAutoFocus,\n testId: 'two-factor-verify',\n onCodeChange: handleCodeChange,\n onSubmit: () => void submit(code),\n }}\n />\n );\n};\n\nexport const TwoFactorVerifyForm = withHydration(TwoFactorVerifyFormScreen);\n","import type { TwoFactorEnrollmentResponse, TwoFactorSetupResponse } from '@passflow/core';\nimport { useContext, useEffect, useRef, useState } from 'react';\nimport { PassflowContext } from '@/context';\nimport {\n enrollmentFailureFrom,\n serverErrorStatusFrom,\n twoFactorRateLimitedMessage,\n twoFactorSendFailedMessage,\n twoFactorSetupCodeChangedMessage,\n twoFactorSetupSavedNewCodeMessage,\n twoFactorSetupSavedSignInMessage,\n twoFactorSignInOverMessage,\n twoFactorTryAgainMessage,\n twoFactorWrongCodeMessage,\n} from '@/utils/auth-error';\nimport { usePassflow } from './use-passflow';\n\n/** Send taps on the email link screen: send, begin and challenge share 3 requests per 5 minutes on the server. */\nexport const TWO_FACTOR_LINK_MAX_SENDS = 3;\n\nexport type TwoFactorEnrollmentScreen =\n | { kind: 'loading' }\n | { kind: 'verify'; notice?: string; digits?: number; deviceTrustAvailable?: boolean }\n | { kind: 'email_link'; sent: boolean; sends: number; busy: boolean; error?: string }\n | {\n kind: 'direct';\n step: 'start' | 'code' | 'codes';\n data: TwoFactorSetupResponse | null;\n codes: string[];\n busy: boolean;\n error?: string;\n /** Shown on the code step until the next confirm. */\n notice?: string;\n }\n | { kind: 'unavailable' }\n | { kind: 'ended'; message: string }\n | { kind: 'read_failed' }\n | { kind: 'finished' };\n\nexport type UseTwoFactorEnrollmentProps = {\n /** The sign-in is finished, by the enrolment's verify or by `complete`. */\n onFinished?: () => void;\n};\n\nexport type UseTwoFactorEnrollmentReturn = {\n screen: TwoFactorEnrollmentScreen;\n /** Reads the state. It has no guard, so Try again and the `not_allowed` re-read work. */\n read: () => Promise<void>;\n sendLink: () => Promise<void>;\n begin: () => Promise<void>;\n confirm: (code: string) => Promise<void>;\n /** \"I've saved these codes\": finishes the sign-in with the code that confirmed. */\n finish: () => Promise<void>;\n /** The verify or recovery form ended the sign-in. */\n end: (type: 'expired' | 'rate_limited') => void;\n /** The verify or recovery form finished the sign-in. */\n complete: () => void;\n};\n\nconst screenFor = ({\n enrollment,\n totp_digits: digits,\n device_trust_available: deviceTrustAvailable,\n}: TwoFactorEnrollmentResponse): TwoFactorEnrollmentScreen => {\n switch (enrollment) {\n case 'verify':\n return { kind: 'verify', digits, deviceTrustAvailable };\n case 'email_link':\n return { kind: 'email_link', sent: false, sends: 0, busy: false };\n case 'direct':\n return { kind: 'direct', step: 'start', data: null, codes: [], busy: false };\n case 'unavailable':\n return { kind: 'unavailable' };\n default:\n return { kind: 'read_failed' };\n }\n};\n\n/**\n * What the verify screen shows for a pending sign-in, as the server decides it. Nothing that spends budget runs on\n * mount: only the state is read, once, and the link send and begin wait for a tap.\n */\nexport const useTwoFactorEnrollment = ({ onFinished }: UseTwoFactorEnrollmentProps = {}): UseTwoFactorEnrollmentReturn => {\n const passflow = usePassflow();\n const isDiscovering = useContext(PassflowContext)?.state.isDiscoveringAppId ?? false;\n const [screen, setScreen] = useState<TwoFactorEnrollmentScreen>({ kind: 'loading' });\n\n const readOnMount = useRef(false);\n const notAllowedReread = useRef(false);\n const beganAgain = useRef(false);\n // The code that confirmed. Verify cannot run before the codes show: the OIDC interceptor follows `redirect_url`\n // on `/auth/2fa/*` immediately, and the codes would vanish.\n const heldCode = useRef<string | null>(null);\n // The state read's `device_trust_available`, for the code screen that follows an enrolment here.\n const deviceTrustAvailable = useRef<boolean | undefined>(undefined);\n\n const updateDirect = (patch: Partial<Extract<TwoFactorEnrollmentScreen, { kind: 'direct' }>>) =>\n setScreen((current) => (current.kind === 'direct' ? { ...current, ...patch } : current));\n\n const endSignIn = () =>\n setScreen({\n kind: 'ended',\n message: heldCode.current === null ? twoFactorSignInOverMessage : twoFactorSetupSavedSignInMessage,\n });\n\n const handleFailure = (error: unknown, stay: (message: string) => void) => {\n const failure = enrollmentFailureFrom(error);\n if (failure === 'over') {\n endSignIn();\n } else if (failure === 'rate_limited') {\n setScreen({ kind: 'ended', message: twoFactorRateLimitedMessage });\n } else if (failure === 'unavailable') {\n setScreen({ kind: 'unavailable' });\n } else if (failure === 'not_allowed' && !notAllowedReread.current) {\n notAllowedReread.current = true;\n void read();\n } else if (failure === 'send_failed') {\n stay(twoFactorSendFailedMessage);\n } else {\n stay(twoFactorTryAgainMessage);\n }\n };\n\n const read = async () => {\n setScreen({ kind: 'loading' });\n try {\n const response = await passflow.getTwoFactorEnrollment();\n deviceTrustAvailable.current = response.device_trust_available;\n setScreen(screenFor(response));\n } catch (error) {\n if (serverErrorStatusFrom(error) === 401) endSignIn();\n else handleFailure(error, () => setScreen({ kind: 'read_failed' }));\n }\n };\n\n useEffect(() => {\n if (isDiscovering || readOnMount.current) return;\n readOnMount.current = true;\n if (passflow.isTwoFactorVerificationRequired()) void read();\n else setScreen({ kind: 'verify' });\n }, [isDiscovering, passflow]);\n\n const sendLink = async () => {\n if (screen.kind !== 'email_link' || screen.busy || screen.sends >= TWO_FACTOR_LINK_MAX_SENDS) return;\n const { sent } = screen;\n const sends = screen.sends + 1;\n const stay = (error: string) => setScreen({ kind: 'email_link', sent, sends, busy: false, error });\n\n setScreen({ kind: 'email_link', sent, sends, busy: true });\n try {\n const { email_sent: emailSent } = await passflow.sendTwoFactorSetupLink();\n if (emailSent) setScreen({ kind: 'email_link', sent: true, sends, busy: false });\n else stay(twoFactorSendFailedMessage);\n } catch (error) {\n handleFailure(error, stay);\n }\n };\n\n const beginEnrollment = async (notice?: string) => {\n updateDirect({ busy: true, error: undefined });\n try {\n const data = await passflow.beginTwoFactorEnrollment();\n updateDirect({ step: 'code', data, busy: false, notice });\n } catch (error) {\n handleFailure(error, (message) => updateDirect({ busy: false, error: message }));\n }\n };\n\n const confirm = async (code: string) => {\n updateDirect({ busy: true, error: undefined, notice: undefined });\n let codes: string[];\n try {\n // The answer may carry no codes: an empty list, null or no field.\n codes = (await passflow.confirmTwoFactorEnrollment(code)).recovery_codes ?? [];\n heldCode.current = code;\n } catch (error) {\n const failure = enrollmentFailureFrom(error);\n if (failure === 'wrong_code') {\n updateDirect({ busy: false, error: twoFactorWrongCodeMessage });\n } else if (failure === 'setup_incomplete' && !beganAgain.current) {\n beganAgain.current = true;\n await beginEnrollment(twoFactorSetupCodeChangedMessage);\n } else {\n handleFailure(error, (message) => updateDirect({ busy: false, error: message }));\n }\n return;\n }\n // No codes to save: the sign-in finishes with the code that confirmed.\n if (codes.length > 0) updateDirect({ step: 'codes', codes, busy: false });\n else await verifyHeldCode(code, screen.kind === 'direct' ? screen.data?.totp_digits : undefined);\n };\n\n const complete = () => {\n setScreen({ kind: 'finished' });\n onFinished?.();\n };\n\n const finish = async () => {\n if (screen.kind !== 'direct' || heldCode.current === null) return;\n await verifyHeldCode(heldCode.current, screen.data?.totp_digits);\n };\n\n const verifyHeldCode = async (code: string, digits?: number) => {\n updateDirect({ busy: true, error: undefined });\n try {\n await passflow.verifyTwoFactor(code);\n complete();\n } catch (error) {\n // The held code goes stale after about 30-60 seconds on the codes: a common case, so it gets its own screen.\n if (enrollmentFailureFrom(error) === 'wrong_code') {\n setScreen({\n kind: 'verify',\n notice: twoFactorSetupSavedNewCodeMessage,\n digits,\n deviceTrustAvailable: deviceTrustAvailable.current,\n });\n } else {\n handleFailure(error, (message) => updateDirect({ busy: false, error: message }));\n }\n }\n };\n\n const end = (type: 'expired' | 'rate_limited') => {\n if (type === 'rate_limited') setScreen({ kind: 'ended', message: twoFactorRateLimitedMessage });\n else endSignIn();\n };\n\n return { screen, read, sendLink, begin: () => beginEnrollment(), confirm, finish, end, complete };\n};\n","import { SIGNED_IN_MESSAGE } from '@/components/form/signed-in';\nimport {\n getTwoFactorRecoveryCodesScreen,\n getTwoFactorSetupCodeScreen,\n getTwoFactorSetupStartScreen,\n} from '@/components/form/two-factor-setup/setup-screen';\nimport type { LoginScreenAction, LoginScreenProps } from '@/components/ui';\nimport { TWO_FACTOR_LINK_MAX_SENDS, type UseTwoFactorEnrollmentReturn } from '@/hooks/use-two-factor-enrollment';\nimport { twoFactorBackToSignInLabel, twoFactorSignInLabel } from '@/utils';\n\nconst TITLE = 'Two-Factor Authentication';\n\n/** The screen for the enrolment state; null on `verify`, which the verify and recovery forms draw. */\nexport const getTwoFactorEnrollmentScreenProps = (\n enrollment: UseTwoFactorEnrollmentReturn,\n onBackToSignIn: () => void,\n): LoginScreenProps | null => {\n const { screen } = enrollment;\n const backToSignIn: LoginScreenAction = { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn };\n\n switch (screen.kind) {\n case 'verify':\n return null;\n\n case 'loading':\n return {\n chrome: { title: TITLE },\n state: { kind: 'status', tone: 'working', message: 'Checking your sign-in...', testId: 'two-factor-loading' },\n };\n\n case 'email_link':\n return {\n chrome: { title: 'Set Up Two-Factor Authentication' },\n state: {\n kind: 'status',\n tone: 'info',\n message: screen.sent\n ? 'Check your email for a link to set up two-factor authentication. After you set it up, sign in again.'\n : 'Your account needs two-factor authentication. We can email you a link to set it up.',\n error: screen.error,\n testId: 'two-factor-email-link',\n primaryAction:\n screen.busy || screen.sends < TWO_FACTOR_LINK_MAX_SENDS\n ? {\n label: screen.busy ? 'Sending...' : screen.sent ? 'Send again' : 'Email me a setup link',\n busy: screen.busy,\n onClick: () => void enrollment.sendLink(),\n }\n : undefined,\n secondaryAction: backToSignIn,\n },\n };\n\n case 'direct':\n if (screen.step === 'codes') {\n return getTwoFactorRecoveryCodesScreen({\n codes: screen.codes,\n busy: screen.busy,\n error: screen.error,\n onContinue: () => void enrollment.finish(),\n });\n }\n if (screen.step === 'code' && screen.data) {\n return getTwoFactorSetupCodeScreen({\n data: screen.data,\n notice: screen.notice,\n busy: screen.busy,\n error: screen.error,\n secondaryAction: backToSignIn,\n onSubmit: (code) => void enrollment.confirm(code),\n });\n }\n return getTwoFactorSetupStartScreen({\n busy: screen.busy,\n error: screen.error,\n secondaryAction: backToSignIn,\n onStart: () => void enrollment.begin(),\n });\n\n case 'unavailable':\n return {\n chrome: { title: TITLE },\n state: {\n kind: 'status',\n tone: 'disabled',\n message: 'Two-factor authentication cannot be set up for your account here. Contact your administrator.',\n testId: 'two-factor-unavailable',\n secondaryAction: backToSignIn,\n },\n };\n\n case 'ended':\n return {\n chrome: { title: TITLE },\n state: {\n kind: 'status',\n tone: 'error',\n message: screen.message,\n testId: 'two-factor-ended',\n primaryAction: { label: twoFactorSignInLabel, onClick: onBackToSignIn },\n },\n };\n\n case 'read_failed':\n return {\n chrome: { title: TITLE },\n state: {\n kind: 'status',\n tone: 'error',\n message: 'We could not continue your sign-in. Try again.',\n recoverable: true,\n testId: 'two-factor-read-failed',\n onRetry: () => void enrollment.read(),\n secondaryAction: backToSignIn,\n },\n };\n\n case 'finished':\n return {\n chrome: { title: TITLE },\n state: { kind: 'status', tone: 'success', message: SIGNED_IN_MESSAGE, testId: 'two-factor-finished' },\n };\n }\n};\n","import type { FC } from 'react';\nimport { useCallback, useEffect, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { TwoFactorRecoveryForm, TwoFactorVerifyForm } from '@/components/form/two-factor-verify';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport { LoginScreen } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useNavigation, usePassflow, useSignInEnding } from '@/hooks';\nimport { useTwoFactorEnrollment } from '@/hooks/use-two-factor-enrollment';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { signInSearch } from '@/utils';\nimport { getTwoFactorEnrollmentScreenProps } from './screen';\n\nimport '@/styles/index.css';\n\nexport type TwoFactorVerifyFlowProps = {\n successAuthRedirect?: SuccessAuthRedirect;\n signInPath?: string;\n};\n\nconst TwoFactorVerifyFlowScreen: FC<TwoFactorVerifyFlowProps> = ({ successAuthRedirect, signInPath = routes.signin.path }) => {\n const [mode, setMode] = useState<'verify' | 'recovery'>('verify');\n const { navigate } = useNavigation();\n const passflow = usePassflow();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n // Read once: a screen must not blank when core's 5 minute pending state expires under it.\n const [pendingOnLanding] = useState(() => passflow.isTwoFactorVerificationRequired());\n\n const goToSignIn = useCallback(\n () => navigate({ to: signInPath, search: signInSearch(searchSource.read()) }),\n [navigate, signInPath, searchSource],\n );\n\n const continueSignIn = async () => {\n // `/auth/2fa/*` is an interceptor-matched endpoint, so an OIDC login that\n // required a second factor has already been dispatched back to the RP by\n // the time this runs. Navigating again would cancel that in flight — see\n // `hasFollowedOIDCRedirect`.\n if (hasFollowedOIDCRedirect()) return;\n\n try {\n // With nowhere to go the user stays: the screen is already the finished one, which says they are signed in.\n await finishSignIn(\n successAuthRedirect,\n successAuthRedirect ? undefined : (await passflow.getAppSettings()).defaults?.redirect,\n );\n } catch {\n // No target to go to: as above.\n }\n };\n\n const enrollment = useTwoFactorEnrollment({ onFinished: () => void continueSignIn() });\n\n // This cannot loop: the sign-in screen sends the user back here only with a pending sign-in.\n useEffect(() => {\n if (!pendingOnLanding) goToSignIn();\n }, [pendingOnLanding, goToSignIn]);\n\n if (!pendingOnLanding) return null;\n\n // The finished screen already says the user is signed in; only a target that could not be used needs its own.\n if (ending === 'checking' || ending === 'refused' || ending === 'unavailable' || ending === 'service-unavailable')\n return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const screenProps = getTwoFactorEnrollmentScreenProps(enrollment, goToSignIn);\n if (screenProps) return <LoginScreen {...screenProps} />;\n\n const { screen } = enrollment;\n const deviceTrustAvailable = screen.kind === 'verify' ? screen.deviceTrustAvailable : undefined;\n\n return mode === 'verify' ? (\n <TwoFactorVerifyForm\n subtitle={screen.kind === 'verify' ? screen.notice : undefined}\n numInputs={screen.kind === 'verify' ? screen.digits : undefined}\n deviceTrustAvailable={deviceTrustAvailable}\n onSuccess={enrollment.complete}\n onUseRecovery={() => setMode('recovery')}\n onEnded={enrollment.end}\n onBackToSignIn={goToSignIn}\n />\n ) : (\n <TwoFactorRecoveryForm\n deviceTrustAvailable={deviceTrustAvailable}\n onSuccess={enrollment.complete}\n onBack={() => setMode('verify')}\n onEnded={enrollment.end}\n onBackToSignIn={goToSignIn}\n />\n );\n};\n\nexport const TwoFactorVerifyFlow = withHydration(TwoFactorVerifyFlowScreen);\n","import type { PassflowSendPasswordResetEmailPayload } from '@passflow/core';\nimport { phone } from 'phone';\n/* eslint-disable max-len */\n/* eslint-disable react/jsx-props-no-spreading */\n/* eslint-disable complexity */\n/* eslint-disable jsx-a11y/label-has-associated-control */\nimport { type FC, useMemo } from 'react';\nimport { Controller, useForm } from 'react-hook-form';\nimport * as Yup from 'yup';\nimport { Button, FieldPhone, FieldText, Icon, Link, LoginAlert } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useForgotPassword, useNavigation } from '@/hooks';\nimport {\n cn,\n emailRegex,\n getAuthMethods,\n getIdentityLabel,\n passwordChangeRequiredMessage,\n passwordChangeRequiredReason,\n useUrlParams,\n} from '@/utils';\nimport { Wrapper } from '../wrapper';\n\nimport '@/styles/index.css';\nimport queryString from 'query-string';\n\nconst searchParamsForgotPasswordSchema = Yup.object().shape({\n defaultMethod: Yup.string().oneOf(['email_or_username', 'phone']).required(),\n});\n\ntype TForgotPassword = {\n successResetRedirect?: string;\n signInPath?: string;\n forgotPasswordSuccessPath?: string;\n};\n\nconst ForgotPasswordScreen: FC<TForgotPassword> = ({\n successResetRedirect,\n signInPath = routes.signin.path,\n forgotPasswordSuccessPath = routes.forgot_password_success.path,\n}) => {\n const { get } = useUrlParams({\n default_method: '',\n email: '',\n username: '',\n phone: '',\n });\n\n const {\n getValues,\n control,\n formState: { errors, isValid },\n } = useForm({\n defaultValues: {\n email_or_username: get('email') || get('username') || '',\n phone: get('phone') ?? '',\n },\n });\n\n const { appSettings, currentStyles, isError: isErrorApp, error: errorApp, loginAppTheme } = useAppSettings();\n\n if (isErrorApp) throw new Error(errorApp);\n\n const authMethods = useMemo(() => getAuthMethods(appSettings?.auth_strategies), [appSettings]);\n const { navigate } = useNavigation();\n const searchSource = useSearchSource();\n\n const params = {\n defaultMethod: get('default_method'),\n };\n const showPasswordChangeNotice = get('reason') === passwordChangeRequiredReason;\n\n try {\n searchParamsForgotPasswordSchema.validateSync(params, { abortEarly: false });\n } catch (err) {\n throw new Error('Invalid default method param');\n }\n\n const { defaultMethod } = params;\n\n const { fetch, error, isError, isLoading } = useForgotPassword();\n\n const onSubmitHanlder = async () => {\n const values = getValues();\n // Only the field on screen is sent: the URL may prefill the other one, which the user never sees.\n const usesPhone = defaultMethod === 'phone';\n const isEmail = !usesPhone && values.email_or_username.match(emailRegex);\n const isUsername = !usesPhone && !isEmail && values.email_or_username.length > 0;\n const validatedPhone = phone(values.phone);\n const isPhone = usesPhone && validatedPhone.isValid;\n\n const payload = {\n ...(isEmail && { email: values.email_or_username }),\n ...(isUsername && { username: values.email_or_username }),\n ...(isPhone && { phone: validatedPhone.phoneNumber }),\n ...(successResetRedirect && { redirect_url: successResetRedirect }),\n } as PassflowSendPasswordResetEmailPayload;\n\n const status = await fetch(payload);\n\n if (status) {\n const currentSearchParams = new URLSearchParams(searchSource.read());\n for (const name of ['redirect_url', 'email', 'phone', 'username']) currentSearchParams.delete(name);\n const newParams = queryString.stringify({\n ...Object.fromEntries(currentSearchParams.entries()),\n ...payload,\n });\n navigate({ to: forgotPasswordSuccessPath, search: newParams });\n }\n };\n\n // if (!state)\n // return (\n // <Navigate\n // to={{\n // pathname: signInPath ?? routes.signin.path,\n // search: window.location.search,\n // }}\n // replace\n // />\n // );\n\n const currentSubtitle =\n defaultMethod === 'email_or_username'\n ? 'Enter the email address you used when you joined and we’ll send you instructions to reset your password.'\n : 'Enter the mobile phone number you used when you joined and we’ll send you the reset link.';\n\n const currentSubscriptions =\n defaultMethod === 'email_or_username'\n ? 'For security reasons, we do NOT store your password. So rest assured that we will never send your password via email.'\n : 'For security reasons, we do NOT store your password. So rest assured that we will never send your password via SMS.';\n\n return (\n <Wrapper\n title='Forgot password?'\n subtitle={currentSubtitle}\n className='passflow-forgot-password-wrapper'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <span className='passflow-form-subscriptions'>{currentSubscriptions}</span>\n <form onSubmit={(e) => e.preventDefault()} className='passflow-form'>\n {showPasswordChangeNotice && <LoginAlert tone='info' message={passwordChangeRequiredMessage} />}\n <div className='passflow-form-container'>\n <div className='passflow-form-field'>\n {defaultMethod === 'email_or_username' && (\n <>\n <div className='passflow-form-field__header'>\n <label htmlFor='identity' className={cn('passflow-field-label', { 'passflow-field-label--error': isError })}>\n {getIdentityLabel(authMethods, 'label')}\n </label>\n </div>\n <Controller\n name='email_or_username'\n control={control}\n rules={{ required: 'Email is required' }}\n render={({ field }) => (\n <FieldText\n {...field}\n isError={isError || Object.hasOwn(errors, 'email_or_username')}\n id='email_or_username'\n type='text'\n name='email_or_username'\n />\n )}\n />\n </>\n )}\n {defaultMethod === 'phone' && (\n <>\n <div className='passflow-form-field__header'>\n <label htmlFor='phone' className={cn('passflow-field-label', { 'passflow-field-label--error': isError })}>\n Phone\n </label>\n </div>\n <Controller\n name='phone'\n control={control}\n rules={{\n required: 'Phone is required',\n validate: (value) => {\n const validatePhone = phone(value);\n if (validatePhone.isValid) return true;\n return 'Invalid phone number';\n },\n }}\n render={({ field }) => (\n <FieldPhone\n {...field}\n onChange={(e) => field.onChange(e)}\n id='phone'\n name='phone'\n isError={isError || Object.hasOwn(errors, 'phone')}\n ref={null}\n />\n )}\n />\n </>\n )}\n {isError && (\n <div className='passflow-form-error'>\n <Icon size='small' id='warning' type='general' className='icon-warning' />\n <span className='passflow-form-error-text'>{error}</span>\n </div>\n )}\n </div>\n </div>\n <div className='passflow-send-reset-wrapper'>\n <Button\n size='big'\n variant='primary'\n type='button'\n disabled={!isValid || isLoading}\n className='passflow-button-send-reset-password'\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onClick={onSubmitHanlder}\n >\n Send reset instructions\n </Button>\n <p className='passflow-remember-password'>\n Remember your password?{' '}\n <Link to={signInPath ?? routes.signin.path} className='passflow-link'>\n Sign In\n </Link>{' '}\n </p>\n </div>\n </form>\n </Wrapper>\n );\n};\n\nexport const ForgotPassword = withHydration(ForgotPasswordScreen);\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable complexity */\nimport * as Yup from 'yup';\nimport { Button } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useForgotPassword } from '@/hooks';\nimport { Wrapper } from '../wrapper';\nimport '@/styles/index.css';\nimport type { PassflowSendPasswordResetEmailPayload } from '@passflow/core';\nimport { useUrlParams, verificationLinkErrorMessage } from '@/utils';\n\nconst searchParamsForgotPasswordSuccessSchema = Yup.object().shape({\n identity: Yup.string().oneOf(['email', 'phone', 'username']).required(),\n identityValue: Yup.string().required(),\n redirectUrl: Yup.string().nullable(),\n});\n\nconst ForgotPasswordSuccessScreen = () => {\n const { currentStyles, loginAppTheme } = useAppSettings();\n const { fetch: refetch } = useForgotPassword();\n const { get } = useUrlParams();\n\n const params = {\n identity: get('email') ? 'email' : get('phone') ? 'phone' : get('username') ? 'username' : null,\n identityValue: get('email') || get('phone') || get('username') || null,\n redirectUrl: get('redirect_url'),\n };\n\n try {\n searchParamsForgotPasswordSuccessSchema.validateSync(params, { abortEarly: false });\n } catch (error) {\n console.error('[passflow] invalid password-reset confirmation link', error);\n throw new Error(verificationLinkErrorMessage);\n }\n\n const onClickResendHandler = async () => {\n const resendPayload = {\n ...(params.identity === 'email' ? { email: params.identityValue } : undefined),\n ...(params.identity === 'phone' ? { phone: params.identityValue } : undefined),\n ...(params.identity === 'username' ? { username: params.identityValue } : undefined),\n ...(params.redirectUrl ? { redirect_url: params.redirectUrl } : {}),\n };\n\n await refetch(resendPayload as PassflowSendPasswordResetEmailPayload);\n };\n\n return (\n <Wrapper\n title={`Check your ${params.identity === 'phone' ? 'phone' : 'email'}`}\n className='passflow-forgot-password-success-wrapper'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <div className='passflow-forgot-password-success-container'>\n <p className='passflow-forgot-password-success-text'>\n We sent a link to{' '}\n {params.identity === 'phone'\n ? 'phone number'\n : params.identity === 'email'\n ? 'email address'\n : 'the email address for'}{' '}\n <strong className='passflow-forgot-password-success-text--strong'>{params.identityValue}</strong>. Click the link to\n reset your password.\n </p>\n <Button\n size='big'\n variant='secondary'\n type='button'\n className='passflow-button-resend-reset-password'\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onClick={onClickResendHandler}\n >\n Resend {params.identity === 'phone' ? 'SMS' : 'email'}\n </Button>\n </div>\n </Wrapper>\n );\n};\n\nexport const ForgotPasswordSuccess = withHydration(ForgotPasswordSuccessScreen);\n","import type { FC } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { useAppSettings, useNavigation } from '@/hooks';\nimport { isSameOriginPath } from '@/utils';\n\nexport type TError = {\n goBackRedirectTo: string;\n error?: string;\n};\n\nconst defaultErrorMessage = 'Something went wrong';\n\nexport const ErrorComponent: FC<TError> = ({ error = defaultErrorMessage, goBackRedirectTo }) => {\n const { navigate } = useNavigation();\n const { currentStyles, loginAppTheme } = useAppSettings();\n\n // The target can come from the request, so this only ever follows a path on this origin.\n const handleGoBack = () => navigate({ to: isSameOriginPath(goBackRedirectTo) ? goBackRedirectTo : '/' });\n\n return (\n <LoginScreen\n chrome={{\n title: '',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={{\n kind: 'general-error',\n message: error,\n onAction: handleGoBack,\n }}\n />\n );\n};\n","/* eslint-disable react/prop-types */\n/* eslint-disable react/jsx-props-no-spreading */\nimport { type ComponentType, useContext } from 'react';\nimport { ErrorBoundary, type FallbackProps } from 'react-error-boundary';\nimport type { TError } from '@/components/error';\nimport type { PassflowProps } from '@/components/flow/passflow';\nimport type { TInvitationJoinFlow, TSignIn, TSignUp } from '@/components/form';\nimport { PassflowContext } from '@/context';\nimport { useHydrated } from '@/hooks/use-hydrated';\n\ntype UnionType = TSignIn | TSignUp | TInvitationJoinFlow | PassflowProps;\n// react-error-boundary 6 types the caught value as unknown: anything can be thrown.\nconst toErrorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));\n\nconst excludeRoutes = ['verify-challenge-otp', 'password/reset', 'two-factor-verify', 'two-factor-recovery'];\n\nexport const withError =\n <P extends UnionType>(Component: ComponentType<P>, ErrorComponent: ComponentType<TError>) =>\n (props: P) => {\n const context = useContext(PassflowContext);\n const hydrated = useHydrated();\n const { successAuthRedirect } = props;\n\n // The URL exists only in the browser: render nothing on the server and in the hydration render.\n if (!hydrated) return null;\n\n const { pathname } = window.location;\n\n // Allow excluded routes to render without checking appId\n if (excludeRoutes.some((route) => pathname.includes(route))) {\n return (\n <ErrorBoundary\n // eslint-disable-next-line react/no-unstable-nested-components\n FallbackComponent={({ error }: FallbackProps) => (\n <ErrorComponent goBackRedirectTo={successAuthRedirect ?? '/'} error={toErrorMessage(error)} />\n )}\n >\n <Component {...props} />\n </ErrorBoundary>\n );\n }\n\n // If we're still discovering the appId, don't show error yet\n if (context?.state.isDiscoveringAppId) {\n return null; // Or render a loading spinner if desired\n }\n\n // After discovery is complete, check if we have the required config\n // Only appId is required - URL defaults to current origin if not provided\n if (!context?.state.appId) {\n const errorMessage = 'Missing appId';\n return <ErrorComponent goBackRedirectTo={successAuthRedirect ?? '/'} error={errorMessage} />;\n }\n\n return (\n <ErrorBoundary\n // eslint-disable-next-line react/no-unstable-nested-components\n FallbackComponent={({ error }: FallbackProps) => (\n <ErrorComponent goBackRedirectTo={successAuthRedirect ?? '/'} error={toErrorMessage(error)} />\n )}\n >\n <Component {...props} />\n </ErrorBoundary>\n );\n };\n\nexport default withError;\n","import { type InvitationToken, parseToken } from '@passflow/core';\nimport { type FC, useEffect } from 'react';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { LoginScreen } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withError } from '@/hocs';\nimport { useAppSettings, useJoinInvite, useNavigation, usePassflow, useSignInEnding } from '@/hooks';\nimport { useHydrated } from '@/hooks/use-hydrated';\nimport { invitationLinkErrorMessage, undefinedOnCatch, useUrlParams } from '@/utils';\n\nexport type TInvitationJoinFlow = {\n successAuthRedirect?: string;\n signInPath?: string;\n signUpPath?: string;\n};\n\nconst InvitationJoinFlow: FC<TInvitationJoinFlow> = ({\n signInPath = routes.signin.path,\n signUpPath = routes.signup.path,\n successAuthRedirect,\n}) => {\n const { appSettings, currentStyles, loginAppTheme } = useAppSettings();\n const { navigate } = useNavigation();\n const searchSource = useSearchSource();\n const { get } = useUrlParams();\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const { fetch: joinInvite, isLoading, error, isError } = useJoinInvite();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const invitationToken = get('invite_token');\n const invitationTokenData = invitationToken ? undefinedOnCatch(parseToken)(invitationToken) : undefined;\n const parsedTokenCache = passflow.getParsedTokens();\n const hasAuthenticatedSession = Boolean(parsedTokenCache?.access_token);\n\n useEffect(() => {\n if (invitationTokenData && !hasAuthenticatedSession) {\n navigate({ to: signInPath, search: searchSource.read() });\n }\n }, [hasAuthenticatedSession, invitationTokenData, navigate, searchSource, signInPath]);\n\n if (!invitationTokenData) {\n console.error('[passflow] invitation token could not be parsed');\n throw new Error(invitationLinkErrorMessage);\n }\n // Hydration renders what the signed-out server rendered.\n if (!hasAuthenticatedSession || !hydrated) return null;\n\n const {\n inviter_name: inviterName,\n tenant_name: tenantName,\n redirect_url: redirectUrl,\n } = invitationTokenData as InvitationToken;\n\n const acceptInvitation = async () => {\n if (!invitationToken) return;\n\n const joined = await joinInvite(invitationToken);\n if (!joined) return;\n\n await finishSignIn(redirectUrl ?? successAuthRedirect, appSettings?.defaults?.redirect);\n };\n\n const navigateToSignIn = () => navigate({ to: signInPath, search: searchSource.read() });\n const navigateToSignUp = () => navigate({ to: signUpPath, search: searchSource.read() });\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n return (\n <LoginScreen\n chrome={{\n title: `You've been invited to join ${tenantName}.`,\n subtitle: 'Review the invitation before continuing.',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={{\n kind: 'invitation',\n identity: parsedTokenCache?.id_token?.email,\n inviterName: inviterName || undefined,\n busy: isLoading,\n error: isError ? error : null,\n testId: 'invitation-join',\n acceptTestId: 'invitation-accept',\n onAccept: () => void acceptInvitation(),\n onSwitchAccount: navigateToSignIn,\n onCreateAccount: navigateToSignUp,\n }}\n />\n );\n};\n\nexport const InvitationJoin = withError(InvitationJoinFlow, ErrorComponent);\n","import { parseToken, type Token } from '@passflow/core';\nimport type { FC } from 'react';\nimport * as Yup from 'yup';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport { LoginScreen, type LoginScreenChrome, type LoginScreenState } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useNavigation, usePassflow, useResetPassword, useSignInEnding } from '@/hooks';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { routeToSecondFactor, undefinedOnCatch, useUrlParams } from '@/utils';\nimport '@/styles/index.css';\n\nconst searchParamsResetPasswordSchema = Yup.object().shape({\n token: Yup.string().required(),\n});\n\ntype TResetPassword = {\n successAuthRedirect?: SuccessAuthRedirect;\n twoFactorVerifyPath?: string;\n /** Where `Back to sign in` goes once the password is saved. */\n signInPath?: string;\n};\n\n/**\n * The reset link's claims. A registration continuation link (an account started by email whose code budget ran out)\n * carries `registration_continuation` and no `redirect_url`.\n */\ntype ResetToken = Token & {\n redirect_url?: string;\n registration_continuation?: string;\n};\n\nconst ResetPasswordScreen: FC<TResetPassword> = ({\n successAuthRedirect,\n twoFactorVerifyPath = routes.two_factor_verify.path,\n signInPath = routes.signin.path,\n}) => {\n const passflow = usePassflow();\n const { fetch, error, isError, isLoading, isPasswordSaved, emailCode } = useResetPassword();\n const { navigate } = useNavigation();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n const { get } = useUrlParams();\n const { appSettings, passwordPolicy, currentStyles, isError: isErrorApp, error: errorApp, loginAppTheme } = useAppSettings();\n\n if (isErrorApp) throw new Error(errorApp);\n\n const params = {\n token: get('token'),\n };\n\n try {\n searchParamsResetPasswordSchema.validateSync(params, { abortEarly: false });\n } catch {\n throw new Error('Invalid reset token.');\n }\n\n const { token: resetToken } = params;\n const resetTokenData = resetToken ? (undefinedOnCatch(parseToken)(resetToken) as ResetToken | undefined) : undefined;\n const isContinuation = Boolean(resetTokenData?.registration_continuation);\n\n // A user with 2FA is signed in only once the second factor passes; an OIDC parent's redirect wins over ours.\n const completeSignIn = async (answerRedirectUrl?: string) => {\n if (routeToSecondFactor(passflow, navigate, twoFactorVerifyPath, searchSource.read())) return;\n if (hasFollowedOIDCRedirect()) return;\n await finishSignIn(\n answerRedirectUrl ?? resetTokenData?.redirect_url ?? successAuthRedirect,\n appSettings?.defaults?.redirect,\n );\n };\n\n const savePassword = async (password: string) => {\n // The token goes along explicitly: core would otherwise read it from the address bar, which a hash or memory\n // router does not keep.\n if (await fetch(password, resetToken ?? undefined)) await completeSignIn();\n };\n\n const verifyEmailCode = async (code: string) => {\n const answer = await emailCode.verify(code);\n if (answer) await completeSignIn(answer.redirect_url);\n };\n\n const backToSignIn = () => {\n emailCode.cancel();\n navigate({ to: signInPath });\n };\n\n const chrome: LoginScreenChrome = {\n title: isContinuation ? 'Create your password' : 'Reset password',\n subtitle: isContinuation ? 'Finish creating your account' : 'Let’s get you back in.',\n variant: 'reset-password',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n const { step } = emailCode;\n\n const state: LoginScreenState =\n step.kind === 'code'\n ? {\n // No resend: the reset link is spent once the password is saved.\n kind: 'email-code',\n message: step.message,\n error: emailCode.error,\n busy: emailCode.isVerifying,\n secondaryAction: { label: 'Back to sign in', onClick: backToSignIn },\n onSubmit: (code) => void verifyEmailCode(code),\n }\n : step.kind === 'link'\n ? {\n kind: 'status',\n tone: 'info',\n message: step.message,\n primaryAction: { label: 'Back to sign in', onClick: backToSignIn },\n }\n : isPasswordSaved\n ? {\n kind: 'status',\n tone: 'info',\n message: error,\n primaryAction: { label: 'Back to sign in', onClick: backToSignIn },\n }\n : {\n kind: 'new-password',\n passwordPolicy,\n hint: isContinuation ? 'Choose a password to finish creating your account.' : 'Enter your new password below.',\n error: isError ? error : null,\n busy: isLoading,\n submitLabel: isContinuation ? 'Create account' : 'Save new password',\n onSubmit: (password) => void savePassword(password),\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const heading: Pick<LoginScreenChrome, 'title' | 'subtitle'> =\n step.kind === 'code'\n ? { title: 'Verify your email', subtitle: 'Enter the code to finish signing in' }\n : step.kind === 'link'\n ? { title: 'Check your email', subtitle: undefined }\n : isPasswordSaved\n ? { title: 'Password saved', subtitle: undefined }\n : { title: chrome.title, subtitle: chrome.subtitle };\n\n return <LoginScreen chrome={{ ...chrome, ...heading }} state={state} />;\n};\n\nexport const ResetPassword = withHydration(ResetPasswordScreen);\n","import type {\n PassflowPasskeyAuthenticateStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignInPayload,\n Providers,\n} from '@passflow/core';\nimport { phone } from 'phone';\nimport queryString from 'query-string';\nimport type { FC } from 'react';\nimport { useMemo, useRef } from 'react';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { hasFollowedOIDCRedirect, readParentChallengeIdFromURL } from '@/components/provider/passflow-provider';\nimport {\n type LoginCredentialsValues,\n type LoginMethodConfig,\n LoginScreen,\n type LoginScreenChrome,\n type LoginScreenState,\n} from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withError, withHydration } from '@/hocs';\nimport { useAppSettings, useNavigation, usePassflow, useProvider, useSignIn, useSignInEnding } from '@/hooks';\nimport type { FederatedLanding, SuccessAuthRedirect } from '@/types';\nimport {\n type AuthMethods,\n authRedirectErrorFrom,\n emailRegex,\n getAuthMethods,\n getIdentityLabel,\n getInvitationAuthChrome,\n getPasswordlessData,\n getUrlErrors,\n passwordChangeRequiredReason,\n routeToSecondFactor,\n urlWithoutParentChallenge,\n useUrlParams,\n} from '@/utils';\n\nconst getLoginMethodConfig = (authMethods: AuthMethods): LoginMethodConfig => {\n const identities: LoginMethodConfig['identities'] = [];\n\n if (authMethods.hasSignInEmailMethods || authMethods.hasSignInUsernameMethods) {\n const label = getIdentityLabel(authMethods, 'label') ?? 'Email or username';\n identities.push({\n id: 'email_or_username',\n label,\n selectLabel: getIdentityLabel(authMethods, 'button') ?? 'Use email',\n requiredMessage: `${label} is required`,\n format: authMethods.hasSignInEmailMethods && !authMethods.hasSignInUsernameMethods ? 'email' : undefined,\n password: authMethods.internal.email.password || authMethods.internal.username.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'email_or_username')?.label,\n });\n }\n\n if (authMethods.hasSignInPhoneMethods) {\n identities.push({\n id: 'phone',\n label: 'Phone number',\n selectLabel: 'Use phone',\n requiredMessage: 'Phone number is required',\n password: authMethods.internal.phone.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'phone')?.label,\n });\n }\n\n return {\n identities,\n passkey: authMethods.passkey,\n providers: authMethods.fim.providers,\n };\n};\n\nexport type TSignIn = {\n successAuthRedirect?: SuccessAuthRedirect;\n relyingPartyId?: string;\n federatedDisplayMode?: 'modal' | 'redirect';\n federatedLanding?: FederatedLanding;\n signUpPath?: string;\n verifyOTPPath?: string;\n verifyMagicLinkPath?: string;\n forgotPasswordPath?: string;\n twoFactorVerifyPath?: string;\n};\n\nconst SignInFormScreen: FC<TSignIn> = ({\n successAuthRedirect,\n relyingPartyId = window.location.hostname,\n federatedLanding,\n signUpPath = routes.signup.path,\n verifyOTPPath = routes.verify_otp.path,\n verifyMagicLinkPath = routes.verify_magic_link.path,\n forgotPasswordPath = routes.forgot_password.path,\n twoFactorVerifyPath = routes.two_factor_verify.path,\n}) => {\n const passflow = usePassflow();\n const { navigate } = useNavigation();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n const {\n appSettings,\n scopes,\n createTenantForNewUser,\n passwordPolicy,\n currentStyles,\n isError: isErrorApp,\n error: errorApp,\n loginAppTheme,\n } = useAppSettings();\n const { federatedWithRedirect } = useProvider(successAuthRedirect, createTenantForNewUser, federatedLanding);\n\n if (isErrorApp) throw new Error(errorApp);\n\n const authMethods = useMemo(() => getAuthMethods(appSettings?.auth_strategies), [appSettings]);\n const loginMethods = useMemo(() => getLoginMethodConfig(authMethods), [authMethods]);\n const { error: errorUrl, message: messageUrl } = getUrlErrors();\n\n if (errorUrl) {\n console.error('[passflow] sign-in redirect returned an error', { error: errorUrl, message: messageUrl });\n throw new Error(authRedirectErrorFrom(errorUrl, messageUrl));\n }\n\n const { get } = useUrlParams({ invite_token: '' });\n const inviteToken = get('invite_token');\n const invitationChrome = getInvitationAuthChrome(inviteToken, 'sign-in');\n // The identifier of the password sign-in in flight, carried to forgot-password if the password must change.\n const passwordIdentityRef = useRef<Pick<PassflowSignInPayload, 'email' | 'username' | 'phone'>>({});\n const goToPasswordReset = () => {\n const identity = passwordIdentityRef.current;\n const params = new URLSearchParams(searchSource.read());\n for (const name of ['email', 'username', 'phone']) params.delete(name);\n navigate({\n to: forgotPasswordPath ?? routes.forgot_password.path,\n search: queryString.stringify({\n ...Object.fromEntries(params.entries()),\n ...identity,\n default_method: identity.phone ? 'phone' : 'email_or_username',\n reason: passwordChangeRequiredReason,\n }),\n });\n };\n const { fetch, isError, error, reset, cancelPasskey, isLoading, pendingOperation, emailCode } = useSignIn({\n onPasswordChangeRequired: goToPasswordReset,\n });\n\n const oidcLayerOwnsRedirect = (): boolean => {\n if (hasFollowedOIDCRedirect()) return true;\n if (readParentChallengeIdFromURL()) {\n console.error(\n '[passflow] login took the legacy token path while parent_challenge_id is present on the URL — the OIDC interceptor did not engage and the RP redirect will not happen',\n );\n }\n return false;\n };\n\n const completeAuthentication = async () => {\n if (routeToSecondFactor(passflow, navigate, twoFactorVerifyPath ?? routes.two_factor_verify.path, searchSource.read()))\n return;\n if (oidcLayerOwnsRedirect()) return;\n await finishSignIn(successAuthRedirect, appSettings?.defaults?.redirect);\n };\n\n const submitPassword = async (userPayload: PassflowSignInPayload) => {\n const payload = {\n ...userPayload,\n ...(inviteToken && { invite_token: inviteToken }),\n } as PassflowSignInPayload;\n\n const { email, username, phone: phoneNumber } = userPayload;\n passwordIdentityRef.current = {\n ...(email && { email }),\n ...(username && { username }),\n ...(phoneNumber && { phone: phoneNumber }),\n };\n const status = await fetch(payload, 'password');\n if (status) await completeAuthentication();\n };\n\n const submitPasskey = async (passkeyPayload: PassflowPasskeyAuthenticateStartPayload) => {\n const payload = {\n ...passkeyPayload,\n ...(inviteToken && { invite_token: inviteToken }),\n } as PassflowPasskeyAuthenticateStartPayload;\n\n passwordIdentityRef.current = {};\n const response = await fetch(payload, 'passkey');\n if (response) await completeAuthentication();\n };\n\n const submitPasswordless = async (\n userPayload: Partial<PassflowPasswordlessSignInPayload>,\n method: LoginCredentialsValues['method'],\n ) => {\n const challengeType = getPasswordlessData(authMethods, method)?.challengeType;\n const payload = {\n ...userPayload,\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n ...(successAuthRedirect && { redirect_url: successAuthRedirect }),\n ...(inviteToken && { invite_token: inviteToken }),\n } as PassflowPasswordlessSignInPayload;\n\n passwordIdentityRef.current = {};\n const response = await fetch(payload, 'passwordless');\n if (!response) return;\n\n // The match code is shown only by the tab holding it: it never goes in a URL.\n const { match_code: _matchCode, ...startAnswer } = response as PassflowPasswordlessResponse;\n const params = new URLSearchParams(searchSource.read());\n // The attempt's own address is the one sent at start, not one left on this page's URL.\n params.delete('redirect_url');\n const newParams = queryString.stringify({\n ...Object.fromEntries(params.entries()),\n ...payload,\n ...startAnswer,\n type: 'passwordless',\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n });\n\n if (challengeType === 'otp') navigate({ to: verifyOTPPath ?? routes.verify_otp.path, search: newParams });\n if (challengeType === 'magic_link')\n navigate({ to: verifyMagicLinkPath ?? routes.verify_magic_link.path, search: newParams });\n };\n\n const handlePassword = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const isUsername = values.method === 'email_or_username' && !isEmail && values.emailOrUsername.length > 0;\n const validatedPhone = phone(values.phone);\n const payload = {\n ...(isEmail && { email: values.emailOrUsername }),\n ...(isUsername && { username: values.emailOrUsername }),\n ...(validatedPhone.isValid && { phone: validatedPhone.phoneNumber }),\n scopes,\n password: values.password,\n };\n\n await submitPassword(payload as PassflowSignInPayload);\n };\n\n const handlePasswordless = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const validatedPhone = phone(values.phone);\n const payload = {\n ...(isEmail && { email: values.emailOrUsername }),\n ...(validatedPhone.isValid && { phone: validatedPhone.phoneNumber }),\n scopes,\n };\n\n await submitPasswordless(payload as Partial<PassflowPasswordlessSignInPayload>, values.method);\n };\n\n const handlePasskey = async () => {\n await submitPasskey({ relying_party_id: relyingPartyId, scopes });\n };\n\n const handleProvider = (provider: Providers) => federatedWithRedirect(provider, inviteToken ?? undefined);\n\n // The emailed code answers like a sign-in: the same 2FA, OIDC and redirect path follows.\n const verifyEmailCode = async (code: string) => {\n if (await emailCode.verify(code)) await completeAuthentication();\n };\n\n const resendEmailCode = async () => {\n if (await emailCode.resend()) await completeAuthentication();\n };\n\n // The application name set in the admin panel's Login Appearance.\n const appName = loginAppTheme?.application_name?.trim();\n const chrome: LoginScreenChrome = {\n title: invitationChrome?.title ?? 'Sign In to your account',\n subtitle: invitationChrome?.subtitle ?? (appName ? `To ${appName}` : undefined),\n variant: 'sign-in',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const { step } = emailCode;\n\n if (step.kind !== 'none') {\n // The server does not answer a sign-in with a link today; the state is mapped anyway.\n const stepState: LoginScreenState =\n step.kind === 'code'\n ? {\n kind: 'email-code',\n message: step.message,\n error: emailCode.error,\n busy: emailCode.isVerifying,\n resend: {\n restartKey: step.challengeId,\n busy: emailCode.isResending,\n onResend: () => void resendEmailCode(),\n },\n secondaryAction: { label: 'Use a different account', onClick: emailCode.cancel },\n onSubmit: (code) => void verifyEmailCode(code),\n }\n : {\n kind: 'status',\n tone: 'info',\n message: step.message,\n primaryAction: { label: 'Back to sign in', onClick: emailCode.cancel },\n };\n\n return (\n <LoginScreen\n chrome={{\n ...chrome,\n title: step.kind === 'code' ? 'Verify your email' : 'Check your email',\n subtitle: step.kind === 'code' ? 'Enter the code to finish signing in' : 'Follow the link to finish signing in',\n }}\n state={stepState}\n />\n );\n }\n\n return (\n <LoginScreen\n chrome={chrome}\n state={{\n kind: 'credentials',\n methods: loginMethods,\n passwordPolicy,\n forcePasskey: Boolean(appSettings?.force_passwordless_login && authMethods.passkey),\n allowPasskeyToggle: true,\n busy: isLoading,\n onCancel: isLoading && pendingOperation === 'passkey' ? cancelPasskey : undefined,\n primaryLabel: isLoading ? 'Signing in…' : 'Sign In',\n error: isError ? error : null,\n forgotPassword: {\n to: forgotPasswordPath ?? routes.forgot_password.path,\n getSearch: (method) =>\n queryString.stringify({\n ...queryString.parse(searchSource.read()),\n default_method: method,\n }),\n },\n footer: {\n prompt: \"Don't have an account?\",\n label: 'Sign Up',\n to: signUpPath ?? routes.signup.path,\n search: searchSource.read(),\n },\n onPassword: (values) => void handlePassword(values),\n onPasswordless: (values) => void handlePasswordless(values),\n onPasskey: () => void handlePasskey(),\n onProvider: handleProvider,\n onReset: reset,\n onStartAgain: () => window.location.assign(urlWithoutParentChallenge(window.location.href)),\n }}\n />\n );\n};\n\nexport const SignInForm = withHydration(SignInFormScreen);\n\nexport const SignIn = withError(SignInFormScreen, ErrorComponent);\n","import type {\n PassflowPasskeyRegisterStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignUpPayload,\n PassflowUserPayload,\n Providers,\n} from '@passflow/core';\nimport { phone } from 'phone';\nimport queryString from 'query-string';\nimport type { FC } from 'react';\nimport { useMemo } from 'react';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport {\n type LoginCredentialsValues,\n type LoginMethodConfig,\n LoginScreen,\n type LoginScreenChrome,\n type LoginScreenState,\n} from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withError, withHydration } from '@/hocs';\nimport { useAppSettings, useNavigation, usePassflow, useProvider, useSignInEnding, useSignUp } from '@/hooks';\nimport type { DefaultMethod, FederatedLanding, SuccessAuthRedirect } from '@/types';\nimport {\n type AuthMethods,\n authRedirectErrorFrom,\n emailRegex,\n getAuthMethods,\n getInvitationAuthChrome,\n getPasswordlessData,\n getUrlErrors,\n routeToSecondFactor,\n urlWithoutParentChallenge,\n useUrlParams,\n} from '@/utils';\n\nconst getSignUpMethodConfig = (authMethods: AuthMethods): LoginMethodConfig => {\n const identities: LoginMethodConfig['identities'] = [];\n\n if (authMethods.hasEmailMethods || authMethods.hasUsernameMethods) {\n const label =\n authMethods.hasEmailMethods && authMethods.hasUsernameMethods\n ? 'Email or username'\n : authMethods.hasUsernameMethods\n ? 'Username'\n : 'Email';\n identities.push({\n id: 'email_or_username',\n label,\n selectLabel: authMethods.hasUsernameMethods && !authMethods.hasEmailMethods ? 'Use username' : 'Use email',\n requiredMessage: `${label} is required`,\n format: authMethods.hasEmailMethods && !authMethods.hasUsernameMethods ? 'email' : undefined,\n password: authMethods.internal.email.password || authMethods.internal.username.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'email_or_username')?.label,\n });\n }\n\n if (authMethods.hasPhoneMethods) {\n identities.push({\n id: 'phone',\n label: 'Phone number',\n selectLabel: 'Use phone',\n requiredMessage: 'Phone number is required',\n password: authMethods.internal.phone.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'phone')?.label,\n });\n }\n\n return {\n identities,\n passkey: authMethods.passkey,\n providers: authMethods.fim.providers,\n };\n};\n\nexport type TSignUp = {\n successAuthRedirect?: SuccessAuthRedirect;\n relyingPartyId?: string;\n federatedDisplayMode?: 'modal' | 'redirect';\n federatedLanding?: FederatedLanding;\n signInPath?: string;\n verifyOTPPath?: string;\n verifyMagicLinkPath?: string;\n twoFactorVerifyPath?: string;\n};\n\nconst SignUpFormScreen: FC<TSignUp> = ({\n successAuthRedirect,\n relyingPartyId = window.location.hostname,\n federatedLanding,\n signInPath = routes.signin.path,\n verifyOTPPath = routes.verify_otp.path,\n verifyMagicLinkPath = routes.verify_magic_link.path,\n twoFactorVerifyPath = routes.two_factor_verify.path,\n}) => {\n const passflow = usePassflow();\n const { navigate } = useNavigation();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n const {\n appSettings,\n scopes,\n createTenantForNewUser,\n passwordPolicy,\n currentStyles,\n isError: isErrorApp,\n error: errorApp,\n loginAppTheme,\n } = useAppSettings();\n const { federatedWithRedirect } = useProvider(successAuthRedirect, createTenantForNewUser, federatedLanding);\n\n if (isErrorApp) throw new Error(errorApp);\n\n const authMethods = useMemo(() => getAuthMethods(appSettings?.auth_strategies), [appSettings]);\n const loginMethods = useMemo(() => getSignUpMethodConfig(authMethods), [authMethods]);\n const { error: errorUrl, message: messageUrl } = getUrlErrors();\n\n if (errorUrl) {\n console.error('[passflow] sign-up redirect returned an error', { error: errorUrl, message: messageUrl });\n throw new Error(authRedirectErrorFrom(errorUrl, messageUrl));\n }\n\n const { get } = useUrlParams({ invite_token: '' });\n const inviteToken = get('invite_token');\n const invitationChrome = getInvitationAuthChrome(inviteToken, 'sign-up');\n const { fetch, isError, error, reset, isLoading, emailCode } = useSignUp();\n\n // The server can answer a sign-up with a 2FA token in place of tokens, as it\n // does a sign-in, so the 2FA screen comes before any success redirect.\n const completeRegistration = async ({ oidcMayOwnRedirect = false } = {}) => {\n if (routeToSecondFactor(passflow, navigate, twoFactorVerifyPath ?? routes.two_factor_verify.path, searchSource.read()))\n return;\n if (oidcMayOwnRedirect && hasFollowedOIDCRedirect()) return;\n await finishSignIn(successAuthRedirect, appSettings?.defaults?.redirect);\n };\n\n const submitPassword = async (userPayload: PassflowUserPayload) => {\n const payload = {\n user: userPayload,\n create_tenant: createTenantForNewUser,\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n } as PassflowSignUpPayload;\n\n if (await fetch(payload, 'password')) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n const submitPasskey = async () => {\n const payload = {\n relying_party_id: relyingPartyId,\n create_tenant: createTenantForNewUser,\n redirect_url: successAuthRedirect ?? '',\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n scopes,\n } as PassflowPasskeyRegisterStartPayload;\n\n if (await fetch(payload, 'passkey')) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n const submitPasswordless = async (userPayload: Partial<PassflowPasswordlessSignInPayload>, method: DefaultMethod | null) => {\n const challengeType = getPasswordlessData(authMethods, method)?.challengeType;\n const payload = {\n ...userPayload,\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n ...(successAuthRedirect ? { redirect_url: successAuthRedirect } : {}),\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n } as PassflowPasswordlessSignInPayload;\n\n const response = await fetch(payload, 'passwordless');\n if (!response) return;\n\n // The match code is shown only by the tab holding it: it never goes in a URL.\n const { match_code: _matchCode, ...startAnswer } = response as PassflowPasswordlessResponse;\n const params = new URLSearchParams(searchSource.read());\n // The attempt's own address is the one sent at start, not one left on this page's URL.\n params.delete('redirect_url');\n const newParams = queryString.stringify({\n ...Object.fromEntries(params.entries()),\n ...payload,\n ...startAnswer,\n type: 'passwordless',\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n });\n\n if (challengeType === 'otp') navigate({ to: verifyOTPPath ?? routes.verify_otp.path, search: newParams });\n if (challengeType === 'magic_link')\n navigate({ to: verifyMagicLinkPath ?? routes.verify_magic_link.path, search: newParams });\n };\n\n const handlePassword = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const isUsername = values.method === 'email_or_username' && !isEmail && values.emailOrUsername.length > 0;\n const validatedPhone = phone(values.phone);\n const user = {\n ...(isEmail ? { email: values.emailOrUsername } : {}),\n ...(isUsername ? { username: values.emailOrUsername } : {}),\n ...(validatedPhone.isValid ? { phone_number: validatedPhone.phoneNumber } : {}),\n password: values.password,\n scopes,\n } as PassflowUserPayload;\n\n await submitPassword(user);\n };\n\n const handlePasswordless = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const validatedPhone = phone(values.phone);\n const payload = {\n ...(isEmail ? { email: values.emailOrUsername } : {}),\n ...(validatedPhone.isValid ? { phone: validatedPhone.phoneNumber } : {}),\n scopes,\n };\n\n await submitPasswordless(payload as Partial<PassflowPasswordlessSignInPayload>, values.method);\n };\n\n const handleProvider = (provider: Providers) => federatedWithRedirect(provider, inviteToken ?? undefined);\n\n // The emailed code answers like a sign-up: the same 2FA, OIDC and redirect path follows.\n const verifyEmailCode = async (code: string) => {\n if (await emailCode.verify(code)) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n const resendEmailCode = async () => {\n if (await emailCode.resend()) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n // The application name set in the admin panel's Login Appearance.\n const appName = loginAppTheme?.application_name?.trim();\n const chrome: LoginScreenChrome = {\n title: invitationChrome?.title ?? 'Create your account',\n subtitle: invitationChrome?.subtitle ?? (appName ? `For ${appName}` : undefined),\n variant: 'sign-in',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const { step } = emailCode;\n\n if (step.kind !== 'none') {\n const stepState: LoginScreenState =\n step.kind === 'code'\n ? {\n kind: 'email-code',\n message: step.message,\n error: emailCode.error,\n busy: emailCode.isVerifying,\n resend: {\n restartKey: step.challengeId,\n busy: emailCode.isResending,\n onResend: () => void resendEmailCode(),\n },\n secondaryAction: { label: 'Use a different email', onClick: emailCode.cancel },\n onSubmit: (code) => void verifyEmailCode(code),\n }\n : {\n kind: 'status',\n tone: 'info',\n message: step.message,\n primaryAction: { label: 'Back to sign up', onClick: emailCode.cancel },\n };\n\n return (\n <LoginScreen\n chrome={{\n ...chrome,\n title: 'Check your email',\n subtitle:\n step.kind === 'code' ? 'Enter the code to finish creating your account' : 'Follow the link to finish signing up',\n }}\n state={stepState}\n />\n );\n }\n\n return (\n <LoginScreen\n chrome={chrome}\n state={{\n kind: 'credentials',\n methods: loginMethods,\n passwordPolicy,\n credentialPurpose: 'sign-up',\n forcePasskey: Boolean(appSettings?.force_passwordless_login && authMethods.passkey),\n allowPasskeyToggle: true,\n busy: isLoading,\n primaryLabel: isLoading ? 'Creating account…' : 'Sign Up',\n passwordlessLabelPrefix: 'Sign Up with',\n passkeyLabel: 'Sign Up with a Passkey',\n error: isError ? error : null,\n footer: {\n prompt: 'Already have an account?',\n label: 'Sign In',\n to: signInPath ?? routes.signin.path,\n search: searchSource.read(),\n },\n onPassword: (values) => void handlePassword(values),\n onPasswordless: (values) => void handlePasswordless(values),\n onPasskey: () => void submitPasskey(),\n onProvider: handleProvider,\n onReset: reset,\n onStartAgain: () => window.location.assign(urlWithoutParentChallenge(window.location.href)),\n }}\n />\n );\n};\n\nexport const SignUpForm = withHydration(SignUpFormScreen);\n\nexport const SignUp = withError(SignUpFormScreen, ErrorComponent);\n","import type { TwoFactorMethod } from '@passflow/core';\nimport * as Dialog from '@radix-ui/react-dialog';\nimport type { FC } from 'react';\n\ntype MethodSelectorProps = {\n availableMethods: TwoFactorMethod[];\n currentMethod: TwoFactorMethod;\n onSelectMethod: (method: TwoFactorMethod) => void;\n isOpen: boolean;\n onClose: () => void;\n};\n\nconst methodLabels: Partial<Record<TwoFactorMethod, string>> = {\n totp: 'Authenticator App',\n email_otp: 'Email Code',\n sms_otp: 'SMS Code',\n passkey: 'Passkey',\n recovery_codes: 'Recovery Code',\n push_fcm: 'Push Notification (FCM)',\n push_webpush: 'Push Notification (Web)',\n};\n\nconst methodIcons: Partial<Record<TwoFactorMethod, string>> = {\n totp: '📱',\n email_otp: '✉️',\n sms_otp: '💬',\n passkey: '🔑',\n recovery_codes: '🔒',\n push_fcm: '🔔',\n push_webpush: '🔔',\n};\n\nexport const MethodSelector: FC<MethodSelectorProps> = ({\n availableMethods,\n currentMethod,\n onSelectMethod,\n isOpen,\n onClose,\n}) => {\n const handleSelect = (method: TwoFactorMethod) => {\n onSelectMethod(method);\n onClose();\n };\n\n return (\n <Dialog.Root open={isOpen} onOpenChange={(open) => !open && onClose()}>\n <Dialog.Portal>\n <Dialog.Overlay className='pf-dialog-overlay' />\n <Dialog.Content className='pf-dialog-content pf-method-selector-dialog'>\n <Dialog.Title className='pf-dialog-title'>Choose Verification Method</Dialog.Title>\n <Dialog.Description className='pf-dialog-description'>\n Select an alternative method to verify your identity\n </Dialog.Description>\n\n <div className='pf-method-selector-list'>\n {availableMethods.map((method) => (\n <button\n key={method}\n type='button'\n className={`pf-method-selector-item ${method === currentMethod ? 'pf-method-selector-item-active' : ''}`}\n onClick={() => handleSelect(method)}\n disabled={method === currentMethod}\n >\n <span className='pf-method-icon'>{methodIcons[method] || '🔐'}</span>\n <span className='pf-method-label'>{methodLabels[method] || method}</span>\n {method === currentMethod && <span className='pf-method-current-badge'>Current</span>}\n </button>\n ))}\n </div>\n\n <Dialog.Close asChild>\n <button type='button' className='pf-dialog-close' aria-label='Close'>\n &times;\n </button>\n </Dialog.Close>\n </Dialog.Content>\n </Dialog.Portal>\n </Dialog.Root>\n );\n};\n","import type { TwoFactorMethod } from '@passflow/core';\nimport type { FC } from 'react';\nimport { useEffect, useId, useRef, useState } from 'react';\nimport { FieldOtp } from '@/components/ui';\nimport { usePassflow } from '@/hooks/use-passflow';\nimport { useTwoFactorChallenge } from '@/hooks/use-two-factor-challenge';\nimport { MethodSelector } from './method-selector';\n\ntype TwoFactorChallengeProps = {\n firstFactorMethod?: string;\n onSuccess?: () => void;\n onError?: (error: Error) => void;\n trustDevice?: boolean;\n};\n\nexport const TwoFactorChallenge: FC<TwoFactorChallengeProps> = ({\n firstFactorMethod,\n onSuccess,\n onError,\n trustDevice = false,\n}) => {\n const passflow = usePassflow();\n const { challenge, isLoading, error, requestChallenge, verify, switchMethod, selectedMethod } = useTwoFactorChallenge();\n\n const [otpValue, setOtpValue] = useState('');\n const [isMethodSelectorOpen, setIsMethodSelectorOpen] = useState(false);\n const otpId = useId();\n const otpLabelId = `${otpId}-label`;\n const otpErrorId = `${otpId}-error`;\n\n // Once per method: every request spends budget, so StrictMode's second effect must not send another.\n // Starts at null because `firstFactorMethod` may be undefined and must still request on mount.\n const requested = useRef<string | undefined | null>(null);\n useEffect(() => {\n if (requested.current === firstFactorMethod) return;\n requested.current = firstFactorMethod;\n requestChallenge(firstFactorMethod);\n }, [requestChallenge, firstFactorMethod]);\n\n // Handle errors\n useEffect(() => {\n if (error && onError) {\n onError(error);\n }\n }, [error, onError]);\n\n const handleVerify = async () => {\n if (!otpValue) {\n return;\n }\n\n const result = await verify(otpValue, trustDevice);\n if (result) {\n onSuccess?.();\n }\n };\n\n const handleSwitchMethod = async (method: TwoFactorMethod) => {\n setOtpValue('');\n await switchMethod(method);\n };\n\n // Email and SMS codes carry no length in the challenge, so they stay at six.\n const codeLength = (selectedMethod || challenge?.method) === 'totp' ? passflow.getTotpDigits() : 6;\n\n // A form that is gone must not submit a code typed just before it left.\n const autoSubmitTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n useEffect(() => () => clearTimeout(autoSubmitTimer.current), []);\n\n const handleOtpChange = (value: string) => {\n setOtpValue(value);\n clearTimeout(autoSubmitTimer.current);\n\n // Auto-submit when the code is complete\n if (value.length === codeLength) {\n autoSubmitTimer.current = setTimeout(() => {\n verify(value, trustDevice).then((result) => {\n if (result) {\n onSuccess?.();\n }\n });\n }, 100);\n }\n };\n\n if (!challenge) {\n return (\n <div className='pf-two-factor-challenge pf-loading'>\n <p>Loading challenge...</p>\n </div>\n );\n }\n\n const currentMethod = selectedMethod || challenge.method;\n const availableMethods = [challenge.method, ...(challenge.alternative_methods || [])];\n\n const renderChallengeInput = () => {\n switch (currentMethod) {\n case 'totp':\n case 'email_otp':\n case 'sms_otp':\n return (\n <div className='pf-challenge-input-wrapper'>\n <FieldOtp\n id={otpId}\n name='code'\n length={codeLength}\n value={otpValue}\n onChange={handleOtpChange}\n state={isLoading ? 'disabled' : error ? 'error' : 'default'}\n labelledBy={otpLabelId}\n describedBy={error ? otpErrorId : undefined}\n autoFocus\n />\n {error && (\n <div id={otpErrorId} className='pf-otp-error'>\n {error.message}\n </div>\n )}\n {currentMethod === 'email_otp' && challenge.code_sent_to && (\n <p className='pf-challenge-hint'>Code sent to {challenge.code_sent_to}</p>\n )}\n {currentMethod === 'sms_otp' && challenge.code_sent_to && (\n <p className='pf-challenge-hint'>Code sent to {challenge.code_sent_to}</p>\n )}\n <button\n type='button'\n onClick={handleVerify}\n disabled={isLoading || otpValue.length !== codeLength}\n className='pf-button pf-button-primary'\n >\n {isLoading ? 'Verifying...' : 'Verify'}\n </button>\n </div>\n );\n\n case 'passkey':\n return (\n <div className='pf-challenge-input-wrapper'>\n <button type='button' onClick={handleVerify} disabled={isLoading} className='pf-button pf-button-primary'>\n {isLoading ? 'Verifying...' : 'Use Passkey'}\n </button>\n </div>\n );\n\n case 'recovery_codes':\n return (\n <div className='pf-challenge-input-wrapper'>\n <input\n type='text'\n value={otpValue}\n onChange={(e) => setOtpValue(e.target.value)}\n placeholder='Enter recovery code'\n disabled={isLoading}\n className='pf-input'\n />\n <button\n type='button'\n onClick={handleVerify}\n disabled={isLoading || !otpValue}\n className='pf-button pf-button-primary'\n >\n {isLoading ? 'Verifying...' : 'Verify'}\n </button>\n </div>\n );\n\n default:\n return <p>Unsupported method: {currentMethod}</p>;\n }\n };\n\n return (\n <div className='pf-two-factor-challenge'>\n <div className='pf-challenge-method-info'>\n <h3>Two-Factor Authentication</h3>\n <p id={otpLabelId}>Enter the verification code</p>\n </div>\n\n {renderChallengeInput()}\n\n {availableMethods.length > 1 && (\n <button\n type='button'\n onClick={() => setIsMethodSelectorOpen(true)}\n className='pf-button pf-button-secondary pf-button-switch-method'\n >\n Use different method\n </button>\n )}\n\n <MethodSelector\n availableMethods={availableMethods}\n currentMethod={currentMethod}\n onSelectMethod={handleSwitchMethod}\n isOpen={isMethodSelectorOpen}\n onClose={() => setIsMethodSelectorOpen(false)}\n />\n </div>\n );\n};\n","import { useRef } from 'react';\nimport { routes, useSearchSource } from '@/context';\nimport { routeToSecondFactor } from '@/utils';\nimport { useNavigation } from './use-navigation';\nimport { usePassflow } from './use-passflow';\n\n/**\n * Sends a screen that starts its request on mount to the second factor. That request holds the closure of the first render,\n * from before the flow registered its router and paths, so this reads them when the answer arrives.\n */\nexport const useSecondFactorRoute = (twoFactorVerifyPath?: string) => {\n const passflow = usePassflow();\n const { navigate, twoFactorVerifyPath: registeredPath } = useNavigation();\n const searchSource = useSearchSource();\n const path = twoFactorVerifyPath ?? registeredPath ?? routes.two_factor_verify.path;\n const latest = useRef({ navigate, searchSource, path });\n latest.current = { navigate, searchSource, path };\n\n return () => routeToSecondFactor(passflow, latest.current.navigate, latest.current.path, latest.current.searchSource.read());\n};\n","/* eslint-disable no-nested-ternary */\nimport type { PassflowPasswordlessResponse, PassflowPasswordlessSignInPayload } from '@passflow/core';\nimport { type FC, useEffect, useMemo, useRef, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { Button, LoginScreen } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useNavigation, usePassflow, useSignIn, useSignInEnding } from '@/hooks';\nimport { useSecondFactorRoute } from '@/hooks/use-second-factor-route';\nimport { Wrapper } from '../wrapper';\nimport '@/styles/index.css';\nimport {\n passwordlessLinkExpiredMessage,\n passwordlessSignInFailedMessage,\n passwordlessWaitCompletedMessage,\n passwordlessWaitDeniedMessage,\n signInSearch,\n useUrlParams,\n} from '@/utils';\n\nconst challengeTypeFullString = {\n email: 'email address',\n phone: 'phone number',\n};\n\nconst WAIT_FAILURE_MESSAGES = {\n denied: passwordlessWaitDeniedMessage,\n expired: passwordlessLinkExpiredMessage,\n completed: passwordlessWaitCompletedMessage,\n};\n\nconst useResendPayload = () => {\n const { createTenantForNewUser } = useAppSettings();\n const { get } = useUrlParams({\n identity: '',\n identity_value: '',\n challenge_type: '',\n type: '',\n redirect_url: '',\n });\n\n const identity = get('email') ? 'email' : get('phone') ? 'phone' : undefined;\n const identityValue = get('email') ? get('email') : get('phone') ? get('phone') : undefined;\n const redirectUrl = get('redirect_url');\n const inviteToken = get('invite_token');\n\n return {\n identity,\n identityValue,\n redirectUrl,\n type: get('type') as 'passkey' | 'password' | 'passwordless',\n resendPayload: {\n ...(identity === 'email' ? { email: identityValue } : undefined),\n ...(identity === 'phone' ? { phone: identityValue } : undefined),\n challenge_type: get('challenge_type'),\n create_tenant: createTenantForNewUser,\n redirect_url: redirectUrl,\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n } as PassflowPasswordlessSignInPayload,\n };\n};\n\n/** A link was sent and this tab has nothing to wait for: the user follows it. */\nconst MagicLinkSent: FC = () => {\n const { currentStyles, loginAppTheme } = useAppSettings();\n const { fetch: refetch } = useSignIn();\n const { identity, identityValue, type, resendPayload } = useResendPayload();\n\n const onClickResendHandler = async () => {\n await refetch(resendPayload, type);\n };\n\n return (\n <Wrapper\n title='Check your email'\n className='passflow-verify-challenge-magic-link-wrapper'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <div className='passflow-verify-challenge-magic-link-container'>\n <p className='passflow-verify-challenge-magic-link-text'>\n We sent a link to {challengeTypeFullString[identity as keyof typeof challengeTypeFullString]}{' '}\n {identityValue && <strong className='passflow-verify-challenge-magic-link-text--strong'>{identityValue}</strong>}.\n Open the link to continue.\n </p>\n {type === 'passwordless' && (\n <Button\n size='big'\n variant='secondary'\n type='button'\n className='passflow-button-resend-magic-link'\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onClick={onClickResendHandler}\n >\n Resend email\n </Button>\n )}\n </div>\n </Wrapper>\n );\n};\n\ntype MagicLinkWaitingProps = {\n challengeId: string;\n signInPath: string;\n onResent: (answer: PassflowPasswordlessResponse) => void;\n};\n\n/** This tab started the sign-in and holds its secret: it takes the session once the link is approved on any device. */\nconst MagicLinkWaiting: FC<MagicLinkWaitingProps> = ({ challengeId, signInPath, onResent }) => {\n const passflow = usePassflow();\n const { appSettings, currentStyles, loginAppTheme } = useAppSettings();\n // The wait below starts once, and settings can arrive after it.\n const appDefault = useRef<string | undefined>(undefined);\n appDefault.current = appSettings?.defaults?.redirect;\n const { navigate } = useNavigation();\n const routeToSecondFactor = useSecondFactorRoute();\n const { fetch: refetch, isLoading: isResending, isError: isResendError, error: resendError } = useSignIn();\n const searchSource = useSearchSource();\n const { redirectUrl, type, resendPayload } = useResendPayload();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const [failure, setFailure] = useState<string | null>(null);\n\n useEffect(() => {\n const controller = new AbortController();\n const { signal } = controller;\n\n const wait = async () => {\n try {\n const result = await passflow.waitForPasswordlessSignIn(challengeId, { signal });\n if (signal.aborted) return;\n\n if (result.status === 'signed-in') {\n await finishSignIn(redirectUrl, appDefault.current);\n } else if (result.status === 'second-factor-required') {\n if (!routeToSecondFactor()) setFailure(passwordlessSignInFailedMessage);\n } else {\n setFailure(WAIT_FAILURE_MESSAGES[result.status]);\n }\n } catch (error) {\n if (signal.aborted) return;\n console.error('[passflow] waiting for the passwordless sign-in failed', error);\n setFailure(passwordlessSignInFailedMessage);\n }\n };\n void wait();\n\n return () => controller.abort();\n }, [passflow, challengeId]);\n\n const resend = async () => {\n const answer = await refetch(resendPayload, 'passwordless');\n if (answer) onResent(answer as PassflowPasswordlessResponse);\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const chrome = {\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n if (failure) {\n return (\n <LoginScreen\n chrome={{ ...chrome, title: 'Sign-in not completed' }}\n state={{\n kind: 'status',\n tone: 'error',\n message: failure,\n testId: 'passwordless-wait-failure',\n primaryAction: {\n label: 'Start again',\n onClick: () => navigate({ to: signInPath, search: signInSearch(searchSource.read()) }),\n },\n }}\n />\n );\n }\n\n return (\n <LoginScreen\n chrome={{ ...chrome, title: 'Check your email' }}\n state={{\n kind: 'passwordless-waiting',\n error: isResendError ? resendError?.message : null,\n resend:\n type === 'passwordless' ? { restartKey: challengeId, busy: isResending, onResend: () => void resend() } : undefined,\n testId: 'passwordless-waiting',\n }}\n />\n );\n};\n\ntype VerifyChallengeMagicLinkProps = {\n signInPath?: string;\n};\n\nconst VerifyChallengeMagicLinkScreen: FC<VerifyChallengeMagicLinkProps> = ({ signInPath = routes.signin.path }) => {\n const passflow = usePassflow();\n const { get, set } = useUrlParams();\n // The address bar does not re-render on a write, so a resend asks for it.\n const [, setResendCount] = useState(0);\n const challengeId = get('challenge_id');\n\n // A pending record is how this screen knows this tab started the sign-in.\n // Read once per challenge: core drops the record when the wait ends, and the outcome must stay on this screen.\n const pending = useMemo(() => (challengeId ? passflow.getPendingPasswordlessSignIn(challengeId) : undefined), [challengeId]);\n\n if (!challengeId || !pending) return <MagicLinkSent />;\n\n return (\n <MagicLinkWaiting\n challengeId={challengeId}\n signInPath={signInPath}\n onResent={(answer) => {\n set({ challenge_id: answer.challenge_id, expires_at: String(answer.expires_at) });\n setResendCount((count) => count + 1);\n }}\n />\n );\n};\n\nexport const VerifyChallengeMagicLink = withHydration(VerifyChallengeMagicLinkScreen);\n","import type { PasswordlessApprovalInfo } from '@passflow/core';\nimport { type FC, useEffect, useState } from 'react';\nimport { LoginScreen, type LoginScreenState } from '@/components/ui';\nimport { useAppSettings, usePassflow } from '@/hooks';\nimport {\n approvalAlreadyDecidedMessage,\n approvalApprovedMessage,\n approvalDeniedMessage,\n approvalErrorFrom,\n approvalInvalidMessage,\n passwordlessLinkExpiredMessage,\n} from '@/utils';\n\ntype VerifyChallengeApprovalProps = {\n challengeId: string | null;\n otp: string | null;\n};\n\ntype ApprovalView =\n | { kind: 'loading' }\n | { kind: 'form'; info: PasswordlessApprovalInfo }\n | { kind: 'decided'; message: string }\n | { kind: 'terminal'; message: string }\n | { kind: 'load-failed'; message: string };\n\nconst viewFromInfo = (info: PasswordlessApprovalInfo): ApprovalView => {\n if (info.state === 'pending') return { kind: 'form', info };\n if (info.state === 'expired') return { kind: 'terminal', message: passwordlessLinkExpiredMessage };\n return { kind: 'terminal', message: approvalAlreadyDecidedMessage };\n};\n\n/**\n * The device that opened an emailed link on a row only another device can sign in with. Opening it writes nothing: the\n * user reads the request, then signs in or answers that it wasn't them, in one click. Errors from these calls are\n * plain and carry no code, but are not logged here anyway, because this screen holds the OTP.\n */\nexport const VerifyChallengeApproval: FC<VerifyChallengeApprovalProps> = ({ challengeId, otp }) => {\n const passflow = usePassflow();\n const { currentStyles, loginAppTheme } = useAppSettings();\n const [view, setView] = useState<ApprovalView>(\n challengeId && otp ? { kind: 'loading' } : { kind: 'terminal', message: approvalInvalidMessage },\n );\n const [error, setError] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [loadAttempt, setLoadAttempt] = useState(0);\n\n // `loadAttempt` only triggers a retry; `passflow` is left out so a replaced instance does not reload a request on screen.\n useEffect(() => {\n if (!challengeId || !otp) return undefined;\n let left = false;\n\n const load = async () => {\n try {\n const info = await passflow.getPasswordlessApproval(challengeId);\n if (!left) setView(viewFromInfo(info));\n } catch (loadError) {\n if (left) return;\n const { message, terminal } = approvalErrorFrom(loadError);\n setView(terminal ? { kind: 'terminal', message } : { kind: 'load-failed', message });\n }\n };\n void load();\n\n return () => {\n left = true;\n };\n }, [challengeId, otp, loadAttempt]);\n\n const decide = async (approve: boolean) => {\n if (!challengeId || !otp) return;\n setBusy(true);\n setError(null);\n try {\n await passflow.decidePasswordlessApproval(challengeId, otp, approve);\n setView({ kind: 'decided', message: approve ? approvalApprovedMessage : approvalDeniedMessage });\n } catch (decideError) {\n const { message, terminal } = approvalErrorFrom(decideError);\n if (terminal) setView({ kind: 'terminal', message });\n else setError(message);\n } finally {\n setBusy(false);\n }\n };\n\n const screenState = ((): LoginScreenState => {\n switch (view.kind) {\n case 'loading':\n return { kind: 'passwordless-approval', loading: true };\n case 'form': {\n const { info } = view;\n return {\n kind: 'passwordless-approval',\n appName: info.app_name,\n browser: info.browser,\n os: info.os,\n location: info.location ? [info.location.city, info.location.country].filter(Boolean).join(', ') : null,\n requestedAt: new Date(info.requested_at).toLocaleString(),\n error,\n busy,\n testId: 'passwordless-approval',\n onApprove: () => void decide(true),\n onDeny: () => void decide(false),\n };\n }\n case 'decided':\n return { kind: 'status', tone: 'success', message: view.message };\n case 'terminal':\n return { kind: 'status', tone: 'error', message: view.message };\n case 'load-failed':\n return {\n kind: 'status',\n tone: 'error',\n message: view.message,\n recoverable: true,\n onRetry: () => {\n setView({ kind: 'loading' });\n setLoadAttempt((attempt) => attempt + 1);\n },\n };\n }\n })();\n\n return (\n <LoginScreen\n chrome={{\n title: view.kind === 'loading' || view.kind === 'form' ? 'Approve sign-in' : 'Sign-in request',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={screenState}\n />\n );\n};\n","import { type FC, type PropsWithChildren, useEffect, useState } from 'react';\nimport { Button } from '@/components/ui';\nimport '@/styles/index.css';\nimport { cn } from '@/utils';\n\ntype TTimerButton = PropsWithChildren & {\n totalSecond: number;\n onClick: () => void;\n className?: string;\n};\n\nexport const TimerButton: FC<TTimerButton> = ({ totalSecond, onClick, className = '', ...props }) => {\n const [seconds, setSeconds] = useState(totalSecond);\n\n useEffect(() => {\n const interval = setInterval(() => {\n if (seconds > 0) {\n setSeconds((prev) => prev - 1);\n }\n }, 1000);\n\n return () => {\n clearInterval(interval);\n };\n }, [seconds]);\n\n const onClickHandler = () => {\n onClick();\n setSeconds(totalSecond);\n };\n\n return (\n <Button\n disabled={seconds > 0}\n size='small'\n variant='clean'\n type='button'\n className={cn(\n 'passflow-button-timer',\n {\n 'passflow-button-timer--active': seconds > 0,\n 'passflow-button-timer--inactive': seconds === 0,\n },\n className,\n )}\n onClick={onClickHandler}\n {...props}\n >\n Resend {seconds > 0 ? `(${seconds})` : ''}\n </Button>\n );\n};\n","import type {\n InternalStrategyChallenge,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInCompletePayload,\n PassflowPasswordlessSignInPayload,\n} from '@passflow/core';\n/* eslint-disable no-void */\n/* eslint-disable complexity */\nimport { type FC, useEffect, useId, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { Button, FieldOtp, Icon } from '@/components/ui';\nimport { useAppSettings, useNavigation, usePasswordlessComplete, useSignIn, useSignInEnding } from '@/hooks';\nimport { useSecondFactorRoute } from '@/hooks/use-second-factor-route';\nimport { useUrlParams } from '@/utils';\nimport { Wrapper } from '../wrapper';\nimport { TimerButton } from './timer-button';\n\nimport '@/styles/index.css';\n\ntype VerifyChallengeOTPManualProps = {\n identity: string | null;\n identityValue: string | null;\n challengeType: string | null;\n challengeId: string | null;\n type: 'passwordless' | 'passkey' | null;\n numInputs: number;\n shouldAutoFocus: boolean;\n signUpPath: string;\n successAuthRedirect?: string;\n twoFactorVerifyPath?: string;\n};\n\nconst challengeTypeFullString = {\n email: 'email address',\n phone: 'phone number',\n};\n\nexport const VerifyChallengeOTPManual: FC<VerifyChallengeOTPManualProps> = ({\n identity,\n identityValue,\n challengeType,\n challengeId,\n type,\n numInputs,\n shouldAutoFocus,\n successAuthRedirect,\n signUpPath,\n twoFactorVerifyPath,\n}) => {\n const routeToSecondFactor = useSecondFactorRoute(twoFactorVerifyPath);\n const { createTenantForNewUser, currentStyles, loginAppTheme } = useAppSettings();\n const { navigate } = useNavigation();\n const { fetch: refetch } = useSignIn();\n const { fetch: fetchPasswordlessComplete, isError, error } = usePasswordlessComplete();\n const [valueOTP, setValueOTP] = useState('');\n const [paramsError, setParamsError] = useState<string | null>(null);\n const { ending, retry, finishSignIn } = useSignInEnding();\n const { get, set } = useUrlParams();\n const otpId = useId();\n const otpErrorId = `${otpId}-error`;\n\n const onChangeOTP = (value: string) => setValueOTP(value);\n\n const onClickResendHandler = async () => {\n if (type && identity && identityValue && challengeType) {\n const inviteToken = get('invite_token');\n const payload: PassflowPasswordlessSignInPayload = {\n create_tenant: createTenantForNewUser,\n challenge_type: challengeType as InternalStrategyChallenge,\n redirect_url: successAuthRedirect ?? '',\n ...(identity === 'email' ? { email: identityValue } : { phone: identityValue }),\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n };\n\n const refetchResponse = (await refetch(payload, type)) as PassflowPasswordlessResponse;\n if (refetchResponse) {\n set({ challenge_id: refetchResponse.challenge_id });\n } else {\n setParamsError('Something went wrong. Please try again later.');\n }\n }\n };\n\n useEffect(() => {\n if (valueOTP.length === numInputs && challengeId) {\n const payload: PassflowPasswordlessSignInCompletePayload = {\n challenge_id: challengeId,\n challenge_type: 'otp',\n otp: valueOTP,\n };\n const fetchData = async () => {\n const response = await fetchPasswordlessComplete(payload);\n if (response) {\n // The code completed the first factor only: no tokens yet.\n if (routeToSecondFactor()) return;\n await finishSignIn(response.redirect_url);\n }\n };\n void fetchData();\n }\n }, [valueOTP, numInputs, fetchPasswordlessComplete, challengeId]);\n\n if (paramsError) throw new Error(paramsError);\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const onClickNavigateBack = () => navigate({ to: signUpPath });\n\n return (\n <Wrapper\n title={`Verify your ${identity}`}\n subtitle={`We sent OTP code to your ${challengeTypeFullString[identity as keyof typeof challengeTypeFullString]}`}\n className='passflow-verify-otp'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <div className='passflow-verify-otp-container'>\n {identityValue && (\n <Button\n size='big'\n type='button'\n variant='outlined'\n className='passflow-verify-otp-button'\n withIcon\n onClick={onClickNavigateBack}\n >\n <Icon id={identity === 'email' ? 'mail' : 'phone'} type='general' size='small' />\n {identityValue}\n <Icon id='edit' type='general' size='small' className='passflow-verify-otp-button-icon' />\n </Button>\n )}\n <div id='otp-wrapper' className='passflow-verify-otp-wrapper'>\n <FieldOtp\n id={otpId}\n name='otp'\n length={numInputs}\n value={valueOTP}\n onChange={onChangeOTP}\n state={isError ? 'error' : 'default'}\n label='Verification code'\n describedBy={isError ? otpErrorId : undefined}\n autoFocus={shouldAutoFocus}\n />\n {isError && (\n <div className='passflow-verify-otp-error'>\n <Icon size='small' id='warning' type='general' className='icon-warning' />\n <span id={otpErrorId} className='passflow-verify-otp-error-text'>\n {error}\n </span>\n </div>\n )}\n </div>\n </div>\n {type === 'passwordless' && (\n <p className='passflow-verify-otp-resend'>\n Don&apos;t receive a code?\n <TimerButton totalSecond={30} onClick={() => void onClickResendHandler()} />\n </p>\n )}\n </Wrapper>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { usePasswordlessComplete, useSignInEnding } from '@/hooks';\nimport { useSecondFactorRoute } from '@/hooks/use-second-factor-route';\nimport { verificationLinkErrorMessage, verificationRequestErrorMessage } from '@/utils';\n\ntype VerifyChallengeOTPRedirectProps = {\n appId: string | null;\n otp: string | null;\n challengeId: string | null;\n twoFactorVerifyPath?: string;\n};\n\nexport const VerifyChallengeOTPRedirect = ({\n otp,\n challengeId,\n appId,\n twoFactorVerifyPath,\n}: VerifyChallengeOTPRedirectProps) => {\n const routeToSecondFactor = useSecondFactorRoute(twoFactorVerifyPath);\n const [paramsError, setParamsError] = useState<string | null>(null);\n const { ending, retry, finishSignIn } = useSignInEnding();\n const { fetch, isError, error } = usePasswordlessComplete();\n const requested = useRef(false);\n\n // Once per opened link: the code is single use, so StrictMode's second effect must not send it again.\n useEffect(() => {\n if (requested.current) return;\n requested.current = true;\n\n const fetchData = async () => {\n if (!appId || !otp || !challengeId) {\n const missingParameters = [!appId && 'app_id', !otp && 'otp', !challengeId && 'challenge_id'].filter(Boolean);\n console.error('[passflow] passwordless verification redirect is missing required parameters', missingParameters);\n setParamsError(verificationLinkErrorMessage);\n return;\n }\n\n const response = await fetch({ otp, challenge_id: challengeId });\n\n if (response) {\n // The link completed the first factor only: no tokens yet.\n if (routeToSecondFactor()) return;\n await finishSignIn(response.redirect_url);\n } else {\n setParamsError(verificationRequestErrorMessage);\n }\n };\n\n void fetchData();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (isError && error) throw new Error(error);\n\n if (paramsError) throw new Error(paramsError);\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n return null;\n};\n","/* eslint-disable complexity */\n/* eslint-disable no-nested-ternary */\nimport type { FC } from 'react';\nimport * as Yup from 'yup';\nimport { withHydration } from '@/hocs/with-hydration';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { VerifyChallengeApproval } from './verify-challenge-approval';\nimport { VerifyChallengeOTPManual } from './verify-challenge-otp-manual';\nimport { VerifyChallengeOTPRedirect } from './verify-challenge-otp-redirect';\n\nimport '@/styles/index.css';\nimport { useUrlParams, verificationLinkErrorMessage } from '@/utils';\n\ntype TVerifyChallengeOTP = {\n numInputs: number;\n shouldAutoFocus: boolean;\n signUpPath: string;\n successAuthRedirect?: SuccessAuthRedirect;\n twoFactorVerifyPath?: string;\n};\n\nconst redirectSearchParamsVerifyChallengeOtpSchema = Yup.object().shape({\n appId: Yup.string().required(),\n challengeId: Yup.string().required(),\n otp: Yup.string().required(),\n});\n\nconst searchParamsVerifyChallengeOtpSchema = Yup.object().shape({\n challengeId: Yup.string().required(),\n identity: Yup.string().oneOf(['email', 'phone']).required(),\n identityValue: Yup.string().required(),\n challengeType: Yup.string().required(),\n type: Yup.string().oneOf(['passwordless', 'passkey']).optional(),\n});\n\nconst VerifyChallengeOTPScreen: FC<TVerifyChallengeOTP> = ({\n successAuthRedirect,\n numInputs,\n shouldAutoFocus,\n signUpPath,\n twoFactorVerifyPath,\n}) => {\n const { get } = useUrlParams({\n otp: '',\n app_id: '',\n challenge_id: '',\n identity: '',\n identity_value: '',\n challenge_type: '',\n type: '',\n flow: '',\n });\n\n // The approving device never completes the link itself, so nothing below applies to it.\n if (get('flow') === 'approval') return <VerifyChallengeApproval challengeId={get('challenge_id')} otp={get('otp')} />;\n\n const typeChallenge = get('type');\n\n if (typeChallenge !== 'passwordless' && typeChallenge !== 'passkey') {\n const redirectParams = {\n appId: get('app_id'),\n challengeId: get('challenge_id'),\n otp: get('otp'),\n };\n\n try {\n redirectSearchParamsVerifyChallengeOtpSchema.validateSync(redirectParams, { abortEarly: false });\n } catch (error) {\n console.error('[passflow] invalid passwordless verification redirect', error);\n throw new Error(verificationLinkErrorMessage);\n }\n\n const { appId, otp, challengeId } = redirectParams;\n\n return (\n <VerifyChallengeOTPRedirect appId={appId} challengeId={challengeId} otp={otp} twoFactorVerifyPath={twoFactorVerifyPath} />\n );\n }\n\n const params = {\n challengeId: get('challenge_id'),\n identity: get('email') ? 'email' : get('phone') ? 'phone' : null,\n identityValue: get('email') ? get('email') : get('phone') ? get('phone') : null,\n challengeType: get('challenge_type'),\n type: get('type'),\n };\n\n try {\n searchParamsVerifyChallengeOtpSchema.validateSync(params, { abortEarly: false });\n } catch (error) {\n console.error('[passflow] invalid passwordless verification link', error);\n throw new Error(verificationLinkErrorMessage);\n }\n\n const { challengeId, identity, identityValue, challengeType, type } = params;\n\n if (!type) {\n console.error('[passflow] passwordless verification link is missing its flow type');\n throw new Error(verificationLinkErrorMessage);\n }\n\n return (\n <VerifyChallengeOTPManual\n identity={identity}\n identityValue={identityValue}\n challengeType={challengeType}\n challengeId={challengeId}\n type={type as 'passwordless' | 'passkey'}\n numInputs={numInputs}\n shouldAutoFocus={shouldAutoFocus}\n signUpPath={signUpPath}\n successAuthRedirect={successAuthRedirect}\n twoFactorVerifyPath={twoFactorVerifyPath}\n />\n );\n};\n\nexport const VerifyChallengeOTP = withHydration(VerifyChallengeOTPScreen);\n","/**\n * The flow's own router: no router library. PassflowFlow has a fixed set of\n * screens, one path parameter (`:token`) and search params, so it matches paths\n * itself and keeps one of three histories, or takes the location from the host.\n *\n * Browser history is the default and works on its own or inside a host router\n * (React Router, TanStack Router, Wouter): the flow moves the URL with\n * `history.pushState` and then fires `popstate`, the event every browser-history\n * router listens to, so the host's location follows. Back and Forward reach the\n * flow through the same event.\n */\nimport { routes } from '@/context';\n\nexport type FlowLocation = { pathname: string; search: string; hash?: string };\nexport type FlowNavigateOptions = { replace: boolean };\nexport type FlowNavigate = (location: FlowLocation, options: FlowNavigateOptions) => void;\n\nexport type FlowHistory = {\n /** The current location. Returns the same object until the location changes. */\n read: () => FlowLocation;\n subscribe: (listener: () => void) => () => void;\n navigate: FlowNavigate;\n};\n\n/** The screens PassflowFlow renders, keyed as in `routes`. */\nexport const FLOW_SCREENS = [\n 'signin',\n 'signup',\n 'verify_otp',\n 'verify_magic_link',\n 'forgot_password',\n 'forgot_password_success',\n 'reset_password',\n 'invitation',\n 'two_factor_verify',\n 'two_factor_setup',\n 'two_factor_setup_magic_link',\n] as const satisfies readonly (keyof typeof routes)[];\n\nexport type FlowScreen = (typeof FLOW_SCREENS)[number];\n\nexport type FlowMatch = { screen: FlowScreen; params: Record<string, string> };\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/** `/two-factor-setup-magic-link/:token` → a pattern for the path's segments, capturing params. */\nconst patternSource = (path: string) =>\n path\n .split('/')\n .map((segment) => (segment.startsWith(':') ? '([^/]+)' : escapeRegExp(segment)))\n .join('/');\n\nconst paramNames = (path: string) =>\n path\n .split('/')\n .filter((segment) => segment.startsWith(':'))\n .map((segment) => segment.slice(1));\n\n// Longest first, so `/forgot-password/success` wins over `/forgot-password`.\nconst SCREENS_BY_LENGTH = [...FLOW_SCREENS].sort((a, b) => routes[b].path.length - routes[a].path.length);\n\nconst decode = (value: string) => {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n};\n\n/** `'/auth/'` → `'/auth'`, `'auth'` → `'/auth'`, `'/'` or `''` → `''`. */\nexport const normalizePrefix = (prefix: string | undefined): string => {\n const trimmed = (prefix ?? '').replace(/^\\/+|\\/+$/g, '');\n return trimmed ? `/${trimmed}` : '';\n};\n\nconst trimTrailingSlash = (pathname: string) => (pathname.length > 1 ? pathname.replace(/\\/+$/, '') : pathname);\n\n/** The screen at `pathname` under `prefix`, or null when the path is not one of the flow's screens. */\nexport const matchScreen = (pathname: string, prefix: string): FlowMatch | null => {\n const path = trimTrailingSlash(pathname);\n for (const screen of SCREENS_BY_LENGTH) {\n const route = routes[screen].path;\n const match = new RegExp(`^${escapeRegExp(prefix)}${patternSource(route)}$`).exec(path);\n if (match) {\n const names = paramNames(route);\n return { screen, params: Object.fromEntries(names.map((name, index) => [name, decode(match[index + 1] ?? '')])) };\n }\n }\n return null;\n};\n\n/**\n * Where the flow is mounted, worked out from the first URL it sees: the part in\n * front of a screen path (`/auth/signin` → `/auth`), or the whole path when it\n * names no screen (`/auth` → `/auth`, `/` → `''`).\n */\nexport const detectPrefix = (pathname: string): string => {\n const path = trimTrailingSlash(pathname);\n for (const screen of SCREENS_BY_LENGTH) {\n const match = new RegExp(`^(.*?)${patternSource(routes[screen].path)}$`).exec(path);\n if (match) return normalizePrefix(match[1]);\n }\n return normalizePrefix(path);\n};\n\n/** The absolute path of a screen under `prefix`; `params` fill `:name` segments. */\nexport const screenPath = (screen: FlowScreen, prefix: string, params: Record<string, string> = {}): string =>\n `${prefix}${routes[screen].path.replace(/:(\\w+)/g, (_, name: string) => encodeURIComponent(params[name] ?? ''))}`;\n\nexport const isUnderPrefix = (pathname: string, prefix: string) =>\n prefix === '' || pathname === prefix || pathname.startsWith(`${prefix}/`);\n\nexport const withQuestionMark = (search: string) => (search && !search.startsWith('?') ? `?${search}` : search);\n\n/** Keeps `read` stable between changes, as `useSyncExternalStore` requires. */\nconst cached = (compute: () => FlowLocation) => {\n let last: FlowLocation | null = null;\n return () => {\n const next = compute();\n if (!last || last.pathname !== next.pathname || last.search !== next.search) last = next;\n return last;\n };\n};\n\nconst listenTo = (events: string[]) => (listener: () => void) => {\n for (const event of events) window.addEventListener(event, listener);\n return () => {\n for (const event of events) window.removeEventListener(event, listener);\n };\n};\n\n/** Tells every browser-history router on the page (the flow included) that the URL moved. */\nconst announceUrlChange = () => window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));\n\nexport const createBrowserHistory = (): FlowHistory => ({\n read: cached(() => ({ pathname: window.location.pathname, search: window.location.search })),\n subscribe: listenTo(['popstate']),\n navigate: ({ pathname, search, hash = '' }, { replace }) => {\n const url = `${pathname}${withQuestionMark(search)}${hash}`;\n // The current state is kept so a host router's own bookkeeping (its history\n // index and key) stays readable after the move.\n if (replace) window.history.replaceState(window.history.state, '', url);\n else window.history.pushState(window.history.state, '', url);\n announceUrlChange();\n },\n});\n\nconst readHash = (): FlowLocation => {\n const raw = window.location.hash.replace(/^#/, '') || '/';\n const queryAt = raw.indexOf('?');\n const pathname = queryAt >= 0 ? raw.slice(0, queryAt) : raw;\n return { pathname: pathname.startsWith('/') ? pathname : `/${pathname}`, search: queryAt >= 0 ? raw.slice(queryAt) : '' };\n};\n\nexport const createHashHistory = (): FlowHistory => ({\n read: cached(readHash),\n subscribe: listenTo(['popstate', 'hashchange']),\n navigate: ({ pathname, search }, { replace }) => {\n const url = `${window.location.pathname}${window.location.search}#${pathname}${withQuestionMark(search)}`;\n if (replace) window.history.replaceState(window.history.state, '', url);\n else window.history.pushState(window.history.state, '', url);\n announceUrlChange();\n },\n});\n\nexport const createMemoryHistory = (initial: FlowLocation = { pathname: '/', search: '' }): FlowHistory => {\n const entries: FlowLocation[] = [initial];\n const listeners = new Set<() => void>();\n return {\n read: () => entries[entries.length - 1] as FlowLocation,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n navigate: ({ pathname, search }, { replace }) => {\n const next = { pathname, search: withQuestionMark(search) };\n if (replace) entries[entries.length - 1] = next;\n else entries.push(next);\n for (const listener of listeners) listener();\n },\n };\n};\n","import { type FC, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { TwoFactorSetupFlow } from '@/components/flow/two-factor-setup';\nimport { TwoFactorSetupMagicLinkFlow } from '@/components/flow/two-factor-setup-magic-link';\nimport { TwoFactorVerifyFlow } from '@/components/flow/two-factor-verify';\nimport {\n ForgotPassword,\n ForgotPasswordSuccess,\n InvitationJoin,\n ResetPassword,\n SignIn,\n SignUp,\n VerifyChallengeMagicLink,\n VerifyChallengeOTP,\n} from '@/components/form';\nimport { NavigationContext, SearchContext, type SearchSource } from '@/context';\nimport '@/styles/index.css';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { withError } from '@/hocs';\nimport { useNavigation, usePassflow, useSignInEnding } from '@/hooks';\nimport type { FederatedLanding, SuccessAuthRedirect } from '@/types';\nimport { authRedirectErrorFrom, getUrlErrors, inAppPath, passwordlessSignInFailedMessage } from '@/utils';\nimport {\n createBrowserHistory,\n createHashHistory,\n createMemoryHistory,\n detectPrefix,\n FLOW_SCREENS,\n type FlowHistory,\n type FlowLocation,\n type FlowMatch,\n type FlowNavigate,\n type FlowScreen,\n isUnderPrefix,\n matchScreen,\n normalizePrefix,\n screenPath,\n withQuestionMark,\n} from './flow-router';\n\nexport type { FlowLocation as PassflowFlowLocation, FlowNavigate as PassflowFlowNavigate } from './flow-router';\n\ntype PassflowBaseProps = {\n successAuthRedirect?: SuccessAuthRedirect;\n federatedDisplayMode?: 'modal' | 'redirect';\n /**\n * Where a federated redirect comes back. `app` (the default) keeps today's redirect URL. `login-page`, for a hosted\n * login page on a PKCE app, comes back to this page, which exchanges the code and forwards the tokens to\n * `successAuthRedirect`, else the app's default redirect.\n */\n federatedLanding?: FederatedLanding;\n error?: string;\n relyingPartyId?: string;\n /**\n * Where the flow is mounted, such as `/auth`: its screens are then `/auth/signin`,\n * `/auth/signup`, and so on. Leave it out and the flow works it out from the first\n * URL it sees (`/auth/signin` or `/auth` → `/auth`; `/` → none).\n */\n pathPrefix?: string;\n /**\n * The history the flow keeps when the app does not pass `location`. `browser`\n * (the default) uses the address bar, on its own or inside the app's router;\n * `hash` keeps the flow's path after `#`; `memory` leaves the URL alone.\n */\n routerType?: 'browser' | 'hash' | 'memory';\n /** @deprecated Never had an effect. Use `pathPrefix`. */\n basename?: string;\n};\n\nexport type PassflowProps = PassflowBaseProps &\n (\n | {\n location?: undefined;\n navigate?: undefined;\n }\n | {\n /**\n * Full control: the app's router owns the location. Pass its current\n * `{ pathname, search }` and a `navigate` that moves it; `routerType` is then\n * not used. A move to an address with a fragment also carries `hash`. Not needed for an app router in browser mode, which the default\n * already follows.\n */\n location: FlowLocation;\n navigate: FlowNavigate;\n }\n );\n\ntype RouterKind = NonNullable<PassflowBaseProps['routerType']>;\n\nconst createHistory = (routerType: RouterKind): FlowHistory => {\n if (routerType === 'hash') return createHashHistory();\n if (routerType === 'memory') return createMemoryHistory();\n return createBrowserHistory();\n};\n\nconst noLocation = () => null;\n\n/**\n * The location the flow renders and how it moves: its own history, or the app's when it passes both. Null on the\n * server and during hydration of a browser or hash history: the server has no URL, so it renders no screen, and the\n * screen appears in the render right after hydration.\n */\nconst useFlowLocation = (\n routerType: RouterKind,\n controlledLocation: FlowLocation | undefined,\n controlledNavigate: FlowNavigate | undefined,\n): { location: FlowLocation | null; navigate: FlowNavigate } => {\n const history = useMemo(() => createHistory(routerType), [routerType]);\n const ownLocation = useSyncExternalStore(\n history.subscribe,\n history.read,\n routerType === 'memory' ? history.read : noLocation,\n );\n if (controlledLocation && controlledNavigate) {\n return {\n location: { pathname: controlledLocation.pathname, search: withQuestionMark(controlledLocation.search ?? '') },\n navigate: controlledNavigate,\n };\n }\n return { location: ownLocation, navigate: history.navigate };\n};\n\ntype PassflowRoutesProps = Required<Pick<PassflowBaseProps, 'federatedDisplayMode' | 'federatedLanding' | 'relyingPartyId'>> &\n Pick<PassflowBaseProps, 'successAuthRedirect' | 'pathPrefix'> & {\n location: FlowLocation;\n navigate: FlowNavigate;\n };\n\nconst PassflowRoutes: FC<PassflowRoutesProps> = ({\n successAuthRedirect,\n federatedDisplayMode,\n federatedLanding,\n relyingPartyId,\n pathPrefix,\n location,\n navigate,\n}) => {\n // Fixed from the first URL unless the app names it.\n const [detectedPrefix] = useState(() => detectPrefix(location.pathname));\n const prefix = pathPrefix === undefined ? detectedPrefix : normalizePrefix(pathPrefix);\n\n const paths = useMemo(\n () => Object.fromEntries(FLOW_SCREENS.map((screen) => [screen, screenPath(screen, prefix)])) as Record<FlowScreen, string>,\n [prefix],\n );\n\n // The forms navigate through the provider. Registered once, reading the latest\n // `navigate` through a ref: an app's inline `navigate` prop changes every render,\n // and re-registering it would re-render the provider and loop.\n const navigateRef = useRef(navigate);\n navigateRef.current = navigate;\n const { setNavigate } = useContext(NavigationContext);\n useEffect(() => {\n setNavigate(({ to, search = '', replace = false }) => {\n const hashAt = to.indexOf('#');\n const hash = hashAt >= 0 ? to.slice(hashAt) : '';\n const target = hashAt >= 0 ? to.slice(0, hashAt) : to;\n const queryAt = target.indexOf('?');\n const pathname = queryAt >= 0 ? target.slice(0, queryAt) : target;\n const query = search || (queryAt >= 0 ? target.slice(queryAt) : '');\n navigateRef.current({ pathname, search: withQuestionMark(query), ...(hash ? { hash } : {}) }, { replace });\n });\n }, [setNavigate]);\n\n // A landing that owes its second factor goes to this flow's own (prefixed)\n // 2FA route; PassflowProvider does the navigation.\n const { setTwoFactorVerifyPath, setSignInPath } = useNavigation();\n useEffect(() => {\n setTwoFactorVerifyPath?.(paths.two_factor_verify);\n return () => setTwoFactorVerifyPath?.(null);\n }, [setTwoFactorVerifyPath, paths.two_factor_verify]);\n useEffect(() => {\n setSignInPath?.(paths.signin);\n return () => setSignInPath?.(null);\n }, [setSignInPath, paths.signin]);\n\n const match = matchScreen(location.pathname, prefix);\n // A path inside the flow that names no screen goes to sign-in, keeping its search\n // params. A path outside the flow belongs to the app: the flow renders nothing.\n const strayInsideFlow = !match && isUnderPrefix(location.pathname, prefix);\n useEffect(() => {\n if (strayInsideFlow) navigateRef.current({ pathname: paths.signin, search: location.search }, { replace: true });\n }, [strayInsideFlow, paths.signin, location.search]);\n\n // The forms read and write search params through the flow's location, not the\n // address bar, so memory, hash and app-driven flows carry them too. A write can\n // happen while a form renders (default params), so it moves after the render.\n const pathnameRef = useRef(location.pathname);\n pathnameRef.current = location.pathname;\n const searchSource = useMemo<SearchSource>(\n () => ({\n read: () => location.search,\n write: (search, { replace }) =>\n queueMicrotask(() => navigateRef.current({ pathname: pathnameRef.current, search }, { replace })),\n }),\n [location.search],\n );\n\n if (!match) return null;\n\n return (\n <SearchContext.Provider value={searchSource}>\n <FlowScreenView\n match={match}\n paths={paths}\n successAuthRedirect={successAuthRedirect}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n relyingPartyId={relyingPartyId}\n />\n </SearchContext.Provider>\n );\n};\n\ntype FlowScreenViewProps = Pick<\n PassflowRoutesProps,\n 'successAuthRedirect' | 'federatedDisplayMode' | 'federatedLanding' | 'relyingPartyId'\n> & {\n match: FlowMatch;\n paths: Record<FlowScreen, string>;\n};\n\n/** The screen a matched path names, wired to the flow's other screens. */\nconst FlowScreenView: FC<FlowScreenViewProps> = ({\n match,\n paths,\n successAuthRedirect,\n federatedDisplayMode,\n federatedLanding,\n relyingPartyId,\n}) => {\n switch (match.screen) {\n case 'signin':\n return (\n <SignIn\n successAuthRedirect={successAuthRedirect}\n relyingPartyId={relyingPartyId}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n signUpPath={paths.signup}\n forgotPasswordPath={paths.forgot_password}\n verifyMagicLinkPath={paths.verify_magic_link}\n verifyOTPPath={paths.verify_otp}\n twoFactorVerifyPath={paths.two_factor_verify}\n />\n );\n case 'signup':\n return (\n <SignUp\n successAuthRedirect={successAuthRedirect}\n relyingPartyId={relyingPartyId}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n signInPath={paths.signin}\n verifyMagicLinkPath={paths.verify_magic_link}\n verifyOTPPath={paths.verify_otp}\n twoFactorVerifyPath={paths.two_factor_verify}\n />\n );\n case 'verify_otp':\n return (\n <VerifyChallengeOTP\n successAuthRedirect={successAuthRedirect}\n numInputs={6}\n shouldAutoFocus\n signUpPath={paths.signup}\n twoFactorVerifyPath={paths.two_factor_verify}\n />\n );\n case 'verify_magic_link':\n return <VerifyChallengeMagicLink signInPath={paths.signin} />;\n case 'forgot_password':\n return (\n <ForgotPassword\n successResetRedirect={successAuthRedirect}\n signInPath={paths.signin}\n forgotPasswordSuccessPath={paths.forgot_password_success}\n />\n );\n case 'forgot_password_success':\n return <ForgotPasswordSuccess />;\n case 'reset_password':\n return (\n <ResetPassword\n successAuthRedirect={successAuthRedirect}\n twoFactorVerifyPath={paths.two_factor_verify}\n signInPath={paths.signin}\n />\n );\n case 'invitation':\n return <InvitationJoin successAuthRedirect={successAuthRedirect} signInPath={paths.signin} signUpPath={paths.signup} />;\n case 'two_factor_verify':\n return <TwoFactorVerifyFlow successAuthRedirect={successAuthRedirect} signInPath={paths.signin} />;\n case 'two_factor_setup':\n return (\n <TwoFactorSetupFlow\n successAuthRedirect={successAuthRedirect}\n twoFactorVerifyPath={paths.two_factor_verify}\n signInPath={paths.signin}\n />\n );\n case 'two_factor_setup_magic_link':\n return <TwoFactorSetupMagicLinkFlow token={match.params.token ?? ''} signInPath={paths.signin} />;\n }\n};\n\nconst PassflowWrapper: FC<PassflowProps> = ({\n successAuthRedirect: requestedRedirect,\n federatedDisplayMode = 'redirect',\n federatedLanding = 'app',\n error = undefined,\n relyingPartyId = window.location.hostname,\n pathPrefix,\n routerType = 'browser',\n location: controlledLocation,\n navigate: controlledNavigate,\n}) => {\n const { error: errorUrlSuccess, message: messageUrlSuccess } = getUrlErrors(requestedRedirect);\n // On an app's own page with the flow's browser router, a full address on this origin is a page of the same app: the\n // sign-in moves there in the app, with no new page load. A hash or memory flow, a location the app passes (offered\n // for routers in hash or memory mode) and a hosted login page keep it as an address to load.\n const followsAddressPath = controlledLocation === undefined && routerType === 'browser';\n const successAuthRedirect =\n federatedLanding === 'app' && followsAddressPath && requestedRedirect\n ? (inAppPath(requestedRedirect) ?? requestedRedirect)\n : requestedRedirect;\n const { location, navigate } = useFlowLocation(routerType, controlledLocation, controlledNavigate);\n const passflow = usePassflow();\n const { federatedLandingOutcome } = useContext(NavigationContext);\n const { ending, retry, finishSignIn } = useSignInEnding();\n\n // Only a code this tab exchanged arms the forward, never the URL or another\n // sign-in. Settings are read here because `appSettings` state may still be null.\n const forwardedRef = useRef(false);\n // Only the outcome arms the forward; any `passflow` instance reads the tokens from storage, so a newer one changes nothing.\n useEffect(() => {\n if (federatedLanding === 'login-page' && federatedLandingOutcome === 'tokens-in-url') void finishSignIn();\n if (federatedLanding !== 'login-page' || federatedLandingOutcome !== 'signed-in' || forwardedRef.current) return;\n forwardedRef.current = true;\n\n const forward = async () => {\n try {\n await finishSignIn(\n successAuthRedirect,\n successAuthRedirect ? undefined : (await passflow.getAppSettings()).defaults?.redirect,\n );\n } catch {\n // No target to forward to: the user stays signed in on this page.\n await finishSignIn();\n }\n };\n void forward();\n }, [federatedLandingOutcome]);\n\n if (federatedLandingOutcome === 'failed') throw new Error(passwordlessSignInFailedMessage);\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n if (errorUrlSuccess) {\n console.error('[passflow] authentication redirect returned an error', {\n error: errorUrlSuccess,\n message: messageUrlSuccess,\n });\n // A federated redirect lands here before SignIn / SignUp mount: allow-listed ids keep the server's localized text.\n throw new Error(authRedirectErrorFrom(errorUrlSuccess, messageUrlSuccess));\n }\n\n if (error) throw new Error(error);\n\n if (!location) return null;\n\n return (\n <PassflowRoutes\n successAuthRedirect={successAuthRedirect}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n relyingPartyId={relyingPartyId}\n pathPrefix={pathPrefix}\n location={location}\n navigate={navigate}\n />\n );\n};\n\nexport const PassflowFlow = withError(PassflowWrapper, ErrorComponent);\n","import type { AuthRedirectOptions } from '@passflow/core';\nimport { type FC, type ReactElement, type ReactNode, useState } from 'react';\nimport { type LoginButtonAppearance, LoginButtonView } from '@/components/ui/login-button';\nimport { useAuth } from '@/hooks/use-auth';\nimport { usePassflow } from '@/hooks/use-passflow';\nimport { type PassflowUser, useUser } from '@/hooks/use-user';\n\n/** What a function child of `LoginButton` receives. */\nexport type LoginButtonRenderProps = {\n isSignedIn: boolean;\n /** The label the default button would show now: `signInLabel`, or the signed-in label. */\n label: ReactNode;\n user: PassflowUser;\n /** True while the sign-out is in flight; a click then does nothing. */\n busy: boolean;\n};\n\nexport type LoginButtonProps = {\n /** Shown while signed out. Default \"Sign in\". */\n signInLabel?: ReactNode;\n /** Shown while signed in. Default: the user's email, else the phone, else \"Sign out\". */\n signedInLabel?: (user: PassflowUser) => ReactNode;\n /** Read by assistive technology after the signed-in label, since a click signs out. Default \"Sign out\". */\n signOutDescription?: string;\n /** Passed to `passflow.authRedirect()` on sign-in. */\n authRedirectOptions?: AuthRedirectOptions;\n /** After a hosted sign-in: where the hosted login sends the browser once signed out. */\n postLogoutRedirectUri?: string;\n /** The look of the default button. Default `passflow`; `shadcn` follows the host app's shadcn/ui theme. */\n appearance?: LoginButtonAppearance;\n /**\n * Your own element as the button, in place of the default one. It is cloned\n * with a click handler that first calls its own `onClick`, then signs in or\n * out unless that called `event.preventDefault()`. A child that calls\n * `onClick()` with no event still signs in or out. Its content is kept as it\n * is: no label is injected. While the sign-out is in flight it gets\n * `disabled` and `aria-busy`; otherwise those stay as you passed them. For a\n * label that switches, pass a function that returns the element; it also\n * receives `busy`.\n */\n children?: ReactElement | ((props: LoginButtonRenderProps) => ReactElement);\n};\n\nconst defaultSignedInLabel = (user: PassflowUser): ReactNode => user.email ?? user.phone ?? 'Sign out';\n\n/**\n * One button that signs in or out. Signed out, a click starts the hosted\n * sign-in (`passflow.authRedirect()`); signed in, it shows who is signed in and\n * a click signs out (`useAuth().logout()`). It switches on sign-in and\n * sign-out events.\n *\n * @example\n * ```tsx\n * <LoginButton />\n * <LoginButton appearance='shadcn' postLogoutRedirectUri='https://app.example.com/' />\n * <LoginButton><MyButton>Account</MyButton></LoginButton>\n * <LoginButton>{({ label }) => <MyButton>{label}</MyButton>}</LoginButton>\n * ```\n */\nexport const LoginButton: FC<LoginButtonProps> = ({\n signInLabel = 'Sign in',\n signedInLabel = defaultSignedInLabel,\n signOutDescription,\n authRedirectOptions,\n postLogoutRedirectUri,\n appearance,\n children,\n}) => {\n const passflow = usePassflow();\n const { isSignedIn, logout } = useAuth();\n const user = useUser();\n const [signingOut, setSigningOut] = useState(false);\n\n const label = isSignedIn ? signedInLabel(user) : signInLabel;\n\n // A failure is reported by core's Error event; the button only returns to its idle state.\n const handleClick = () => {\n if (signingOut) return;\n if (!isSignedIn) {\n passflow.authRedirect(authRedirectOptions).catch(() => undefined);\n return;\n }\n setSigningOut(true);\n logout(postLogoutRedirectUri ? { postLogoutRedirectUri } : undefined)\n .catch(() => undefined)\n .finally(() => setSigningOut(false));\n };\n\n return (\n <LoginButtonView\n state={signingOut ? 'signing-out' : isSignedIn ? 'signed-in' : 'signed-out'}\n label={label}\n signOutDescription={signOutDescription}\n appearance={appearance}\n onClick={handleClick}\n >\n {typeof children === 'function' ? children({ isSignedIn, label, user, busy: signingOut }) : children}\n </LoginButtonView>\n );\n};\n"],"mappings":";8B,mqCCSsB,oBAAXsF,SACTA,OAAOC,wBAAA,KAELC,QAAQC,IAAI,yBCThB,IAAMC,EAAwE,CAC5E,UAAW,CACTC,SAAU,CACRC,QAAS,6DACTC,MAAO,eAETC,aAAc,CACZF,QAAS,+EACTC,MAAO,QAETE,QAAS,CACPH,QAAS,iFACTC,MAAO,SAGX,UAAW,CACTF,SAAU,CACRC,QAAS,oFACTC,MAAO,QAETC,aAAc,CACZF,QAAS,oFACTC,MAAO,QAETE,QAAS,CACPH,QAAS,sFACTC,MAAO,UAOAG,EACX,6FAIWC,EACX,+FAMWC,EAA+B,2BAM/BC,EAAA,CAAgBC,EAAgBC,IAA0CX,EAAgBU,GAAMC,GAOhGC,iBAAgD,IAAIC,IAAI,CACnE,8CACA,oCACA,oDACA,wCACA,uCACA,sBACA,oBACA,yBACA,kCACA,+BACA,oCACA,0CACA,kCA7B2C,uCAiCvCC,EAAA,CAAaC,EAAgBC,IAChB,iBAAVD,GAAgC,OAAVA,EAAkBA,EAAkCC,QAAS,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AAO,MAAM,IAAIkF,MAAMlF,GAE3B,OAAK6K,iBAGHrN,EAACwmE,GAAD,CACuBlP,sBACCmP,uBACJlnC,mBACFoZ,iBACJ+tB,aACFr5D,WACAuE,aAVQ,MAe+B0pD,ICrVjD6M,GAAwB9b,GAAkCA,EAAK7gD,OAAS6gD,EAAKzrD,OAAS,WAgB/EwnE,GAAA,EACXhxB,cAAc,UACdixB,gBAAgBF,GAChB7W,qBACAgX,sBACAC,wBACAhX,aACAjiD,eAEA,MAAMH,EAAWH,MACXa,WAAEA,EAAAoB,OAAYA,GAAW4kB,KACzBw2B,EAAOD,MACNoc,EAAYC,GAAiB7oE,GAAS,GAEvCgN,EAAQiD,EAAaw4D,EAAchc,GAAQjV;AAejD,OACEp3C,EAACqxD,GAAD,CACEnnD,MAAOs+D,EAAa,cAAgB34D,EAAa,YAAc,aACxDjD,QACa0kD,qBACRC,aACZh2C,QAlBE,KACAitD,IACC34D,GAIL44D,GAAc,GACdx3D,EAAOs3D,EAAwB,CAAEA,8BAA0B,GACxDtyC,MAAA,QACAyyC,QAAA,IAAcD,GAAc,KAN7Bt5D,EAAS6mB,aAAasyC,GAAqBryC,MAAA,UAiB1C3mB,SAAoB,mBAAbA,EAA0BA,EAAS,CAAEO,aAAYjD,QAAOy/C,OAAMtoB,KAAMykC,IAAgBl5D,Y"}
1
+ {"version":3,"file":"index.es.js","names":["unhandled","subscribe","withQuestionMark","_Fragment","flags","_Fragment","error","error","error","logoRed","eyeOn","eyeOff","caretDown","onePassword","browserChrome","dotsVertical","linkedin","validationError","_Fragment","_Fragment","ERROR_ID","_Fragment","_Fragment","_Fragment","err","error","error","_Fragment","_Fragment","completionOptions","queryString","Wrapper","_Fragment","Wrapper","queryString","queryString","Dialog","challengeTypeFullString","Wrapper","Wrapper","FETCH_PRIORITY_OIDC","Passflow","PassflowEvent","SERVICE_UNAVAILABLE_ERROR_ID","SERVICE_UNAVAILABLE_MESSAGE","classifyUpgradeError","isEmailVerificationStep","isValidJWTFormat","parseToken","parseUpgradeChallenge","registerFetchMiddleware","requiredAcrLevel","React","cloneElement","createContext","forwardRef","useCallback","useContext","useEffect","useId","useLayoutEffect","useMemo","useReducer","useRef","useState","useSyncExternalStore","clsx","Fragment","jsx","jsxs","Yup","DialogPrimitive","OTPInput","REGEXP_ONLY_DIGITS","REGEXP_ONLY_DIGITS_AND_CHARS","getCountryForTimezone","defaultCountries","parseCountry","usePhoneInput","qs","phone","Controller","useForm","PopoverPrimitive","ErrorBoundary","from","window","passflowReactAppVersion","console","log","AUTH_ERROR_COPY","password","message","scope","passwordless","passkey","verificationLinkErrorMessage","verificationRequestErrorMessage","passwordChangeRequiredReason","authErrorFor","flow","operation","SERVER_MESSAGE_ERROR_IDS","Set","readField","value","field","readServerError","error","response","body","status","serverMessageFor","serverError","id","has","trimmed","trim","REFUSED_PARENT_COPY","Map","authErrorFrom","refusedParent","get","startAgain","authRedirectErrorFrom","emailCodeErrorMessage","serverMessage","passwordlessLinkExpiredMessage","passwordlessSignInFailedMessage","approvalInvalidMessage","approvalUnavailableMessage","approvalAlreadyDecidedMessage","approvalConnectionMessage","approvalMatchMessage","attemptsLeft","approvalErrorFrom","terminal","resetLinkInvalidMessage","isPasswordSavedRateLimit","twoFactorSignInOverMessage","twoFactorRateLimitedMessage","twoFactorWrongCodeMessage","twoFactorSendFailedMessage","twoFactorBackToSignInLabel","twoFactorSignInLabel","serverErrorIdFrom","serverErrorStatusFrom","OVER_PARENT_IDS","OVER_MESSAGES","enrollmentFailureFrom","DEVICE_ERROR_COPY","code_required","code_invalid","code_expired","code_declined","code_already_approved","too_many_attempts","mode_disabled","app_unavailable","bad_credentials","missing_credentials","second_factor_invalid","missing_second_factor","account_blocked","passkey_failed","passkey_unsupported","offline","generic","RECOVERABLE","REASON_TO_TYPE","invalid_user_code","unknown_user_code","expired_user_code","denied","already_approved","unknown_client","passkey_unavailable","unavailable","blocked","WEBAUTHN_NAME_TO_TYPE","NotAllowedError","AbortError","TimeoutError","UnknownError","NotSupportedError","InvalidStateError","ConstraintError","SecurityError","UNSUPPORTED_MESSAGE_PATTERNS","DeviceApiError","Error","reason","code","constructor","params","super","description","this","name","build","type","detail","isRecoverable","classifyDeviceError","err","isDOMExceptionLike","raw","lowered","toLowerCase","some","p","includes","byName","deviceErrorOfType","classifyTwoFactorError","errorTypeOf","isTerminalTwoFactorError","getUserFriendlyErrorMessage","cn","classes","messageOr","fallback","readEmailVerificationStep","answer","challengeId","challenge_id","kind","initialEmailCodeStepState","step","emailCodeStepReducer","state","event","submitFormPost","action","fields","form","document","createElement","method","style","display","key","Object","entries","input","appendChild","submit","getAuthMethods","strategies","methods","internal","username","email","otp","magicLink","fim","providers","hasEmailMethods","hasSignInEmailMethods","hasPhoneMethods","hasSignInPhoneMethods","hasUsernameMethods","hasSignInUsernameMethods","strategy","identity","challenge","fim_type","fimType","push","getIdentityLabel","getPasswordlessData","currentMethod","label","challengeType","decodeOnceMore","decodeURIComponent","getUrlErrors","subUrl","searchParams","URLSearchParams","split","location","search","DEFAULT_HAND_OFF_SCOPES","withScope","list","handOffScopes","handOff","scopes","returnPathKey","startHostedSignIn","passflow","options","redirectUrl","sessionStorage","removeItem","authRedirect","pathname","hash","origin","setItem","takeReturnPath","getItem","startsWith","url","decoded","URL","replace","rootRelativePath","undefinedOnCatch","fn","t","authAction","title","completion","getInvitationAuthChrome","inviteToken","intent","invitation","tenantName","tenant_name","inviterName","inviter_name","subtitle","subscribe$1","onClient","onServer","useHydrated","usePassflow","context","PassflowContext","AuthContext","AuthProvider","children","onSessionExpired","hydrated","isLoading","setIsLoading","isSessionExpired","setIsSessionExpired","isSignedIn","setIsSignedIn","isAuthenticated","subscriber","onAuthChange","eventType","payload","SessionExpired","SignIn","Register","subscribe","SignOut","unsubscribe","getTokens","async","doRefresh","tokens","parsedTokens","getParsedTokens","e","logout","logOut","Provider","defaultNavigate","to","searchParam","href","NavigationContext","navigate","setNavigate","router","initialState","appSettings","passwordPolicy","appId","createTenantForNewUser","parseQueryParams","isDiscoveringAppId","hasSettingsError","passflowReducer","update","found","length","handOffScopesUpdate","keys","routes","signin","path","signup","verify_otp","verify_magic_link","forgot_password","forgot_password_success","reset_password","two_factor_verify","two_factor_recovery","two_factor_setup","two_factor_setup_magic_link","addressBarSearch","read","write","history","replaceState","pushState","SearchContext","useSearchSource","UpgradeContext","noop","INERT_UPGRADE_CONTEXT","enabled","prompt","selectedFactor","selectFactor","cancel","dismiss","elevate","Promise","resolve","isValidUrl","newUrl","protocol","withoutTrailingSlash","isSameOriginPath","target","signInSearch","delete","toString","routeToSecondFactor","twoFactorVerifyPath","isTwoFactorVerificationRequired","urlCarriesTwoFactorToken","substring","urlCarriesAccessToken","STORAGE_KEY_PREFIX","REDIRECT_COUNT_KEY","LAST_ERROR_KEY","TwoFactorLoopPrevention","canRedirect","getRedirectCount","incrementRedirect","count","String","Number","parseInt","reset","setLastErrorType","errorType","getLastErrorType","isRepeatingError","getLoopDetectedMessage","activeInstance","pendingRelease","registerUpgradeAuthInstance","instance","queueMicrotask","releaseUpgradeAuthInstance","requireInstance","withAuth","next","attachAuth","withQuestionMark$1","readParentChallengeIdFromURL","Array","urlWithoutParentChallenge","hashAt","indexOf","slice","beforeHash","queryAt","kept","filter","pair","isParentChallengePair","join","useUrlParams","defaultValues","source","replaceAll","hasChanged","set","getAll","newSearchParams","emailRegex","passwordValidation","string","required","test","errors","restrict_min_password_length","restrictMinPasswordLength","min_password_length","minPasswordLength","require_lowercase","requireLowerCase","require_number","requireNumber","require_symbol","requireSymbol","require_uppercase","requireUpperCase","validationError","inner","ValidationError","Ripple","size","x","y","className","width","height","left","top","Button","variant","onClick","withIcon","asIcon","withRipple","pressed","rest","ripples","setRipples","styles","ariaDisabled","timer","setTimeout","clearTimeout","preventDefault","rect","currentTarget","getBoundingClientRect","rippleSize","Math","max","clientX","clientY","newRipple","Date","now","prev","ContinuingStatus","appName","role","COUNTRY_FLAG_POSITIONS","ad","ae","af","ag","ai","al","am","an","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","br","bs","bt","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gg","gh","gi","gl","gm","gn","gq","gr","gs","gt","gu","gw","gy","hk","hn","hr","ht","hu","ic","ie","il","im","in","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","xk","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pn","pr","ps","pt","pw","py","qa","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sk","sl","sm","sn","so","sr","ss","st","sv","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","tr","tt","tv","tw","tz","ua","ug","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","ye","za","zm","zw","COUNTRY_FLAG_ALIASES","bq","gf","gp","io","pm","re","yt","CountryFlag","iso2","country","normalized","candidate","getSupportedCountry","toUpperCase","backgroundImage","backgroundPosition","Dialog","Root","DialogTrigger","Trigger","DialogPortal","Portal","DialogClose","Close","DialogOverlay","props","ref","Overlay","displayName","DialogContent","Content","DialogHeader","DialogFooter","DialogTitle","Title","DialogDescription","Description","CHARSETS","numeric","pattern","inputMode","alphanumeric","Slot","char","isActive","hasFakeCaret","FieldOtp","onChange","onComplete","charset","labelledBy","describedBy","autoFocus","maxLength","autoComplete","disabled","noScriptCSSFallback","containerClassName","render","slots","map","slot","position","htmlFor","FieldPassword","withMessages","validationErrors","isError","isShowPassword","setIsShowPassword","errorStyles","changeIcon","handleShowPassword","requirementsMessage","requires","requiresString","requirements","Intl","ListFormat","format","requirement","generateMessage","Icon","decorative","nonEmpty","getBackgroundImage","image","applyLoginThemeStyles","root","property","primary_color","text_color","content_color","secondary_text_color","background_color","background_image","card_color","input_background_color","input_border_color","button_text_color","passkey_button_text_color","passkey_button_background_color","divider_color","federated_button_background_color","federated_button_text_color","getLoginThemeCssVariables","removeProperty","setProperty","useIsomorphicLayoutEffect","useAppSettings","setIsError","errorMessage","setErrorMessage","isFetchingRef","dispatch","current","discovered","urlsToTry","r","fetch","ok","settings","json","discoveredAppId","login_app","app_id","setAppId","discoveredScopes","createTenant","create_tenant_for_new_user","discoveryError","warn","getAppSettings","finalStateUpdates","defaultScopes","defaults","defaultCreateTenant","auth_strategies","getPasswordPolicySettings","fetchAllSettings","currentTheme","theme","matchMedia","matches","login_app_theme","color_scheme","getCurrentTheme","selectedStyle","dark_style","light_style","documentElement","loginAppTheme","currentStyles","useAuth","useAuthCloudRedirect","cloudPassflowUrl","catch","readConsentChallengeId","requestPath","consentChallengeId","encodeURIComponent","useConsent","setStatus","info","setInfo","granted","setGranted","setError","cancelled","res","credentials","headers","Accept","error_description","data","requested_scopes","fetchInfo","toggleScope","add","decide","decision","base","endpoint","granted_scopes","csrf_token","JSON","stringify","errBody","allow","deny","metadataByScope","scope_metadata","meta","scopeMetadata","grantedScopes","DEVICE_ENDPOINTS","SECOND_FACTOR_METHODS","parseDeviceResponse","useDeviceVerify","setEmail","userCode","setUserCode","ticketRef","firstFactorTicketRef","approveAfterSecondFactorRef","secondFactorMethods","setSecondFactorMethods","activeRef","csrf","post","user_code","fail","classified","loadInfo","submitCode","holdTicket","second_factor_required","approval_ticket","known","m","toSecondFactorMethods","second_factor_methods","authenticatePassword","emailValue","owesSecondFactor","authenticatePasskey","PublicKeyCredential","DOMException","start","startAuthentication","assertion","optionsJSON","publicKey","passkey_challenge_id","passkey_data","approveWithTicket","signInWithPassword","signInWithPasskey","approve","confirmWithPassword","confirmWithPasskey","submitSecondFactor","clearError","isSecondFactorPending","useEmailCodeStep","isVerifying","setIsVerifying","isResending","setIsResending","epochRef","verifyingRef","resendingRef","stepRef","optionsRef","enter","onRelease","verify","epoch","verifyEmailCode","resend","repeat","leaving","twoFactor","clearPartialAuthState","canResend","Boolean","useForgotPassword","sendPasswordResetEmail","useJoinInvite","token","joinInvitation","invitationJoinErrorFrom","useLogout","parseSearch","parsed","parse","fromEntries","useNavigation","setTwoFactorVerifyPath","signInPath","setSignInPath","newNavigate","searchParamDefault","useOutsideClick","onClickOutside","handleClick","contains","addEventListener","removeEventListener","usePassflowStore","events","onStoreChange","bscr","_eventType","_payload","getCachedTokens","getSnapshot","getServerSnapshot","usePasswordlessComplete","passwordlessSignInComplete","passwordlessCompleteErrorMessage","getFullRedirectUrl","getLoginPageLandingUrl","redirectTo","useProvider","federatedLanding","landsOnLoginPage","pkce_enabled","pkceEnabled","redirect_url","create_tenant","parent_challenge_id","entry","federatedWithPopup","provider","federatedAuthWithPopup","invite_token","federatedWithRedirect","federatedAuthWithRedirect","IDLE","isFailing","since","nextRetryAt","EVENTS","RefreshFailing","RefreshRecovered","useRefreshStatus","failing","useResetPassword","isPasswordSaved","setIsPasswordSaved","emailCode","newPassword","resetToken","resetPassword","newPasswordErrorMessage","useSessionExpired","expiredReason","setExpiredReason","resetSessionExpired","FieldText","linkedin_default","matchTextColor","icons","general","logo","warning","mail","edit","close","check","trash","google","gitlab","apple","atlassian","bitbucket","discord","dropbox","facebook","github","hubspot","linear","linkedin","linledin","microsoft","notion","slack","tiktok","twitch","twitter","xero","src","alt","LoginAlert","tone","useFocusAfterBusy","busy","inputRef","wasBusy","focus","LoginDivider","LoginActionStack","LoginProgress","onCancel","LoginScreenNotice","codeTestId","appNameTestId","LoginCodeEntry","initialCode","submitLabel","testId","onSubmit","setCode","normalizedCode","autoCapitalize","autoCorrect","spellCheck","Switch","checked","generatedId","inputId","LoginConsent","allowLabel","denyLabel","busyLabel","allowTestId","denyTestId","onToggleScope","onAllow","onDeny","item","Link","ProvidersBox","initialValues","email_or_username","LoginCredentials","computedDefaultMethod","initialMethod","identities","getDefaultMethod","defaultMethod","setDefaultMethod","passkeyOnly","setPasskeyOnly","forcePasskey","previousComputedMethod","previousForcePasskey","control","getValues","trigger","watch","formState","isDirty","isValid","isSubmitted","touchedFields","handleSubmit","mode","nextForcePasskey","currentIdentity","find","hasPassword","hasPasswordless","passwordlessLabel","hasPasskey","hasIdentity","showCredentialFields","showStandalonePasskey","hasCredentialActions","controlsDisabled","errorScope","hasIdentityError","hasPasswordError","isNewPassword","credentialPurpose","identityError","toCredentials","values","emailOrUsername","handleReset","onReset","handleMethodChange","submitCurrentMethod","onPassword","onPasswordless","selectedIdentityValue","alternateIdentity","formAlert","onStartAgain","notice","allowPasskeyToggle","handlePasskeyExperienceChange","primaryLabel","selectLabel","rules","requiredMessage","validate","FieldPhone","forgotPassword","getSearch","validateSync","primaryTestId","submitPasswordless","passwordlessLabelPrefix","onPasskey","passkeyLabel","footer","onProvider","LoginDeviceApproval","actionLabel","actionTestId","onApprove","VisuallyHidden","PROMPT_ID","ERROR_ID$1","RESEND_HINT_ID","EmailCodeResendButton","cooldownSeconds","locked","onResend","remaining","setRemaining","seconds","coolingDown","LoginEmailCode","secondaryAction","seenOutcome","setSeenOutcome","restartKey","seenRestartKey","setSeenRestartKey","LoginGeneralError","onAction","LoginInvitation","acceptLabel","switchAccountLabel","createAccountLabel","acceptTestId","onAccept","onSwitchAccount","onCreateAccount","ERROR_ID","VALIDATION_ERROR_ID","LoginNewPassword","hint","validationMessage","showValidationAlert","messages","LoginPasskeyProgress","working","recoverable","retryLabel","onRetry","LoginPasswordlessApprovalForm","browser","os","requestedAt","LoginPasswordlessApproval","loading","LoginPasswordlessWaiting","METHOD_COPY","totp","switchLabel","recovery_codes","LoginSecondFactor","onMethodChange","setMethod","alternate","copy","isTOTP","LoginScreenShell","iconId","customCss","customLogo","customLogoAlt","removeBranding","LoginStatus","primaryAction","canRetry","LoginTwoFactorCode","factor","trustDevice","canSubmit","alert","onCodeChange","alertId","digits","placeholder","LoginTwoFactorRecoveryCodes","codes","copyLabel","continueLabel","onCopy","onContinue","SecondaryAction","LoginTwoFactorSetupStart","startLabel","onStart","LoginTwoFactorSetupCode","qrCode","qrAlt","secret","secretLabel","showSecretLabel","hideSecretLabel","codeLabel","secretShown","setSecretShown","shown","LoginTwoFactorSetup","LoginScreen","chrome","content","UpgradeFactorList","factors","selected","onSelect","CODE_FIELD_ID","CODE_ERROR_ID","UpgradeChallengeView","showAlternatives","cancelLabel","alternativesLabel","onSelectFactor","onToggleAlternatives","reported","active","codeContract","needsCode","hasAlternatives","report","noValidate","DEFAULT_FACTOR_LABELS","email_otp","sms_otp","UPGRADE_UNSATISFIABLE_DETAIL","countOf","unit","upgradeRateLimitedMessage","retryAfter","serverText","minutes","ceil","hours","waitDuration","OTP_CODE_CONTRACT","freeze","TOTP_CODE_CONTRACT","UPGRADE_FACTOR_CODE_CONTRACTS","toDialogFactors","labels","override","readString","readRecord","DIALOG_KIND_BY_UPGRADE_KIND","wrong_code","challenge_spent","not_registered","prepare_not_required","exhausted","attempts_exhausted","rate_limited","session_changed","fatal","network","upgradeKindOf","record","tagged","hasOwn","hasTransportFacts","dialogOutcomeFromError","readAssuranceBar","bar","acrValues","level","maxAge","describeAssuranceBar","parts","challengeBar","requiredLevel","terminalFromError","handlers","onDismiss","obtained","onSignIn","retryable","toDialogState","outcome","ui","previousKind","previousError","suggested","upgradeDialogDismissHandler","Spinner","TONE","success","insufficient","unsatisfiable","transport","BarRow","term","UpgradeStatus","autoClose","autoCloseMs","autoDismiss","signInLabel","dismissLabel","DESCRIPTION_ID","UpgradeDialog","open","onOpenChange","errorStateOf","summaryError","summary","proof","factorsSignature","replaySignature","replay","maxBodyBytes","allowStreamingBody","UpgradeProvider","facade","backend","interceptFetch","requireChallengeChannel","shouldIntercept","onUpgradeDiagnostic","maxAttempts","relyingPartyId","onSignInRequired","failures","renderDialog","upgradeFacade","upgrade","setPrompt","setState","setSelectedFactor","setBusy","setShowAlternatives","setOutcome","installed","setInstalled","resolveRef","requestRef","reportedSelectionRef","userCancelledRef","cancelRequestedRef","shouldInterceptRef","diagnosticRef","signInRef","failuresRef","factorsRef","replayRef","replayPredicate","policy","settlePrompt","result","clearPromptView","promptHandler","request","onRequirementRaised","f","handleFlightSettled","summaryToState","signInRequired","userCancelled","summaryToOutcome","teardown","enable","d","onFlightSettled","isArray","elevatesHostedSession","hostedUpgrade","onFactorSelected","signInAgain","toggleAlternatives","requested","statedBar","waiter","channels","imperativeChallenge","asError","dialogState","dialogProps","SignInReturnFailed","onSignInAgain","StepUpFailed","AUTH_ENDPOINT_PATTERN","PASSWORDLESS_STATUS_PATTERN","bootParentChallengeId","oidcRedirectFollowed","hasFollowedOIDCRedirect","useOIDCInterceptor","parentChallengeId","isAuthURL","followsAnswer","injectParentChallenge","obj","followRedirectURL","formPost","form_post","assign","unregisterFetchMiddleware","init","Request","outInit","rewritten","text","clone","priority","OriginalXHROpen","XMLHttpRequest","prototype","OriginalXHRSend","send","tracker","WeakMap","urlStr","isAuth","follows","responseText","call","outBody","relyingPartyErrorDescriptions","login_required","interaction_required","unmet_authentication_requirements","carriesAnswer","useSessionExchangeOnMount","landedWithTwoFactorToken","currentPassflow","baseUrl","exchangeState","setExchangeState","stepUpFailure","setStepUpFailure","parentMeta","setParentMeta","attemptedRef","exchange","showForm","answerOrShowForm","redirect_uri","response_mode","dest","answerRelyingParty","oidc_prompt_none","readBody","retry","run","OIDCExchangeContext","PassflowProvider","initialNavigate","config","appIdFromToken","apiUrl","audience","aud","twoFactorTokenAppId","needsDiscovery","appIdPropRef","mountHandOff","landedWithAccessToken","takeTokensFromUrl","fixedConfig","keyStoragePrefix","tokenExchange","platform","refreshCoordination","refreshStrikes","passflowRef","liveInstanceConfig","instanceConfigRef","instanceConfig","scopesKey","deferFederatedLanding","pending","scheduled","dispose","useDisposeOnReplace","discoveryAttemptedRef","discoverAppId","passflowValue","handleSetNavigate","flowTwoFactorVerifyPath","setFlowTwoFactorVerifyPath","resolvedTwoFactorVerifyPath","flowSignInPath","setFlowSignInPath","federatedLandingOutcome","signInReturnFailed","setPending","setFederatedLandingOutcome","setSignInReturnFailed","takenRef","currentPassflowRef","navigateRef","returnToStartPage","TwoFactorRequired","signIn","setTokens","completeFederatedLanding","tokensTakenRef","handleTokensRedirect","landingTakenRef","useSecondFactorLanding","navigationValue","oidcExchangeValue","hosted","upgradeEnabled","upgradeOptions","signInForStepUp","showContinuing","app_name","useSignInEnding","ending","setEnding","lastEnding","latestSignInPath","handOver","address","sent","refresh_token","tokenParams","getUrlWithTokens","leaveFor","checkRedirectUrl","last","finishSignIn","appDefault","isSignInPage","useSignIn","onPasswordChangeRequired","onPasswordChangeRequiredRef","lastPasswordPayloadRef","resendPasswordRequest","pendingOperation","setPendingOperation","attemptRef","attempt","isCurrent","passwordlessSignIn","passkeyAuthenticate","handlePasswordChange","cancelPasskey","useSignUp","signUp","cleanup","passwordlessResponse","passkeyRegister","useTrustedDevices","setData","devices","getTrustedDevices","revoke","deviceId","revokeTrustedDevice","device","refetch","useTwoFactorChallenge","setChallenge","selectedMethod","setSelectedMethod","requestChallenge","firstFactorMethod","first_factor_method","verifyV2","trust_device","switchMethod","switchToAlternative","useTwoFactorManage","recoveryCodes","setRecoveryCodes","disable","disableTwoFactor","regenerateCodes","regenerateTwoFactorRecoveryCodes","useTwoFactorMethods","availableMethods","setAvailableMethods","registeredMethods","setRegisteredMethods","refresh","getRegisteredMethods","available","removeMethod","methodId","setupErrorMessage","failure","useTwoFactorSetup","setupData","setSetupData","setStep","checkedRef","getTwoFactorStatus","beginSetup","beginTwoFactorSetup","confirmSetup","confirmTwoFactorSetup","finish","knownErrorCodes","useTwoFactorSetupMagicLink","isDiscovering","isRetrying","setIsRetrying","isValidated","setIsValidated","sessionToken","setSessionToken","userId","setUserId","expiresIn","setExpiresIn","validatedOnMount","shouldClearOnUnmount","validateToken","validateTwoFactorSetupMagicLink","clearMagicLinkSession","useTwoFactorStatus","useTwoFactorVerify","setErrorType","errorDetails","setErrorDetails","isVerificationRequired","handleError","verifyTwoFactor","useRecoveryCode","useTwoFactorRecoveryCode","EMPTY_FACTORS","useUpgrade","readPromptFactors","factorTypes","errorKind","USER_EVENTS","Refresh","claim","id_token","access_token","readUser","sub","phonenumber","signedOut","useUser","user","setUser","sameUser","b","a","useUserPasskeys","getUserPasskeys","createUserPasskey","passkeyUsername","passkeyDisplayName","addUserPasskey","editUserPasskey","newName","passkeyId","renameUserPasskey","userPasskeys","deleteUserPasskey","inputProps","startingValue","show","setShow","filterValue","setFilterValue","isFocused","setIsFocused","refWrapper","searchInputRef","userTZ","DateTimeFormat","resolvedOptions","timeZone","userCountry","countrySwitchRef","inputValue","setCountry","handlePhoneValueChange","defaultCountry","toLocaleLowerCase","nextValue","filteredCountries","defCountry","countryName","preferredCountries","allCountries","preferredIso","handleClose","restoreFocus","querySelector","handleChangeCountry","renderCountry","dialCode","tabIndex","onKeyDown","querySelectorAll","currentIndex","min","handleOptionKeyDown","onFocus","onBlur","HSL_TRIPLET","toCssColor","COLOR_VARIABLES","THEME_ATTRIBUTES","useShadcnTheme","element","applied","clear","apply","getComputedStyle","properties","color","getPropertyValue","readShadcnTheme","observer","MutationObserver","observe","attributes","attributeFilter","colorScheme","disconnect","LoginButtonView","signOutDescription","appearance","buttonRef","descriptionId","own","defaultPrevented","signedIn","Popover","PopoverTrigger","PopoverAnchor","Anchor","PopoverContent","align","sideOffset","withHydration","Component","Hydrated","ConsentFlow","screen","consent","client_id","app_logo_url","getConsentLoginScreenProps","toCredentialsError","getDeviceLoginScreenProps","authenticated","getDeviceLoginMethods","deviceNotice","DeviceVerifyFlow","attemptedPasskeyChallenge","challengeKey","isAutomaticPasskeyReady","getTwoFactorSetupStartScreen","getTwoFactorSetupCodeScreen","fallbackDigits","totp_digits","qr_code","getTwoFactorRecoveryCodesScreen","navigator","clipboard","writeText","TwoFactorSetupForm","onBackToSignIn","numInputs","shownError","backToSignIn","handleComplete","skipsCodes","skipCodesRef","TwoFactorSetupFlow","shouldBlockRender","setShouldBlockRender","MAGIC_LINK_SEGMENT","ERROR_SUBTITLES","EXPIRED_TOKEN","INVALID_TOKEN","REVOKED_TOKEN","SERVER_ERROR","errorState","TwoFactorSetupMagicLinkFlow","tokenProp","onSuccess","onError","redirectOnSuccess","exec","tokenFromUrl","searchSource","goToSignIn","SIGNED_IN_MESSAGE","COULD_NOT_FINISH","screens","checking","refused","SignInEndingScreen","custom_css","logo_url","application_name","remove_passflow_logo","TwoFactorRecoveryForm","onBack","onEnded","trustDeviceLabel","deviceTrustAvailable","setTrustDevice","redeemRecoveryCode","onEndedRef","completionOptions$1","TwoFactorVerifyForm","onUseRecovery","shouldAutoFocus","totpDigits","getTotpDigits","computedSubtitle","completionOptions","TITLE","TwoFactorVerifyFlow","successAuthRedirect","setMode","pendingOnLanding","enrollment","onFinished","setScreen","readOnMount","notAllowedReread","beganAgain","heldCode","updateDirect","patch","endSignIn","handleFailure","stay","getTwoFactorEnrollment","device_trust_available","sends","screenFor","beginEnrollment","beginTwoFactorEnrollment","complete","verifyHeldCode","sendLink","email_sent","emailSent","sendTwoFactorSetupLink","begin","confirm","confirmTwoFactorEnrollment","end","useTwoFactorEnrollment","redirect","continueSignIn","screenProps","getTwoFactorEnrollmentScreenProps","searchParamsForgotPasswordSchema","object","shape","oneOf","ForgotPassword","successResetRedirect","forgotPasswordSuccessPath","default_method","isErrorApp","errorApp","authMethods","showPasswordChangeNotice","abortEarly","currentSubscriptions","usesPhone","isEmail","match","isUsername","validatedPhone","isPhone","phoneNumber","currentSearchParams","newParams","searchParamsForgotPasswordSuccessSchema","identityValue","nullable","ForgotPasswordSuccess","resendPayload","ErrorComponent","goBackRedirectTo","toErrorMessage","excludeRoutes","withError","route","FallbackComponent","InvitationJoin","signUpPath","joinInvite","invitationToken","invitationTokenData","parsedTokenCache","hasAuthenticatedSession","acceptInvitation","searchParamsResetPasswordSchema","ResetPassword","resetTokenData","isContinuation","registration_continuation","completeSignIn","answerRedirectUrl","savePassword","heading","SignInFormScreen","hostname","verifyOTPPath","verifyMagicLinkPath","forgotPasswordPath","loginMethods","getLoginMethodConfig","errorUrl","messageUrl","invitationChrome","passwordIdentityRef","completeAuthentication","handlePassword","userPayload","submitPassword","handlePasswordless","challenge_type","match_code","_matchCode","startAnswer","handlePasskey","passkeyPayload","submitPasskey","relying_party_id","stepState","resendEmailCode","force_passwordless_login","SignInForm","SignUpFormScreen","getSignUpMethodConfig","completeRegistration","oidcMayOwnRedirect","phone_number","SignUpForm","SignUp","methodLabels","push_fcm","push_webpush","methodIcons","MethodSelector","onSelectMethod","isOpen","onClose","handleSelect","asChild","TwoFactorChallenge","otpValue","setOtpValue","isMethodSelectorOpen","setIsMethodSelectorOpen","otpId","otpLabelId","otpErrorId","handleVerify","codeLength","autoSubmitTimer","handleOtpChange","then","alternative_methods","code_sent_to","renderChallengeInput","useSecondFactorRoute","registeredPath","latest","challengeTypeFullString$1","WAIT_FAILURE_MESSAGES","expired","completed","useResendPayload","identity_value","MagicLinkSent","MagicLinkWaiting","onResent","isResendError","resendError","setFailure","controller","AbortController","signal","waitForPasswordlessSignIn","aborted","wait","abort","VerifyChallengeMagicLink","setResendCount","getPendingPasswordlessSignIn","expires_at","VerifyChallengeApproval","view","setView","loadAttempt","setLoadAttempt","getPasswordlessApproval","viewFromInfo","loadError","load","decidePasswordlessApproval","decideError","screenState","city","requested_at","toLocaleString","TimerButton","totalSecond","setSeconds","interval","setInterval","clearInterval","challengeTypeFullString","VerifyChallengeOTPManual","fetchPasswordlessComplete","valueOTP","setValueOTP","paramsError","setParamsError","fetchData","refetchResponse","onClickResendHandler","VerifyChallengeOTPRedirect","missingParameters","redirectSearchParamsVerifyChallengeOtpSchema","searchParamsVerifyChallengeOtpSchema","optional","VerifyChallengeOTP","typeChallenge","redirectParams","FLOW_SCREENS","escapeRegExp","patternSource","segment","paramNames","SCREENS_BY_LENGTH","sort","decode","normalizePrefix","prefix","trimTrailingSlash","screenPath","_","withQuestionMark","cached","compute","listenTo","listener","announceUrlChange","dispatchEvent","PopStateEvent","readHash","createHistory","routerType","initial","listeners","createMemoryHistory","noLocation","PassflowRoutes","federatedDisplayMode","pathPrefix","detectedPrefix","RegExp","detectPrefix","paths","query","names","index","matchScreen","strayInsideFlow","isUnderPrefix","pathnameRef","FlowScreenView","PassflowFlow","requestedRedirect","controlledLocation","controlledNavigate","errorUrlSuccess","messageUrlSuccess","inAppPath","ownLocation","useFlowLocation","forwardedRef","forward","defaultSignedInLabel","LoginButton","signedInLabel","authRedirectOptions","postLogoutRedirectUri","signingOut","setSigningOut","finally"],"sources":["../package.json","../src/utils/get-app-version.ts","../src/utils/auth-error.ts","../src/utils/classify-device-error.ts","../src/utils/classify-two-factor-error.ts","../src/utils/cn.ts","../src/utils/email-verification.ts","../src/utils/form-post.ts","../src/utils/get-auth-methods.ts","../src/utils/get-form-labels.ts","../src/utils/get-url-errors.ts","../src/utils/hand-off.ts","../src/utils/get-url-with-tokens.ts","../src/utils/hosted-sign-in.ts","../src/utils/undefined-on-catch.ts","../src/utils/invitation-auth-chrome.ts","../src/hooks/use-hydrated.ts","../src/hooks/use-passflow.ts","../src/context/auth-context.tsx","../src/context/navigation-context.ts","../src/context/passflow-context.ts","../src/context/router-context.ts","../src/context/search-context.ts","../src/context/upgrade-context.ts","../src/utils/validate-url.ts","../src/utils/is-sign-in-page.ts","../src/utils/second-factor.ts","../src/utils/two-factor-loop-prevention.ts","../src/utils/upgrade-auth.ts","../src/utils/url-params.ts","../src/utils/validation-schemas/index.ts","../src/components/ui/button/index.tsx","../src/components/ui/continuing-status/index.tsx","../src/assets/icons/flags.png","../src/components/ui/country-flag/positions.ts","../src/components/ui/country-flag/index.tsx","../src/components/ui/dialog/index.tsx","../src/components/ui/fields/field-otp.tsx","../src/components/ui/fields/field-password.tsx","../src/utils/login-theme.ts","../src/hooks/use-isomorphic-layout-effect.ts","../src/hooks/use-app-settings.ts","../src/hooks/use-auth.ts","../src/hooks/use-auth-cloud-redirect.ts","../src/hooks/use-consent.ts","../src/hooks/use-device-verify.ts","../src/hooks/use-email-code-step.ts","../src/hooks/use-forgot-password.ts","../src/hooks/use-join-invite.ts","../src/hooks/use-logout.ts","../src/hooks/use-navigation.ts","../src/hooks/use-outsideclick.ts","../src/hooks/use-passflow-store.ts","../src/hooks/use-passwordless-complete.ts","../src/hooks/use-provider.ts","../src/hooks/use-refresh-status.ts","../src/hooks/use-reset-password.ts","../src/hooks/use-session-expired.ts","../src/components/ui/fields/field-text.tsx","../src/assets/icons/general/browser-chrome.svg","../src/assets/icons/general/caret-down.svg","../src/assets/icons/general/check.svg","../src/assets/icons/general/close.svg","../src/assets/icons/general/dots-vertical.svg","../src/assets/icons/general/edit.svg","../src/assets/icons/general/eye-off.svg","../src/assets/icons/general/eye-on.svg","../src/assets/icons/general/key.svg","../src/assets/icons/general/label.svg","../src/assets/icons/general/logo.svg","../src/assets/icons/general/logo-red.svg","../src/assets/icons/general/mail.svg","../src/assets/icons/general/one-password.svg","../src/assets/icons/general/passkey.svg","../src/assets/icons/general/phone.svg","../src/assets/icons/general/search.svg","../src/assets/icons/general/trash.svg","../src/assets/icons/general/warning.svg","../src/assets/icons/providers/apple.svg","../src/assets/icons/providers/atlassian.svg","../src/assets/icons/providers/bitbucket.svg","../src/assets/icons/providers/discord.svg","../src/assets/icons/providers/dropbox.svg","../src/assets/icons/providers/facebook.svg","../src/assets/icons/providers/github.svg","../src/assets/icons/providers/gitlab.svg","../src/assets/icons/providers/google.svg","../src/assets/icons/providers/hubspot.svg","../src/assets/icons/providers/linear.svg","../src/assets/icons/providers/linkedin.svg","../src/assets/icons/providers/microsoft.svg","../src/assets/icons/providers/notion.svg","../src/assets/icons/providers/slack.svg","../src/assets/icons/providers/tiktok.svg","../src/assets/icons/providers/twitch.svg","../src/assets/icons/providers/twitter.svg","../src/assets/icons/providers/xero.svg","../src/components/ui/icon/index.tsx","../src/components/ui/login-screen/shared.tsx","../src/components/ui/login-screen/code-entry.tsx","../src/components/ui/switch/index.tsx","../src/components/ui/login-screen/consent.tsx","../src/components/ui/link/index.tsx","../src/components/ui/providers-box/index.tsx","../src/components/ui/login-screen/credentials.tsx","../src/components/ui/login-screen/device-approval.tsx","../src/components/ui/visually-hidden/index.tsx","../src/components/ui/login-screen/email-code.tsx","../src/components/ui/login-screen/general-error.tsx","../src/components/ui/login-screen/invitation.tsx","../src/components/ui/login-screen/new-password.tsx","../src/components/ui/login-screen/passkey-progress.tsx","../src/components/ui/login-screen/passwordless-approval.tsx","../src/components/ui/login-screen/passwordless-waiting.tsx","../src/components/ui/login-screen/second-factor.tsx","../src/components/ui/login-screen/shell.tsx","../src/components/ui/login-screen/status.tsx","../src/components/ui/login-screen/two-factor-code.tsx","../src/components/ui/login-screen/two-factor-recovery-codes.tsx","../src/components/ui/login-screen/two-factor-setup.tsx","../src/components/ui/login-screen/login-screen.tsx","../src/components/ui/upgrade-dialog/factor-list.tsx","../src/components/ui/upgrade-dialog/challenge.tsx","../src/components/ui/upgrade-dialog/state-mapping.ts","../src/components/ui/spinner/index.tsx","../src/components/ui/upgrade-dialog/status.tsx","../src/components/ui/upgrade-dialog/upgrade-dialog.tsx","../src/components/provider/upgrade-provider.tsx","../src/components/provider/use-dispose-on-replace.ts","../src/components/provider/passflow-provider.tsx","../src/hooks/use-sign-in-ending.ts","../src/hooks/use-signin.ts","../src/hooks/use-signup.ts","../src/hooks/use-trusted-devices.ts","../src/hooks/use-two-factor-challenge.ts","../src/hooks/use-two-factor-manage.ts","../src/hooks/use-two-factor-methods.ts","../src/hooks/use-two-factor-setup.ts","../src/hooks/use-two-factor-setup-magic-link.ts","../src/hooks/use-two-factor-status.ts","../src/hooks/use-two-factor-verify.ts","../src/hooks/use-upgrade.ts","../src/hooks/use-user.ts","../src/hooks/use-user-passkeys.ts","../src/components/ui/fields/field-phone.tsx","../src/components/ui/login-button/shadcn-theme.ts","../src/components/ui/login-button/use-shadcn-theme.ts","../src/components/ui/login-button/login-button.tsx","../src/components/ui/popover/index.tsx","../src/hocs/with-hydration.tsx","../src/components/flow/consent/screen.ts","../src/components/flow/consent/index.tsx","../src/components/flow/device-verify/screen.ts","../src/components/flow/device-verify/index.tsx","../src/components/form/two-factor-setup/setup-screen.ts","../src/components/form/two-factor-setup/two-factor-setup-form.tsx","../src/components/flow/two-factor-setup/index.tsx","../src/components/flow/two-factor-setup-magic-link/index.tsx","../src/components/form/signed-in/index.tsx","../src/components/form/two-factor-verify/two-factor-recovery-form.tsx","../src/components/form/two-factor-verify/two-factor-verify-form.tsx","../src/hooks/use-two-factor-enrollment.ts","../src/components/flow/two-factor-verify/screen.ts","../src/components/flow/two-factor-verify/index.tsx","../src/components/form/forgot-password/forgot-password.tsx","../src/components/form/forgot-password/forgot-password-success.tsx","../src/components/error/index.tsx","../src/hocs/with-error.tsx","../src/components/form/invitation-join/index.tsx","../src/components/form/reset-password/index.tsx","../src/components/form/signin/index.tsx","../src/components/form/signup/index.tsx","../src/components/form/two-factor-challenge/method-selector.tsx","../src/components/form/two-factor-challenge/index.tsx","../src/hooks/use-second-factor-route.ts","../src/components/form/verify-challenge/verify-challenge-magic-link.tsx","../src/components/form/verify-challenge/verify-challenge-approval.tsx","../src/components/form/verify-challenge/timer-button.tsx","../src/components/form/verify-challenge/verify-challenge-otp-manual.tsx","../src/components/form/verify-challenge/verify-challenge-otp-redirect.tsx","../src/components/form/verify-challenge/verify-challenge-otp.tsx","../src/components/flow/passflow/flow-router.ts","../src/components/flow/passflow/index.tsx","../src/components/login-button/index.tsx"],"sourcesContent":["{\n \"name\": \"@passflow/react\",\n \"description\": \"Passflow React UI Kit\",\n \"version\": \"0.28.0\",\n \"type\": \"module\",\n \"files\": [\n \"dist\",\n \"src/styles/fonts/*-OFL.txt\",\n \"CHANGELOG.md\"\n ],\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.es.js\",\n \"types\": \"dist/src/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/src/index.d.ts\",\n \"default\": \"./dist/index.es.js\"\n },\n \"require\": {\n \"types\": \"./dist/src/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./dist/style.css\": \"./dist/style.css\"\n },\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"tsc && vite build && node scripts/check-dist-css.mjs && pnpm build:types\",\n \"build:types\": \"tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && node scripts/fix-dts-specifiers.mjs && node scripts/emit-cts-types.mjs\",\n \"prepack\": \"pnpm build\",\n \"lint\": \"biome check src\",\n \"lint:fix\": \"biome check --write src\",\n \"format\": \"biome format src\",\n \"format:fix\": \"biome format --write src\",\n \"preview\": \"vite preview\",\n \"test\": \"playwright install chromium && playwright test --config=playwright/playwright.config.ts\",\n \"test:ui\": \"playwright install chromium && playwright test --config=playwright/playwright.ui.config.ts --ui\",\n \"test:unit\": \"vitest run && vitest run --config vitest.react18.config.ts\",\n \"test:unit:react18\": \"vitest run --config vitest.react18.config.ts\",\n \"test:unit:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"storybook\": \"storybook dev -p 6006\",\n \"build-storybook\": \"storybook build\"\n },\n \"engines\": {\n \"node\": \"^22.12.0 || ^24.0.0 || >=26.0.0\"\n },\n \"peerDependencies\": {\n \"react\": \"^18.0.0 || ^19.0.0\",\n \"react-dom\": \"^18.0.0 || ^19.0.0\"\n },\n \"dependencies\": {\n \"@passflow/core\": \"^0.32.1\",\n \"@radix-ui/react-dialog\": \"^1.3.1\",\n \"@radix-ui/react-popover\": \"^1.3.1\",\n \"@simplewebauthn/browser\": \"^14.0.0\",\n \"clsx\": \"^2.1.1\",\n \"countries-and-timezones\": \"^3.11.0\",\n \"dayjs\": \"^1.11.23\",\n \"input-otp\": \"^1.5.0\",\n \"phone\": \"^3.1.72\",\n \"query-string\": \"^10.0.0\",\n \"react-error-boundary\": \"^6.1.6\",\n \"react-hook-form\": \"^7.91.0\",\n \"react-international-phone\": \"^4.8.0\",\n \"yup\": \"^1.7.1\"\n },\n \"devDependencies\": {\n \"@axe-core/playwright\": \"4.14.0\",\n \"@biomejs/biome\": \"^2.6.4\",\n \"@playwright/test\": \"^1.64.1\",\n \"@storybook/addon-a11y\": \"10.6.5\",\n \"@storybook/addon-docs\": \"10.6.5\",\n \"@storybook/addon-themes\": \"10.6.5\",\n \"@storybook/react-vite\": \"10.6.5\",\n \"@tanstack/react-router\": \"^1.170.46\",\n \"@testing-library/jest-dom\": \"^7.0.1\",\n \"@testing-library/react\": \"^16.3.3\",\n \"@testing-library/user-event\": \"^14.6.8\",\n \"@types/node\": \"^22.20.5\",\n \"@types/react\": \"^19.3.0\",\n \"@types/react-dom\": \"^19.3.0\",\n \"@vitejs/plugin-react\": \"^6.1.2\",\n \"@vitest/coverage-v8\": \"^5.0.5\",\n \"cssnano\": \"^9.9.0\",\n \"jsdom\": \"^30.1.3\",\n \"react\": \"^19.3.1\",\n \"react-18\": \"npm:react@18.3.1\",\n \"react-dom\": \"^19.3.1\",\n \"react-dom-18\": \"npm:react-dom@18.3.1\",\n \"react-router\": \"8.5.1\",\n \"storybook\": \"10.6.5\",\n \"terser\": \"^5.51.2\",\n \"tsc-alias\": \"^1.9.9\",\n \"typescript\": \"7.0.2\",\n \"vite\": \"^8.3.5\",\n \"vite-plugin-environment\": \"^1.1.4\",\n \"vitest\": \"^5.0.5\",\n \"wouter\": \"^3.13.0\"\n },\n \"authors\": [\n {\n \"name\": \"Ivan Holiak\",\n \"url\": \"https://github.com/IvanHoliak\"\n },\n {\n \"name\": \"Jack Rudenko\",\n \"url\": \"https://madappgang.com\"\n }\n ],\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/usepassflow/passflow-react-sdk/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/usepassflow/passflow-react-sdk.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"keywords\": [\n \"passflow\",\n \"auth\",\n \"authentication\",\n \"passwordless\",\n \"session\",\n \"jwt\",\n \"react\",\n \"ui\",\n \"ui-kit\",\n \"react-ui-kit\",\n \"passflow-react-ui-kit\"\n ],\n \"packageManager\": \"pnpm@12.16.1\"\n}\n","import { version } from '../../package.json';\n\ndeclare global {\n interface Window {\n passflowReactAppVersion: () => void;\n }\n}\n\n// Runs when the module loads, so it must not assume a browser: SSR and plain Node have no window.\nif (typeof window !== 'undefined') {\n window.passflowReactAppVersion = () => {\n // eslint-disable-next-line no-console\n console.log(`App Version: ${version}`);\n };\n}\n","import { SERVICE_UNAVAILABLE_ERROR_ID, SERVICE_UNAVAILABLE_MESSAGE } from '@passflow/core';\nimport type { AuthFlow, AuthOperation, AuthUiError } from '@/types';\n\nconst AUTH_ERROR_COPY: Record<AuthFlow, Record<AuthOperation, AuthUiError>> = {\n 'sign-in': {\n password: {\n message: \"We couldn't sign you in. Check your details and try again.\",\n scope: 'credentials',\n },\n passwordless: {\n message: \"We couldn't start passwordless sign-in. Check your connection and try again.\",\n scope: 'form',\n },\n passkey: {\n message: \"We couldn't complete passkey sign-in. Try again or use another sign-in method.\",\n scope: 'form',\n },\n },\n 'sign-up': {\n password: {\n message: \"We couldn't create your account. Check the information you entered and try again.\",\n scope: 'form',\n },\n passwordless: {\n message: \"We couldn't start passwordless registration. Check your connection and try again.\",\n scope: 'form',\n },\n passkey: {\n message: \"We couldn't create your account with a passkey. Try again or choose another method.\",\n scope: 'form',\n },\n },\n};\n\nexport const authRedirectErrorMessage = \"We couldn't continue this authentication request. Return to the app and try again.\";\n\nexport const verificationLinkErrorMessage =\n 'This verification link is invalid or incomplete. Request a new link or code and try again.';\n\nexport const invitationLinkErrorMessage = 'This invitation link is invalid or has expired.';\n\nexport const verificationRequestErrorMessage =\n 'This verification request is no longer available. Start again to request a new link or code.';\n\n/** The server refuses a sign-in until the password is changed; only the emailed reset flow can continue. */\nexport const passwordChangeRequiredErrorId = 'error.api.password.change.required';\n\n/** The `reason` value that sends a user whose password must change to forgot-password. */\nexport const passwordChangeRequiredReason = 'password_change_required';\n\n/** Shown on forgot-password for that reason. Fixed SDK copy: text from the URL is never displayed. */\nexport const passwordChangeRequiredMessage =\n 'You must change your password before you can sign in. Reset your password to continue.';\n\nexport const authErrorFor = (flow: AuthFlow, operation: AuthOperation): AuthUiError => AUTH_ERROR_COPY[flow][operation];\n\n/**\n * Server error ids whose `message` is written for the end user (localized, no operator detail) and may be shown as\n * is. Every other id keeps the SDK's fixed copy, so server text that was not meant for a sign-in screen never reaches\n * one. `error.not.found` is deliberately absent: it is a generic id across the API (its text can name a missing user).\n */\nexport const SERVER_MESSAGE_ERROR_IDS: ReadonlySet<string> = new Set([\n 'error.registration.email.domain_not_allowed',\n 'error.registration.email.required',\n 'error.registration.email.not_verified_by_provider',\n 'error.invite.email.domain_not_allowed',\n 'error.verification.code.rate_limited',\n 'error.otp.incorrect',\n 'error.otp.expired',\n 'error.otp.already.used',\n 'error.challenge.address.changed',\n 'error.challenge.app_mismatch',\n 'error.email.verification.required',\n 'error.registration.continuation.invalid',\n 'error.api.plan.upgrade_required',\n passwordChangeRequiredErrorId,\n]);\n\nconst readField = (value: unknown, field: string): unknown =>\n typeof value === 'object' && value !== null ? (value as Record<string, unknown>)[field] : undefined;\n\n/**\n * The `{ id, message, status }` body of a server error. Core converts most failures to a `PassflowError`, but it\n * rejects a 429 on a non-idempotent request (`POST /auth/validate`, `/auth/register`) with the raw axios error, whose\n * body sits at `response.data.error`; read that shape too so a rate limit is classified by its id like any other.\n */\nconst readServerError = (error: unknown): unknown => {\n if (typeof readField(error, 'id') === 'string') return error;\n const response = readField(error, 'response');\n const body = readField(readField(response, 'data'), 'error');\n if (typeof body !== 'object' || body === null) return error;\n return { status: readField(response, 'status'), ...body };\n};\n\n/**\n * The server's own message for an allow-listed error id, trimmed; `null` for anything else. Duck-typed on\n * `{ id, message }`, so it reads a `PassflowError`, a raw axios rejection's body, or a plain object such as a\n * redirect's query. A request that Passflow did not answer (no response, or a gateway 502/503/504 without a Passflow\n * body) carries core's service-unavailable id and always gets core's fixed message.\n */\nexport const serverMessageFor = (error: unknown): string | null => {\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n if (id === SERVICE_UNAVAILABLE_ERROR_ID) return SERVICE_UNAVAILABLE_MESSAGE;\n const message = readField(serverError, 'message');\n if (typeof id !== 'string' || !SERVER_MESSAGE_ERROR_IDS.has(id)) return null;\n if (typeof message !== 'string') return null;\n const trimmed = message.trim();\n return trimmed === '' ? null : trimmed;\n};\n\n/** A parent challenge the server refused: each id has its own copy, and only starting again can help. */\nconst REFUSED_PARENT_COPY: ReadonlyMap<unknown, string> = new Map([\n ['error.auth.flow.parent.expired', 'This sign-in request has expired. Start again.'],\n ['error.auth.flow.parent.not.found', \"We couldn't find this sign-in request. Start again.\"],\n ['error.auth.flow.parent.completed', 'This sign-in request was already completed. Start again.'],\n]);\n\n/** A hook's display error: a refused parent's copy, the server's message for an allow-listed id, else the operation's fixed copy. */\nexport const authErrorFrom = (error: unknown, flow: AuthFlow, operation: AuthOperation): AuthUiError => {\n const refusedParent = REFUSED_PARENT_COPY.get(readField(readServerError(error), 'id'));\n if (refusedParent !== undefined) return { message: refusedParent, scope: 'form', startAgain: true };\n\n const message = serverMessageFor(error);\n return message === null ? authErrorFor(flow, operation) : { message, scope: 'form' };\n};\n\n/**\n * The message for a federated redirect that came back as `?error=<id>&message=<text>`: the server's text when the id\n * is allow-listed, else the generic redirect copy.\n */\nexport const authRedirectErrorFrom = (error: string, message: string | null): string =>\n serverMessageFor({ id: error, message }) ?? authRedirectErrorMessage;\n\nexport const invitationJoinErrorMessage = \"We couldn't accept this invitation. Try again.\";\n\n/** Invitation join error: the server's message for an allow-listed id, else the fixed copy. */\nexport const invitationJoinErrorFrom = (error: unknown): string => serverMessageFor(error) ?? invitationJoinErrorMessage;\n\nexport const emailCodeInvalidMessage = 'This code is no longer valid. Request a new code.';\nexport const emailCodeUnavailableMessage = \"We couldn't check the code. Try again.\";\nexport const emailCodeRestartMessage = \"We couldn't verify the code. Go back and start again.\";\n\n/**\n * Error copy for the emailed-code step (`/auth/validate`, resend): allow-listed ids (wrong, expired or spent code,\n * rate limit, ...) show the server message; Passflow being unavailable shows core's message; `error.not.found`\n * (unknown or spent challenge) asks for a new code; a raw axios failure with no response (offline, CORS, timeout)\n * asks to retry; every other server answer (401, a missing PKCE verifier, an unlisted 4xx or a 5xx) asks to start\n * again, and the screen keeps its way back to the form.\n */\nexport const emailCodeErrorMessage = (error: unknown): string => {\n const serverMessage = serverMessageFor(error);\n if (serverMessage !== null) return serverMessage;\n\n if (readField(readServerError(error), 'id') === 'error.not.found') return emailCodeInvalidMessage;\n // An axios failure with no response is not converted to a PassflowError by core: nothing was decided server-side.\n if (readField(error, 'isAxiosError') === true && readField(error, 'response') === undefined) {\n return emailCodeUnavailableMessage;\n }\n return emailCodeRestartMessage;\n};\n\n// The tab waiting on a cross-device sign-in.\nexport const passwordlessWaitDeniedMessage = 'This sign-in was denied. Start again.';\nexport const passwordlessLinkExpiredMessage = 'This link expired. Start again.';\nexport const passwordlessWaitCompletedMessage = 'This sign-in was already used. Start again.';\nexport const passwordlessSignInFailedMessage = 'Sign-in failed. Start again.';\n\n// The device approving a cross-device sign-in.\nexport const approvalInvalidMessage = 'This link is not valid. Start again from the page where you signed in.';\nexport const approvalUnavailableMessage = 'This sign-in cannot be approved here. Start again.';\nexport const approvalAlreadyDecidedMessage = 'This sign-in was already decided.';\nexport const approvalAttemptsMessage = 'Too many wrong codes. This sign-in was denied. Start again.';\nexport const approvalConnectionMessage = 'Check your connection and try again.';\nexport const approvalUnknownErrorMessage = 'Something went wrong. Try again later.';\nexport const approvalApprovedMessage = 'Approved. Return to the tab that started sign-in. You can close this tab.';\nexport const approvalDeniedMessage = 'Denied. No one was signed in. You can close this tab.';\n\nexport type ApprovalError = {\n message: string;\n /** Nothing more can be done on this screen: the form goes away. */\n terminal: boolean;\n};\n\nconst approvalMatchMessage = (attemptsLeft?: number): string => {\n if (attemptsLeft === undefined) return 'That code does not match.';\n return `That code does not match. ${attemptsLeft} ${attemptsLeft === 1 ? 'try' : 'tries'} left.`;\n};\n\n/** A wrong code on the approve screen: the tries left must be read again before showing the message. */\nexport const isApprovalMatchError = (error: unknown): boolean =>\n readField(readServerError(error), 'id') === 'error.auth.passwordless.approval.match.invalid';\n\n/**\n * Error copy for the approve screen. `attemptsLeft` is the count re-read after the rejection. A request Passflow did\n * not answer carries core's service-unavailable id; a plain core error with no response body may also arrive as id\n * `error.passwordless.approval` or with status 0. Nothing was decided in either case, so the screen stays.\n */\nexport const approvalErrorFrom = (error: unknown, attemptsLeft?: number): ApprovalError => {\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n\n switch (id) {\n case 'error.auth.passwordless.approval.invalid':\n return { message: approvalInvalidMessage, terminal: true };\n case 'error.auth.passwordless.approval.unavailable':\n return { message: approvalUnavailableMessage, terminal: true };\n case 'error.otp.expired':\n return { message: passwordlessLinkExpiredMessage, terminal: true };\n case 'error.otp.already.used':\n return { message: approvalAlreadyDecidedMessage, terminal: true };\n case 'error.auth.passwordless.approval.match.invalid':\n return { message: approvalMatchMessage(attemptsLeft), terminal: false };\n case 'error.auth.passwordless.approval.attempts':\n return { message: approvalAttemptsMessage, terminal: true };\n }\n\n if (id === SERVICE_UNAVAILABLE_ERROR_ID) return { message: SERVICE_UNAVAILABLE_MESSAGE, terminal: false };\n if (id === 'error.passwordless.approval' || readField(serverError, 'status') === 0) {\n return { message: approvalConnectionMessage, terminal: false };\n }\n return { message: approvalUnknownErrorMessage, terminal: false };\n};\n\n/**\n * A failed passwordless completion. A row that only another device can approve has its own copy. Passflow being\n * unavailable (core's service-unavailable id, on the completion or the exchange) shows core's message: nothing was\n * refused, so the user can try again. A failed exchange that Passflow answered comes after the row was spent, so\n * retrying cannot work (id `error.pkce.exchange`). A raw 429 on the completion itself arrives as id\n * `error.passwordless.complete`: the code was not refused, so the user can try again.\n */\nexport const passwordlessCompleteErrorMessage = (error: unknown): string => {\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n\n if (id === 'error.auth.passwordless.approval.unavailable') return approvalUnavailableMessage;\n if (id === SERVICE_UNAVAILABLE_ERROR_ID) return SERVICE_UNAVAILABLE_MESSAGE;\n if (id === 'error.pkce.exchange') return passwordlessSignInFailedMessage;\n if (id === 'error.passwordless.complete' || readField(serverError, 'status') === 0) return approvalConnectionMessage;\n return verificationRequestErrorMessage;\n};\n\nexport const resetLinkInvalidMessage = 'This link is invalid or has expired. Request a new one.';\nexport const newPasswordUnavailableMessage = \"We couldn't save your password. Try again.\";\nexport const passwordSavedRateLimitedMessage =\n 'Your password was saved, but we cannot send a verification code right now. Wait a few minutes, then sign in with your new password.';\n\n/**\n * A 429 from `/auth/password/change`: the password was already changed, only the emailed code that should follow\n * was refused, so the screen must not ask for the password again.\n */\nexport const isPasswordSavedRateLimit = (error: unknown): boolean => {\n const serverError = readServerError(error);\n return readField(serverError, 'id') === 'error.verification.code.rate_limited' || readField(serverError, 'status') === 429;\n};\n\n/**\n * Error copy for the new-password screen (reset link or registration continuation): allow-listed ids show the server\n * message; Passflow being unavailable shows core's message; a refused or spent link (any other 4xx, an `error.token.*`\n * id) asks for a new one; any other server or network failure asks to retry. The raw message of anything else is\n * never shown.\n */\nexport const newPasswordErrorMessage = (error: unknown): string => {\n if (isPasswordSavedRateLimit(error)) return passwordSavedRateLimitedMessage;\n const serverMessage = serverMessageFor(error);\n if (serverMessage !== null) return serverMessage;\n\n const serverError = readServerError(error);\n const id = readField(serverError, 'id');\n const status = readField(serverError, 'status');\n if (typeof id === 'string' && id.startsWith('error.token.')) return resetLinkInvalidMessage;\n if (typeof status === 'number' && status >= 400 && status < 500) return resetLinkInvalidMessage;\n return newPasswordUnavailableMessage;\n};\n\n// First-time 2FA enrolment and the verify screens.\nexport const twoFactorSignInOverMessage = 'Your sign-in has ended. Sign in again.';\nexport const twoFactorSetupSavedSignInMessage = 'Your setup is saved. Sign in again.';\nexport const twoFactorSetupSavedNewCodeMessage =\n 'Your setup is saved. Enter a new code from your authenticator app to finish signing in.';\nexport const twoFactorSetupCodeChangedMessage = 'Your setup code changed. Scan this new QR code.';\nexport const twoFactorRateLimitedMessage = 'Too many attempts. Sign in again later.';\nexport const twoFactorWrongCodeMessage = 'Invalid code. Please check your authenticator app and try again.';\nexport const twoFactorWrongRecoveryCodeMessage = 'Invalid recovery code.';\nexport const twoFactorNotEnabledMessage =\n 'Two-factor authentication is not enabled for your account. Please contact your administrator to enable 2FA.';\nexport const twoFactorSendFailedMessage = 'We could not send the setup email. Try again later or contact your administrator.';\nexport const twoFactorTryAgainMessage = 'Something went wrong. Try again.';\nexport const twoFactorLinkAlreadyUsedMessage = 'This link was already used. Sign in.';\nexport const twoFactorBackToSignInLabel = 'Back to sign in';\nexport const twoFactorSignInLabel = 'Sign in';\n\nexport type EnrollmentFailure =\n | 'over'\n | 'rate_limited'\n | 'wrong_code'\n | 'setup_incomplete'\n | 'not_allowed'\n | 'send_failed'\n | 'unavailable'\n | 'other';\n\n/** The id of a server error, in a `PassflowError` or a raw axios rejection's object body. */\nexport const serverErrorIdFrom = (error: unknown): unknown => readField(readServerError(error), 'id');\n\n/** The HTTP status of a server error. `readServerError` skips a raw 429's string body, so its response is read too. */\nexport const serverErrorStatusFrom = (error: unknown): unknown =>\n readField(readServerError(error), 'status') ?? readField(readField(error, 'response'), 'status');\n\n/** The refused parents: a retry gets the same answer. */\nconst OVER_PARENT_IDS: ReadonlySet<unknown> = new Set([\n 'error.auth.flow.parent.not.found',\n 'error.auth.flow.parent.expired',\n 'error.auth.flow.parent.completed',\n 'error.auth.flow.parent.kind',\n 'error.auth.flow.parent.pkce.missing',\n]);\n\n/** Core throws these with no id or status once its 5 minute pending state has gone. */\nconst OVER_MESSAGES: ReadonlySet<unknown> = new Set([\n '2FA verification expired or not required. User must sign in first.',\n 'No TFA token found. User must sign in first.',\n]);\n\n/**\n * What a failed confirm, verify, begin or send means for the sign-in. The order matters: several ids answer 401 and do\n * not mean the sign-in ended. Network errors, core's format errors and a `TypeError` from a string body are `other`.\n */\nexport const enrollmentFailureFrom = (error: unknown): EnrollmentFailure => {\n const id = serverErrorIdFrom(error);\n const status = serverErrorStatusFrom(error);\n\n if (status === 429 || id === 'error.2fa.rate_limit_exceeded') return 'rate_limited';\n if (id === 'error.api.request.2fa_code.invalid' || id === 'error.2fa.recovery_code.invalid') return 'wrong_code';\n if (id === 'error.2fa.setup.incomplete') return 'setup_incomplete';\n if (id === 'error.2fa.enrollment.not_allowed') return 'not_allowed';\n if (id === 'error.2fa.setup_link.send_failed') return 'send_failed';\n if (status === 501 || id === 'error.not.implemented') return 'unavailable';\n if (id === 'error.2fa.not_enabled' || id === 'error.2fa.storage.error') return 'other';\n if (OVER_PARENT_IDS.has(id)) return 'over';\n if (status === 401 || id === 'PKCE_VERIFIER_MISSING' || id === 'error.pkce.exchange') return 'over';\n if (OVER_MESSAGES.has(readField(error, 'message'))) return 'over';\n return 'other';\n};\n","import type { DeviceError, DeviceErrorType } from '@/types/device-errors';\n\n/**\n * Turns anything that can go wrong on the device verification page into a\n * {@link DeviceError} — a sentence a person can read, plus the technical detail\n * demoted to `detail`.\n *\n * See types/device-errors.ts for why this exists at all. In short: the raw\n * strings are written for operators, and they leak.\n */\n\n/**\n * The user-facing copy. One entry per {@link DeviceErrorType}, and this table IS\n * the contract — nothing else in the flow may produce a user-visible sentence.\n *\n * Voice notes, since these are the words on the screen where someone authorizes\n * a shell:\n * - Say what happened, then what to do. Never why, in our terms.\n * - No jargon a user did not bring with them: no \"credential\", \"authenticator\",\n * \"assertion\", \"CSRF\", \"origin\", \"token\", \"challenge\", \"resident key\".\n * \"Passkey\" stays — it is the word on the button they just tapped.\n * - Never blame them, and never imply they broke something.\n * - Where we genuinely cannot tell (see passkey_failed), say so plainly and\n * offer both remedies rather than guessing at one.\n */\nconst DEVICE_ERROR_COPY: Record<DeviceErrorType, string> = {\n code_required: 'Enter the code shown on your device to continue.',\n code_invalid: \"That code isn't right. Check the code on your device and enter it again.\",\n code_expired: 'This code has expired. Start again on your device to get a new one.',\n code_declined: 'This request was already declined. Start again on your device if you still want to sign in.',\n code_already_approved: 'This device is already signed in. You can close this page and head back to it.',\n too_many_attempts: 'Too many incorrect codes were entered. Wait a few minutes, then try again.',\n mode_disabled:\n \"This app can't be signed in to this way. Ask whoever set it up to turn on QR sign-in, or sign in from your computer instead.\",\n app_unavailable: 'The app that asked you to sign in is no longer available. Start again from your device.',\n bad_credentials: \"That email or password isn't right.\",\n missing_credentials: 'Enter your email and password to continue.',\n second_factor_invalid: \"That code isn't right. Check it and enter it again.\",\n missing_second_factor: 'Enter the code to continue.',\n account_blocked: 'This account has been blocked. Contact whoever manages it for help.',\n // The three-cause sentence is deliberate, not hedging: the browser reports\n // \"cancelled\", \"timed out\" and \"no passkey here\" identically (by design — it\n // must not become an oracle for which accounts live on a device), so naming\n // one cause would be a guess presented as a fact.\n passkey_failed:\n \"We couldn't confirm your passkey. You may have cancelled it, waited too long, or there may be no passkey for this site on this device.\",\n passkey_unsupported:\n \"This device can't use a passkey to sign in here. Use a device you've set up a passkey on, or return to the app that asked you to sign in and start again.\",\n offline: \"We couldn't reach the server. Check your connection and try again.\",\n generic: 'Something went wrong on our end. Refresh the page and try again.',\n};\n\n/** Failures the user can plausibly clear by acting on this page. */\nconst RECOVERABLE: ReadonlySet<DeviceErrorType> = new Set<DeviceErrorType>([\n 'code_required',\n 'code_invalid',\n 'bad_credentials',\n 'missing_credentials',\n 'second_factor_invalid',\n 'missing_second_factor',\n 'passkey_failed',\n 'offline',\n 'generic',\n]);\n\n/**\n * Server `reason` codes -> our types.\n *\n * The server sends a stable machine reason precisely so this mapping can exist:\n * see the deviceReason* / deviceLookupError.Code constants in\n * src/web/oidc/device_page.go and device_verify.go. Its `error_description` is\n * for operators and never reaches the screen.\n *\n * Anything absent from this table — `csrf token missing or invalid`,\n * `cross-origin request refused`, `invalid JSON body`, `auth flow manager is not\n * wired` — deliberately falls through to `generic`. Those are our bugs or our\n * attacker's business, and in both cases the user's remedy is the same and their\n * screen should say so without teaching them the word \"CSRF\".\n */\nconst REASON_TO_TYPE: Record<string, DeviceErrorType> = {\n code_required: 'code_required',\n invalid_user_code: 'code_invalid',\n unknown_user_code: 'code_invalid',\n expired_user_code: 'code_expired',\n denied: 'code_declined',\n already_approved: 'code_already_approved',\n too_many_attempts: 'too_many_attempts',\n mode_disabled: 'mode_disabled',\n unknown_client: 'app_unavailable',\n passkey_unavailable: 'app_unavailable',\n unavailable: 'app_unavailable',\n bad_credentials: 'bad_credentials',\n missing_credentials: 'missing_credentials',\n second_factor_invalid: 'second_factor_invalid',\n missing_second_factor: 'missing_second_factor',\n blocked: 'account_blocked',\n passkey_failed: 'passkey_failed',\n};\n\n/**\n * WebAuthn DOMException names -> our types.\n *\n * Only the names that reliably mean something distinct to a USER are mapped.\n * NotAllowedError is the big one and it is intentionally lossy: it covers\n * cancel, timeout AND no-matching-credential, because the spec has browsers\n * conflate them so a page cannot probe which passkeys a device holds.\n */\nconst WEBAUTHN_NAME_TO_TYPE: Record<string, DeviceErrorType> = {\n NotAllowedError: 'passkey_failed',\n AbortError: 'passkey_failed',\n TimeoutError: 'passkey_failed',\n UnknownError: 'passkey_failed',\n // The authenticator or browser cannot satisfy the request as asked.\n NotSupportedError: 'passkey_unsupported',\n InvalidStateError: 'passkey_unsupported',\n ConstraintError: 'passkey_unsupported',\n // RP ID / origin misconfiguration. A deployment bug, not a user's problem —\n // they cannot fix it, so do not invite them to retry forever.\n SecurityError: 'passkey_unsupported',\n};\n\n/**\n * Message fragments that mean \"this authenticator cannot do discoverable\n * credentials\", whatever DOMException name the browser happened to attach.\n *\n * This is here because of a specific, observed regression: a real user hit\n *\n * \"Resident credentials or empty 'allowCredentials' lists are not supported\n * at this time.\"\n *\n * — Chrome's internal string for a virtual/limited authenticator being asked for\n * a discoverable credential. Matching on text as well as on name is belt and\n * braces: the name for this case is not stable across Chrome versions, and the\n * one thing that must never happen is this sentence reaching a user again.\n */\nconst UNSUPPORTED_MESSAGE_PATTERNS: readonly string[] = [\n 'resident credentials',\n 'allowcredentials',\n 'not supported at this time',\n 'discoverable credentials',\n 'is not supported',\n];\n\n/**\n * An error carrying a server-supplied reason code. Thrown by the device API\n * client so the classifier can map precisely rather than sniff strings.\n */\nexport class DeviceApiError extends Error {\n /** Stable machine reason from the server. */\n readonly reason: string;\n /** The OAuth2 error code (`invalid_request`, `unauthorized_client`, ...). */\n readonly code: string;\n /** HTTP status. */\n readonly status: number;\n\n constructor(params: { reason: string; code: string; status: number; description: string }) {\n // The Error message is the OPERATOR's string — it goes to the console and to\n // `detail`, never to the screen. classifyDeviceError picks the user's words.\n super(params.description || params.code || `device request failed (${params.status})`);\n this.name = 'DeviceApiError';\n this.reason = params.reason;\n this.code = params.code;\n this.status = params.status;\n }\n}\n\nconst build = (type: DeviceErrorType, detail?: string): DeviceError => ({\n type,\n message: DEVICE_ERROR_COPY[type],\n detail,\n isRecoverable: RECOVERABLE.has(type),\n});\n\nconst isDOMExceptionLike = (err: unknown): err is { name: string; message: string } =>\n typeof err === 'object' && err !== null && 'name' in err && typeof (err as { name: unknown }).name === 'string';\n\n/**\n * Classify any failure from the device verification flow.\n *\n * Order matters: the server's own reason wins when we have one (it knows more\n * than we can infer), then WebAuthn's message text, then WebAuthn's name, then\n * the network, then a safe default. Every path ends in copy from\n * DEVICE_ERROR_COPY — there is deliberately no branch that forwards a raw\n * string to `message`.\n */\nexport function classifyDeviceError(err: unknown): DeviceError {\n // 1. The server told us exactly what happened.\n if (err instanceof DeviceApiError) {\n const type = REASON_TO_TYPE[err.reason] ?? 'generic';\n return build(type, `${err.code}${err.reason ? `/${err.reason}` : ''}: ${err.message}`);\n }\n\n if (isDOMExceptionLike(err)) {\n const name = err.name;\n const raw = typeof err.message === 'string' ? err.message : '';\n const detail = raw ? `${name}: ${raw}` : name;\n\n // 2. The resident-credential family, matched on text. Checked BEFORE the\n // name table because the name for this case is not dependable — see\n // UNSUPPORTED_MESSAGE_PATTERNS.\n const lowered = raw.toLowerCase();\n if (UNSUPPORTED_MESSAGE_PATTERNS.some((p) => lowered.includes(p))) {\n return build('passkey_unsupported', detail);\n }\n\n // 3. A WebAuthn name we recognise.\n const byName = WEBAUTHN_NAME_TO_TYPE[name];\n if (byName) {\n return build(byName, detail);\n }\n\n // 4. fetch() rejects with TypeError when it cannot reach the network at all.\n if (name === 'TypeError') {\n return build('offline', detail);\n }\n\n return build('generic', detail);\n }\n\n return build('generic', typeof err === 'string' ? err : undefined);\n}\n\n/**\n * The copy for a type, without an error to classify. For states that are known\n * up front rather than thrown — e.g. a browser with no WebAuthn at all.\n */\nexport function deviceErrorOfType(type: DeviceErrorType, detail?: string): DeviceError {\n return build(type, detail);\n}\n","import type { TwoFactorError, TwoFactorErrorType } from '@/types/two-factor-errors';\nimport {\n enrollmentFailureFrom,\n serverErrorIdFrom,\n twoFactorNotEnabledMessage,\n twoFactorRateLimitedMessage,\n twoFactorSignInOverMessage,\n twoFactorTryAgainMessage,\n twoFactorWrongCodeMessage,\n} from './auth-error';\n\nconst errorTypeOf = (error: unknown): TwoFactorErrorType => {\n if (serverErrorIdFrom(error) === 'error.2fa.not_enabled') return 'not_enabled';\n\n switch (enrollmentFailureFrom(error)) {\n case 'over':\n return 'expired';\n case 'rate_limited':\n return 'rate_limited';\n case 'wrong_code':\n return 'invalid_code';\n default:\n return 'generic';\n }\n};\n\n/**\n * Classify a 2FA error from the error itself, not its message: the server localises messages.\n */\nexport function classifyTwoFactorError(error: unknown): TwoFactorError {\n const type = errorTypeOf(error);\n return {\n type,\n message: (error as Error | null)?.message ?? twoFactorTryAgainMessage,\n isRecoverable: type !== 'not_enabled',\n };\n}\n\n/** No further code can be taken on the screen: only the way back to sign in is left. */\nexport const isTerminalTwoFactorError = (type: TwoFactorErrorType | undefined): boolean =>\n type === 'not_enabled' || type === 'expired' || type === 'rate_limited';\n\n/**\n * Get user-friendly error message based on error type\n */\nexport function getUserFriendlyErrorMessage(error: TwoFactorError): string {\n switch (error.type) {\n case 'expired':\n return twoFactorSignInOverMessage;\n case 'rate_limited':\n return twoFactorRateLimitedMessage;\n case 'not_enabled':\n return twoFactorNotEnabledMessage;\n case 'invalid_code':\n return twoFactorWrongCodeMessage;\n default:\n return error.message;\n }\n}\n","import clsx, { type ClassValue } from 'clsx';\n\n// Joins class names. The library styles with `passflow-*` classes only, so\n// there are no utility-class conflicts to resolve.\nexport const cn = (...classes: ClassValue[]) => clsx(classes);\n","import { isEmailVerificationStep } from '@passflow/core';\nimport type { EmailCodeStep, EmailVerificationStep } from '@/types';\n\nexport const emailCodeSentFallbackMessage = 'We sent a code to your email.';\nexport const emailLinkSentFallbackMessage = 'Check your email for a link to finish signing up.';\n\nconst messageOr = (message: unknown, fallback: string): string =>\n typeof message === 'string' && message.trim() !== '' ? message.trim() : fallback;\n\n/**\n * Reads an auth answer as an email verification step: `code` when the server emailed a code (a non-empty\n * `challenge_id`), `link` when it emailed a link instead. `null` for anything else (tokens, a 2FA token, no answer).\n */\nexport const readEmailVerificationStep = (answer: unknown): EmailVerificationStep | null => {\n if (!isEmailVerificationStep(answer)) return null;\n const challengeId = (answer as { challenge_id?: unknown }).challenge_id;\n if (typeof challengeId === 'string' && challengeId !== '') {\n return { kind: 'code', challengeId, message: messageOr(answer.message, emailCodeSentFallbackMessage) };\n }\n return { kind: 'link', message: messageOr(answer.message, emailLinkSentFallbackMessage) };\n};\n\nexport type EmailCodeStepState = {\n step: EmailCodeStep;\n /** The display message of the last failed verify or resend; cleared by the next attempt or a new code. */\n error: string | null;\n};\n\nexport type EmailCodeStepEvent =\n | { type: 'ENTER'; step: EmailVerificationStep }\n | { type: 'VERIFY_STARTED' }\n | { type: 'VERIFY_OK' }\n | { type: 'VERIFY_FAILED'; message: string }\n | { type: 'RESENT'; challengeId: string; message: string }\n | { type: 'LINK_SENT'; message: string }\n | { type: 'RESEND_FAILED'; message: string }\n | { type: 'CANCEL' };\n\nexport const initialEmailCodeStepState: EmailCodeStepState = { step: { kind: 'none' }, error: null };\n\n/**\n * The emailed-code step as a transition table. Only `ENTER` leaves `none`: a verify or resend answer that lands\n * after the user went back is a real race, not a bug, so it is ignored rather than resurrecting the step. Verify and\n * resend events only change a `code` step; in `link` there is nothing left to verify or resend.\n */\nexport const emailCodeStepReducer = (state: EmailCodeStepState, event: EmailCodeStepEvent): EmailCodeStepState => {\n switch (event.type) {\n case 'ENTER':\n return { step: event.step, error: null };\n case 'CANCEL':\n return initialEmailCodeStepState;\n case 'VERIFY_STARTED':\n case 'VERIFY_OK':\n return state.step.kind === 'code' && state.error !== null ? { ...state, error: null } : state;\n case 'VERIFY_FAILED':\n case 'RESEND_FAILED':\n return state.step.kind === 'code' ? { ...state, error: event.message } : state;\n case 'RESENT':\n return state.step.kind === 'code'\n ? { step: { kind: 'code', challengeId: event.challengeId, message: event.message }, error: null }\n : state;\n case 'LINK_SENT':\n return state.step.kind === 'code' ? { step: { kind: 'link', message: event.message }, error: null } : state;\n default: {\n const unhandled: never = event;\n return unhandled;\n }\n }\n};\n","/**\n * Execute a `form_post` answer: OIDC response_mode=form_post requires the\n * parameters to arrive as a POST body, which only a real form submission can\n * do cross-origin.\n */\nexport const submitFormPost = (action: string, fields: Record<string, string>): void => {\n const form = document.createElement('form');\n form.method = 'POST';\n form.action = action;\n form.style.display = 'none';\n\n for (const [key, value] of Object.entries(fields)) {\n const input = document.createElement('input');\n input.type = 'hidden';\n input.name = key;\n input.value = value;\n form.appendChild(input);\n }\n\n document.body.appendChild(form);\n form.submit();\n};\n","import type { AuthStrategies, FimStrategy, InternalStrategy, Providers } from '@passflow/core';\n\nexport type AuthMethods = {\n internal: {\n username: {\n password: boolean;\n };\n email: {\n password: boolean;\n otp: boolean;\n magicLink: boolean;\n };\n phone: {\n password: boolean;\n otp: boolean;\n magicLink: boolean;\n };\n };\n fim: {\n providers: Providers[];\n };\n passkey: boolean;\n hasEmailMethods: boolean;\n hasSignInEmailMethods: boolean;\n hasPhoneMethods: boolean;\n hasSignInPhoneMethods: boolean;\n hasUsernameMethods: boolean;\n hasSignInUsernameMethods: boolean;\n};\n\nexport const getAuthMethods = (strategies?: AuthStrategies[]): AuthMethods => {\n const methods: AuthMethods = {\n internal: {\n username: {\n password: false,\n },\n email: {\n password: false,\n otp: false,\n magicLink: false,\n },\n phone: {\n password: false,\n otp: false,\n magicLink: false,\n },\n },\n fim: {\n providers: [],\n },\n passkey: false,\n hasEmailMethods: false,\n hasSignInEmailMethods: false,\n hasPhoneMethods: false,\n hasSignInPhoneMethods: false,\n hasUsernameMethods: false,\n hasSignInUsernameMethods: false,\n };\n\n if (!strategies) return methods;\n\n for (const strategy of strategies) {\n const { identity, challenge, fim_type: fimType } = strategy.strategy as InternalStrategy & FimStrategy;\n\n switch (strategy.type) {\n case 'internal':\n switch (identity) {\n case 'email':\n if (challenge === 'magic_link') methods.internal.email.magicLink = true;\n else methods.internal.email[challenge as keyof AuthMethods['internal']['email']] = true;\n methods.hasEmailMethods = true;\n\n if (methods.internal.email.magicLink || methods.internal.email.otp || methods.internal.email.password)\n methods.hasSignInEmailMethods = true;\n\n break;\n case 'phone':\n if (challenge === 'magic_link') methods.internal.phone.magicLink = true;\n else methods.internal.phone[challenge as keyof AuthMethods['internal']['phone']] = true;\n methods.hasPhoneMethods = true;\n\n if (methods.internal.phone.magicLink || methods.internal.phone.otp || methods.internal.phone.password)\n methods.hasSignInPhoneMethods = true;\n\n break;\n case 'username':\n methods.internal.username[challenge as keyof AuthMethods['internal']['username']] = true;\n methods.hasUsernameMethods = true;\n\n if (methods.internal.username.password) methods.hasSignInUsernameMethods = true;\n\n break;\n default:\n throw new Error(`Unsupported identity type: ${identity}`);\n }\n break;\n case 'fim':\n methods.fim.providers.push(fimType);\n break;\n case 'passkey':\n methods.passkey = true;\n break;\n default:\n throw new Error(`Unsupported strategy type: ${strategy.type}`);\n }\n }\n\n return methods;\n};\n","import type { InternalStrategyChallenge } from '@passflow/core';\n/* eslint-disable complexity */\nimport type { DefaultMethod } from '@/types';\nimport type { AuthMethods } from './get-auth-methods';\n\nexport const getIdentityLabel = (methods: AuthMethods, type: 'label' | 'button') => {\n if (methods.hasSignInEmailMethods && methods.hasSignInUsernameMethods)\n return type === 'label' ? 'Email or username' : 'Use email or username';\n if (methods.hasSignInEmailMethods) return type === 'label' ? 'Email' : 'Use email';\n if (methods.hasSignInUsernameMethods) return type === 'label' ? 'Username' : 'Use username';\n\n return null;\n};\n\nexport const getPasswordlessData = (\n methods: AuthMethods,\n currentMethod: DefaultMethod | null,\n): { label: string; challengeType: InternalStrategyChallenge } | null => {\n if (currentMethod === 'phone') {\n if (methods.internal.phone.otp) return { label: 'SMS code', challengeType: 'otp' };\n if (methods.internal.phone.magicLink) return { label: 'SMS link', challengeType: 'magic_link' };\n }\n\n if (currentMethod === 'email_or_username') {\n if (methods.internal.email.otp) return { label: 'email code', challengeType: 'otp' };\n if (methods.internal.email.magicLink) return { label: 'email link', challengeType: 'magic_link' };\n }\n\n return null;\n};\n\nexport const getValidationErrorsLabel = (methods: AuthMethods) => {\n if (methods.hasSignInEmailMethods && methods.hasSignInUsernameMethods) return 'Email or username is required';\n if (methods.hasSignInEmailMethods) return 'Email is required';\n if (methods.hasSignInUsernameMethods) return 'Username is required';\n\n return 'Field is required';\n};\n","// URLSearchParams has already decoded the value once; a second pass undoes double encoding. A literal `%` in the\n// text (e.g. \"100%\") would make that second pass throw, so the once-decoded value is kept instead.\nconst decodeOnceMore = (value: string): string => {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n};\n\nexport const getUrlErrors = (subUrl?: string) => {\n const searchParams = new URLSearchParams(subUrl ? subUrl.split('?')[1] : window.location.search);\n const error = searchParams.get('error');\n const message = searchParams.get('message');\n\n return { error, message: message ? decodeOnceMore(message) : null };\n};\n","import type { HandOff, PassflowState } from '@/context/passflow-context';\n\n/** Hand-off scopes when the app asked for none and neither discovery nor the app's settings named any. */\nconst DEFAULT_HAND_OFF_SCOPES = ['openid', 'profile', 'id'];\n\n/** `list` with `scope` added at the end, in order and without duplicates. */\nexport const withScope = (list: readonly string[], scope: string): string[] => [...new Set([...list, scope])];\n\n/**\n * The scopes the app asked for, which decide what goes back to it. The one place they are read: `undefined` when\n * there is no hand-off (embedded use), never the sign-in scopes in `state.scopes`.\n */\nexport const handOffScopes = (handOff: HandOff | undefined): string[] | undefined =>\n handOff ? (handOff.scopes ?? DEFAULT_HAND_OFF_SCOPES) : undefined;\n\n/**\n * What found scopes write under a hand-off: the hand-off scopes (with `id`) and the sign-in scopes (also with\n * `offline`), and only while the hand-off scopes are unset, so the first value found wins and a requested value is\n * never replaced. Nothing without a hand-off or when nothing was found.\n */\nexport const handOffScopesUpdate = (state: PassflowState, found: string[] | undefined): Partial<PassflowState> => {\n if (!state.handOff || state.handOff.scopes !== undefined || !found?.length) return {};\n const scopes = withScope(found, 'id');\n return { handOff: { ...state.handOff, scopes }, scopes: withScope(scopes, 'offline') };\n};\n","import type { Passflow } from '@passflow/core';\nimport type { HandOff } from '@/context/passflow-context';\nimport { handOffScopes } from './hand-off';\n\nexport type TokenUrlFormat = 'query' | 'hash';\n\nconst grantsRefreshToken = (scopes: string[]): boolean => scopes.includes('offline') || scopes.includes('offline_access');\n\n/**\n * `url` with the stored tokens appended. Without `handOff` every token goes. With it, the refresh token goes only\n * when the app asked for `offline` or `offline_access`, and the app's `state` is appended.\n */\nexport const getUrlWithTokens = async (\n passflow: Passflow,\n url: string,\n format: TokenUrlFormat = 'hash',\n handOff?: HandOff,\n): Promise<string> => {\n const tokens = await passflow.getTokens(false);\n\n if (tokens) {\n const sent: Record<string, unknown> = { ...tokens, scopes: undefined };\n const requested = handOffScopes(handOff);\n if (requested && !grantsRefreshToken(requested)) sent.refresh_token = undefined;\n\n const params = Object.entries(sent)\n .filter(([, value]) => value)\n .map(([key, value]) => `${key}=${encodeURIComponent(value as string)}`);\n if (handOff?.state) params.push(`state=${encodeURIComponent(handOff.state)}`);\n const tokenParams = params.join('&');\n\n if (format === 'hash') {\n // Use hash fragment (more secure - not sent to server)\n return `${url}#${tokenParams}`;\n }\n // Use query parameters\n return `${url}?${tokenParams}`;\n }\n return url;\n};\n","import type { AuthRedirectOptions, Passflow } from '@passflow/core';\n\nconst returnPathKey = 'passflow_return_to';\n\n/**\n * Starts the hosted sign-in. With no `redirectUrl`, the hosted login sends the\n * browser back to the origin root, `${origin}/`, and the page the user started\n * on waits in sessionStorage until `takeReturnPath()` reads it. The root works\n * because the provider takes the sign-in return on whatever page it mounts on,\n * and an app served from the origin root is loaded at `/` with or without an SPA\n * fallback. An app served under a sub-path is not at `/`: it passes its own\n * `redirectUrl`, such as `${origin}/app/`.\n *\n * A `redirectUrl` the caller gives is used as it is, and any page an earlier,\n * abandoned sign-in stored is forgotten, so that landing goes nowhere else.\n */\nexport const startHostedSignIn = (passflow: Passflow, options?: AuthRedirectOptions): Promise<void> => {\n if (options?.redirectUrl) {\n try {\n sessionStorage.removeItem(returnPathKey);\n } catch {}\n return passflow.authRedirect(options);\n }\n const { pathname, search, hash, origin } = window.location;\n try {\n sessionStorage.setItem(returnPathKey, pathname + search + hash);\n } catch {}\n return passflow.authRedirect({ ...options, redirectUrl: `${origin}/` });\n};\n\n/**\n * The stored value as a path on this origin, with dot segments resolved, or\n * undefined. The check runs on the resolved path: `/..//evil.example` resolves\n * to `//evil.example`, which a browser reads as another host. A `\\` anywhere is\n * refused, since browsers read it as `/`. The percent-decoded path is checked\n * the same way, with tabs and newlines removed as a URL parser removes them, so\n * a router that decodes `to` cannot turn `/%09/evil.example` into another host.\n */\nconst rootRelativePath = (value: string): string | undefined => {\n if (!value.startsWith('/') || value.includes('\\\\')) return undefined;\n let url: URL;\n let decoded: string;\n try {\n url = new URL(value, window.location.origin);\n decoded = decodeURIComponent(url.pathname).replace(/[\\t\\n\\r]/g, '');\n } catch {\n return undefined;\n }\n if (url.origin !== window.location.origin) return undefined;\n if (url.pathname.startsWith('//') || decoded.startsWith('//') || decoded.includes('\\\\')) return undefined;\n return url.pathname + url.search + url.hash;\n};\n\n/**\n * Reads and forgets the page stored by `startHostedSignIn()`. Undefined when\n * none is stored; `/` when the stored value is not a path on this origin.\n */\nexport const takeReturnPath = (): string | undefined => {\n let value: string | null;\n try {\n value = sessionStorage.getItem(returnPathKey);\n sessionStorage.removeItem(returnPathKey);\n } catch {\n return undefined;\n }\n if (value === null) return undefined;\n return rootRelativePath(value) ?? '/';\n};\n","export function undefinedOnCatch<T, K>(fn: (t: K) => T): (t: K) => T | undefined {\n return (t: K) => {\n try {\n return fn(t);\n } catch (error) {\n return undefined;\n }\n };\n}\n","import { type InvitationToken, parseToken } from '@passflow/core';\nimport { undefinedOnCatch } from './undefined-on-catch';\n\nexport type InvitationAuthIntent = 'sign-in' | 'sign-up';\n\ntype InvitationAuthChrome = {\n title: string;\n subtitle: string;\n};\n\nconst authAction = {\n 'sign-in': {\n title: 'Sign in',\n completion: 'sign in',\n },\n 'sign-up': {\n title: 'Create your account',\n completion: 'create your account',\n },\n} as const;\n\nexport const getInvitationAuthChrome = (\n inviteToken: string | null | undefined,\n intent: InvitationAuthIntent,\n): InvitationAuthChrome | null => {\n if (!inviteToken) return null;\n\n const invitation = undefinedOnCatch(parseToken)(inviteToken) as InvitationToken | undefined;\n const tenantName = invitation?.tenant_name?.trim();\n const inviterName = invitation?.inviter_name?.trim();\n const action = authAction[intent];\n\n return {\n title: tenantName ? `${action.title} to join ${tenantName}.` : `${action.title} to continue your invitation.`,\n subtitle: inviterName\n ? `${inviterName} invited you. After you ${action.completion}, you'll continue to the invitation.`\n : `After you ${action.completion}, you'll continue to the invitation.`,\n };\n};\n","import { useSyncExternalStore } from 'react';\n\nconst subscribe = () => () => undefined;\nconst onClient = () => true;\nconst onServer = () => false;\n\n/**\n * False on the server and during hydration, true from the render right after hydration and in any render that is\n * not a hydration. A session lives only in the browser, so what a component renders from it waits for this: the\n * server renders signed out, and the first client render must match it.\n */\nexport const useHydrated = (): boolean => useSyncExternalStore(subscribe, onClient, onServer);\n","import type { Passflow } from '@passflow/core';\nimport { useContext } from 'react';\nimport { PassflowContext } from '@/context';\n\nexport const usePassflow = (): Passflow => {\n const context = useContext(PassflowContext);\n if (!context) {\n throw new Error('useAuth must be used within an PassflowProvider');\n }\n\n const { passflow } = context;\n\n return passflow;\n};\n","import {\n type LogOutOptions,\n type ParsedTokens,\n PassflowEvent,\n type PassflowSubscriber,\n type SessionExpiredReason,\n type Tokens,\n} from '@passflow/core';\nimport { createContext, type FC, type PropsWithChildren, useCallback, useEffect, useState } from 'react';\nimport { useHydrated } from '../hooks/use-hydrated';\nimport { usePassflow } from '../hooks/use-passflow';\n\nexport type SessionExpiredHandler = (reason: SessionExpiredReason) => void;\n\nexport type AuthContextValue = {\n /**\n * Reads the session now. On a server-rendered page, render from `isSignedIn` instead: the server has no session, so\n * output that calls this during render differs between the server and the browser.\n */\n isAuthenticated: () => boolean;\n /** Whether a user is signed in. Updates on sign-in, sign-up, sign-out and session expiry, so a component can render on it. */\n isSignedIn: boolean;\n /**\n * Signs the user out. After a hosted sign-in core then leaves the page for the hosted login's sign-out, which ends\n * at `postLogoutRedirectUri`, so code after `await logout()` may not run.\n */\n logout: (options?: LogOutOptions) => Promise<void>;\n isLoading: boolean;\n isSessionExpired: boolean;\n getTokens: (doRefresh: boolean) => Promise<{ tokens: Tokens | undefined; parsedTokens: ParsedTokens | undefined }>;\n};\n\nexport const AuthContext = createContext<AuthContextValue | undefined>(undefined);\n\nexport type AuthProviderProps = PropsWithChildren<{\n /**\n * Called when the session has really ended: last auth strike, no successor token pair\n * in time, or another user's tokens in storage. A transient refresh failure keeps the\n * session and does not call this. Use this to redirect to your login page.\n */\n onSessionExpired?: SessionExpiredHandler;\n}>;\n\nexport const AuthProvider: FC<AuthProviderProps> = ({ children, onSessionExpired }) => {\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isSessionExpired, setIsSessionExpired] = useState<boolean>(false);\n const [isSignedIn, setIsSignedIn] = useState<boolean>(() => passflow.isAuthenticated());\n\n useEffect(() => {\n // The session may have changed between the first render and this subscription.\n setIsSignedIn(passflow.isAuthenticated());\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n setIsSignedIn(passflow.isAuthenticated());\n if (eventType === PassflowEvent.SessionExpired) {\n const reason = (payload as { reason?: SessionExpiredReason })?.reason ?? 'refresh_failed';\n setIsSessionExpired(true);\n onSessionExpired?.(reason);\n } else if (eventType === PassflowEvent.SignIn || eventType === PassflowEvent.Register) {\n // Reset session expired state on successful auth\n setIsSessionExpired(false);\n }\n },\n };\n\n passflow.subscribe(subscriber, [\n PassflowEvent.SessionExpired,\n PassflowEvent.SignIn,\n PassflowEvent.Register,\n PassflowEvent.SignOut,\n ]);\n\n return () => {\n passflow.unsubscribe(subscriber);\n };\n }, [passflow, onSessionExpired]);\n\n const isAuthenticated = useCallback(() => passflow.isAuthenticated(), [passflow]);\n\n const getTokens = useCallback(\n async (doRefresh: boolean) => {\n setIsLoading(true);\n\n try {\n const tokens = await passflow.getTokens(doRefresh);\n const parsedTokens = tokens ? passflow.getParsedTokens() : undefined;\n\n return {\n tokens,\n parsedTokens,\n };\n } catch (e) {\n return {\n tokens: undefined,\n parsedTokens: undefined,\n };\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const logout = useCallback(\n async (options?: LogOutOptions) => {\n try {\n await passflow.logOut(options);\n } finally {\n setIsSignedIn(passflow.isAuthenticated());\n }\n },\n [passflow],\n );\n\n const value = {\n isAuthenticated,\n isSignedIn: hydrated && isSignedIn,\n logout,\n isLoading,\n isSessionExpired,\n getTokens,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n};\n","import { createContext } from 'react';\n\nexport type NavigateOptions = {\n to: string;\n search?: string;\n replace?: boolean;\n};\n\nexport type RouterType = 'default' | 'react-router' | 'tanstack-router' | 'wouter';\n\nexport type NavigateFunction = (options: NavigateOptions) => void;\n\n/** `tokens-in-url`: a non-PKCE return that the server already sent to this page, so it has nowhere further to go. */\nexport type FederatedLandingOutcome = 'signed-in' | 'tokens-in-url' | 'failed';\n\nexport type NavigationContextType = {\n navigate: NavigateFunction;\n setNavigate: (navigate: NavigateFunction | null) => void;\n router: RouterType;\n /**\n * Where a sign-in that owes its second factor is sent when it lands on a\n * page outside the forms (a federated redirect carrying `#tfa_token=`).\n * `PassflowProvider` resolves it: a mounted `PassflowFlow` registers its own\n * (prefixed) route, else the provider's `twoFactorVerifyPath` prop, else\n * `routes.two_factor_verify.path`.\n */\n twoFactorVerifyPath?: string;\n /** Registers the 2FA route of a mounted flow; `null` withdraws it. */\n setTwoFactorVerifyPath?: (path: string | null) => void;\n /** The sign-in page: a sign-in whose target is this page has nowhere to go. A mounted `PassflowFlow` registers its own. */\n signInPath?: string;\n /** Registers the sign-in page of a mounted flow; `null` withdraws it. */\n setSignInPath?: (path: string | null) => void;\n /** How a PKCE federated redirect that landed on this page ended. A second factor owed is not an outcome here. */\n federatedLandingOutcome?: FederatedLandingOutcome;\n};\n\nexport const defaultNavigate: NavigateFunction = ({ to, search, replace }) => {\n const searchParam = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n if (replace) {\n window.location.replace(`${to}${searchParam}`);\n } else {\n window.location.href = `${to}${searchParam}`;\n }\n};\n\nexport const NavigationContext = createContext<NavigationContextType>({\n navigate: defaultNavigate,\n setNavigate: () => undefined,\n router: 'default',\n});\n","import type { AppSettings, Passflow, PassflowPasswordPolicySettings } from '@passflow/core';\nimport { createContext, type Dispatch } from 'react';\nimport { handOffScopesUpdate } from '@/utils/hand-off';\n\n/**\n * What the app that sent the user to the hosted login asked for. `scopes` decide what goes back to it (`id` gives an\n * ID token, `offline` or `offline_access` a refresh token); unset, they are filled from the app's configuration.\n * `state` is echoed back to the app.\n */\nexport type HandOff = { scopes?: string[]; state?: string };\n\nexport type PassflowState = {\n appSettings: AppSettings | null;\n passwordPolicy: PassflowPasswordPolicySettings | null;\n url?: string;\n appId?: string;\n scopes?: string[];\n createTenantForNewUser?: boolean;\n parseQueryParams?: boolean;\n isDiscoveringAppId?: boolean;\n hasSettingsError?: boolean;\n handOff?: HandOff;\n};\n\nexport type PassflowAction =\n /** Merged into the state: a dispatch carries only the fields it changes. */\n | { type: 'SET_PASSFLOW_STATE'; payload: Partial<PassflowState> }\n /** Scopes found in the app's configuration, applied under a hand-off against the current state. */\n | { type: 'SET_FOUND_SCOPES'; found: string[] | undefined };\n\nexport type PassflowContextType = {\n state: PassflowState;\n dispatch: Dispatch<PassflowAction>;\n passflow: Passflow;\n};\n\nexport const initialState: PassflowState = {\n appSettings: null,\n passwordPolicy: null,\n url: undefined,\n appId: undefined,\n scopes: undefined,\n createTenantForNewUser: undefined,\n parseQueryParams: true,\n isDiscoveringAppId: false,\n hasSettingsError: false,\n handOff: undefined,\n};\n\nexport const PassflowContext = createContext<PassflowContextType | undefined>(undefined);\n\nexport const passflowReducer = (state: PassflowState, action: PassflowAction): PassflowState => {\n switch (action.type) {\n case 'SET_PASSFLOW_STATE':\n return { ...state, ...action.payload };\n case 'SET_FOUND_SCOPES': {\n const update = handOffScopesUpdate(state, action.found);\n return Object.keys(update).length ? { ...state, ...update } : state;\n }\n default:\n return state;\n }\n};\n","export const routes = {\n signin: {\n path: '/signin',\n },\n signup: {\n path: '/signup',\n },\n verify_otp: {\n path: '/verify-challenge-otp',\n },\n verify_magic_link: {\n path: '/verify-challenge-magic-link',\n },\n forgot_password: {\n path: '/forgot-password',\n },\n forgot_password_success: {\n path: '/forgot-password/success',\n },\n reset_password: {\n path: '/password/reset',\n },\n invitation: {\n path: '/invitation',\n },\n passkey: {\n path: '/passkeysss',\n },\n two_factor_verify: {\n path: '/two-factor-verify',\n },\n two_factor_recovery: {\n path: '/two-factor-recovery',\n },\n two_factor_setup: {\n path: '/two-factor-setup',\n },\n two_factor_setup_magic_link: {\n path: '/two-factor-setup-magic-link/:token',\n },\n};\n","import { createContext, useContext } from 'react';\n\n/**\n * Where the forms read and write their search params (`?challenge_id=…`).\n *\n * Outside PassflowFlow it is the address bar, as it always was. Inside, PassflowFlow\n * provides its own location, so the forms see the right params when the flow keeps a\n * memory or hash history, or is driven by an app router that does not use the address\n * bar. In the default browser mode both are the same URL.\n */\nexport type SearchSource = {\n /** The current search string, with its leading `?` or empty. */\n read: () => string;\n /** Moves to the same path with a new search string. */\n write: (search: string, options: { replace: boolean }) => void;\n};\n\nexport const addressBarSearch: SearchSource = {\n read: () => window.location.search,\n write: (search, { replace }) => {\n const url = `${window.location.pathname}${search}${window.location.hash}`;\n if (replace) window.history.replaceState(null, '', url);\n else window.history.pushState(null, '', url);\n },\n};\n\nexport const SearchContext = createContext<SearchSource>(addressBarSearch);\n\nexport const useSearchSource = () => useContext(SearchContext);\n","/**\n * The assurance-upgrade context — the one channel between `UpgradeProvider`\n * and `useUpgrade` (architecture §8.2, §13.3).\n *\n * The provider owns the controller, the prompt handler and every transition;\n * this module owns only the shape they are read through. Two hooks each\n * installing a prompt handler would produce two prompts and defeat\n * single-flight, so nothing here installs anything.\n *\n * `status` is §13.5's `UpgradeHookState`, which is §13.3's settlement table\n * read down the hook column. Two consequences the types enforce:\n *\n * - **`insufficient` is a first-class state, not an error and not a success.**\n * \"Elevated to AAL2; this action requires AAL3\" is the normal path for an\n * AAL3 endpoint and a TOTP-only user, and a design cannot both claim the\n * server is the authority and delete the path by which its second refusal\n * reaches the user.\n * - **Cancellation is not a status.** It is `elevate()` resolving `null`. The\n * hook is the one surface where that is right, because there the\n * cancellation IS the whole value: the consumer is rendering a decision, not\n * handling a transport outcome.\n */\n\nimport type { AssuranceBar, UpgradeChallenge, UpgradeFactor, UpgradeFactorType } from '@passflow/core';\nimport { createContext } from 'react';\n\n/** What a protected elevation can fail with, in the hook's vocabulary (§13.3's table). */\nexport type UpgradeErrorStatusKind =\n | 'exhausted'\n | 'unsatisfiable'\n | 'unavailable'\n | 'transport'\n | 'rate_limited'\n | 'sign_in_required';\n\n/**\n * The hook's observable state. Exactly one terminal state per flight, taken\n * from the controller's outcome summary (§13.4).\n *\n * `idle` is also where a flight abandoned by a session change lands: nothing\n * happened, and nothing is reported as though it had.\n */\nexport type UpgradeHookState =\n | { status: 'idle' }\n | { status: 'challenged'; challenge: UpgradeChallenge; factors: UpgradeFactorType[] }\n | { status: 'submitting' }\n | { status: 'success' }\n | { status: 'insufficient'; obtained: AssuranceBar; required: AssuranceBar }\n | { status: 'error'; kind: UpgradeErrorStatusKind; error: Error };\n\n/** The states a flight can settle in. `null` alongside these is cancellation. */\nexport type UpgradeSettledState = Extract<UpgradeHookState, { status: 'idle' | 'success' | 'insufficient' | 'error' }>;\n\n/** A bar a caller states for itself on the imperative seam (§13.2 T10 / H-6). */\nexport type UpgradeElevateOptions = {\n acrValues?: string;\n maxAge?: number;\n};\n\n/** The open prompt, as the dialog and the hook read it. */\nexport type UpgradePromptView = {\n challenge: UpgradeChallenge;\n /** Already ranked by `selectFactors`; index 0 is the suggested factor. */\n factors: readonly UpgradeFactor[];\n /** The previous attempt's failure, when the controller re-prompted. */\n previousError?: Error;\n};\n\nexport type UpgradeContextValue = {\n /** True when the provider installed a prompt handler on this `Passflow` instance. */\n enabled: boolean;\n state: UpgradeHookState;\n /** The open prompt, or `null` when no elevation is collecting an answer. */\n prompt: UpgradePromptView | null;\n selectedFactor: UpgradeFactorType | null;\n /**\n * The factor-selection signal. Reports the user's choice to the controller\n * through `UpgradePromptRequest.onFactorSelected` the moment it is made and\n * before any answer is submitted — §13.2's late-join boundary (T3), which is\n * selection and not submission.\n */\n selectFactor: (factor: UpgradeFactorType) => void;\n /** Answers the open prompt. Resolves the controller's promise exactly once. */\n submit: (code?: string) => void;\n /** Declines the open prompt. Exactly once; never leaves the promise pending. */\n cancel: () => void;\n /** Acknowledges a terminal state, closing the dialog. Settles nothing. */\n dismiss: () => void;\n /**\n * Drives an elevation directly — a \"verify now\" button, or a headless\n * caller. Resolves **`null`** when the user cancelled, and otherwise the\n * flight's terminal state; it never rejects, because the hook's contract is\n * a rendered decision rather than a thrown transport outcome.\n */\n elevate: (options?: UpgradeElevateOptions) => Promise<UpgradeSettledState | null>;\n};\n\nexport const UpgradeContext = createContext<UpgradeContextValue | undefined>(undefined);\n\nconst noop = (): void => undefined;\n\n/**\n * What `useUpgrade` reads outside an `UpgradeProvider`: idle, inert, and it\n * does not throw (§9.5 H8) — a component that merely wants to know whether an\n * elevation is running is not a bug.\n *\n * `elevate` resolves `{ status: 'idle' }` rather than `null`: nothing was\n * asked and nothing was declined, and `null` means the user declined.\n */\nexport const INERT_UPGRADE_CONTEXT: UpgradeContextValue = {\n enabled: false,\n state: { status: 'idle' },\n prompt: null,\n selectedFactor: null,\n selectFactor: noop,\n submit: noop,\n cancel: noop,\n dismiss: noop,\n elevate: () => Promise.resolve({ status: 'idle' }),\n};\n","export const isValidUrl = (url: string): boolean => {\n try {\n const newUrl = new URL(url);\n return newUrl.protocol === 'http:' || newUrl.protocol === 'https:';\n } catch {\n return false;\n }\n};\n","import { routes } from '@/context';\nimport { isValidUrl } from './validate-url';\n\nconst withoutTrailingSlash = (path: string) => path.replace(/\\/+$/, '') || '/';\n\n/** Whether a target is a path on this page's origin, as opposed to a full address or anything that could leave it. */\nexport const isSameOriginPath = (target: string): boolean => {\n if (isValidUrl(target)) return false;\n try {\n return new URL(target, window.location.href).origin === window.location.origin;\n } catch {\n return false;\n }\n};\n\n/**\n * The path, query and fragment a target names on this page's origin, or `null` when it leads elsewhere. A full\n * address on this origin counts: it is the same app, so getting there needs no new page load.\n */\nexport const inAppPath = (target: string): string | null => {\n if (isSameOriginPath(target)) return target;\n if (!isValidUrl(target)) return null;\n const url = new URL(target);\n return url.origin === window.location.origin ? `${url.pathname}${url.search}${url.hash}` : null;\n};\n\n/** Whether a sign-in's target is the sign-in page of this app, whatever its query or fragment. */\nexport const isSignInPage = (target: string, signInPath: string = routes.signin.path): boolean => {\n try {\n const url = new URL(target, window.location.href);\n return url.origin === window.location.origin && withoutTrailingSlash(url.pathname) === withoutTrailingSlash(signInPath);\n } catch {\n return false;\n }\n};\n","import { isValidJWTFormat, type Passflow, parseToken } from '@passflow/core';\nimport type { NavigateFunction } from '@/context';\nimport { undefinedOnCatch } from './undefined-on-catch';\n\n/**\n * The search for a new sign-in or its 2FA step: the original one, without anything that belonged to this attempt. A\n * reset token must not reach the verify URL, and the attempt's own destination is not carried across 2FA.\n */\nexport const signInSearch = (search: string): string => {\n const params = new URLSearchParams(search);\n for (const key of ['challenge_id', 'expires_at', 'match_code', 'otp', 'flow', 'token', 'redirect_url']) params.delete(key);\n return params.toString();\n};\n\n/**\n * Sends a sign-in that still owes its second factor to the 2FA screen.\n *\n * Every sign-in path can end this way: the server answers with a 2FA token in\n * place of tokens, `@passflow/core` keeps it and saves no session, and\n * `isTwoFactorVerificationRequired()` reads true. The caller must then stop:\n * no success redirect, and no `getUrlWithTokens` — there are no tokens yet.\n *\n * @param search the current search; what `signInSearch` keeps goes onto the 2FA URL\n * @returns true when it navigated, so the caller returns without redirecting\n */\nexport const routeToSecondFactor = (\n passflow: Pick<Passflow, 'isTwoFactorVerificationRequired'>,\n navigate: NavigateFunction,\n twoFactorVerifyPath: string,\n search = '',\n): boolean => {\n if (!passflow.isTwoFactorVerificationRequired()) return false;\n navigate({ to: twoFactorVerifyPath, search: signInSearch(search) || undefined });\n return true;\n};\n\n/**\n * Whether the current URL is a landing that owes its second factor: a\n * federated sign-in on a non-PKCE app comes back with `#tfa_token=` in the\n * fragment and no tokens. Read it before `@passflow/core` is constructed,\n * because core adopts the token and strips the fragment as it starts.\n */\nexport const urlCarriesTwoFactorToken = (): boolean => {\n if (typeof window === 'undefined' || !window.location.hash) return false;\n return new URLSearchParams(window.location.hash.substring(1)).has('tfa_token');\n};\n\n/**\n * Whether the current URL is a return with tokens in the query or the fragment. Read it before `@passflow/core` is\n * constructed, because core adopts them and strips them as it starts.\n */\nexport const urlCarriesAccessToken = (): boolean =>\n typeof window !== 'undefined' &&\n (new URLSearchParams(window.location.search).has('access_token') ||\n new URLSearchParams(window.location.hash.substring(1)).has('access_token'));\n\n/**\n * The app a `#tfa_token=` landing belongs to: the one the token names in `aud`. A federated return carries no `appid`,\n * and the server takes the token only under that app, so discovery (which answers with the default login app) would be\n * wrong. Read for routing only: the server checks the signature and refuses any other pairing.\n *\n * Only on a page served by the API's own origin, the hosted login, which already takes its app from the URL. Any other\n * page keeps its app whatever a link says.\n */\nexport const twoFactorTokenAppId = (apiUrl: string | undefined): string | undefined => {\n if (!apiUrl || !urlCarriesTwoFactorToken()) return undefined;\n const api = undefinedOnCatch((url: string) => new URL(url, window.location.href))(apiUrl);\n if (api?.origin !== window.location.origin) return undefined;\n const token = new URLSearchParams(window.location.hash.substring(1)).get('tfa_token') ?? '';\n if (!isValidJWTFormat(token)) return undefined;\n const audience: unknown = undefinedOnCatch(parseToken)(token)?.aud;\n const appId = Array.isArray(audience) ? audience[0] : audience;\n return typeof appId === 'string' && appId ? appId : undefined;\n};\n","const STORAGE_KEY_PREFIX = 'passflow_2fa';\nconst REDIRECT_COUNT_KEY = `${STORAGE_KEY_PREFIX}_redirect_count`;\nconst LAST_ERROR_KEY = `${STORAGE_KEY_PREFIX}_last_error_type`;\nconst MAX_REDIRECTS = 3;\n\n/**\n * Loop prevention for 2FA redirect cycles\n */\nexport const TwoFactorLoopPrevention = {\n /**\n * Check if redirect should be allowed\n * @returns true if redirect is safe, false if loop detected\n */\n canRedirect(): boolean {\n try {\n const count = this.getRedirectCount();\n return count < MAX_REDIRECTS;\n } catch {\n // If sessionStorage is unavailable, allow redirect once\n return true;\n }\n },\n\n /**\n * Increment redirect counter\n */\n incrementRedirect(): void {\n try {\n const count = this.getRedirectCount();\n sessionStorage.setItem(REDIRECT_COUNT_KEY, String(count + 1));\n } catch {\n // Silently fail if sessionStorage unavailable\n }\n },\n\n /**\n * Get current redirect count\n */\n getRedirectCount(): number {\n try {\n const value = sessionStorage.getItem(REDIRECT_COUNT_KEY);\n return value ? Number.parseInt(value, 10) : 0;\n } catch {\n return 0;\n }\n },\n\n /**\n * Reset redirect counter (call on successful auth)\n */\n reset(): void {\n try {\n sessionStorage.removeItem(REDIRECT_COUNT_KEY);\n sessionStorage.removeItem(LAST_ERROR_KEY);\n } catch {\n // Silently fail if sessionStorage unavailable\n }\n },\n\n /**\n * Track last error type to detect repeated errors\n */\n setLastErrorType(errorType: string): void {\n try {\n sessionStorage.setItem(LAST_ERROR_KEY, errorType);\n } catch {\n // Silently fail if sessionStorage unavailable\n }\n },\n\n /**\n * Get last error type\n */\n getLastErrorType(): string | null {\n try {\n return sessionStorage.getItem(LAST_ERROR_KEY);\n } catch {\n return null;\n }\n },\n\n /**\n * Check if same error is repeating\n */\n isRepeatingError(errorType: string): boolean {\n const lastError = this.getLastErrorType();\n return lastError === errorType && this.getRedirectCount() > 0;\n },\n\n /**\n * Get user-friendly message when loop is detected\n */\n getLoopDetectedMessage(): string {\n return 'Unable to complete authentication. This may be a configuration issue. Please contact support.';\n },\n};\n\nexport default TwoFactorLoopPrevention;\n","/**\n * The free-function adapters — `withAuth` and `attachAuth` (§13.5).\n *\n * The core exposes both as methods on a configured `Passflow` instance, because\n * that is where the resolved interception scope is bound. The developer-facing\n * form is a bare import, so these two functions translate one into the other\n * and do nothing else:\n *\n * ```tsx\n * import { attachAuth } from '@passflow/react';\n *\n * const api = axios.create({ baseURL: 'https://api.example.com' });\n * useEffect(() => attachAuth(api), []);\n * ```\n *\n * **NO LOGIC IN AN ADAPTER.** Neither function parses a challenge, compares a\n * bar, decides scope, counts a retry or chooses an error class. Every one of\n * those decisions lives in the core's `handleChallenge`, which is what makes\n * all four surfaces behave identically.\n *\n * The instance is published by `UpgradeProvider`, which reads it from\n * `PassflowContext` — so the binding is the provider's instance, resolved at\n * call time rather than captured at import time.\n *\n * **The publication is synchronous, during the provider's render, and that is\n * load-bearing.** React runs a child's effects before its parent's in the same\n * commit, so publishing from the provider's `useEffect` would be too late for\n * the documented `useEffect(() => attachAuth(api), [])` above: the child's\n * effect would reach `requireInstance` with nothing registered and throw, and a\n * throw inside an effect tears the tree down. Attach order must not matter, so\n * the registry is written in render.\n *\n * **And the release is deferred by a microtask, which is what makes the pair\n * survive React Strict Mode.** Strict Mode mounts, unmounts and remounts\n * effects in development, and the child-before-parent effect order holds on the\n * remount pass too — while render, which is what published the instance, does\n * not run again. So an immediate release in the provider's effect cleanup\n * leaves the registry empty exactly when the remounting child's effect reads\n * it, and `attachAuth` throws again (verified: it does). Scheduling the release\n * instead means a re-registration in the same tick cancels it, which is\n * precisely a Strict Mode remount; a real unmount has no re-registration, so\n * the release lands one microtask later. Nothing observes that gap but a caller\n * reaching for an instance that has just been torn down.\n */\n\nimport type { FetchLike, Passflow, ResponseInterceptorHost, WithAuthOptions } from '@passflow/core';\n\nlet activeInstance: Passflow | null = null;\n\n/**\n * The instance a scheduled release is waiting to clear, or `null` when no\n * release is pending. Any registration clears it, which is how a Strict Mode\n * remount cancels the release its own cleanup just scheduled.\n */\nlet pendingRelease: Passflow | null = null;\n\n/**\n * Publishes the provider's `Passflow` instance to the free functions, and\n * returns an unregister suitable as a React effect cleanup.\n *\n * Last registration wins, and the returned unregister is *deferred*: it clears\n * the instance on a microtask, and only if nothing has registered in the\n * meantime. See the module comment — that deferral is what keeps a Strict Mode\n * mount → unmount → remount from leaving the free functions unbound, and it is\n * why register and release are symmetric rather than one in render and one in a\n * cleanup that nothing undoes.\n */\nexport const registerUpgradeAuthInstance = (instance: Passflow): (() => void) => {\n activeInstance = instance;\n pendingRelease = null;\n return () => {\n pendingRelease = instance;\n queueMicrotask(() => {\n // A register (or a later release) superseded this one: leave it alone.\n if (pendingRelease !== instance) return;\n pendingRelease = null;\n releaseUpgradeAuthInstance(instance);\n });\n };\n};\n\n/**\n * Clears `instance` if it is still the registered one, and does nothing\n * otherwise. Idempotent, so an effect cleanup that runs after a newer provider\n * has already published cannot unbind the live instance.\n */\nexport const releaseUpgradeAuthInstance = (instance: Passflow): void => {\n if (activeInstance === instance) activeInstance = null;\n};\n\n/** The instance the free functions bind to, or `null` outside a provider. */\nexport const upgradeAuthInstance = (): Passflow | null => activeInstance;\n\nconst requireInstance = (name: string): Passflow => {\n if (activeInstance === null) {\n throw new Error(\n `[passflow] ${name}() needs a mounted <PassflowProvider>: the interception scope is bound to a configured Passflow instance. Call it from inside your app (an effect or a component), or use passflow.${name}() from usePassflow().`,\n );\n }\n return activeInstance;\n};\n\n/**\n * Wraps a `fetch` and returns the wrapper. Installs nothing and touches no\n * global — two verbs exist because the semantics genuinely differ: an axios\n * interceptor mutates, a fetch wrapper returns.\n *\n * A token goes only to the page's own origin and the ones in `options.origins`;\n * a request to any other origin is sent without it.\n */\nexport const withAuth = (next?: FetchLike, options?: WithAuthOptions): FetchLike =>\n requireInstance('withAuth').withAuth(next, options);\n\n/**\n * Attaches step-up handling to an axios instance the caller already owns,\n * **mutating** it, and returns the `detach()` disposer — which is exactly what\n * a React effect needs.\n *\n * The parameter is typed structurally (duck-typed on\n * `interceptors.response.use`), so this package's axios version is not a\n * constraint on the caller's. `options.origins` works as it does for `withAuth`.\n */\nexport const attachAuth = (instance: ResponseInterceptorHost, options?: WithAuthOptions): (() => void) =>\n requireInstance('attachAuth').attachAuth(instance, options);\n","/**\n * Utility for native handling of URL parameters\n */\nimport { useSearchSource } from '../context/search-context';\n\n/**\n * Some mail clients deliver a link with its `&` separators HTML-escaped as `&amp;`. Only that escape is undone: any\n * wider entity decoding would read a key such as `&notice=` as the `&not` entity.\n */\nconst unescapeAmpersands = (search: string): string => search.replaceAll('&amp;', '&');\n\nconst withQuestionMark = (params: URLSearchParams) => (params.toString() ? `?${params.toString()}` : '');\n\n/**\n * Read `parent_challenge_id` from the current URL's query string.\n * Returns `undefined` when not present so callers can short-circuit\n * the OIDC interceptor on non-OIDC mounts.\n *\n * Lowercases only the parameter KEYS (not values) so the\n * KSUID-shaped value isn't corrupted on the way through. (URL params\n * are case-sensitive per RFC 3986; some Passflow URLs use mixed\n * case like `appId=...`. The lowercase-keys treatment mirrors what\n * the bundled login-app was doing pre-SDK-migration.)\n */\nexport const readParentChallengeIdFromURL = (): string | undefined => {\n if (typeof window === 'undefined') return undefined;\n const raw = new URLSearchParams(window.location.search);\n // Lowercase only keys, preserve values (values are often\n // case-sensitive — KSUIDs, JWTs, OIDC state, etc.).\n const lower = new URLSearchParams(Array.from(raw, ([key, value]) => [key.toLowerCase(), value]));\n const value = lower.get('parent_challenge_id');\n return value || undefined;\n};\n\nconst isParentChallengePair = (pair: string): boolean =>\n Array.from(new URLSearchParams(pair).keys())[0]?.toLowerCase() === 'parent_challenge_id';\n\n/**\n * The URL without `parent_challenge_id`, in any key case. Works on the raw query, so every other param keeps its\n * exact encoding.\n */\nexport const urlWithoutParentChallenge = (url: string): string => {\n const hashAt = url.indexOf('#');\n const hash = hashAt < 0 ? '' : url.slice(hashAt);\n const beforeHash = hashAt < 0 ? url : url.slice(0, hashAt);\n const queryAt = beforeHash.indexOf('?');\n if (queryAt < 0) return url;\n\n const kept = beforeHash\n .slice(queryAt + 1)\n .split('&')\n .filter((pair) => !isParentChallengePair(pair));\n return `${beforeHash.slice(0, queryAt)}${kept.length > 0 ? `?${kept.join('&')}` : ''}${hash}`;\n};\n\n/**\n * Get URL parameters. Inside PassflowFlow they come from the flow's location; outside it, from the\n * address bar.\n * @param defaultValues Default values\n * @returns Object with methods getAll, get, set\n */\nexport const useUrlParams = <T extends Record<string, string>>(defaultValues?: T) => {\n const source = useSearchSource();\n const searchParams = new URLSearchParams(unescapeAmpersands(source.read()));\n\n // Set default values if parameters don't exist\n if (defaultValues) {\n let hasChanged = false;\n\n for (const [key, value] of Object.entries(defaultValues)) {\n if (!searchParams.has(key) && value !== '') {\n searchParams.set(key, value);\n hasChanged = true;\n }\n }\n\n if (hasChanged) {\n source.write(withQuestionMark(searchParams), { replace: true });\n }\n }\n\n /**\n * Get all parameters\n */\n const getAll = () => {\n const params: Record<string, string> = {};\n\n for (const [key, value] of searchParams.entries()) {\n params[key] = value;\n }\n\n return params;\n };\n\n /**\n * Get parameter value\n * @param key Parameter key\n */\n const get = (key: string) => {\n const value = searchParams.get(key);\n return value === '' ? null : value;\n };\n\n /**\n * Set parameters\n * @param params Object with parameters\n */\n const set = (params: Record<string, string>) => {\n const newSearchParams = new URLSearchParams(source.read());\n\n for (const [key, value] of Object.entries(params)) {\n if (value === null || value === undefined || value === '') {\n newSearchParams.delete(key);\n } else {\n newSearchParams.set(key, value);\n }\n }\n\n source.write(withQuestionMark(newSearchParams), { replace: false });\n };\n\n return {\n getAll,\n get,\n set,\n };\n};\n","/* eslint-disable complexity */\n/* eslint-disable max-len */\nimport type { PassflowPasswordPolicySettings } from '@passflow/core';\nimport * as Yup from 'yup';\n\nexport const emailRegex =\n /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|.(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\nexport const phoneNumberRegex =\n /^(\\+{0,})(\\d{0,})([(]{1}\\d{1,3}[)]{0,}){0,}(\\s?\\d+|\\+\\d{2,3}\\s{1}\\d+|\\d+){1}[\\s|-]?\\d+([\\s|-]?\\d+){1,2}(\\s){0,}$/gm;\n\nexport const passwordValidation = (passwordPolicy: PassflowPasswordPolicySettings | null) =>\n Yup.string()\n .required()\n .test({\n test: (value: string) => {\n const errors: string[] = [];\n\n if (passwordPolicy) {\n const {\n restrict_min_password_length: restrictMinPasswordLength,\n min_password_length: minPasswordLength,\n require_lowercase: requireLowerCase,\n require_number: requireNumber,\n require_symbol: requireSymbol,\n require_uppercase: requireUpperCase,\n } = passwordPolicy;\n\n // An unrestricted minimum leaves only the non-empty check, which `.required()` already makes.\n // Counted in characters, as the server counts them: an emoji is one, not two UTF-16 units.\n if (restrictMinPasswordLength && [...(value ?? '')].length < minPasswordLength) errors.push('length');\n // Any script's capitals and small letters, as the server checks them.\n if (requireUpperCase && !/\\p{Lu}/u.test(value)) errors.push('uppercase');\n if (requireLowerCase && !/\\p{Ll}/u.test(value)) errors.push('lowercase');\n if (requireNumber && !/\\d/.test(value)) errors.push('number');\n // Exactly the symbols the server's password check counts; `~` and backslash are not among them.\n if (requireSymbol && !/[!$%^&*()_+{}:@[\\];'#<>?,./|\\-=]/.test(value)) errors.push('symbol');\n }\n\n if (errors.length > 0) {\n const validationError = {\n errors,\n inner: true,\n path: 'password',\n field: 'password',\n message: errors,\n value,\n name: 'ValidationError',\n } as Yup.ValidationError & {\n inner: boolean;\n field: string;\n message: string[];\n };\n\n return new Yup.ValidationError(validationError, value, 'password');\n }\n\n return true;\n },\n });\n","/* eslint-disable react/button-has-type */\n/* eslint-disable react/jsx-props-no-spreading */\nimport {\n type ButtonHTMLAttributes,\n type CSSProperties,\n type FC,\n type JSX,\n type MouseEvent,\n type PropsWithChildren,\n useEffect,\n useState,\n} from 'react';\nimport { cn } from '@/utils';\nimport '@/styles/index.css';\n\ntype RippleProps = {\n size: number;\n x: number;\n y: number;\n};\n\nexport const Ripple: FC<RippleProps> = ({ size, x, y }) => {\n const style: CSSProperties = {\n width: size,\n height: size,\n left: x,\n top: y,\n };\n\n return <span className='passflow-ripple passflow-ripple-effect' style={style} />;\n};\n\ntype TButton = PropsWithChildren &\n ButtonHTMLAttributes<HTMLButtonElement> & {\n size: 'small' | 'medium' | 'big';\n /**\n * `link` is an action set in running text: no box, link colour, no ripple.\n */\n variant: 'primary' | 'secondary' | 'outlined' | 'warning' | 'clean' | 'provider' | 'dark' | 'option' | 'link';\n type: 'button' | 'submit' | 'reset';\n withIcon?: boolean;\n asIcon?: boolean;\n className?: string;\n withRipple?: boolean;\n /**\n * The `option` variant's second line — the hint under the label. Rendered\n * only by that variant, which owns the two-line geometry. It is part of the\n * button's accessible name (\"label hint\"), because it is visible text.\n */\n description?: string;\n /**\n * Toggle state for the `option` variant: mirrored to `aria-pressed` and\n * styled by the variant itself, so no call site has to describe what\n * \"selected\" looks like.\n */\n pressed?: boolean;\n };\n\nexport const Button: FC<TButton> = ({\n size,\n variant,\n type,\n onClick,\n withIcon = false,\n asIcon = false,\n className = '',\n children,\n withRipple = true,\n description,\n pressed,\n ...rest\n}) => {\n const [ripples, setRipples] = useState<JSX.Element[]>();\n\n const styles = {\n 'passflow-button passflow-button--big': size === 'big',\n 'passflow-button passflow-button--medium': size === 'medium',\n 'passflow-button passflow-button--small': size === 'small',\n 'passflow-button--primary': variant === 'primary',\n 'passflow-button--secondary': variant === 'secondary',\n 'passflow-button--outlined': variant === 'outlined',\n 'passflow-button--warning': variant === 'warning',\n 'passflow-button--clean': variant === 'clean',\n 'passflow-button--provider': variant === 'provider',\n 'passflow-button--dark': variant === 'dark',\n 'passflow-button--option': variant === 'option',\n 'passflow-button--link': variant === 'link',\n 'passflow-button--with-icon': withIcon,\n 'passflow-button--as-icon': asIcon,\n };\n\n // `aria-disabled` is the focusable disabled state: the button keeps focus (so a\n // control that locks itself after a press, like a resend countdown, does not drop\n // the keyboard user), looks disabled, and ignores presses.\n const ariaDisabled = rest['aria-disabled'] === true || rest['aria-disabled'] === 'true';\n\n const handleClick = (e: MouseEvent<HTMLButtonElement>) => {\n if (ariaDisabled) {\n e.preventDefault();\n return;\n }\n const rect = e.currentTarget.getBoundingClientRect();\n const rippleSize = Math.max(rect.width, rect.height);\n const x = e.clientX - rect.left - rippleSize / 2;\n const y = e.clientY - rect.top - rippleSize / 2;\n\n const newRipple = <Ripple key={Date.now()} size={rippleSize} x={x} y={y} />;\n\n setRipples((prev) => (prev ? [...prev, newRipple] : [newRipple]));\n\n onClick?.(e);\n };\n\n useEffect(() => {\n let timer: NodeJS.Timeout;\n if (ripples) {\n timer = setTimeout(() => {\n setRipples(undefined);\n }, 1000);\n }\n return () => clearTimeout(timer);\n }, [ripples]);\n\n return (\n <button className={cn(styles, className)} type={type} aria-pressed={pressed} onClick={handleClick} {...rest}>\n {variant === 'option' ? (\n // WCAG 2.5.3 (Label in Name): the button is named from its content, so\n // both visible lines are in the name (\"label hint\") and a voice user can\n // say what they see. The space keeps the two lines separate words in\n // that name; the column flex layout does not render it.\n <>\n <span className='passflow-button__option-label'>{children}</span>\n {description ? (\n <>\n {' '}\n <span className='passflow-button__option-hint'>{description}</span>\n </>\n ) : null}\n </>\n ) : (\n children\n )}\n {withRipple && variant !== 'link' && (\n <div aria-hidden className='passflow-ripple-container'>\n {ripples}\n </div>\n )}\n </button>\n );\n};\n","import type { FC } from 'react';\nimport './style.css';\n\nexport type ContinuingStatusProps = {\n /** The app the user is being taken to; without it the line stays generic. */\n appName?: string;\n};\n\n/** The full-page line shown while a session is handed over to the app that asked for it. */\nexport const ContinuingStatus: FC<ContinuingStatusProps> = ({ appName }) => (\n <div className='passflow-continuing-status' role='status'>\n {appName ? `Continuing to ${appName}…` : 'Continuing…'}\n </div>\n);\n","export default \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZgAAAGACAMAAACnYISRAAADAFBMVEUAAAAxQ5cSO5wAOJP////OESYBAAAANJgAJ33SDzT80Rb/AADKAADzKDgEfj3bFRr/zgDoDi4JhQHuHCYAak0AlEIAaDt1qtv/3wAAN4rdKBAAN6lFjdwBMnwOrS3cIyADh1EAVqVLsdjCKC/44BUBeV0BcsIEm0oEKov84kLVBgcAH6UCrcoAZsPpKjv+yAABAHYAoVtysuEAZQAetTrfIA7VKCQBKGXoAxLiCxcAc89ZgbwdRIoLSqn7+fgCki+kMTYAAJcAAK0Almy/CS/+6AYiSaYAUMPiPShkz//vKi0MHIy1Bwb9mgQiXjn88u8AmQADUpP/xyIxjyyHxuMAot7p6Ob9uAs5XbXUIT352gHFCx4jnkQMsF83lQT2PzNwGT06dMQAjMPhFyf1gQPdG0c1qDQAcijw9fjrhoivGyfFICYAAM0Bf/7hZmk9dir65OWNJCrTrjnwsSwmQILmVgUAoeHUOkn2zM3fOwh9mcj/eQDRyc7+mTL//wAHaajh6vPxsbKpstft8e8EOLhJcLQCmbTW4O0AAP/789j51tgfHRDphSjivAztj5XkcxHd3Nn821q2t7jyvcCUlZPuxwuTy6fsoKTqS00CcGlIZaLQHR7pYCSip6QTOIbozhy0yOSKvHblcn3xVm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ImhJyaFE7O2JQfsVK9NrJQtezObCA29lN0PaoYgNNzPCYYMMpJOPIjEkKUMyKmeRSnzeL3I0+DzeoNBD/J6PayYoWUhIjR0MXfcAdUMYNdlbQ3YRzUxRGIKbQjZCkUxmWvXwl5VMsCLz9vtsV996xVXXHG119Pg9Znw+7rGkBAakejNH6GR28+1mne8fpWUpBMPxIPF2Apt8BDFtLScql5Mg93X4PVecevExFNX2L3dPnsDK0anY0NDIhMDv1gN3/fII4/Az3Ef9d8Oo4gNy09wMclSIC4QGlFMdfUsxPi8dp/Xc/Wtn2y+9Wq7N2i3ByNi2NCoFlP07DL97c+WI1icI5J04kEXQ7yvVowvaPd5HigBHrD77EGfLy4x6KAr5JqEynjCi0nhN76UxS0GN/7xxvHx8c+9XtDki6uUYTGhgyiolTIeofkritFRYYVV2KH/L3eOjztLvD47jMqE5n8hvfnTxZSPjIwMas0fgiJuHPGKgdoV9JaMj5eM5/mCcCQbLpdV3yqgJAbYPTrvhB8uszPK1zkn/D4lLjFMENx4PB67HXZgJchgMUJcVoKPmGK0CaYAsVwK7+NPTBCGy/agNwgPO75vKpsYIi4xxWinZMjEPA46CDdxiQHACAb8MAzXS4i4xBSjncSkNv/Eegx9tEbEJaYY7bS/hoaGhobGP8xff9MS7Xw+B5wAAAAASUVORK5CYII=\"","// Coordinates in the bundled 408×384 flag sprite.\n// Geometry belongs to CountryFlag so consumers never construct sprite styles.\nexport const COUNTRY_FLAG_POSITIONS = {\n ad: '-48px -27px',\n ae: '-72px -27px',\n af: '-96px -27px',\n ag: '-120px -27px',\n ai: '-144px -27px',\n al: '-168px -27px',\n am: '-192px -27px',\n an: '-216px -27px',\n ao: '-240px -27px',\n aq: '-264px -27px',\n ar: '-288px -27px',\n as: '-312px -27px',\n at: '-336px -27px',\n au: '-360px -27px',\n aw: '-384px -27px',\n ax: '-0px -51px',\n az: '-24px -51px',\n ba: '-48px -51px',\n bb: '-72px -51px',\n bd: '-96px -51px',\n be: '-120px -51px',\n bf: '-144px -51px',\n bg: '-168px -51px',\n bh: '-192px -51px',\n bi: '-216px -51px',\n bj: '-240px -51px',\n bl: '-264px -51px',\n bm: '-288px -51px',\n bn: '-312px -51px',\n bo: '-336px -51px',\n br: '-360px -51px',\n bs: '-384px -51px',\n bt: '-0px -75px',\n bw: '-24px -75px',\n by: '-48px -75px',\n bz: '-72px -75px',\n ca: '-96px -75px',\n cc: '-120px -75px',\n cd: '-144px -75px',\n cf: '-168px -75px',\n cg: '-192px -75px',\n ch: '-216px -75px',\n ci: '-240px -75px',\n ck: '-264px -75px',\n cl: '-288px -75px',\n cm: '-312px -75px',\n cn: '-336px -75px',\n co: '-360px -75px',\n cr: '-384px -75px',\n cu: '-0px -99px',\n cv: '-24px -99px',\n cw: '-48px -99px',\n cx: '-72px -99px',\n cy: '-96px -99px',\n cz: '-120px -99px',\n de: '-144px -99px',\n dj: '-168px -99px',\n dk: '-192px -99px',\n dm: '-216px -99px',\n do: '-240px -99px',\n dz: '-264px -99px',\n ec: '-288px -99px',\n ee: '-312px -99px',\n eg: '-336px -99px',\n eh: '-360px -99px',\n er: '-384px -99px',\n es: '-0px -123px',\n et: '-24px -123px',\n eu: '-48px -123px',\n fi: '-72px -123px',\n fj: '-96px -123px',\n fk: '-120px -123px',\n fm: '-144px -123px',\n fo: '-168px -123px',\n fr: '-192px -123px',\n ga: '-216px -123px',\n gb: '-240px -123px',\n gd: '-264px -123px',\n ge: '-288px -123px',\n gg: '-312px -123px',\n gh: '-336px -123px',\n gi: '-360px -123px',\n gl: '-384px -123px',\n gm: '-0px -147px',\n gn: '-24px -147px',\n gq: '-48px -147px',\n gr: '-72px -147px',\n gs: '-96px -147px',\n gt: '-120px -147px',\n gu: '-144px -147px',\n gw: '-168px -147px',\n gy: '-192px -147px',\n hk: '-216px -147px',\n hn: '-240px -147px',\n hr: '-264px -147px',\n ht: '-288px -147px',\n hu: '-312px -147px',\n ic: '-336px -147px',\n id: '-360px -147px',\n ie: '-384px -147px',\n il: '-0px -171px',\n im: '-24px -171px',\n in: '-48px -171px',\n iq: '-72px -171px',\n ir: '-96px -171px',\n is: '-120px -171px',\n it: '-144px -171px',\n je: '-168px -171px',\n jm: '-192px -171px',\n jo: '-216px -171px',\n jp: '-240px -171px',\n ke: '-264px -171px',\n kg: '-288px -171px',\n kh: '-312px -171px',\n ki: '-336px -171px',\n xk: '-144px 3px',\n km: '-360px -171px',\n kn: '-384px -171px',\n kp: '-0px -195px',\n kr: '-24px -195px',\n kw: '-48px -195px',\n ky: '-72px -195px',\n kz: '-96px -195px',\n la: '-120px -195px',\n lb: '-144px -195px',\n lc: '-168px -195px',\n li: '-192px -195px',\n lk: '-216px -195px',\n lr: '-240px -195px',\n ls: '-264px -195px',\n lt: '-288px -195px',\n lu: '-312px -195px',\n lv: '-336px -195px',\n ly: '-360px -195px',\n ma: '-384px -195px',\n mc: '-0px -219px',\n md: '-24px -219px',\n me: '-48px -219px',\n mf: '-72px -219px',\n mg: '-96px -219px',\n mh: '-120px -219px',\n mk: '-144px -219px',\n ml: '-168px -219px',\n mm: '-192px -219px',\n mn: '-216px -219px',\n mo: '-240px -219px',\n mp: '-264px -219px',\n mq: '-288px -219px',\n mr: '-312px -219px',\n ms: '-336px -219px',\n mt: '-360px -219px',\n mu: '-384px -219px',\n mv: '-0px -243px',\n mw: '-24px -243px',\n mx: '-48px -243px',\n my: '-72px -243px',\n mz: '-96px -243px',\n na: '-120px -243px',\n nc: '-144px -243px',\n ne: '-168px -243px',\n nf: '-192px -243px',\n ng: '-216px -243px',\n ni: '-240px -243px',\n nl: '-264px -243px',\n no: '-288px -243px',\n np: '-312px -243px',\n nr: '-336px -243px',\n nu: '-360px -243px',\n nz: '-384px -243px',\n om: '-0px -267px',\n pa: '-24px -267px',\n pe: '-48px -267px',\n pf: '-72px -267px',\n pg: '-96px -267px',\n ph: '-120px -267px',\n pk: '-192px -267px',\n pl: '-216px -267px',\n pn: '-240px -267px',\n pr: '-264px -267px',\n ps: '-288px -267px',\n pt: '-312px -267px',\n pw: '-336px -267px',\n py: '-360px -267px',\n qa: '-384px -267px',\n ro: '-0px -291px',\n rs: '-24px -291px',\n ru: '-48px -291px',\n rw: '-72px -291px',\n sa: '-96px -291px',\n sb: '-120px -291px',\n sc: '-144px -291px',\n sd: '-168px -291px',\n se: '-192px -291px',\n sg: '-216px -291px',\n sh: '-240px -291px',\n si: '-264px -291px',\n sk: '-288px -291px',\n sl: '-312px -291px',\n sm: '-336px -291px',\n sn: '-360px -291px',\n so: '-384px -291px',\n sr: '-0px -315px',\n ss: '-24px -315px',\n st: '-48px -315px',\n sv: '-72px -315px',\n sy: '-96px -315px',\n sz: '-120px -315px',\n tc: '-144px -315px',\n td: '-168px -315px',\n tf: '-192px -315px',\n tg: '-216px -315px',\n th: '-240px -315px',\n tj: '-264px -315px',\n tk: '-288px -315px',\n tl: '-312px -315px',\n tm: '-336px -315px',\n tn: '-360px -315px',\n to: '-384px -315px',\n tr: '-0px -339px',\n tt: '-24px -339px',\n tv: '-48px -339px',\n tw: '-72px -339px',\n tz: '-96px -339px',\n ua: '-120px -339px',\n ug: '-144px -339px',\n us: '-168px -339px',\n uy: '-192px -339px',\n uz: '-216px -339px',\n va: '-240px -339px',\n vc: '-264px -339px',\n ve: '-288px -339px',\n vg: '-312px -339px',\n vi: '-336px -339px',\n vn: '-360px -339px',\n vu: '-384px -339px',\n wf: '-0px -363px',\n ws: '-24px -363px',\n ye: '-48px -363px',\n za: '-96px -363px',\n zm: '-120px -363px',\n zw: '-144px -363px',\n} as const;\n\nexport type SupportedCountryFlag = keyof typeof COUNTRY_FLAG_POSITIONS;\n","import type { CSSProperties, FC } from 'react';\nimport flags from '@/assets/icons/flags.png';\nimport { cn } from '@/utils';\nimport { COUNTRY_FLAG_POSITIONS, type SupportedCountryFlag } from './positions';\nimport './style.css';\n\nexport type CountryFlagProps = {\n iso2: string;\n className?: string;\n};\n\nconst COUNTRY_FLAG_ALIASES: Record<string, SupportedCountryFlag> = {\n bq: 'nl',\n gf: 'fr',\n gp: 'fr',\n io: 'gb',\n pm: 'fr',\n re: 'fr',\n yt: 'fr',\n};\n\nconst getSupportedCountry = (iso2: string): SupportedCountryFlag | null => {\n const normalized = iso2.trim().toLowerCase();\n const candidate = COUNTRY_FLAG_ALIASES[normalized] ?? normalized;\n return candidate in COUNTRY_FLAG_POSITIONS ? (candidate as SupportedCountryFlag) : null;\n};\n\nexport const CountryFlag: FC<CountryFlagProps> = ({ iso2, className }) => {\n const country = getSupportedCountry(iso2);\n\n if (!country) {\n return (\n <span\n aria-hidden='true'\n className={cn('passflow-country-flag passflow-country-flag--fallback', className)}\n data-country-flag={iso2.toLowerCase()}\n >\n {iso2.slice(0, 2).toUpperCase() || '–'}\n </span>\n );\n }\n\n const style: CSSProperties = {\n backgroundImage: `url(${flags})`,\n backgroundPosition: COUNTRY_FLAG_POSITIONS[country],\n };\n\n return (\n <span\n aria-hidden='true'\n className={cn('passflow-country-flag', className)}\n data-country-flag={iso2.toLowerCase()}\n style={style}\n />\n );\n};\n","import * as DialogPrimitive from '@radix-ui/react-dialog';\n/* eslint-disable react/jsx-props-no-spreading */\nimport { type ComponentPropsWithoutRef, type ElementRef, forwardRef, type HTMLAttributes } from 'react';\nimport { cn } from '@/utils';\n\nconst Dialog = DialogPrimitive.Root;\n\nconst DialogTrigger = DialogPrimitive.Trigger;\n\nconst DialogPortal = DialogPrimitive.Portal;\n\nconst DialogClose = DialogPrimitive.Close;\n\nconst DialogOverlay = forwardRef<\n ElementRef<typeof DialogPrimitive.Overlay>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay ref={ref} className={cn('passflow-dialog-overlay', className)} {...props} />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\nconst DialogContent = forwardRef<\n ElementRef<typeof DialogPrimitive.Content>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Content ref={ref} className={cn('passflow-dialog-content', className)} {...props}>\n {children}\n </DialogPrimitive.Content>\n </DialogPortal>\n));\nDialogContent.displayName = DialogPrimitive.Content.displayName;\n\nconst DialogHeader = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (\n <div className={cn('passflow-dialog-header', className)} {...props} />\n);\nDialogHeader.displayName = 'DialogHeader';\n\nconst DialogFooter = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (\n <div className={cn('passflow-dialog-footer', className)} {...props} />\n);\nDialogFooter.displayName = 'DialogFooter';\n\nconst DialogTitle = forwardRef<\n ElementRef<typeof DialogPrimitive.Title>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Title ref={ref} className={cn('passflow-dialog-title', className)} {...props} />\n));\nDialogTitle.displayName = DialogPrimitive.Title.displayName;\n\nconst DialogDescription = forwardRef<\n ElementRef<typeof DialogPrimitive.Description>,\n ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Description ref={ref} className={cn('passflow-dialog-description', className)} {...props} />\n));\nDialogDescription.displayName = DialogPrimitive.Description.displayName;\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n};\n","import { OTPInput, REGEXP_ONLY_DIGITS, REGEXP_ONLY_DIGITS_AND_CHARS, type SlotProps } from 'input-otp';\nimport { type FC, forwardRef } from 'react';\nimport { cn } from '@/utils';\nimport '@/styles/index.css';\nimport './field-otp.css';\n\nexport type FieldOtpCharset = 'numeric' | 'alphanumeric';\n\nexport type FieldOtpState = 'default' | 'error' | 'disabled';\n\ntype FieldOtpBaseProps = {\n /** Id of the one real `<input>`; the boxes are drawn from its value. */\n id: string;\n /** Form field name, for a native form submit. */\n name?: string;\n /** Number of characters in the code, and of boxes drawn. */\n length: number;\n value: string;\n onChange: (value: string) => void;\n /** Called once the code reaches `length` characters. */\n onComplete?: (value: string) => void;\n /** Which characters are accepted; also picks the on-screen keyboard. Default `numeric`. */\n charset?: FieldOtpCharset;\n /** `error` marks the code invalid (`aria-invalid`); `disabled` locks it. Default `default`. */\n state?: FieldOtpState;\n /** Id of the element that describes it, such as the error message. */\n describedBy?: string;\n autoFocus?: boolean;\n};\n\n/**\n * The code field is named either by a visible label it draws itself (`label`),\n * or by an element the screen already shows (`labelledBy`), never both. A\n * hidden-only name fails axe `label-title-only` once `describedBy` is set.\n */\nexport type FieldOtpProps = FieldOtpBaseProps &\n (\n | {\n /** Visible prompt drawn above the boxes, as the field's `<label>`. */\n label: string;\n labelledBy?: never;\n }\n | {\n /** Id of a visible element on the screen that names the code field, such as a prompt or heading. */\n labelledBy: string;\n label?: never;\n }\n );\n\nconst CHARSETS: Record<FieldOtpCharset, { pattern: string; inputMode: 'numeric' | 'text' }> = {\n numeric: { pattern: REGEXP_ONLY_DIGITS, inputMode: 'numeric' },\n alphanumeric: { pattern: REGEXP_ONLY_DIGITS_AND_CHARS, inputMode: 'text' },\n};\n\ntype SlotViewProps = SlotProps & { state: FieldOtpState };\n\nconst Slot: FC<SlotViewProps> = ({ char, isActive, hasFakeCaret, state }) => (\n <div\n className={cn('passflow-field-otp', {\n 'passflow-field-otp--active': isActive,\n 'passflow-field-otp--error': state === 'error',\n 'passflow-field-otp--disabled': state === 'disabled',\n })}\n >\n {char}\n {hasFakeCaret ? <span className='passflow-field-otp__caret' /> : null}\n </div>\n);\n\n/**\n * A one-time code entered as a row of boxes.\n *\n * There is one real `<input>` (named, `autocomplete=\"one-time-code\"`), so SMS\n * autofill, password managers and pasting a whole code all work. The boxes are\n * a drawing of its value, hidden from assistive technology. With `label` the\n * field draws its own visible label above the boxes; with `labelledBy` it is\n * named by a prompt the screen already shows. Its ref is the real `<input>`,\n * so a screen can return focus to it after the field was locked.\n */\nexport const FieldOtp = forwardRef<HTMLInputElement, FieldOtpProps>(function FieldOtp(\n {\n id,\n name,\n length,\n value,\n onChange,\n onComplete,\n charset = 'numeric',\n state = 'default',\n label,\n labelledBy,\n describedBy,\n autoFocus = false,\n },\n ref,\n) {\n const { pattern, inputMode } = CHARSETS[charset];\n\n const input = (\n <OTPInput\n ref={ref}\n id={id}\n name={name}\n maxLength={length}\n value={value}\n onChange={onChange}\n onComplete={onComplete}\n pattern={pattern}\n inputMode={inputMode}\n autoComplete='one-time-code'\n disabled={state === 'disabled'}\n aria-labelledby={labelledBy}\n aria-describedby={describedBy}\n aria-invalid={state === 'error' ? true : undefined}\n autoFocus={autoFocus}\n noScriptCSSFallback={null}\n containerClassName={cn('passflow-field-otp-group', { 'passflow-field-otp-group--disabled': state === 'disabled' })}\n render={({ slots }) => (\n <div className='passflow-field-otp-slots' aria-hidden>\n {slots.map((slot, position) => (\n // Slots are positions in the code: the index is their identity.\n // biome-ignore lint/suspicious/noArrayIndexKey: a slot is its position\n <Slot key={position} {...slot} state={state} />\n ))}\n </div>\n )}\n />\n );\n\n if (label === undefined) return input;\n\n return (\n <div className='passflow-field-otp-field'>\n <label htmlFor={id} className='passflow-field-label'>\n {label}\n </label>\n {input}\n </div>\n );\n});\n","/* eslint-disable react/jsx-props-no-spreading */\nimport { forwardRef, type InputHTMLAttributes, useState } from 'react';\nimport { Button, Icon } from '..';\nimport '@/styles/index.css';\nimport type { PassflowPasswordPolicySettings } from '@passflow/core';\nimport { cn } from '@/utils';\n\ntype TFieldPassword = InputHTMLAttributes<HTMLInputElement> & {\n id: string;\n value: string;\n passwordPolicy: PassflowPasswordPolicySettings | null;\n withMessages?: boolean;\n validationErrors?: string | string[];\n isError?: boolean;\n className?: string;\n disabled?: boolean;\n};\n\n/** The character-class line, or `null` when the policy requires no class. */\nconst generateMessage = (\n requires: Record<'requireLowerCase' | 'requireUpperCase' | 'requireSymbol' | 'requireNumber', boolean>,\n) => {\n const requiresString = {\n requireNumber: 'number',\n requireSymbol: 'symbol',\n requireLowerCase: 'lowercase letter',\n requireUpperCase: 'uppercase letter',\n };\n const requirements = Object.keys(requires).filter((key) => requires[key as keyof typeof requires]);\n if (requirements.length === 0) return null;\n const requirementsString = new Intl.ListFormat('en').format(\n requirements.map((requirement) => requiresString[requirement as keyof typeof requiresString]),\n );\n\n return `Must contain a ${requirementsString}`;\n};\n\nexport const FieldPassword = forwardRef<HTMLInputElement, TFieldPassword>(\n (\n {\n id,\n value,\n passwordPolicy,\n withMessages = false,\n validationErrors = [],\n isError = false,\n className = '',\n disabled = false,\n ...rest\n },\n ref,\n ) => {\n const [isShowPassword, setIsShowPassword] = useState(false);\n\n const styles = {\n 'passflow-field--error': isError,\n };\n\n const errorStyles = (fields: string[]) => {\n if (value.length > 0 && !fields.some((field) => validationErrors.includes(field)))\n return 'passflow-password-validation-item--success';\n return null;\n };\n\n const changeIcon = (fields: string[]) => {\n if (value.length > 0 && !fields.some((field) => validationErrors.includes(field))) return 'check';\n return 'close';\n };\n\n const handleShowPassword = () => setIsShowPassword((prev) => !prev);\n\n const minPasswordLength = passwordPolicy?.min_password_length ?? 0;\n // A minimum of zero asks for nothing beyond the non-empty password every field requires.\n const restrictMinPasswordLength = (passwordPolicy?.restrict_min_password_length ?? false) && minPasswordLength > 0;\n const requireLowerCase = passwordPolicy?.require_lowercase ?? false;\n const requireNumber = passwordPolicy?.require_number ?? false;\n const requireSymbol = passwordPolicy?.require_symbol ?? false;\n const requireUpperCase = passwordPolicy?.require_uppercase ?? false;\n const requirementsMessage = generateMessage({\n requireNumber,\n requireSymbol,\n requireLowerCase,\n requireUpperCase,\n });\n\n return (\n <>\n <div className='passflow-field-wrapper'>\n <input\n ref={ref}\n id={id}\n value={value}\n type={isShowPassword ? 'text' : 'password'}\n className={cn('passflow-field-input passflow-field--focused passflow-field-input--with-icon', styles, className)}\n disabled={disabled}\n {...rest}\n />\n {isShowPassword ? (\n <Button\n className='passflow-button-display-password passflow-field-icon-button'\n size='small'\n type='button'\n variant='clean'\n asIcon\n withIcon\n disabled={disabled}\n aria-label='Hide password'\n onClick={handleShowPassword}\n >\n <Icon size='small' type='general' id='eye-on' decorative />\n </Button>\n ) : (\n <Button\n className='passflow-button-display-password passflow-field-icon-button'\n size='small'\n type='button'\n variant='clean'\n asIcon\n withIcon\n disabled={disabled}\n aria-label='Show password'\n onClick={handleShowPassword}\n >\n <Icon size='small' type='general' id='eye-off' decorative />\n </Button>\n )}\n </div>\n {withMessages && passwordPolicy && (restrictMinPasswordLength || requirementsMessage) && (\n <div className='passflow-password-validation'>\n {restrictMinPasswordLength && (\n <p className={cn('passflow-password-validation-item', errorStyles(['length']))}>\n <Icon size='small' id={changeIcon(['length'])} type='general' className={cn(errorStyles(['length']))} />\n At least {minPasswordLength} characters\n </p>\n )}\n {requirementsMessage && (\n <p\n className={cn('passflow-password-validation-item', errorStyles(['uppercase', 'lowercase', 'number', 'symbol']))}\n >\n <Icon\n size='small'\n id={changeIcon(['uppercase', 'lowercase', 'number', 'symbol'])}\n type='general'\n className={cn(errorStyles(['uppercase', 'lowercase', 'number', 'symbol']))}\n />\n {requirementsMessage}\n </p>\n )}\n </div>\n )}\n </>\n );\n },\n);\n","import type { LoginWebAppStyle } from '@passflow/core';\n\nexport type CompatibleLoginWebAppStyle = Partial<LoginWebAppStyle> & {\n /** Legacy field used by themes created before text_color was introduced. */\n content_color?: string;\n};\n\nconst nonEmpty = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value.trim() : null);\n\nconst getBackgroundImage = (value: unknown): string | null => {\n if (typeof value !== 'string') return null;\n\n const image = nonEmpty(value);\n return image ? `url(${image})` : 'none';\n};\n\nexport const getLoginThemeCssVariables = (style: CompatibleLoginWebAppStyle): Record<string, string | null> => ({\n '--passflow-primary-color': nonEmpty(style.primary_color),\n '--passflow-text-color': nonEmpty(style.text_color) ?? nonEmpty(style.content_color),\n '--passflow-secondary-text-color': nonEmpty(style.secondary_text_color),\n '--passflow-background-color': nonEmpty(style.background_color),\n '--passflow-background-image': getBackgroundImage(style.background_image),\n '--passflow-card-color': nonEmpty(style.card_color),\n '--passflow-branding-background-color': nonEmpty(style.card_color),\n '--passflow-input-background-color': nonEmpty(style.input_background_color),\n '--passflow-input-border-color': nonEmpty(style.input_border_color),\n '--passflow-button-text-color': nonEmpty(style.button_text_color),\n '--passflow-passkey-button-text-color': nonEmpty(style.passkey_button_text_color),\n '--passflow-passkey-button-background-color': nonEmpty(style.passkey_button_background_color),\n '--passflow-divider-color': nonEmpty(style.divider_color),\n '--passflow-federated_button_background_color': nonEmpty(style.federated_button_background_color),\n '--passflow-federated_button_text_color': nonEmpty(style.federated_button_text_color),\n});\n\nexport const applyLoginThemeStyles = (root: HTMLElement, style: CompatibleLoginWebAppStyle): void => {\n for (const [property, value] of Object.entries(getLoginThemeCssVariables(style))) {\n if (value === null) root.style.removeProperty(property);\n else root.style.setProperty(property, value);\n }\n};\n","import { useEffect, useLayoutEffect } from 'react';\n\n/**\n * A layout effect in the browser and a plain effect on the server, where a layout effect does nothing and React 18\n * warns about it. Neither runs during a server render.\n */\nexport const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n","import type { AppSettings, LoginWebAppStyle, LoginWebAppTheme, PassflowPasswordPolicySettings } from '@passflow/core';\nimport { useContext, useRef, useState } from 'react';\nimport { PassflowContext, type PassflowState } from '@/context';\nimport { applyLoginThemeStyles, type CompatibleLoginWebAppStyle } from '@/utils/login-theme';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseAppSettingsProps = () => {\n appSettings: AppSettings | null;\n passwordPolicy: PassflowPasswordPolicySettings | null;\n isLoading: boolean;\n isError: boolean;\n error: string;\n reset: () => void;\n currentTheme: string;\n currentStyles: LoginWebAppStyle | null;\n scopes: string[];\n createTenantForNewUser: boolean;\n loginAppTheme?: LoginWebAppTheme;\n};\n\nconst hasPasswordStrategy = (strategies: AppSettings['auth_strategies']): boolean => {\n return strategies?.some((strategy) => strategy.type === 'internal' && strategy.strategy?.challenge === 'password') ?? false;\n};\n\nexport const useAppSettings: UseAppSettingsProps = () => {\n const passflow = usePassflow();\n const context = useContext(PassflowContext);\n const [isError, setIsError] = useState(false);\n const [errorMessage, setErrorMessage] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const isFetchingRef = useRef(false);\n\n if (!context) {\n throw new Error('useAppSetting must be used within an PassflowProvider');\n }\n\n const { state, dispatch } = context;\n\n useIsomorphicLayoutEffect(() => {\n // The provider is still looking for the app id: settings read now would be the empty default.\n if (state.isDiscoveringAppId) return;\n if (state.appSettings || state.hasSettingsError || isFetchingRef.current) return;\n\n const fetchAllSettings = async (): Promise<void> => {\n isFetchingRef.current = true;\n setIsLoading(true);\n try {\n // If appId is not provided, try to discover it from /settings endpoint\n if (!passflow.appId) {\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { isDiscoveringAppId: true } });\n const discovered: Partial<PassflowState> = { isDiscoveringAppId: false };\n\n try {\n // Try relative path first (works with dev server proxy and same-origin production)\n // Then fall back to absolute URL if configured\n const urlsToTry = ['/settings'];\n if (passflow.url) {\n urlsToTry.push(`${passflow.url}/settings`);\n }\n\n let response: Response | null = null;\n for (const url of urlsToTry) {\n try {\n const r = await fetch(url);\n if (r.ok) {\n response = r;\n break;\n }\n } catch {}\n }\n\n if (response) {\n const settings = await response.json();\n\n // Support both response formats:\n // Production: { login_app: { app_id: \"...\", ... } }\n // Dev: { appId: \"...\" }\n const discoveredAppId = settings.login_app?.app_id || settings.appId;\n\n if (discoveredAppId) {\n passflow.setAppId(discoveredAppId);\n discovered.appId = discoveredAppId;\n\n const discoveredScopes = settings.login_app?.scopes || settings.scopes;\n if (state.handOff) dispatch({ type: 'SET_FOUND_SCOPES', found: discoveredScopes });\n else if (!state.scopes && discoveredScopes) discovered.scopes = discoveredScopes;\n\n const createTenant = settings.login_app?.create_tenant_for_new_user ?? settings.createTenantForNewUser;\n if (state.createTenantForNewUser === undefined && createTenant !== undefined) {\n discovered.createTenantForNewUser = createTenant;\n }\n }\n }\n } catch (discoveryError) {\n console.warn('Failed to discover appId from /settings:', discoveryError);\n // Continue with the flow - we'll handle missing appId later\n }\n\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: discovered });\n }\n\n // Discovery has finished. With no app id this is the bare default sign-in form, on empty settings.\n let appSettings = {} as AppSettings;\n if (passflow.appId) {\n appSettings = await passflow.getAppSettings();\n }\n\n // Each dispatch carries only what it changes, so nothing written meanwhile is overwritten.\n const finalStateUpdates: Partial<PassflowState> = { appSettings };\n\n // Under a hand-off the reducer applies the found scopes to the current state: a value discovery wrote while\n // this request was open stays.\n const defaultScopes = appSettings.defaults?.scopes;\n if (state.handOff) dispatch({ type: 'SET_FOUND_SCOPES', found: defaultScopes });\n else if (!state.scopes && defaultScopes) finalStateUpdates.scopes = defaultScopes;\n const defaultCreateTenant = appSettings.defaults?.create_tenant_for_new_user;\n if (state.createTenantForNewUser === undefined && defaultCreateTenant !== undefined) {\n finalStateUpdates.createTenantForNewUser = defaultCreateTenant;\n }\n\n let passwordPolicy = null;\n if (appSettings.auth_strategies && hasPasswordStrategy(appSettings.auth_strategies)) {\n passwordPolicy = await passflow.getPasswordPolicySettings();\n }\n finalStateUpdates.passwordPolicy = passwordPolicy;\n\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: finalStateUpdates });\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n // Set error flag in context to prevent infinite retry loop\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { hasSettingsError: true } });\n } finally {\n setIsLoading(false);\n isFetchingRef.current = false;\n }\n };\n void fetchAllSettings();\n }, [dispatch, state.appSettings, state.hasSettingsError, state.isDiscoveringAppId, passflow]);\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n // Clear error flag in context to allow retry\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { hasSettingsError: false } });\n };\n\n // `custom_css` is not written here: each screen passes `currentStyles.custom_css`\n // to its shell, which renders it inline.\n const applyThemeStyles = (style: CompatibleLoginWebAppStyle) => {\n applyLoginThemeStyles(document.documentElement, style);\n };\n\n const getCurrentTheme = () => {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n\n if (state.appSettings?.login_app_theme?.color_scheme === 'system') return theme;\n\n return state.appSettings?.login_app_theme?.color_scheme ?? theme;\n };\n\n const currentTheme = getCurrentTheme();\n\n const selectedStyle = state.appSettings?.login_app_theme\n ? currentTheme === 'dark'\n ? state.appSettings?.login_app_theme.dark_style\n : state.appSettings?.login_app_theme.light_style\n : null;\n\n if (selectedStyle) {\n applyThemeStyles(selectedStyle);\n }\n\n return {\n appSettings: state.appSettings,\n scopes: state.scopes ?? [],\n createTenantForNewUser: state.createTenantForNewUser ?? false,\n loginAppTheme: state.appSettings?.login_app_theme,\n passwordPolicy: state.passwordPolicy,\n currentStyles: selectedStyle,\n currentTheme: currentTheme,\n isLoading,\n isError,\n error: errorMessage,\n reset,\n } as const;\n};\n","import { useContext } from 'react';\nimport { AuthContext, type AuthContextValue } from '@/context';\n\nexport const useAuth = (): AuthContextValue => {\n const context = useContext(AuthContext);\n if (!context) {\n throw new Error('useAuth must be used within an AuthProvider');\n }\n\n return context;\n};\n","import { startHostedSignIn } from '@/utils/hosted-sign-in';\nimport { usePassflow } from './use-passflow';\n\ntype UseAuthCloudRedirectProps = (cloudPassflowUrl: string) => () => void;\n\nexport const useAuthCloudRedirect: UseAuthCloudRedirectProps = (cloudPassflowUrl: string) => {\n const passflow = usePassflow();\n\n // A failed redirect is reported by core's `Error` event (operation `auth-redirect`); the page stays where it is.\n const redirect = () => {\n startHostedSignIn(passflow, { url: cloudPassflowUrl }).catch(() => {});\n };\n\n return redirect;\n};\n","import { useCallback, useEffect, useMemo, useState } from 'react';\nimport { submitFormPost } from '@/utils/form-post';\n\n/**\n * The OIDC consent decision, as a hook.\n *\n * The URL is the bearer. `consent_challenge_id` identifies the consent step the\n * server staged for the user who just signed in, and that id is handed only to\n * this browser, in the redirect that ends sign-in. Possessing it is what\n * authorizes reading the staged request — there is no Authorization header on\n * the GET. The server hands back a `csrf_token` with the request metadata, and\n * every state-changing POST must carry it back in `X-Passflow-CSRF`. That token\n * is the only thing separating a real decision from one a third-party page\n * forged on the user's behalf, so it is never optional and never cached across\n * challenges.\n *\n * The decision endpoints answer with a discriminated response rather than a\n * redirect status, because the OIDC `response_mode` decides HOW the user gets\n * back to the client: `query` is an ordinary navigation, `form_post` must be a\n * POST with the parameters in a form body (they cannot go in a URL). The server\n * knows which; the client just executes what it is told.\n */\n\nexport type ConsentScopeMetadata = {\n scope: string;\n label: string;\n description: string;\n};\n\n/** What GET /oidc/requests/{consent_challenge_id} hands the page to render itself. */\nexport type ConsentInfo = {\n client_id: string;\n app_name: string;\n app_logo_url: string;\n requested_scopes: string[];\n scope_metadata: ConsentScopeMetadata[];\n redirect_uri: string;\n state: string;\n response_mode: '' | 'query' | 'form_post';\n first_party: boolean;\n csrf_token: string;\n};\n\ntype DecisionResponse =\n | { kind: 'redirect'; url: string }\n | { kind: 'form_post'; action: string; fields: Record<string, string> };\n\ntype ApiErrorBody = {\n error?: string;\n error_description?: string;\n};\n\nexport type ConsentStatus =\n /** Fetching the staged request. */\n | 'loading'\n /** Metadata in hand; awaiting the user's decision. */\n | 'ready'\n /** A decision is in flight. */\n | 'working'\n /** Decision accepted; the browser is on its way back to the client. */\n | 'redirecting'\n /** The link itself is unusable — missing, expired, or rejected id. Terminal. */\n | 'invalid';\n\nexport type ConsentError = {\n message: string;\n description?: string;\n};\n\nexport type UseConsentProps = {\n status: ConsentStatus;\n info: ConsentInfo | null;\n /** The scopes still switched on. A subset of `info.requested_scopes`. */\n grantedScopes: string[];\n error: ConsentError | null;\n /** Metadata for a scope, falling back to the bare scope string. */\n scopeMetadata: (scope: string) => ConsentScopeMetadata;\n /** Switch one requested scope on or off before deciding. */\n toggleScope: (scope: string) => void;\n /** Grant the currently-selected subset. */\n allow: () => Promise<void>;\n /** Refuse the request outright (OAuth2 `access_denied`). */\n deny: () => Promise<void>;\n};\n\nconst readConsentChallengeId = (): string => new URLSearchParams(window.location.search).get('consent_challenge_id') ?? '';\n\nconst requestPath = (consentChallengeId: string): string => `/oidc/requests/${encodeURIComponent(consentChallengeId)}`;\n\nexport const useConsent = (): UseConsentProps => {\n const consentChallengeId = useMemo(readConsentChallengeId, []);\n\n const [status, setStatus] = useState<ConsentStatus>('loading');\n const [info, setInfo] = useState<ConsentInfo | null>(null);\n const [granted, setGranted] = useState<Set<string>>(new Set());\n const [error, setError] = useState<ConsentError | null>(null);\n\n useEffect(() => {\n if (!consentChallengeId) {\n setStatus('invalid');\n setError({\n message: 'Invalid consent link',\n description: 'This consent link is missing required information. Please return to the application and try again.',\n });\n return;\n }\n\n let cancelled = false;\n\n const fetchInfo = async (): Promise<void> => {\n try {\n const res = await fetch(requestPath(consentChallengeId), {\n method: 'GET',\n credentials: 'same-origin',\n headers: { Accept: 'application/json' },\n });\n if (cancelled) return;\n\n if (!res.ok) {\n const body = ((await res.json().catch(() => ({}))) ?? {}) as ApiErrorBody;\n setStatus('invalid');\n setError({\n message: res.status >= 500 ? 'Something went wrong' : 'Consent request unavailable',\n description:\n body.error_description ||\n 'We could not load this consent request. Please return to the application and try again.',\n });\n return;\n }\n\n const data = (await res.json()) as ConsentInfo;\n if (cancelled) return;\n\n setInfo(data);\n // Everything asked for starts granted; the user switches OFF what they\n // do not want. Starting from none would train people to hit Allow on an\n // empty grant and wonder why the app is broken.\n setGranted(new Set(data.requested_scopes));\n setStatus('ready');\n } catch (err) {\n if (cancelled) return;\n setStatus('invalid');\n setError({\n message: 'Connection error',\n description: err instanceof Error ? err.message : 'Could not reach the server. Please check your connection.',\n });\n }\n };\n\n void fetchInfo();\n\n return () => {\n cancelled = true;\n };\n }, [consentChallengeId]);\n\n const toggleScope = useCallback((scope: string): void => {\n setGranted((prev) => {\n const next = new Set(prev);\n if (next.has(scope)) next.delete(scope);\n else next.add(scope);\n return next;\n });\n // Changing the selection invalidates whatever the last failed submit said.\n setError(null);\n }, []);\n\n const decide = useCallback(\n async (decision: 'allow' | 'deny'): Promise<void> => {\n if (!info) return;\n\n setStatus('working');\n setError(null);\n\n const base = requestPath(consentChallengeId);\n const endpoint = decision === 'allow' ? `${base}/consent` : `${base}/reject`;\n const body =\n decision === 'allow'\n ? { granted_scopes: info.requested_scopes.filter((scope) => granted.has(scope)) }\n : { error: 'access_denied', error_description: 'User denied consent' };\n\n try {\n const res = await fetch(endpoint, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'X-Passflow-CSRF': info.csrf_token,\n },\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n const errBody = ((await res.json().catch(() => ({}))) ?? {}) as ApiErrorBody;\n setStatus('ready');\n setError({\n message: errBody.error_description || 'Could not submit your decision. Please try again.',\n });\n return;\n }\n\n const data = (await res.json()) as DecisionResponse;\n\n if (data.kind === 'redirect') {\n setStatus('redirecting');\n window.location.href = data.url;\n return;\n }\n\n if (data.kind === 'form_post') {\n setStatus('redirecting');\n submitFormPost(data.action, data.fields);\n return;\n }\n\n setStatus('ready');\n setError({ message: 'Unexpected response from server.' });\n } catch (err) {\n setStatus('ready');\n setError({\n message: err instanceof Error ? err.message : 'Could not reach the server. Please try again.',\n });\n }\n },\n [granted, info, consentChallengeId],\n );\n\n const allow = useCallback(() => decide('allow'), [decide]);\n const deny = useCallback(() => decide('deny'), [decide]);\n\n const metadataByScope = useMemo(() => new Map((info?.scope_metadata ?? []).map((meta) => [meta.scope, meta])), [info]);\n\n const scopeMetadata = useCallback(\n (scope: string): ConsentScopeMetadata => metadataByScope.get(scope) ?? { scope, label: scope, description: '' },\n [metadataByScope],\n );\n\n const grantedScopes = useMemo(() => (info?.requested_scopes ?? []).filter((scope) => granted.has(scope)), [granted, info]);\n\n return { status, info, grantedScopes, error, scopeMetadata, toggleScope, allow, deny };\n};\n","import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { DeviceError } from '@/types/device-errors';\nimport { classifyDeviceError, DeviceApiError } from '@/utils';\n\n/**\n * The RFC 8628 verification flow, as a hook.\n *\n * ── The one rule the whole thing is built around ────────────────────────────\n * Signing in and approving are TWO ACTS, and this hook keeps them two. Proving\n * who you are (`/oidc/device/authenticate`) yields an approval ticket and\n * NOTHING else — no tokens, no session. Approving (`/oidc/device/approve`) is\n * what releases tokens to the waiting terminal, and it needs that ticket.\n *\n * The gap between them is not ceremony, it is RFC 8628 §5.4: an attacker can\n * start a device grant and walk a victim into approving it (STORM-2372). They\n * know the user_code — they created it — and the page is public, so they can\n * read its CSRF token too. Neither can be the authority for approval. Only the\n * ticket, held in this hook's memory and bound to the browser that actually\n * authenticated, can be.\n *\n * So: never collapse authenticate+approve into one call \"for convenience\".\n * Mode 1 puts both behind one TAP (see confirmWithPassword) — that is a UI\n * affordance and is fine, because the human still looked at the code first.\n * Mode 3 skips the tap entirely, which it earns by using an origin-bound\n * passkey; see the note on confirmWithPasskey.\n *\n * When the app requires a second factor, the first ticket cannot approve: the\n * server refuses it. The page asks for the factor (`/oidc/device/second-factor`)\n * and approves with the ticket that answers, which records both.\n */\n\n/** The UI the server resolved for this challenge. A closed set — the client does not choose. */\nexport type DeviceUIMode = 'consent' | 'full_login' | 'passkey';\n\n/** What GET /oidc/device/info hands the page to render itself. */\nexport type DeviceVerifyInfo = {\n mode: DeviceUIMode;\n /** Absent for `passkey` mode, by design — see device_page.go. */\n user_code?: string;\n app_name: string;\n csrf_token: string;\n methods: {\n password: boolean;\n passkey: boolean;\n };\n};\n\n/** A second factor the verification page can take. */\nexport type DeviceSecondFactorMethod = 'totp' | 'recovery_codes';\n\nexport type DeviceVerifyStatus =\n /** Asking the server what to render. */\n | 'loading'\n /** No code yet — show the entry form. */\n | 'code_entry'\n /** Info in hand; awaiting the user. */\n | 'ready'\n /** A call is in flight. */\n | 'working'\n /** A first factor proven; the app wants a second before anything can be approved. */\n | 'second_factor'\n /** Identity proven, ticket held, not yet approved. */\n | 'signed_in'\n /** Approved. The terminal has its tokens. */\n | 'done'\n /** The mode is switched off. Terminal, and nothing approvable is rendered. */\n | 'refused'\n /** Terminal failure — bad/expired code, dead app. */\n | 'failed';\n\nexport type UseDeviceVerifyProps = {\n status: DeviceVerifyStatus;\n info: DeviceVerifyInfo | null;\n error: DeviceError | null;\n /** The email that authenticated, once one has. */\n email: string | null;\n /** Whether an approval ticket is held. */\n isAuthenticated: boolean;\n /** Whether a first-factor ticket is waiting for its second factor. */\n isSecondFactorPending: boolean;\n /** The second factors the server takes, once a sign-in owes one. */\n secondFactorMethods: DeviceSecondFactorMethod[];\n /** Re-run the info lookup for a code typed by hand. */\n submitCode: (code: string) => void;\n /** Prove identity with a password. Does NOT approve. */\n signInWithPassword: (email: string, password: string) => Promise<void>;\n /** Prove identity with a passkey. Does NOT approve. */\n signInWithPasskey: () => Promise<void>;\n /** Approve, using the ticket already held. */\n approve: () => Promise<void>;\n /** One tap: prove identity if needed, then approve. */\n confirmWithPassword: (email: string, password: string) => Promise<void>;\n /** Passkey ceremony then approve, with no tap in between. */\n confirmWithPasskey: () => Promise<void>;\n /**\n * Prove the second factor. Approves too when the act that asked for it was\n * an approval (consent's tap, the passkey mode); otherwise lands on signed_in.\n */\n submitSecondFactor: (method: DeviceSecondFactorMethod, code: string) => Promise<void>;\n /** Clear a recoverable error so the user can try again. */\n clearError: () => void;\n};\n\nconst DEVICE_ENDPOINTS = {\n info: '/oidc/device/info',\n authenticate: '/oidc/device/authenticate',\n approve: '/oidc/device/approve',\n passkeyStart: '/oidc/device/passkey/start',\n secondFactor: '/oidc/device/second-factor',\n} as const;\n\n/** What /oidc/device/authenticate answers with. */\ntype DeviceAuthenticateResponse = {\n approval_ticket: string;\n email?: string;\n /** The app requires a second factor; this ticket cannot approve until one is given. */\n second_factor_required?: boolean;\n second_factor_methods?: string[];\n};\n\nconst SECOND_FACTOR_METHODS: readonly DeviceSecondFactorMethod[] = ['totp', 'recovery_codes'];\n\n/** The factors the server offers that this page can take, in its order. */\nconst toSecondFactorMethods = (methods: string[] | undefined): DeviceSecondFactorMethod[] => {\n const known = (methods ?? []).filter((m): m is DeviceSecondFactorMethod =>\n SECOND_FACTOR_METHODS.includes(m as DeviceSecondFactorMethod),\n );\n return known.length > 0 ? known : ['totp'];\n};\n\n/** Read `user_code` off the URL — the QR encodes verification_uri_complete. */\nconst readUserCodeFromURL = (): string => new URLSearchParams(window.location.search).get('user_code') ?? '';\n\n/**\n * Parse a device endpoint's response, turning any failure into a DeviceApiError\n * that carries the server's stable `reason`.\n */\nconst parseDeviceResponse = async <T>(res: Response): Promise<T> => {\n const body: unknown = await res.json().catch(() => ({}));\n const data = (body ?? {}) as Record<string, unknown>;\n\n if (!res.ok) {\n throw new DeviceApiError({\n reason: typeof data.reason === 'string' ? data.reason : '',\n code: typeof data.error === 'string' ? data.error : '',\n status: res.status,\n description: typeof data.error_description === 'string' ? data.error_description : '',\n });\n }\n return data as T;\n};\n\nexport const useDeviceVerify = (): UseDeviceVerifyProps => {\n const [status, setStatus] = useState<DeviceVerifyStatus>('loading');\n const [info, setInfo] = useState<DeviceVerifyInfo | null>(null);\n const [error, setError] = useState<DeviceError | null>(null);\n const [email, setEmail] = useState<string | null>(null);\n const [userCode, setUserCode] = useState<string>(() => readUserCodeFromURL());\n\n /**\n * The approval ticket. A ref, not state: it is an authorization handle, so it\n * must be readable synchronously by the call that follows the one that earned\n * it. `confirmWithPassword` authenticates and approves back-to-back within a\n * single event; a state read there would still be null, and the approve would\n * be refused for no reason a user could understand.\n */\n const ticketRef = useRef<string | null>(null);\n\n /**\n * The first-factor ticket, while the app still wants a second. Kept apart\n * from ticketRef because it cannot approve, so isAuthenticated must not\n * claim a sign-in the approval would refuse.\n */\n const firstFactorTicketRef = useRef<string | null>(null);\n /** Whether the act that asked for the second factor was an approval. */\n const approveAfterSecondFactorRef = useRef(false);\n const [secondFactorMethods, setSecondFactorMethods] = useState<DeviceSecondFactorMethod[]>([]);\n\n /** Guards against setting state after unmount, and against double-fires. */\n const activeRef = useRef(true);\n useEffect(() => {\n activeRef.current = true;\n return () => {\n activeRef.current = false;\n };\n }, []);\n\n const csrf = info?.csrf_token ?? '';\n\n /**\n * Every back-channel POST: same-origin, JSON, the challenge's CSRF token, and\n * the user_code that scopes it.\n */\n const post = useCallback(\n async <T>(path: string, body: Record<string, unknown>): Promise<T> => {\n const res = await fetch(path, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'X-Passflow-CSRF': csrf,\n },\n body: JSON.stringify({ ...body, user_code: userCode }),\n });\n return parseDeviceResponse<T>(res);\n },\n [csrf, userCode],\n );\n\n /**\n * Record a failure: classified for the user, logged in full for us.\n *\n * This is the ONLY place a failure becomes user-visible, which is what makes\n * \"no technical string reaches the screen\" checkable rather than aspirational.\n */\n const fail = useCallback((err: unknown, terminal: DeviceVerifyStatus | null = null) => {\n const classified = classifyDeviceError(err);\n // The detail the user must never read, kept exactly where a developer will\n // look for it first.\n if (classified.detail) {\n console.error('[passflow] device verification:', classified.detail, err);\n }\n if (!activeRef.current) return;\n setError(classified);\n if (terminal) {\n setStatus(terminal);\n return;\n }\n setStatus(\n classified.type === 'mode_disabled'\n ? 'refused'\n : firstFactorTicketRef.current\n ? 'second_factor'\n : ticketRef.current\n ? 'signed_in'\n : 'ready',\n );\n }, []);\n\n // ── Load what to render ───────────────────────────────────────────────────\n const loadInfo = useCallback(async (code: string) => {\n if (!code) {\n setStatus('code_entry');\n setError(null);\n return;\n }\n setStatus('loading');\n setError(null);\n try {\n const res = await fetch(`${DEVICE_ENDPOINTS.info}?user_code=${encodeURIComponent(code)}`, {\n method: 'GET',\n credentials: 'same-origin',\n headers: { Accept: 'application/json' },\n });\n const data = await parseDeviceResponse<DeviceVerifyInfo>(res);\n if (!activeRef.current) return;\n setInfo(data);\n setStatus('ready');\n } catch (err) {\n const classified = classifyDeviceError(err);\n if (classified.detail) {\n console.error('[passflow] device verification:', classified.detail, err);\n }\n if (!activeRef.current) return;\n\n // `code_required` is not a failure — it is the code entry form.\n if (classified.type === 'code_required') {\n setError(null);\n setStatus('code_entry');\n return;\n }\n setError(classified);\n // A disabled mode gets its own terminal state so the page can render a\n // refusal with NOTHING approvable on it. A bad or dead code lands on the\n // entry form, where the remedy (type it again) actually lives.\n setStatus(classified.type === 'mode_disabled' ? 'refused' : 'failed');\n }\n }, []);\n\n useEffect(() => {\n void loadInfo(userCode);\n }, [loadInfo, userCode]);\n\n const submitCode = useCallback((code: string) => {\n setUserCode(code.trim());\n }, []);\n\n // ── Prove identity. Yields a ticket; approves nothing. ────────────────────\n /**\n * Hold the ticket an authentication earned. Returns true when the app wants\n * a second factor first, in which case the ticket cannot approve yet.\n */\n const holdTicket = useCallback((res: DeviceAuthenticateResponse): boolean => {\n if (res.second_factor_required) {\n firstFactorTicketRef.current = res.approval_ticket;\n ticketRef.current = null;\n if (activeRef.current) setSecondFactorMethods(toSecondFactorMethods(res.second_factor_methods));\n return true;\n }\n firstFactorTicketRef.current = null;\n ticketRef.current = res.approval_ticket;\n return false;\n }, []);\n\n const authenticatePassword = useCallback(\n async (emailValue: string, password: string): Promise<boolean> => {\n const res = await post<DeviceAuthenticateResponse>(DEVICE_ENDPOINTS.authenticate, {\n method: 'password',\n email: emailValue,\n password,\n });\n const owesSecondFactor = holdTicket(res);\n if (activeRef.current) setEmail(res.email ?? emailValue);\n return owesSecondFactor;\n },\n [post, holdTicket],\n );\n\n const authenticatePasskey = useCallback(async (): Promise<boolean> => {\n // Thrown as a DOMException so it travels the same road as every real\n // WebAuthn failure and lands on the same classified copy — rather than\n // becoming a second, parallel way for this page to describe a passkey\n // problem, which is how the copy drifts.\n if (typeof window === 'undefined' || !window.PublicKeyCredential) {\n throw new DOMException('this browser does not implement PublicKeyCredential', 'NotSupportedError');\n }\n\n const start = await post<{ passkey_challenge_id: string; publicKey: PublicKeyCredentialRequestOptionsJSON }>(\n DEVICE_ENDPOINTS.passkeyStart,\n {},\n );\n\n // The SDK's existing WebAuthn primitive, not a hand-rolled base64url dance.\n // @simplewebauthn/browser (v14, the same copy @passflow/core uses) takes the\n // server's JSON options as-is. Loaded on demand: only this branch needs it.\n const { startAuthentication } = await import('@simplewebauthn/browser');\n const assertion = await startAuthentication({ optionsJSON: start.publicKey });\n\n const res = await post<DeviceAuthenticateResponse>(DEVICE_ENDPOINTS.authenticate, {\n method: 'passkey',\n passkey_challenge_id: start.passkey_challenge_id,\n passkey_data: assertion,\n });\n const owesSecondFactor = holdTicket(res);\n if (activeRef.current) setEmail(res.email ?? null);\n return owesSecondFactor;\n }, [post, holdTicket]);\n\n // ── The act that releases tokens ──────────────────────────────────────────\n const approveWithTicket = useCallback(async (): Promise<void> => {\n await post(DEVICE_ENDPOINTS.approve, { approval_ticket: ticketRef.current });\n if (!activeRef.current) return;\n setStatus('done');\n }, [post]);\n\n const signInWithPassword = useCallback(\n async (emailValue: string, password: string) => {\n setStatus('working');\n setError(null);\n try {\n const owesSecondFactor = await authenticatePassword(emailValue, password);\n if (!activeRef.current) return;\n approveAfterSecondFactorRef.current = false;\n setStatus(owesSecondFactor ? 'second_factor' : 'signed_in');\n } catch (err) {\n fail(err);\n }\n },\n [authenticatePassword, fail],\n );\n\n const signInWithPasskey = useCallback(async () => {\n setStatus('working');\n setError(null);\n try {\n const owesSecondFactor = await authenticatePasskey();\n if (!activeRef.current) return;\n approveAfterSecondFactorRef.current = false;\n setStatus(owesSecondFactor ? 'second_factor' : 'signed_in');\n } catch (err) {\n fail(err);\n }\n }, [authenticatePasskey, fail]);\n\n const approve = useCallback(async () => {\n setStatus('working');\n setError(null);\n try {\n await approveWithTicket();\n } catch (err) {\n fail(err);\n }\n }, [approveWithTicket, fail]);\n\n /**\n * Mode 1's single tap: prove identity if we have not already, then approve.\n *\n * Two calls behind one button is the affordance; it is NOT a collapse of the\n * §5.4 check. The check is that a human read the code and chose to proceed,\n * and that is exactly what the tap is.\n */\n const confirmWithPassword = useCallback(\n async (emailValue: string, password: string) => {\n setStatus('working');\n setError(null);\n try {\n if (!ticketRef.current && (await authenticatePassword(emailValue, password))) {\n approveAfterSecondFactorRef.current = true;\n if (activeRef.current) setStatus('second_factor');\n return;\n }\n await approveWithTicket();\n } catch (err) {\n fail(err);\n }\n },\n [authenticatePassword, approveWithTicket, fail],\n );\n\n /**\n * Passkey then approve, with nothing in between.\n *\n * For Mode 3 this runs on load, with no user gesture, and both halves of that\n * are deliberate:\n * - WebAuthn L3's get() carries no transient-activation requirement (unlike\n * create()), so firing on load is legal. The phone's own biometric prompt\n * IS the interaction; a button first would add a step that protects nothing.\n * - No §5.4 confirm follows, because a passkey is origin-bound: the\n * authenticator scopes the assertion to this origin, so it cannot be\n * produced on an attacker's page or replayed to one. There is no phished\n * approval to catch and so nothing for the human to compare.\n */\n const confirmWithPasskey = useCallback(async () => {\n setStatus('working');\n setError(null);\n try {\n if (await authenticatePasskey()) {\n approveAfterSecondFactorRef.current = true;\n if (activeRef.current) setStatus('second_factor');\n return;\n }\n await approveWithTicket();\n } catch (err) {\n fail(err);\n }\n }, [authenticatePasskey, approveWithTicket, fail]);\n\n /**\n * The second factor, for a sign-in whose app requires one. The server checks\n * the code for the user the first ticket names and answers with a ticket\n * recording both factors, which is the one that can approve.\n *\n * It approves straight away when the act that asked for the factor was\n * itself an approval: consent's tap, or the passkey mode, which has none.\n */\n const submitSecondFactor = useCallback(\n async (method: DeviceSecondFactorMethod, code: string) => {\n setStatus('working');\n setError(null);\n try {\n const res = await post<{ approval_ticket: string }>(DEVICE_ENDPOINTS.secondFactor, {\n approval_ticket: firstFactorTicketRef.current,\n method,\n code,\n });\n ticketRef.current = res.approval_ticket;\n firstFactorTicketRef.current = null;\n if (approveAfterSecondFactorRef.current) {\n await approveWithTicket();\n return;\n }\n if (activeRef.current) setStatus('signed_in');\n } catch (err) {\n fail(err);\n }\n },\n [post, approveWithTicket, fail],\n );\n\n const clearError = useCallback(() => setError(null), []);\n\n return {\n status,\n info,\n error,\n email,\n isAuthenticated: ticketRef.current !== null,\n isSecondFactorPending: firstFactorTicketRef.current !== null,\n secondFactorMethods,\n submitCode,\n signInWithPassword,\n signInWithPasskey,\n approve,\n confirmWithPassword,\n confirmWithPasskey,\n submitSecondFactor,\n clearError,\n };\n};\n","import type { PassflowAuthorizationResponse } from '@passflow/core';\nimport { useCallback, useEffect, useReducer, useRef, useState } from 'react';\nimport type { EmailCodeStep } from '@/types';\nimport { emailCodeErrorMessage, emailCodeStepReducer, initialEmailCodeStepState, readEmailVerificationStep } from '@/utils';\nimport { usePassflow } from './use-passflow';\n\nexport type UseEmailCodeStepOptions = {\n /**\n * Repeats the request that produced the step (the same sign-up or sign-in body). Absent when the code cannot be\n * sent again, as after a password change: the reset link is spent.\n */\n resend?: () => Promise<unknown>;\n /** The step ended (cancelled, verified, or turned into a link): anything held only for resend can be dropped. */\n onRelease?: () => void;\n};\n\nexport type UseEmailCodeStep = {\n step: EmailCodeStep;\n /** Enters the step when `answer` is an email verification step; `false` (nothing changes) for any other answer. */\n enter: (answer: unknown) => boolean;\n /**\n * Posts the code. Resolves the session answer on success (the caller runs its post-auth path), `null` on a failure\n * (shown in `error`), when a verify is already in flight, or when the step was left meanwhile.\n */\n verify: (otp: string) => Promise<PassflowAuthorizationResponse | null>;\n /**\n * Sends a new code by repeating the original request. Resolves `null` normally (the step moves to the new code or\n * to the link); resolves the session answer in the rare case the repeated request signed the user in directly.\n */\n resend: () => Promise<PassflowAuthorizationResponse | null>;\n canResend: boolean;\n /** Leaves the step for the screen's own form. Ignored while a verify is in flight. */\n cancel: () => void;\n isVerifying: boolean;\n isResending: boolean;\n error: string | null;\n};\n\n/**\n * The emailed-code step of a sign-up, sign-in or password change: holds the step, posts the code with\n * `passflow.verifyEmailCode`, and resends by repeating the original request. An answer that arrives after the user\n * left the step (or after a newer step replaced it) is dropped.\n */\nexport const useEmailCodeStep = (options: UseEmailCodeStepOptions = {}): UseEmailCodeStep => {\n const passflow = usePassflow();\n const [state, dispatch] = useReducer(emailCodeStepReducer, initialEmailCodeStepState);\n const [isVerifying, setIsVerifying] = useState(false);\n const [isResending, setIsResending] = useState(false);\n\n // Bumped whenever the step is entered or left: an async answer from an older epoch is stale.\n const epochRef = useRef(0);\n const verifyingRef = useRef(false);\n const resendingRef = useRef(false);\n const stepRef = useRef<EmailCodeStep>(state.step);\n stepRef.current = state.step;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(\n () => () => {\n epochRef.current += 1;\n },\n [],\n );\n\n const enter = useCallback((answer: unknown): boolean => {\n const step = readEmailVerificationStep(answer);\n if (step === null) return false;\n epochRef.current += 1;\n verifyingRef.current = false;\n resendingRef.current = false;\n setIsVerifying(false);\n setIsResending(false);\n dispatch({ type: 'ENTER', step });\n if (step.kind === 'link') optionsRef.current.onRelease?.();\n return true;\n }, []);\n\n const verify = useCallback(\n async (otp: string): Promise<PassflowAuthorizationResponse | null> => {\n const step = stepRef.current;\n if (step.kind !== 'code' || verifyingRef.current) return null;\n const epoch = epochRef.current;\n verifyingRef.current = true;\n setIsVerifying(true);\n dispatch({ type: 'VERIFY_STARTED' });\n\n try {\n const answer = await passflow.verifyEmailCode({ challenge_id: step.challengeId, otp });\n if (epoch !== epochRef.current) return null;\n\n // Not expected from /auth/validate, but core passes it through: show the new step rather than sign in.\n const next = readEmailVerificationStep(answer);\n if (next !== null) {\n enter(answer);\n return null;\n }\n\n // Stays \"verifying\" until the screen leaves: the caller now runs its post-auth path.\n dispatch({ type: 'VERIFY_OK' });\n optionsRef.current.onRelease?.();\n return answer;\n } catch (error) {\n if (epoch !== epochRef.current) return null;\n console.error('[passflow] email code verification failed', error);\n verifyingRef.current = false;\n setIsVerifying(false);\n dispatch({ type: 'VERIFY_FAILED', message: emailCodeErrorMessage(error) });\n return null;\n }\n },\n [passflow, enter],\n );\n\n const resend = useCallback(async (): Promise<PassflowAuthorizationResponse | null> => {\n const repeat = optionsRef.current.resend;\n if (!repeat || stepRef.current.kind !== 'code' || verifyingRef.current || resendingRef.current) return null;\n const epoch = epochRef.current;\n resendingRef.current = true;\n setIsResending(true);\n\n try {\n const answer = await repeat();\n if (epoch !== epochRef.current) return null;\n const next = readEmailVerificationStep(answer);\n if (next?.kind === 'code') dispatch({ type: 'RESENT', challengeId: next.challengeId, message: next.message });\n else if (next?.kind === 'link') {\n dispatch({ type: 'LINK_SENT', message: next.message });\n optionsRef.current.onRelease?.();\n } else {\n // The repeated request signed the user in (the address was verified meanwhile).\n optionsRef.current.onRelease?.();\n return (answer ?? null) as PassflowAuthorizationResponse | null;\n }\n return null;\n } catch (error) {\n if (epoch !== epochRef.current) return null;\n console.error('[passflow] email code resend failed', error);\n dispatch({ type: 'RESEND_FAILED', message: emailCodeErrorMessage(error) });\n return null;\n } finally {\n if (epoch === epochRef.current) {\n resendingRef.current = false;\n setIsResending(false);\n }\n }\n }, []);\n\n const cancel = useCallback(() => {\n if (verifyingRef.current) return;\n const leaving = stepRef.current;\n epochRef.current += 1;\n resendingRef.current = false;\n setIsResending(false);\n dispatch({ type: 'CANCEL' });\n // A code step on a PKCE app holds a verifier for /auth/validate; the user gave up on it. This public call also\n // clears a pending second factor, which a code step never has.\n if (leaving.kind === 'code') passflow.twoFactor?.clearPartialAuthState();\n optionsRef.current.onRelease?.();\n }, [passflow]);\n\n return {\n step: state.step,\n enter,\n verify,\n resend,\n canResend: Boolean(options.resend) && state.step.kind === 'code',\n cancel,\n isVerifying,\n isResending,\n error: state.error,\n };\n};\n","import type { PassflowSendPasswordResetEmailPayload } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseForgotPasswordProps = () => {\n fetch: (payload: PassflowSendPasswordResetEmailPayload) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n reset: () => void;\n};\n\nexport const useForgotPassword: UseForgotPasswordProps = () => {\n const passflow = usePassflow();\n const [isError, setIsError] = useState(false);\n const [errorMessage, setErrorMessage] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (payload: PassflowSendPasswordResetEmailPayload): Promise<boolean> => {\n try {\n setIsLoading(true);\n await passflow.sendPasswordResetEmail(payload);\n setIsLoading(false);\n return true;\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n return false;\n }\n },\n [passflow.sendPasswordResetEmail],\n );\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n };\n\n return { fetch, isLoading, isError, error: errorMessage, reset } as const;\n};\n","import { useCallback, useState } from 'react';\nimport { invitationJoinErrorFrom } from '@/utils';\nimport { usePassflow } from './use-passflow';\n\nexport type UseJoinInviteProps = () => {\n fetch: (token: string) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\nexport const useJoinInvite: UseJoinInviteProps = () => {\n const passflow = usePassflow();\n const [errorMessage, setErrorMessage] = useState('');\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (token: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n\n try {\n await passflow.joinInvitation(token);\n return true;\n } catch (error) {\n console.error('[passflow] accepting invitation failed', error);\n setIsError(true);\n setErrorMessage(invitationJoinErrorFrom(error));\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow.joinInvitation],\n );\n\n return { fetch, isLoading, isError, error: errorMessage } as const;\n};\n","import type { LogOutOptions } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseLogoutProps = () => {\n /** After a hosted sign-in core leaves the page once signed out, so code after `await fetch()` may not run. */\n fetch: (options?: LogOutOptions) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\nexport const useLogout: UseLogoutProps = () => {\n const passflow = usePassflow();\n const [errorMessage, setErrorMessage] = useState('');\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (options?: LogOutOptions): Promise<boolean> => {\n try {\n setIsLoading(true);\n await passflow.logOut(options);\n setIsLoading(false);\n return true;\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n return false;\n }\n },\n [passflow],\n );\n\n return { fetch, isLoading, isError, error: errorMessage } as const;\n};\n","import qs from 'query-string';\nimport { useCallback, useContext } from 'react';\nimport { type NavigateFunction, type NavigateOptions, NavigationContext } from '@/context';\n\nexport type ReactRouterNavigateOptions = {\n pathname: string;\n search: string;\n replace?: boolean;\n};\n\nexport type TanstackRouterNavigateOptions = {\n to: string;\n search: Record<string, unknown>;\n replace?: boolean;\n};\n\nexport type WouterNavigateOptions = {\n to: string;\n search?: Record<string, unknown>;\n replace?: boolean;\n};\n\nexport type ReachRouterNavigateOptions = {\n to: string;\n search?: Record<string, unknown>;\n replace?: boolean;\n};\n\nconst parseSearch = (search: string): Record<string, string> => {\n if (!search) return {};\n const parsed = qs.parse(search.startsWith('?') ? search.slice(1) : search);\n return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));\n};\n\nexport const useNavigation = () => {\n const { navigate, setNavigate, router, twoFactorVerifyPath, setTwoFactorVerifyPath, signInPath, setSignInPath } =\n useContext(NavigationContext);\n\n const wrappedSetNavigate = useCallback(\n (\n newNavigate:\n | ((\n to:\n | NavigateOptions\n | string\n | ReactRouterNavigateOptions\n | TanstackRouterNavigateOptions\n | WouterNavigateOptions\n | ReachRouterNavigateOptions,\n ) => void)\n | null,\n ) => {\n if (!newNavigate) {\n setNavigate(null);\n return;\n }\n\n const wrappedNavigate = ((options: NavigateOptions) => {\n const { to, search = '', replace = false } = options;\n\n switch (router) {\n case 'react-router':\n newNavigate({\n pathname: to,\n search: search.startsWith('?') ? search : `?${search}`,\n replace,\n } as ReactRouterNavigateOptions);\n break;\n\n case 'tanstack-router':\n newNavigate({\n to,\n search: parseSearch(search),\n replace,\n } as TanstackRouterNavigateOptions);\n break;\n\n case 'wouter': {\n const searchParamWouter = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n newNavigate({ to: `${to}${searchParamWouter}`, replace } as WouterNavigateOptions);\n break;\n }\n\n default: {\n // default router\n const searchParamDefault = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n if (replace) {\n window.location.replace(`${to}${searchParamDefault}`);\n } else {\n window.location.href = `${to}${searchParamDefault}`;\n }\n }\n }\n }) as NavigateFunction;\n\n setNavigate(wrappedNavigate);\n },\n [setNavigate, router],\n );\n\n return {\n navigate,\n setNavigate: wrappedSetNavigate,\n router,\n twoFactorVerifyPath,\n setTwoFactorVerifyPath,\n signInPath,\n setSignInPath,\n };\n};\n","import { type RefObject, useEffect } from 'react';\n\nexport const useOutsideClick = <T extends HTMLElement>(ref: RefObject<T | null>, onClickOutside?: () => void) => {\n useEffect(() => {\n const handleClick = (event: MouseEvent) => {\n if (ref.current && !ref.current.contains(event.target as Node)) {\n if (onClickOutside) {\n onClickOutside();\n }\n }\n };\n\n document.addEventListener('click', handleClick, true);\n\n return () => {\n document.removeEventListener('click', handleClick, true);\n };\n }, [onClickOutside, ref]);\n};\n","import type { Passflow, PassflowEvent, PassflowEventPayload, PassflowSubscriber, Tokens } from '@passflow/core';\nimport { useSyncExternalStore } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport function usePassflowStore(events?: PassflowEvent[]) {\n const passflow = usePassflow();\n const passflowSnapshot = useSyncExternalStore(subscribe(passflow, events), getSnapshot(passflow), getServerSnapshot);\n return passflowSnapshot;\n}\n\n// wrapper around react's subscribe\nfunction subscribe(passflow: Passflow, event?: PassflowEvent[]): (onStoreChange: () => void) => () => void {\n return (onStoreChange: () => void): (() => void) => {\n const bscr = subscriber(onStoreChange);\n passflow.subscribe(bscr, event);\n return () => {\n passflow.unsubscribe(bscr);\n };\n };\n}\n\nfunction subscriber(onStoreChange: () => void): PassflowSubscriber {\n return {\n onAuthChange: <E extends PassflowEvent>(_eventType: E, _payload?: PassflowEventPayload[E]) => {\n onStoreChange();\n },\n };\n}\n\nfunction getSnapshot(passflow: Passflow): () => Tokens | undefined {\n return () => {\n return passflow.getCachedTokens();\n };\n}\n\n// The server has no session; hydration renders with this, then switches to the cached tokens.\nfunction getServerSnapshot(): Tokens | undefined {\n return undefined;\n}\n","import type { PassflowPasswordlessSignInCompletePayload, PassflowValidationResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { passwordlessCompleteErrorMessage } from '@/utils';\nimport { usePassflow } from './use-passflow';\n\nexport type UsePasswordlessCompleteProps = () => {\n fetch: (payload: PassflowPasswordlessSignInCompletePayload) => Promise<PassflowValidationResponse | null>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n reset: () => void;\n};\n\nexport const usePasswordlessComplete: UsePasswordlessCompleteProps = () => {\n const passflow = usePassflow();\n const [errorMessage, setErrorMessage] = useState('');\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n\n try {\n return await passflow.passwordlessSignInComplete(payload);\n } catch (error) {\n console.error('[passflow] passwordless verification failed', error);\n setIsError(true);\n setErrorMessage(passwordlessCompleteErrorMessage(error));\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n };\n\n return {\n fetch,\n isLoading,\n isError,\n error: errorMessage,\n reset,\n } as const;\n};\n","import type { PassflowFederatedAuthPayload, Providers } from '@passflow/core';\nimport { useContext } from 'react';\nimport { PassflowContext } from '@/context';\nimport type { FederatedLanding } from '@/types';\nimport { isValidUrl, readParentChallengeIdFromURL } from '@/utils';\nimport { handOffScopes } from '@/utils/hand-off';\nimport { usePassflow } from './use-passflow';\n\nconst getFullRedirectUrl = (redirectUrl?: string): string => {\n if (redirectUrl && isValidUrl(redirectUrl)) {\n return redirectUrl;\n }\n return redirectUrl ? `${window.location.origin}${redirectUrl.startsWith('/') ? '' : '/'}${redirectUrl}` : '';\n};\n\n/**\n * The login page itself as the federated landing: it keeps the code, exchanges it and forwards. No trailing slash and\n * nothing else in the query, because the server refuses anything but this exact shape, an empty `redirectto=` too.\n */\nconst getLoginPageLandingUrl = (appId: string, redirectUrl?: string): string => {\n const { origin, pathname } = window.location;\n const target = getFullRedirectUrl(redirectUrl);\n const redirectTo = target ? `&redirectto=${encodeURIComponent(target)}` : '';\n return `${origin}${pathname.replace(/\\/+$/, '') || '/'}?appid=${encodeURIComponent(appId)}${redirectTo}`;\n};\n\nconst withoutUndefined = <T extends Record<string, unknown>>(value: T): Partial<T> =>\n Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as Partial<T>;\n\nexport type UseProviderProps = (\n redirectUrl?: string,\n createTenant?: boolean,\n federatedLanding?: FederatedLanding,\n) => {\n federatedWithPopup: (provider: Providers, inviteToken?: string) => void;\n federatedWithRedirect: (provider: Providers, inviteToken?: string) => void;\n};\n\nexport const useProvider: UseProviderProps = (redirectUrl, createTenant, federatedLanding = 'app') => {\n const passflow = usePassflow();\n const context = useContext(PassflowContext);\n const appId = context?.state.appId;\n const landsOnLoginPage =\n federatedLanding === 'login-page' && Boolean(context?.state.appSettings?.pkce_enabled) && !readParentChallengeIdFromURL();\n\n // The app's mode as the sign-in form already loaded it: the start must not wait for a settings read. In Simple mode\n // the tokens go back to the app, so they get the scopes it asked for and its state. In SDK mode this sign-in only\n // starts the hosted session, which then issues the app its code, so it uses the sign-in scopes. Unknown is not Simple\n // for the state, which is echoed only in Simple mode.\n const handOff = context?.state.handOff;\n const pkceEnabled = context?.state.appSettings?.pkce_enabled;\n const scopes = handOff && pkceEnabled !== true ? handOffScopes(handOff) : context?.state.scopes;\n\n const payload = withoutUndefined({\n redirect_url: landsOnLoginPage && appId ? getLoginPageLandingUrl(appId, redirectUrl) : getFullRedirectUrl(redirectUrl),\n scopes,\n create_tenant: createTenant,\n state: pkceEnabled === false ? handOff?.state : undefined,\n parent_challenge_id: readParentChallengeIdFromURL(),\n });\n\n const federatedWithPopup = (provider: Providers, inviteToken?: string) =>\n passflow.federatedAuthWithPopup({ provider, invite_token: inviteToken, ...payload } as PassflowFederatedAuthPayload);\n const federatedWithRedirect = (provider: Providers, inviteToken?: string) =>\n passflow.federatedAuthWithRedirect({ provider, invite_token: inviteToken, ...payload } as PassflowFederatedAuthPayload);\n\n return {\n federatedWithPopup,\n federatedWithRedirect,\n };\n};\n","import { PassflowEvent, type PassflowEventPayload, type PassflowSubscriber } from '@passflow/core';\nimport { useEffect, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport interface UseRefreshStatusResult {\n /**\n * True inside a transient-failure episode: a token refresh failed for a reason that\n * does not end the session (network, 5xx) and core is retrying. The session is kept.\n */\n isFailing: boolean;\n /**\n * Epoch ms of the episode's first transient failure (`RefreshFailing.since`).\n */\n since: number | null;\n /**\n * Epoch ms of the pending retry, when core knows it (`RefreshFailing.nextRetryAt`).\n */\n nextRetryAt: number | null;\n}\n\nconst IDLE: UseRefreshStatusResult = { isFailing: false, since: null, nextRetryAt: null };\n\nconst EVENTS = [\n PassflowEvent.RefreshFailing,\n PassflowEvent.RefreshRecovered,\n PassflowEvent.SessionExpired,\n PassflowEvent.SignOut,\n PassflowEvent.SignIn,\n PassflowEvent.Register,\n];\n\n/**\n * Hook to show a \"connection trouble\" notice while token refresh is failing transiently.\n *\n * Set by `RefreshFailing`; cleared by `RefreshRecovered`, and by `SessionExpired`,\n * `SignOut`, `SignIn` and `Register`, which end or replace the session the episode\n * belonged to. A real end of the session is reported by `useSessionExpired`, not here.\n *\n * Core reports the episode only as events (there is no getter to read on mount), so a\n * component that mounts after `RefreshFailing` starts idle. Call the hook in a component\n * that lives for the whole app, near `PassflowProvider`.\n *\n * @example\n * ```tsx\n * function ConnectionNotice() {\n * const { isFailing } = useRefreshStatus();\n * return isFailing ? <Banner>Reconnecting...</Banner> : null;\n * }\n * ```\n */\nexport function useRefreshStatus(): UseRefreshStatusResult {\n const passflow = usePassflow();\n const [status, setStatus] = useState<UseRefreshStatusResult>(IDLE);\n\n useEffect(() => {\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.RefreshFailing) {\n const failing = payload as PassflowEventPayload[PassflowEvent.RefreshFailing] | undefined;\n setStatus({\n isFailing: true,\n since: failing?.since ?? null,\n nextRetryAt: failing?.nextRetryAt ?? null,\n });\n } else {\n setStatus(IDLE);\n }\n },\n };\n\n passflow.subscribe(subscriber, EVENTS);\n\n return () => {\n passflow.unsubscribe(subscriber);\n };\n }, [passflow]);\n\n return status;\n}\n","import { useCallback, useState } from 'react';\nimport { isPasswordSavedRateLimit, newPasswordErrorMessage } from '@/utils';\nimport { type UseEmailCodeStep, useEmailCodeStep } from './use-email-code-step';\nimport { usePassflow } from './use-passflow';\n\nexport type UseResetPasswordProps = () => {\n /**\n * Saves the new password. Pass the reset link's `token` when you have it: without it core looks for `?token=` in\n * the address bar, which a hash or memory router does not keep. Resolves `true` for a session, `false` on an error\n * or when the server asks for an emailed code first (`emailCode` then holds the step).\n */\n fetch: (newPassword: string, resetToken?: string) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n error: string;\n /**\n * The password was changed, but the emailed code that should follow was refused for now (429). Asking for the\n * password again would be wrong: the user should sign in with it later.\n */\n isPasswordSaved: boolean;\n reset: () => void;\n /** The emailed-code step a password change may answer with. No resend: the reset link is spent. */\n emailCode: UseEmailCodeStep;\n};\n\nexport const useResetPassword: UseResetPasswordProps = () => {\n const passflow = usePassflow();\n const [isError, setIsError] = useState(false);\n const [errorMessage, setErrorMessage] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const [isPasswordSaved, setIsPasswordSaved] = useState(false);\n const emailCode = useEmailCodeStep();\n\n const fetch = useCallback(\n async (newPassword: string, resetToken?: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n const answer = resetToken\n ? await passflow.resetPassword(newPassword, undefined, resetToken)\n : await passflow.resetPassword(newPassword);\n return !emailCode.enter(answer);\n } catch (e) {\n console.error('[passflow] password change failed', e);\n setIsError(true);\n setErrorMessage(newPasswordErrorMessage(e));\n setIsPasswordSaved(isPasswordSavedRateLimit(e));\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow.resetPassword, emailCode.enter],\n );\n\n const reset = () => {\n setIsError(false);\n setErrorMessage('');\n setIsLoading(false);\n setIsPasswordSaved(false);\n };\n\n return { fetch, isLoading, isError, error: errorMessage, isPasswordSaved, reset, emailCode } as const;\n};\n","import { PassflowEvent, type PassflowSubscriber, type SessionExpiredReason } from '@passflow/core';\nimport { useEffect, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport interface UseSessionExpiredOptions {\n /**\n * Called when the session expires.\n * Use this to redirect to your login page.\n */\n onSessionExpired?: (reason: SessionExpiredReason) => void;\n}\n\nexport interface UseSessionExpiredResult {\n /**\n * True if the session has expired and user needs to re-authenticate.\n */\n isSessionExpired: boolean;\n /**\n * The reason why the session expired, if applicable.\n */\n expiredReason: SessionExpiredReason | null;\n /**\n * Reset the session expired state (e.g., after redirecting to login).\n */\n resetSessionExpired: () => void;\n}\n\n/**\n * Hook to handle session expiration events.\n *\n * Core emits SessionExpired only when the session has really ended: the last\n * auth strike (`'refresh_failed'`), no successor token pair in time\n * (`'successor_timeout'`), or another user's tokens in storage\n * (`'identity_changed'`). A transient refresh failure (network, 5xx) keeps the\n * session and is reported as RefreshFailing / RefreshRecovered instead; see\n * `useRefreshStatus`. This hook lets you react to the real end and redirect\n * users to your login page.\n *\n * @example\n * ```tsx\n * function App() {\n * const { isSessionExpired } = useSessionExpired({\n * onSessionExpired: (reason) => {\n * console.log('Session expired:', reason);\n * window.location.href = '/login';\n * },\n * });\n *\n * if (isSessionExpired) {\n * return <div>Redirecting to login...</div>;\n * }\n *\n * return <YourApp />;\n * }\n * ```\n */\nexport function useSessionExpired(options?: UseSessionExpiredOptions): UseSessionExpiredResult {\n const passflow = usePassflow();\n const [isSessionExpired, setIsSessionExpired] = useState(false);\n const [expiredReason, setExpiredReason] = useState<SessionExpiredReason | null>(null);\n\n useEffect(() => {\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.SessionExpired) {\n const reason = (payload as { reason?: SessionExpiredReason })?.reason ?? 'refresh_failed';\n setIsSessionExpired(true);\n setExpiredReason(reason);\n options?.onSessionExpired?.(reason);\n } else if (eventType === PassflowEvent.SignIn || eventType === PassflowEvent.Register) {\n // Reset on successful auth\n setIsSessionExpired(false);\n setExpiredReason(null);\n }\n },\n };\n\n passflow.subscribe(subscriber, [PassflowEvent.SessionExpired, PassflowEvent.SignIn, PassflowEvent.Register]);\n\n return () => {\n passflow.unsubscribe(subscriber);\n };\n }, [passflow, options?.onSessionExpired]);\n\n const resetSessionExpired = () => {\n setIsSessionExpired(false);\n setExpiredReason(null);\n };\n\n return {\n isSessionExpired,\n expiredReason,\n resetSessionExpired,\n };\n}\n","/* eslint-disable react/jsx-props-no-spreading */\nimport { forwardRef, type InputHTMLAttributes } from 'react';\nimport '@/styles/index.css';\nimport { cn } from '@/utils';\n\ntype TFieldText = InputHTMLAttributes<HTMLInputElement> & {\n id: string;\n isError?: boolean;\n className?: string;\n disabled?: boolean;\n};\n\nexport const FieldText = forwardRef<HTMLInputElement, TFieldText>(\n ({ id, isError = false, className = '', disabled = false, ...rest }, ref) => {\n const styles = {\n 'passflow-field--error': isError,\n };\n\n return (\n <input\n ref={ref}\n id={id}\n type='text'\n className={cn('passflow-field-input passflow-field--focused', styles, className)}\n disabled={disabled}\n {...rest}\n />\n );\n },\n);\n","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='6'%20fill='%23F3F5F7'/%3e%3cg%20clip-path='url(%23clip0_2691_4741)'%3e%3cpath%20d='M21.9999%2019.3334C20.5272%2019.3334%2019.3333%2020.5273%2019.3333%2022C19.3333%2023.4728%2020.5272%2024.6667%2021.9999%2024.6667C23.4727%2024.6667%2024.6666%2023.4728%2024.6666%2022C24.6666%2020.5273%2023.4727%2019.3334%2021.9999%2019.3334ZM21.9999%2019.3334H28.1133M16.6333%2018.04L19.6933%2023.3334M21.2533%2028.6267L24.3066%2023.3334M28.6666%2022C28.6666%2025.6819%2025.6818%2028.6667%2021.9999%2028.6667C18.318%2028.6667%2015.3333%2025.6819%2015.3333%2022C15.3333%2018.3181%2018.318%2015.3334%2021.9999%2015.3334C25.6818%2015.3334%2028.6666%2018.3181%2028.6666%2022Z'%20stroke='%237F7F7F'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2691_4741'%3e%3crect%20width='16'%20height='16'%20fill='white'%20transform='translate(14%2014)'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M4%206L8%2010L12%206H4Z'%20fill='%236B6F76'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M4%208L6.82843%2010.8284L12.4847%205.17155'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M10.6666%2010.6667L7.99993%208.00001M7.99993%208.00001L5.33325%205.33333M7.99993%208.00001L10.6666%205.33333M7.99993%208.00001L5.33325%2010.6667'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.00004%208.66667C8.36823%208.66667%208.66671%208.36819%208.66671%208C8.66671%207.63181%208.36823%207.33333%208.00004%207.33333C7.63185%207.33333%207.33337%207.63181%207.33337%208C7.33337%208.36819%207.63185%208.66667%208.00004%208.66667Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3cpath%20d='M8.00004%204C8.36823%204%208.66671%203.70152%208.66671%203.33333C8.66671%202.96514%208.36823%202.66667%208.00004%202.66667C7.63185%202.66667%207.33337%202.96514%207.33337%203.33333C7.33337%203.70152%207.63185%204%208.00004%204Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3cpath%20d='M8.00004%2013.3333C8.36823%2013.3333%208.66671%2013.0349%208.66671%2012.6667C8.66671%2012.2985%208.36823%2012%208.00004%2012C7.63185%2012%207.33337%2012.2985%207.33337%2012.6667C7.33337%2013.0349%207.63185%2013.3333%208.00004%2013.3333Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.6231%206.86026L9.13975%204.37687M2%2014L4.10117%2013.7665C4.35789%2013.738%204.48624%2013.7238%204.60622%2013.6849C4.71266%2013.6505%204.81395%2013.6018%204.90735%2013.5402C5.01263%2013.4708%205.10395%2013.3794%205.28659%2013.1968L13.4857%204.99772C14.1714%204.31195%2014.1714%203.2001%2013.4857%202.51433C12.7999%201.82856%2011.6881%201.82856%2011.0023%202.51433L2.80321%2010.7134C2.62056%2010.896%202.52924%2010.9874%202.45982%2011.0926C2.39823%2011.186%202.34955%2011.2873%202.31509%2011.3938C2.27625%2011.5138%202.26199%2011.6421%202.23346%2011.8988L2%2014Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M7.16196%203.39488C7.4329%203.35482%207.7124%203.33333%208.00028%203.33333C11.4036%203.33333%2013.6369%206.33656%2014.3871%207.52455C14.4779%207.66833%2014.5233%207.74023%2014.5488%207.85112C14.5678%207.93439%2014.5678%208.06578%2014.5487%208.14905C14.5233%208.25993%2014.4776%208.3323%2014.3861%208.47705C14.1862%208.79343%2013.8814%209.23807%2013.4777%209.7203M4.48288%204.47669C3.0415%205.45447%202.06297%206.81292%201.61407%207.52352C1.52286%207.66791%201.47725%207.74011%201.45183%207.85099C1.43273%207.93426%201.43272%208.06563%201.45181%208.14891C1.47722%208.25979%201.52262%208.33168%201.61342%208.47545C2.36369%209.66344%204.59694%2012.6667%208.00028%2012.6667C9.37255%2012.6667%2010.5546%2012.1784%2011.5259%2011.5177M2.00028%202L14.0003%2014M6.58606%206.58579C6.22413%206.94772%206.00028%207.44772%206.00028%208C6.00028%209.10457%206.89571%2010%208.00028%2010C8.55256%2010%209.05256%209.77614%209.41449%209.41421'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M1.61342%208.47545C1.52262%208.33169%201.47723%208.25981%201.45182%208.14895C1.43273%208.06567%201.43273%207.93434%201.45182%207.85106C1.47723%207.74019%201.52262%207.66831%201.61341%207.52455C2.36369%206.33656%204.59693%203.33334%208.00027%203.33334C11.4036%203.33334%2013.6369%206.33656%2014.3871%207.52455C14.4779%207.66831%2014.5233%207.74019%2014.5487%207.85106C14.5678%207.93434%2014.5678%208.06567%2014.5487%208.14895C14.5233%208.25981%2014.4779%208.33169%2014.3871%208.47545C13.6369%209.66344%2011.4036%2012.6667%208.00027%2012.6667C4.59693%2012.6667%202.36369%209.66344%201.61342%208.47545Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3cpath%20d='M8.00027%2010C9.10484%2010%2010.0003%209.10457%2010.0003%208C10.0003%206.89543%209.10484%206%208.00027%206C6.8957%206%206.00027%206.89543%206.00027%208C6.00027%209.10457%206.8957%2010%208.00027%2010Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.1111%206.1333C11.1111%205.81483%2010.9896%205.49636%2010.7466%205.25338C10.5037%205.01039%2010.1852%204.88889%209.86669%204.88889M9.86669%209.86667C11.9286%209.86667%2013.6%208.1952%2013.6%206.13333C13.6%204.07147%2011.9286%202.4%209.86669%202.4C7.80483%202.4%206.13336%204.07147%206.13336%206.13333C6.13336%206.30362%206.14476%206.47125%206.16684%206.63549C6.20316%206.90562%206.22131%207.04069%206.20909%207.12615C6.19636%207.21516%206.18015%207.26313%206.13627%207.34163C6.09416%207.41698%206.01993%207.4912%205.87148%207.63965L2.69162%2010.8195C2.584%2010.9271%202.53019%2010.9809%202.49171%2011.0437C2.4576%2011.0994%202.43246%2011.1601%202.41722%2011.2236C2.40002%2011.2952%202.40002%2011.3713%202.40002%2011.5235V12.6044C2.40002%2012.9529%202.40002%2013.1272%202.46784%2013.2603C2.5275%2013.3773%202.62269%2013.4725%202.73976%2013.5322C2.87286%2013.6%203.0471%2013.6%203.39558%2013.6H4.88891V12.3556H6.13336V11.1111H7.3778L8.36037%2010.1285C8.50882%209.98009%208.58305%209.90587%208.6584%209.86375C8.73689%209.81988%208.78486%209.80367%208.87388%209.79093C8.95933%209.77871%209.0944%209.79687%209.36453%209.83319C9.52878%209.85527%209.6964%209.86667%209.86669%209.86667Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='43'%20height='10'%20viewBox='0%200%2043%2010'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.91%209H5.346L5.236%207.988H3.674L3.564%209H0L2.178%200.53H6.732L8.91%209ZM4.158%203.665L4.037%204.721H4.873L4.752%203.665H4.158ZM16.6389%206.712C16.5215%207.482%2016.1145%208.087%2015.4179%208.527C14.7212%208.95967%2013.8082%209.176%2012.6789%209.176C11.5495%209.176%2010.6365%208.95967%209.93988%208.527C9.25054%208.09433%208.84354%207.49667%208.71888%206.734C8.68954%206.52867%208.66388%206.25367%208.64188%205.909C8.62721%205.557%208.61988%205.17933%208.61988%204.776C8.61988%204.38733%208.62721%204.028%208.64188%203.698C8.66388%203.36067%208.68954%203.09667%208.71888%202.906C8.84354%202.09933%209.25421%201.47233%209.95088%201.025C10.6475%200.577666%2011.5569%200.354%2012.6789%200.354C13.8082%200.354%2014.7212%200.577666%2015.4179%201.025C16.1145%201.465%2016.5215%202.07733%2016.6389%202.862C16.6682%203.05267%2016.6902%203.31667%2016.7049%203.654C16.7269%203.984%2016.7379%204.347%2016.7379%204.743C16.7379%205.161%2016.7269%205.54233%2016.7049%205.887C16.6902%206.23167%2016.6682%206.50667%2016.6389%206.712ZM12.9759%206.206V3.324C12.9759%203.126%2012.8769%203.027%2012.6789%203.027C12.4809%203.027%2012.3819%203.126%2012.3819%203.324V6.206C12.3819%206.404%2012.4809%206.503%2012.6789%206.503C12.8769%206.503%2012.9759%206.404%2012.9759%206.206ZM25.1574%206.712C25.0401%207.482%2024.6331%208.087%2023.9364%208.527C23.2398%208.95967%2022.3268%209.176%2021.1974%209.176C20.0681%209.176%2019.1551%208.95967%2018.4584%208.527C17.7691%208.09433%2017.3621%207.49667%2017.2374%206.734C17.2081%206.52867%2017.1824%206.25367%2017.1604%205.909C17.1458%205.557%2017.1384%205.17933%2017.1384%204.776C17.1384%204.38733%2017.1458%204.028%2017.1604%203.698C17.1824%203.36067%2017.2081%203.09667%2017.2374%202.906C17.3621%202.09933%2017.7728%201.47233%2018.4694%201.025C19.1661%200.577666%2020.0754%200.354%2021.1974%200.354C22.3268%200.354%2023.2398%200.577666%2023.9364%201.025C24.6331%201.465%2025.0401%202.07733%2025.1574%202.862C25.1868%203.05267%2025.2088%203.31667%2025.2234%203.654C25.2454%203.984%2025.2564%204.347%2025.2564%204.743C25.2564%205.161%2025.2454%205.54233%2025.2234%205.887C25.2088%206.23167%2025.1868%206.50667%2025.1574%206.712ZM21.4944%206.206V3.324C21.4944%203.126%2021.3954%203.027%2021.1974%203.027C20.9994%203.027%2020.9004%203.126%2020.9004%203.324V6.206C20.9004%206.404%2020.9994%206.503%2021.1974%206.503C21.3954%206.503%2021.4944%206.404%2021.4944%206.206ZM33.555%200.53V3.797H31.432V9H27.769V3.797H25.635V0.53H33.555ZM38.4495%202.906V0.53H42.0135V9H38.4495V6.272H37.5585V9H33.9945V0.53H37.5585V2.906H38.4495Z'%20fill='%236B6F76'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='8'%20fill='%231E1E1E'%20/%3e%3cpath%20d='M21.2532%2031H13.6932V12.52H24.9012C25.9252%2012.52%2026.8612%2012.72%2027.7092%2013.12C28.5732%2013.504%2029.2612%2014.184%2029.7732%2015.16C30.2852%2016.12%2030.5412%2017.456%2030.5412%2019.168C30.5412%2020.848%2030.2772%2022.184%2029.7492%2023.176C29.2212%2024.152%2028.5252%2024.856%2027.6612%2025.288C26.8132%2025.704%2025.8932%2025.912%2024.9012%2025.912H21.2532V31ZM23.1252%2018.592H20.8212V19.888H23.1972C23.3252%2019.888%2023.4612%2019.848%2023.6052%2019.768C23.7652%2019.688%2023.8452%2019.52%2023.8452%2019.264C23.8452%2018.992%2023.7572%2018.816%2023.5812%2018.736C23.4052%2018.64%2023.2532%2018.592%2023.1252%2018.592Z'%20fill='white'%20/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='8'%20fill='%23D85D5D'%20/%3e%3cpath%20d='M21.2532%2031H13.6932V12.52H24.9012C25.9252%2012.52%2026.8612%2012.72%2027.7092%2013.12C28.5732%2013.504%2029.2612%2014.184%2029.7732%2015.16C30.2852%2016.12%2030.5412%2017.456%2030.5412%2019.168C30.5412%2020.848%2030.2772%2022.184%2029.7492%2023.176C29.2212%2024.152%2028.5252%2024.856%2027.6612%2025.288C26.8132%2025.704%2025.8932%2025.912%2024.9012%2025.912H21.2532V31ZM23.1252%2018.592H20.8212V19.888H23.1972C23.3252%2019.888%2023.4612%2019.848%2023.6052%2019.768C23.7652%2019.688%2023.8452%2019.52%2023.8452%2019.264C23.8452%2018.992%2023.7572%2018.816%2023.5812%2018.736C23.4052%2018.64%2023.2532%2018.592%2023.1252%2018.592Z'%20fill='white'%20/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M1.33337%204.66666L6.77665%208.47696C7.21743%208.78551%207.43783%208.93978%207.67755%208.99954C7.8893%209.05232%208.11078%209.05232%208.32253%208.99954C8.56226%208.93978%208.78265%208.78551%209.22343%208.47696L14.6667%204.66666M4.53337%2013.3333H11.4667C12.5868%2013.3333%2013.1469%2013.3333%2013.5747%2013.1153C13.951%2012.9236%2014.257%2012.6176%2014.4487%2012.2413C14.6667%2011.8135%2014.6667%2011.2534%2014.6667%2010.1333V5.86666C14.6667%204.74656%2014.6667%204.18651%2014.4487%203.75868C14.257%203.38236%2013.951%203.0764%2013.5747%202.88465C13.1469%202.66666%2012.5868%202.66666%2011.4667%202.66666H4.53337C3.41327%202.66666%202.85322%202.66666%202.42539%202.88465C2.04907%203.0764%201.74311%203.38236%201.55136%203.75868C1.33337%204.18651%201.33337%204.74656%201.33337%205.86666V10.1333C1.33337%2011.2534%201.33337%2011.8135%201.55136%2012.2413C1.74311%2012.6176%202.04907%2012.9236%202.42539%2013.1153C2.85322%2013.3333%203.41327%2013.3333%204.53337%2013.3333Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='6'%20fill='%23F3F5F7'/%3e%3cg%20clip-path='url(%23clip0_2691_4730)'%3e%3cpath%20d='M20.8039%2020.4084V18.2344C20.8039%2017.9893%2021.0026%2017.7906%2021.2477%2017.7906H22.7785C23.0236%2017.7906%2023.2222%2017.9893%2023.2222%2018.2344V22.2139C23.2222%2022.2748%2023.1918%2022.3212%2023.1614%2022.3669L22.7785%2022.7498C22.6864%2022.8419%2022.6864%2022.9797%2022.7785%2023.0558L23.1614%2023.4386C23.1819%2023.4582%2023.198%2023.4821%2023.2086%2023.5085C23.2191%2023.5349%2023.2237%2023.5633%2023.2222%2023.5916V25.7648C23.2222%2025.8825%2023.1755%2025.9954%2023.0923%2026.0786C23.009%2026.1618%2022.8962%2026.2086%2022.7785%2026.2086H21.2477C21.13%2026.2086%2021.0171%2026.1618%2020.9339%2026.0786C20.8507%2025.9954%2020.8039%2025.8825%2020.8039%2025.7648V21.7853C20.8039%2021.7244%2020.8344%2021.678%2020.8648%2021.6323L21.2477%2021.2494C21.3398%2021.1573%2021.3398%2021.0195%2021.2477%2020.9434L20.8648%2020.5606C20.8443%2020.5411%2020.8282%2020.5174%2020.8177%2020.4911C20.8072%2020.4649%2020.8025%2020.4366%2020.8039%2020.4084ZM27.7064%2022C27.7064%2021.2503%2027.5587%2020.5079%2027.2718%2019.8153C26.9849%2019.1227%2026.5644%2018.4933%2026.0343%2017.9632C25.5042%2017.4331%2024.8748%2017.0126%2024.1822%2016.7257C23.4895%2016.4388%2022.7472%2016.2911%2021.9975%2016.2911C21.2478%2016.2911%2020.5054%2016.4388%2019.8128%2016.7257C19.1201%2017.0126%2018.4908%2017.4331%2017.9607%2017.9632C17.4305%2018.4933%2017.01%2019.1227%2016.7231%2019.8153C16.4362%2020.5079%2016.2886%2021.2503%2016.2886%2022C16.2886%2023.5141%2016.89%2024.9662%2017.9607%2026.0368C19.0313%2027.1074%2020.4834%2027.7089%2021.9975%2027.7089C23.5116%2027.7089%2024.9637%2027.1074%2026.0343%2026.0368C27.1049%2024.9662%2027.7064%2023.5141%2027.7064%2022ZM29.5127%2022C29.5127%2026.1477%2026.1452%2029.5%2022.0127%2029.5C17.865%2029.5%2014.5127%2026.1325%2014.5127%2022C14.5127%2017.8523%2017.8802%2014.5%2022.0127%2014.5C26.1452%2014.5%2029.5127%2017.8523%2029.5127%2022Z'%20fill='%237F7F7F'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2691_4730'%3e%3crect%20width='16'%20height='16'%20fill='white'%20transform='translate(14%2014)'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='44'%20height='44'%20viewBox='0%200%2044%2044'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='44'%20height='44'%20rx='6'%20fill='%23F3F5F7'/%3e%3cpath%20d='M25.3333%2020C25.3333%2019.6587%2025.2031%2019.3175%2024.9428%2019.0572C24.6825%2018.7968%2024.3412%2018.6667%2024%2018.6667M24%2024C26.2091%2024%2028%2022.2091%2028%2020C28%2017.7909%2026.2091%2016%2024%2016C21.7909%2016%2020%2017.7909%2020%2020C20%2020.1825%2020.0122%2020.3621%2020.0359%2020.538C20.0748%2020.8275%2020.0942%2020.9722%2020.0811%2021.0637C20.0675%2021.1591%2020.0501%2021.2105%2020.0031%2021.2946C19.958%2021.3753%2019.8785%2021.4549%2019.7194%2021.6139L16.3124%2025.0209C16.1971%2025.1362%2016.1395%2025.1939%2016.0982%2025.2611C16.0617%2025.3208%2016.0348%2025.3858%2016.0184%2025.4538C16%2025.5306%2016%2025.6121%2016%2025.7752V26.9333C16%2027.3067%2016%2027.4934%2016.0727%2027.636C16.1366%2027.7614%2016.2386%2027.8634%2016.364%2027.9273C16.5066%2028%2016.6933%2028%2017.0667%2028H18.6667V26.6667H20V25.3333H21.3333L22.3861%2024.2806C22.5451%2024.1215%2022.6247%2024.042%2022.7054%2023.9969C22.7895%2023.9499%2022.8409%2023.9325%2022.9363%2023.9189C23.0278%2023.9058%2023.1725%2023.9252%2023.462%2023.9641C23.6379%2023.9878%2023.8175%2024%2024%2024Z'%20stroke='%237F7F7F'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='17'%20height='16'%20viewBox='0%200%2017%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.49998%2011.6666H8.50665M5.96665%2014.6666H11.0333C11.78%2014.6666%2012.1534%2014.6666%2012.4386%2014.5213C12.6895%2014.3934%2012.8935%2014.1895%2013.0213%2013.9386C13.1666%2013.6534%2013.1666%2013.28%2013.1666%2012.5333V3.46659C13.1666%202.71985%2013.1666%202.34648%2013.0213%202.06126C12.8935%201.81038%2012.6895%201.60641%2012.4386%201.47858C12.1534%201.33325%2011.78%201.33325%2011.0333%201.33325H5.96665C5.21991%201.33325%204.84654%201.33325%204.56133%201.47858C4.31044%201.60641%204.10647%201.81038%203.97864%202.06126C3.83331%202.34648%203.83331%202.71985%203.83331%203.46659V12.5333C3.83331%2013.28%203.83331%2013.6534%203.97864%2013.9386C4.10647%2014.1895%204.31044%2014.3934%204.56133%2014.5213C4.84654%2014.6666%205.21991%2014.6666%205.96665%2014.6666ZM8.83331%2011.6666C8.83331%2011.8507%208.68407%2011.9999%208.49998%2011.9999C8.31588%2011.9999%208.16665%2011.8507%208.16665%2011.6666C8.16665%2011.4825%208.31588%2011.3333%208.49998%2011.3333C8.68407%2011.3333%208.83331%2011.4825%208.83331%2011.6666Z'%20stroke='%237F7F7F'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M14%2014L11.1%2011.1M12.6667%207.33333C12.6667%2010.2789%2010.2789%2012.6667%207.33333%2012.6667C4.38781%2012.6667%202%2010.2789%202%207.33333C2%204.38781%204.38781%202%207.33333%202C10.2789%202%2012.6667%204.38781%2012.6667%207.33333Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M6%202H10M2%204H14M12.6667%204L12.1991%2011.0129C12.129%2012.065%2012.0939%2012.5911%2011.8667%2012.99C11.6666%2013.3412%2011.3648%2013.6235%2011.0011%2013.7998C10.588%2014%2010.0607%2014%209.00623%2014H6.99377C5.93927%2014%205.41202%2014%204.99889%2013.7998C4.63517%2013.6235%204.33339%2013.3412%204.13332%2012.99C3.90607%2012.5911%203.871%2012.065%203.80086%2011.0129L3.33333%204M6.66667%207V10.3333M9.33333%207V10.3333'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_823)'%3e%3cpath%20d='M7.99992%205.33334V8M7.99992%2010.6667H8.00659M14.6666%208C14.6666%2011.6819%2011.6818%2014.6667%207.99992%2014.6667C4.31802%2014.6667%201.33325%2011.6819%201.33325%208C1.33325%204.3181%204.31802%201.33334%207.99992%201.33334C11.6818%201.33334%2014.6666%204.3181%2014.6666%208Z'%20stroke='%236B6F76'%20stroke-width='1.5'%20stroke-linecap='round'%20stroke-linejoin='round'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2502_823'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M13.6167%204.77308C13.5312%204.83608%2012.0218%205.64397%2012.0218%207.44037C12.0218%209.51818%2013.9425%2010.2533%2014%2010.2715C13.9912%2010.3162%2013.6948%2011.2781%2012.9873%2012.2583C12.3564%2013.1207%2011.6976%2013.9818%2010.6952%2013.9818C9.69291%2013.9818%209.43498%2013.4287%208.27784%2013.4287C7.15021%2013.4287%206.74928%2014%205.83245%2014C4.9156%2014%204.27588%2013.2019%203.54034%2012.2218C2.68836%2011.0709%202%209.28291%202%207.58597C2%204.86409%203.86316%203.42054%205.69684%203.42054C6.67116%203.42054%207.48335%204.02821%208.09508%204.02821C8.67726%204.02821%209.58531%203.38414%2010.6937%203.38414C11.1139%203.38414%2012.6233%203.42054%2013.6167%204.77308ZM10.1676%202.23182C10.6259%201.71517%2010.9503%200.998298%2010.9503%200.281428C10.9503%200.182018%2010.9414%200.0812084%2010.9223%200C10.1764%200.0266027%209.28899%200.471848%208.75398%201.0613C8.33385%201.51495%207.94176%202.23182%207.94176%202.95849C7.94176%203.06771%207.96092%203.17691%207.9698%203.21192C8.01697%203.22032%208.09361%203.23012%208.17025%203.23012C8.83946%203.23012%209.68112%202.80448%2010.1676%202.23182Z'%20fill='black'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M5.14981%207.46537C4.94085%207.24181%204.61205%207.2541%204.47223%207.54219L1.03899%2014.4048C1.00767%2014.4674%200.992879%2014.5369%200.996019%2014.6068C0.999159%2014.6768%201.02013%2014.7447%201.05693%2014.8042C1.09373%2014.8637%201.14514%2014.9128%201.20627%2014.9469C1.26741%2014.9809%201.33623%2014.9987%201.4062%2014.9987H6.18693C6.26393%2015.0002%206.33969%2014.9792%206.40492%2014.9382C6.47014%2014.8973%206.52201%2014.8382%206.55414%2014.7682C7.58512%2012.641%206.96054%209.39978%205.14981%207.46537Z'%20fill='url(%23paint0_linear_2502_832)'/%3e%3cpath%20d='M7.66883%201.22039C5.74824%204.2626%205.875%207.63208%207.14029%2010.1611L9.44499%2014.7705C9.47857%2014.8394%209.53076%2014.8975%209.59567%2014.9382C9.66057%2014.979%209.73558%2015.0007%209.81221%2015.001H14.5929C14.6629%2015.001%2014.7317%2014.9832%2014.7929%2014.9492C14.854%2014.9151%2014.9054%2014.866%2014.9422%2014.8065C14.979%2014.747%2015%2014.6791%2015.0031%2014.6092C15.0063%2014.5393%2014.9915%2014.4697%2014.9601%2014.4071C14.9601%2014.4071%208.52849%201.53844%208.37023%201.21808C8.22196%200.929997%207.85474%200.923851%207.66883%201.22039Z'%20fill='%232681FF'/%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_2502_832'%20x1='7.03199'%20y1='8.52553'%20x2='3.40822'%20y2='14.802'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%230052CC'/%3e%3cstop%20offset='0.92'%20stop-color='%232684FF'/%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_831)'%3e%3cpath%20d='M0.519254%200.768994C0.44444%200.768029%200.370321%200.783452%200.302102%200.814182C0.233882%200.84491%200.173216%200.890198%200.124362%200.94687C0.0755086%201.00354%200.0396522%201.07021%200.0193102%201.14222C-0.00103186%201.21422%20-0.00536625%201.28981%200.00661131%201.36366L2.18278%2014.5745C2.2099%2014.7362%202.2931%2014.883%202.41779%2014.9894C2.54249%2015.0959%202.70068%2015.155%202.8646%2015.1563H13.3046C13.4274%2015.1579%2013.5468%2015.1153%2013.6409%2015.0362C13.735%2014.9572%2013.7976%2014.847%2013.8172%2014.7257L15.9934%201.36622C16.0054%201.29237%2016.001%201.21678%2015.9807%201.14478C15.9603%201.07278%2015.9245%201.0061%2015.8756%200.94943C15.8268%200.892766%2015.7661%200.84747%2015.6979%200.816742C15.6297%200.786016%2015.5556%200.770592%2015.4807%200.771557L0.519254%200.768994ZM9.68272%2010.317H6.35057L5.44832%205.60322H10.4902L9.68272%2010.317Z'%20fill='%232684FF'/%3e%3cpath%20d='M15.3013%205.60321H10.4902L9.68272%2010.3169H6.35055L2.41602%2014.9871C2.54072%2015.0949%202.69972%2015.1549%202.86458%2015.1563H13.3071C13.43%2015.1579%2013.5494%2015.1153%2013.6434%2015.0362C13.7375%2014.9572%2013.8001%2014.847%2013.8198%2014.7257L15.3013%205.60321Z'%20fill='url(%23paint0_linear_2502_831)'/%3e%3c/g%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_2502_831'%20x1='16.4138'%20y1='6.92327'%20x2='8.46264'%20y2='13.1288'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20offset='0.18'%20stop-color='%230052CC'/%3e%3cstop%20offset='1'%20stop-color='%232684FF'/%3e%3c/linearGradient%3e%3cclipPath%20id='clip0_2502_831'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_836)'%3e%3cpath%20d='M13.5535%202.79193C12.5178%202.30734%2011.4104%201.95517%2010.2526%201.75464C10.1104%202.01171%209.94432%202.35748%209.82976%202.63254C8.59904%202.44745%207.37956%202.44745%206.17144%202.63254C6.05693%202.35748%205.88704%202.01171%205.74358%201.75464C4.58454%201.95517%203.47584%202.30864%202.44013%202.79449C0.351095%205.95129%20-0.215207%209.02968%200.0679444%2012.0644C1.4535%2013.099%202.79627%2013.7276%204.11638%2014.139C4.44233%2013.6903%204.73302%2013.2134%204.98345%2012.7109C4.5065%2012.5297%204.04969%2012.306%203.61805%2012.0464C3.73256%2011.9615%203.84457%2011.8729%203.95278%2011.7816C6.58546%2013.013%209.44592%2013.013%2012.0471%2011.7816C12.1566%2011.8729%2012.2686%2011.9615%2012.3819%2012.0464C11.949%2012.3073%2011.491%2012.531%2011.014%2012.7122C11.2644%2013.2134%2011.5538%2013.6916%2011.881%2014.1402C13.2024%2013.7289%2014.5464%2013.1004%2015.932%2012.0644C16.2642%208.5464%2015.3645%205.49628%2013.5535%202.79193ZM5.34212%2010.1981C4.55182%2010.1981%203.9037%209.46024%203.9037%208.56184C3.9037%207.66337%204.53798%206.92429%205.34212%206.92429C6.14628%206.92429%206.79438%207.66207%206.78054%208.56184C6.78178%209.46024%206.14628%2010.1981%205.34212%2010.1981ZM10.6578%2010.1981C9.86752%2010.1981%209.21944%209.46024%209.21944%208.56184C9.21944%207.66337%209.85368%206.92429%2010.6578%206.92429C11.462%206.92429%2012.1101%207.66207%2012.0962%208.56184C12.0962%209.46024%2011.462%2010.1981%2010.6578%2010.1981Z'%20fill='%235865F2'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2502_836'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.01032%204.15504L4.00518%206.71006L8.01032%209.26513L4.00518%2011.8201L0%209.25129L4.00518%206.69625L0%204.15504L4.00518%201.60001L8.01032%204.15504ZM3.98446%2012.6418L7.98964%2010.0868L11.9948%2012.6418L7.98964%2015.1969L3.98446%2012.6418ZM8.01032%209.25129L12.0155%206.69625L8.01032%204.15504L11.9948%201.60001L16%204.15504L11.9948%206.71006L16%209.26513L11.9948%2011.8201L8.01032%209.25129Z'%20fill='%230061FF'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8%2015C11.866%2015%2015%2011.866%2015%207.99997C15%204.13401%2011.866%201%208%201C4.134%201%201%204.13401%201%207.99997C1%2011.866%204.134%2015%208%2015Z'%20fill='%231977F3'/%3e%3cpath%20d='M10.6065%2010.1416L10.9172%208.16548H8.97241V6.88336C8.97241%206.34321%209.24363%205.81556%2010.1154%205.81556H11V4.1336C11%204.1336%2010.1973%204%209.43%204C7.82844%204%206.78107%204.94574%206.78107%206.65942V8.16548H5V10.1416H6.78107V14.9174C7.13809%2014.9721%207.50398%2015%207.87671%2015C8.24951%2015%208.6154%2014.9712%208.97241%2014.9174V10.1416H10.6065Z'%20fill='white'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M7.97914%201C4.11986%201%201%204.20833%201%208.17748C1%2011.3502%202.999%2014.0359%205.77214%2014.9864C6.11886%2015.0579%206.24586%2014.832%206.24586%2014.642C6.24586%2014.4756%206.23443%2013.9052%206.23443%2013.311C4.293%2013.7388%203.88871%2012.4554%203.88871%2012.4554C3.57671%2011.6235%203.11443%2011.4097%203.11443%2011.4097C2.479%2010.97%203.16071%2010.97%203.16071%2010.97C3.86557%2011.0176%204.23543%2011.7068%204.23543%2011.7068C4.85929%2012.8%205.86457%2012.4911%206.269%2012.3009C6.32671%2011.8375%206.51171%2011.5166%206.70814%2011.3384C5.15971%2011.172%203.53057%2010.5541%203.53057%207.79715C3.53057%207.01285%203.80771%206.37119%204.24686%205.87215C4.17757%205.69394%203.93486%204.95704%204.31629%203.97077C4.31629%203.97077%204.90557%203.7806%206.23429%204.70752C6.80316%204.55041%207.38982%204.47049%207.97914%204.46981C8.56843%204.46981%209.16914%204.55308%209.72386%204.70752C11.0527%203.7806%2011.642%203.97077%2011.642%203.97077C12.0234%204.95704%2011.7806%205.69394%2011.7113%205.87215C12.162%206.37119%2012.4277%207.01285%2012.4277%207.79715C12.4277%2010.5541%2010.7986%2011.1601%209.23857%2011.3384C9.49286%2011.5642%209.71229%2011.9919%209.71229%2012.6693C9.71229%2013.6318%209.70086%2014.4043%209.70086%2014.6418C9.70086%2014.832%209.828%2015.0579%2010.1746%2014.9866C12.9477%2014.0358%2014.9467%2011.3502%2014.9467%208.17748C14.9581%204.20833%2011.8269%201%207.97914%201Z'%20fill='%2324292F'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_2502_834)'%3e%3cpath%20d='M7.99957%2015.3683L10.9471%206.30157H5.05627L7.99957%2015.3683Z'%20fill='%23E24329'/%3e%3cpath%20d='M0.92752%206.30157L0.0299048%209.05617C-0.0513217%209.30625%200.0363974%209.58242%200.25079%209.73834L7.99948%2015.3683L0.92752%206.30157Z'%20fill='%23FCA326'/%3e%3cpath%20d='M0.92749%206.30164H5.05611L3.27927%200.841173C3.18833%200.561813%202.792%200.561813%202.69779%200.841173L0.92749%206.30164Z'%20fill='%23E24329'/%3e%3cpath%20d='M15.0757%206.30157L15.9701%209.05617C16.0513%209.30625%2015.9636%209.58242%2015.7492%209.73834L7.99939%2015.3683L15.0757%206.30157Z'%20fill='%23FCA326'/%3e%3cpath%20d='M15.0757%206.30164H10.947L12.7206%200.841173C12.8116%200.561813%2013.2079%200.561813%2013.3021%200.841173L15.0757%206.30164Z'%20fill='%23E24329'/%3e%3cpath%20d='M7.99939%2015.3683L10.947%206.30157H15.0757L7.99939%2015.3683Z'%20fill='%23FC6D26'/%3e%3cpath%20d='M7.9994%2015.3683L0.92749%206.30157H5.05611L7.9994%2015.3683Z'%20fill='%23FC6D26'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_2502_834'%3e%3crect%20width='16'%20height='16'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M14.7%208.15554C14.7%207.57997%2014.6533%207.15997%2014.5523%206.72443H7.97998V9.32218H11.8377C11.76%209.96777%2011.34%2010.94%2010.4066%2011.5933L10.3936%2011.6803L12.4716%2013.2901L12.6155%2013.3045C13.9378%2012.0834%2014.7%2010.2867%2014.7%208.15554Z'%20fill='%234285F4'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M7.98022%2015C9.87019%2015%2011.4568%2014.3778%2012.6158%2013.3045L10.4069%2011.5933C9.81576%2012.0055%209.02242%2012.2933%207.98022%2012.2933C6.12911%2012.2933%204.558%2011.0722%203.99793%209.38446L3.91586%209.39143L1.75507%2011.0637L1.72681%2011.1422C2.87791%2013.4289%205.2424%2015%207.98022%2015Z'%20fill='%2334A853'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M3.9977%209.38448C3.84994%208.94893%203.76439%208.48223%203.76439%208.00002C3.76439%207.51778%203.8499%207.05111%203.98993%206.61557L3.98602%206.52279L1.79819%204.82367L1.72662%204.85773C1.25218%205.80664%200.97998%206.87219%200.97998%207.99998C0.97998%209.12777%201.25223%2010.1933%201.72662%2011.1422L3.99774%209.38443'%20fill='%23FBBC04'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M7.98022%203.70662C9.29466%203.70662%2010.1813%204.27442%2010.6869%204.7489L12.6625%202.82C11.4492%201.69221%209.87019%201%207.98022%201C5.2424%201%202.87795%202.5711%201.72681%204.85776L3.99016%206.6156C4.558%204.92782%206.12911%203.70666%207.98022%203.70666'%20fill='%23EA4335'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.013%205.51301V3.9479C11.4349%203.74999%2011.7057%203.32811%2011.7083%202.86197V2.82551C11.7083%202.15884%2011.1667%201.61978%2010.5026%201.61978H10.4661C9.79948%201.61978%209.26042%202.15884%209.26042%202.82551V2.86197C9.26302%203.32811%209.53385%203.74999%209.95573%203.9479V5.51301C9.35937%205.60415%208.79948%205.85155%208.33073%206.22915L4.03646%202.8828C4.06771%202.77343%204.08333%202.65884%204.08594%202.54426C4.08594%201.79426%203.47917%201.18488%202.72917%201.18488C1.97917%201.18228%201.36979%201.78905%201.36719%202.53905C1.36719%203.29165%201.97396%203.90103%202.72396%203.90103C2.96094%203.90103%203.1901%203.83593%203.39323%203.71874L7.6224%207.0104C6.84635%208.18488%206.86719%209.71353%207.67448%2010.8672L6.38802%2012.1536C6.28646%2012.1198%206.17708%2012.1042%206.06771%2012.1016C5.45313%2012.1016%204.95313%2012.6016%204.95313%2013.2187C4.95313%2013.8333%205.45313%2014.3333%206.06771%2014.3333C6.6849%2014.3333%207.1849%2013.8333%207.1849%2013.2187C7.18229%2013.1094%207.16406%2013%207.13281%2012.8958L8.40365%2011.625C9.54167%2012.5%2011.1016%2012.5755%2012.3177%2011.8125C13.5339%2011.0521%2014.1484%209.61457%2013.8568%208.20832C13.5651%206.80468%2012.4297%205.72915%2011.013%205.51301ZM10.4844%2010.6641C9.84375%2010.6797%209.24479%2010.3489%208.92187%209.79686C8.59635%209.24478%208.59635%208.56249%208.92187%208.0104C9.24479%207.45832%209.84375%207.12759%2010.4844%207.14322C11.4323%207.17707%2012.1823%207.95572%2012.1823%208.90363C12.1849%209.84895%2011.4349%2010.6276%2010.487%2010.6614'%20fill='%23FF7A59'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cmask%20id='mask0_2502_833'%20style='mask-type:luminance'%20maskUnits='userSpaceOnUse'%20x='1'%20y='1'%20width='14'%20height='14'%3e%3cpath%20d='M15%201H1V15H15V1Z'%20fill='white'/%3e%3c/mask%3e%3cg%20mask='url(%23mask0_2502_833)'%3e%3cpath%20d='M1.17156%209.61322C1.14041%209.48043%201.2986%209.39678%201.39505%209.49324L6.50679%2014.6049C6.60323%2014.7014%206.5196%2014.8596%206.38681%2014.8284C3.80721%2014.2233%201.77669%2012.1928%201.17156%209.61322ZM1.00026%207.56447C0.997795%207.60414%201.01271%207.64286%201.0408%207.67096L8.32907%2014.9592C8.35714%2014.9873%208.39585%2015.0022%208.43554%2014.9997C8.7672%2014.9791%209.09263%2014.9353%209.41029%2014.8701C9.51732%2014.8481%209.55449%2014.7166%209.47721%2014.6394L1.36063%206.52279C1.28337%206.44552%201.15187%206.48271%201.12989%206.58974C1.06466%206.90734%201.02092%207.23279%201.00026%207.56447ZM1.58953%205.15876C1.56622%205.21109%201.57809%205.27224%201.6186%205.31276L10.6872%2014.3814C10.7278%2014.4219%2010.7889%2014.4338%2010.8412%2014.4105C11.0913%2014.2991%2011.3336%2014.1735%2011.5672%2014.0347C11.6445%2013.9888%2011.6565%2013.8826%2011.5929%2013.819L2.18099%204.40714C2.11742%204.34356%202.01121%204.35549%201.96529%204.43279C1.8265%204.66636%201.70091%204.9087%201.58953%205.15876ZM2.77222%203.53036C2.7204%203.47855%202.7172%203.39544%202.76602%203.34079C4.04913%201.9043%205.9156%201%207.99327%201C11.863%201%2015%204.13702%2015%208.00672C15%2010.0844%2014.0957%2011.9509%2012.6592%2013.234C12.6046%2013.2828%2012.5214%2013.2796%2012.4696%2013.2278L2.77222%203.53036Z'%20fill='url(%23paint0_linear_2502_833)'/%3e%3c/g%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_2502_833'%20x1='8'%20y1='1'%20x2='8'%20y2='15'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%235C6BF1'/%3e%3cstop%20offset='1'%20stop-color='%23283188'/%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M12.9289%2012.9289H10.8545V9.68033C10.8545%208.90563%2010.8407%207.90839%209.77562%207.90839C8.69517%207.90839%208.52983%208.7524%208.52983%209.62391V12.9287H6.45547V6.24817H8.44688V7.16113H8.47481C8.88025%206.46785%209.63695%206.05224%2010.4396%206.08204C12.5421%206.08204%2012.9297%207.46497%2012.9297%209.2641L12.9289%2012.9289ZM4.11485%205.33497C3.45446%205.33497%202.91079%204.79161%202.91079%204.1312C2.91079%203.47081%203.45421%202.92738%204.1146%202.92738C4.77493%202.92738%205.31829%203.47068%205.31841%204.13096C5.31841%204.79123%204.77512%205.33491%204.11485%205.33497ZM5.15203%2012.9289H3.07549V6.24817H5.15203V12.9289ZM13.963%201.00097H2.03305C1.47303%200.994641%201.00683%201.45002%201%202.01004V13.9897C1.00658%2014.55%201.47272%2015.0059%202.03305%2014.9999H13.963C14.5247%2015.007%2014.9925%2014.5511%2015%2013.9897V2.00923C14.9925%201.44802%2014.5241%200.992699%2013.963%201.00009V1.00097Z'%20fill='%230A66C2'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M1%201H15V15H1V1Z'%20fill='%23F3F3F3'/%3e%3cpath%20d='M2%202H8V8H2V2Z'%20fill='%23F35325'/%3e%3cpath%20d='M8%202H14V8H8V2Z'%20fill='%2381BC06'/%3e%3cpath%20d='M2%208H8V14H2V8Z'%20fill='%2305A6F0'/%3e%3cpath%20d='M8%208H14V14H8V8Z'%20fill='%23FFBA08'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M2.33281%201.60396L10.0795%201.03183C11.031%200.95016%2011.2756%201.00523%2011.8738%201.44016L14.3467%203.18223C14.7546%203.48183%2014.8904%203.5635%2014.8904%203.8897V13.4438C14.8904%2014.0425%2014.6729%2014.3967%2013.9118%2014.4509L4.91582%2014.9955C4.34462%2015.0225%204.07255%2014.9409%203.77341%2014.5596L1.95248%2012.1917C1.62581%2011.7559%201.49048%2011.4297%201.49048%2011.0484V2.55596C1.49048%202.06643%201.70795%201.65809%202.33281%201.60396Z'%20fill='white'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M10.0795%201.03183L2.33281%201.60396C1.70795%201.65809%201.49048%202.06643%201.49048%202.55596V11.0484C1.49048%2011.4297%201.62581%2011.7559%201.95248%2012.1917L3.77341%2014.5596C4.07255%2014.9409%204.34462%2015.0225%204.91582%2014.9955L13.9118%2014.4509C14.6724%2014.3967%2014.8904%2014.0425%2014.8904%2013.4438V3.8897C14.8904%203.5803%2014.7681%203.49116%2014.4083%203.22703C14.3876%203.21212%2014.3669%203.19718%2014.3462%203.18223L11.8738%201.44016C11.2756%201.00523%2011.031%200.95016%2010.0795%201.03183ZM5.11929%203.73336C4.38475%203.78283%204.21815%203.79403%203.80095%203.45476L2.74021%202.61103C2.63241%202.50183%202.68654%202.36556%202.95814%202.33849L10.4052%201.79436C11.0306%201.73976%2011.3563%201.95769%2011.6008%202.14809L12.8781%203.07349C12.9327%203.10103%2013.0685%203.26389%2012.9052%203.26389L5.21449%203.72683L5.11929%203.73336ZM4.26295%2013.3621V5.25144C4.26295%204.89724%204.37168%204.7339%204.69742%204.70637L13.5305%204.1893C13.8301%204.16223%2013.9654%204.35263%2013.9654%204.70637V12.7629C13.9654%2013.1171%2013.9108%2013.4167%2013.4218%2013.4438L4.96902%2013.9338C4.47995%2013.9609%204.26295%2013.798%204.26295%2013.3621ZM12.607%205.68637C12.6611%205.93137%2012.607%206.17637%2012.362%206.20437L11.9546%206.2851V12.2734C11.6008%2012.4638%2011.2751%2012.5725%2011.003%2012.5725C10.5681%2012.5725%2010.4593%2012.4363%2010.1336%2012.0284L7.46942%207.83677V11.8921L8.31224%2012.083C8.31224%2012.083%208.31224%2012.573%207.63229%2012.573L5.75769%2012.6817C5.70309%2012.5725%205.75769%2012.3005%205.94762%2012.2463L6.43716%2012.1105V6.7485L5.75769%206.69344C5.70309%206.44844%205.83889%206.0947%206.21969%206.06717L8.23104%205.93184L11.003%2010.1776V6.42137L10.2965%206.34017C10.2419%206.0401%2010.4593%205.82217%2010.7309%205.79557L12.607%205.68637Z'%20fill='black'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.94137%209.84695C3.94137%2010.6564%203.28013%2011.3176%202.47069%2011.3176C1.66124%2011.3176%201%2010.6564%201%209.84695C1%209.03747%201.66124%208.37625%202.47069%208.37625H3.94137V9.84695Z'%20fill='%23E01E5A'/%3e%3cpath%20d='M4.68237%209.84695C4.68237%209.03747%205.34361%208.37625%206.15306%208.37625C6.9625%208.37625%207.62374%209.03747%207.62374%209.84695V13.5293C7.62374%2014.3388%206.9625%2015%206.15306%2015C5.34361%2015%204.68237%2014.3388%204.68237%2013.5293V9.84695Z'%20fill='%23E01E5A'/%3e%3cpath%20d='M6.15306%203.94137C5.34361%203.94137%204.68237%203.28013%204.68237%202.47069C4.68237%201.66124%205.34361%201%206.15306%201C6.9625%201%207.62374%201.66124%207.62374%202.47069V3.94137H6.15306Z'%20fill='%2336C5F0'/%3e%3cpath%20d='M6.15309%204.68237C6.96254%204.68237%207.62378%205.34361%207.62378%206.15306C7.62378%206.9625%206.96254%207.62374%206.15309%207.62374H2.47069C1.66124%207.62374%201%206.9625%201%206.15306C1%205.34361%201.66124%204.68237%202.47069%204.68237H6.15309Z'%20fill='%2336C5F0'/%3e%3cpath%20d='M12.0585%206.15306C12.0585%205.34361%2012.7197%204.68237%2013.5291%204.68237C14.3386%204.68237%2014.9998%205.34361%2014.9998%206.15306C14.9998%206.9625%2014.3386%207.62374%2013.5291%207.62374H12.0585V6.15306Z'%20fill='%232EB67D'/%3e%3cpath%20d='M11.3176%206.15309C11.3176%206.96254%2010.6563%207.62378%209.84685%207.62378C9.03744%207.62378%208.37622%206.96254%208.37622%206.15309V2.47069C8.37622%201.66124%209.03744%201%209.84685%201C10.6563%201%2011.3176%201.66124%2011.3176%202.47069V6.15309Z'%20fill='%232EB67D'/%3e%3cpath%20d='M9.84685%2012.0586C10.6563%2012.0586%2011.3176%2012.7199%2011.3176%2013.5293C11.3176%2014.3388%2010.6563%2015%209.84685%2015C9.03744%2015%208.37622%2014.3388%208.37622%2013.5293V12.0586H9.84685Z'%20fill='%23ECB22E'/%3e%3cpath%20d='M9.84685%2011.3176C9.03744%2011.3176%208.37622%2010.6564%208.37622%209.84695C8.37622%209.03747%209.03744%208.37625%209.84685%208.37625H13.5293C14.3388%208.37625%2015%209.03747%2015%209.84695C15%2010.6564%2014.3388%2011.3176%2013.5293%2011.3176H9.84685Z'%20fill='%23ECB22E'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M6.60974%205.91839V5.33278C6.40646%205.30058%206.20114%205.28293%205.99535%205.27998C4.00296%205.27577%202.23902%206.56688%201.64074%208.46732C1.04245%2010.3678%201.74866%2012.4365%203.38415%2013.5744C2.15905%2012.2633%201.81888%2010.3546%202.51559%208.70096C3.21229%207.0473%204.81576%205.95753%206.60974%205.91839Z'%20fill='%2325F4EE'/%3e%3cpath%20d='M6.72004%2012.552C7.834%2012.5505%208.74966%2011.6729%208.79844%2010.56V0.6288H10.6128C10.5758%200.421288%2010.5581%200.210783%2010.56%200H8.07844V9.9216C8.03716%2011.0402%207.11934%2011.9262%206.00004%2011.928C5.66555%2011.9252%205.33652%2011.8429%205.04004%2011.688C5.42976%2012.2279%206.05416%2012.5491%206.72004%2012.552Z'%20fill='%2325F4EE'/%3e%3cpath%20d='M14.0014%203.9984V3.4464C13.3337%203.44663%2012.6808%203.24959%2012.1246%202.88C12.6122%203.44675%2013.271%203.83934%2014.0014%203.9984Z'%20fill='%2325F4EE'/%3e%3cpath%20d='M12.125%202.87999C11.5772%202.25615%2011.2752%201.45422%2011.2754%200.623993H10.613C10.786%201.55168%2011.3327%202.36746%2012.125%202.87999Z'%20fill='%23FE2C55'/%3e%3cpath%20d='M5.99519%207.7616C5.03925%207.76652%204.20933%208.42142%203.98229%209.34998C3.75525%2010.2786%204.18936%2011.2426%205.03519%2011.688C4.57688%2011.0552%204.51214%2010.219%204.86761%209.5232C5.22308%208.82744%205.9387%208.3898%206.71999%208.3904C6.92831%208.39298%207.13519%208.42532%207.33439%208.4864V5.9616C7.13099%205.93112%206.92567%205.91509%206.71999%205.9136H6.60959V7.8336C6.40937%207.7799%206.20243%207.75566%205.99519%207.7616Z'%20fill='%23FE2C55'/%3e%3cpath%20d='M14.0015%203.99841V5.91841C12.7654%205.91603%2011.5613%205.52475%2010.5599%204.80001V9.84481C10.5546%2012.3621%208.51245%2014.4%205.99511%2014.4C5.06025%2014.4017%204.1479%2014.1132%203.38391%2013.5744C4.6589%2014.9457%206.64315%2015.3971%208.38585%2014.7123C10.1285%2014.0275%2011.2747%2012.346%2011.2751%2010.4736V5.44321C12.2799%206.16321%2013.4854%206.54937%2014.7215%206.54721V4.07521C14.4795%204.07445%2014.2382%204.04871%2014.0015%203.99841Z'%20fill='%23FE2C55'/%3e%3cpath%20d='M10.56%209.8448V4.79999C11.5645%205.52056%2012.7702%205.9068%2014.0064%205.90399V3.98399C13.2761%203.82977%2012.6157%203.4423%2012.1248%202.87999C11.3324%202.36746%2010.7857%201.55168%2010.6128%200.623993H8.7984V10.56C8.7621%2011.4464%208.16834%2012.2126%207.31904%2012.4691C6.46968%2012.7255%205.55115%2012.4159%205.03038%2011.6976C4.18454%2011.2522%203.75043%2010.2882%203.97747%209.35958C4.20452%208.43102%205.03444%207.77612%205.99038%207.7712C6.19878%207.77306%206.40578%207.8054%206.6048%207.8672V5.94719C4.80073%205.97776%203.18515%207.07136%202.48647%208.73486C1.78778%2010.3984%202.13799%2012.3176%203.37918%2013.6272C4.1507%2014.1482%205.06437%2014.4181%205.99518%2014.4C8.5125%2014.4%2010.5547%2012.3621%2010.56%209.8448Z'%20fill='black'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M14%207.94593L11.75%2010.1081H9.5L7.53124%2012V10.1081H5V2H14V7.94593Z'%20fill='white'/%3e%3cpath%20d='M4.70834%201L2%203.67857V13.3215H5.25V16L7.95833%2013.3215H10.125L15%208.5V1H4.70834ZM13.9166%207.96428L11.75%2010.1072H9.5833L7.6875%2011.9822V10.1072H5.25V2.07143H13.9166V7.96428Z'%20fill='%239146FF'/%3e%3cpath%20d='M12%204H11V7H12V4Z'%20fill='%239146FF'/%3e%3cpath%20d='M9%204H8V7H9V4Z'%20fill='%239146FF'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M9.14163%206.50461L13.6089%201H12.5503L8.67137%205.77958L5.57328%201H2L6.68492%208.22757L2%2014H3.05866L7.15491%208.9526L10.4267%2014H14L9.14137%206.50461H9.14163ZM7.69165%208.29124L7.21697%207.57154L3.44011%201.84479H5.06615L8.11412%206.46646L8.5888%207.18616L12.5508%2013.1936H10.9248L7.69165%208.29152V8.29124Z'%20fill='black'%20stroke='black'%20stroke-width='0.5'/%3e%3c/svg%3e\"","export default \"data:image/svg+xml,%3csvg%20width='16'%20height='16'%20viewBox='0%200%2016%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cmask%20id='mask0_2502_830'%20style='mask-type:luminance'%20maskUnits='userSpaceOnUse'%20x='1'%20y='1'%20width='14'%20height='14'%3e%3cpath%20d='M15%201H1V15H15V1Z'%20fill='white'/%3e%3c/mask%3e%3cg%20mask='url(%23mask0_2502_830)'%3e%3cpath%20d='M7.99994%2014.9733C11.8512%2014.9733%2014.9732%2011.8513%2014.9732%207.99997C14.9732%204.14873%2011.8512%201.02667%207.99994%201.02667C4.14867%201.02667%201.02661%204.14873%201.02661%207.99997C1.02661%2011.8513%204.14867%2014.9733%207.99994%2014.9733Z'%20fill='%231AB4D7'/%3e%3cpath%20d='M4.36467%207.97988L5.55473%206.78688C5.59418%206.74667%205.61619%206.69343%205.61619%206.63697C5.61619%206.5193%205.52054%206.42374%205.40287%206.42374C5.34555%206.42374%205.29181%206.44621%205.2513%206.48723L4.06231%207.67564L2.86801%206.48544C2.82765%206.44566%202.77418%206.42374%202.71748%206.42374C2.59995%206.42374%202.50427%206.51925%202.50427%206.6368C2.50427%206.69415%202.52716%206.74796%202.56825%206.7885L3.75814%207.97822L2.56887%209.16973C2.52707%209.21089%202.50427%209.26479%202.50427%209.3224C2.50427%209.44007%202.59995%209.53548%202.71748%209.53548C2.77428%209.53548%202.8278%209.51343%202.86801%209.47325L4.06046%208.28241L5.24838%209.46891C5.29051%209.51245%205.34487%209.53562%205.40287%209.53562C5.52042%209.53562%205.61608%209.44007%205.61608%209.3224C5.61608%209.26563%205.59409%209.21229%205.55406%209.17211L4.36467%207.97988Z'%20fill='white'/%3e%3cpath%20d='M11.4393%207.97953C11.4393%208.19316%2011.6131%208.36697%2011.827%208.36697C12.0404%208.36697%2012.2142%208.19316%2012.2142%207.97953C12.2142%207.76582%2012.0404%207.59204%2011.827%207.59204C11.6131%207.59204%2011.4393%207.76582%2011.4393%207.97953Z'%20fill='white'/%3e%3cpath%20d='M10.7045%207.97969C10.7045%207.36096%2011.2078%206.85753%2011.8266%206.85753C12.4451%206.85753%2012.9485%207.36096%2012.9485%207.97969C12.9485%208.59828%2012.4451%209.10151%2011.8266%209.10151C11.2078%209.10151%2010.7045%208.59828%2010.7045%207.97969ZM10.2631%207.97969C10.2631%208.84167%2010.9645%209.543%2011.8266%209.543C12.6887%209.543%2013.3905%208.84167%2013.3905%207.97969C13.3905%207.11757%2012.6887%206.41608%2011.8266%206.41608C10.9645%206.41608%2010.2631%207.11757%2010.2631%207.97969Z'%20fill='white'/%3e%3cpath%20d='M10.152%206.44279L10.0864%206.4426C9.88947%206.4426%209.69956%206.50471%209.54094%206.62696C9.52001%206.5313%209.43447%206.45933%209.33269%206.45933C9.21544%206.45933%209.1215%206.55325%209.12122%206.67071L9.12192%209.3041C9.12227%209.42135%209.21789%209.51662%209.33514%209.51662C9.45246%209.51662%209.54808%209.42135%209.54836%209.30382L9.54843%207.68463C9.54843%207.14496%209.59778%206.927%2010.0601%206.86923C10.1028%206.86392%2010.1494%206.86475%2010.1494%206.86475C10.276%206.86041%2010.3659%206.77348%2010.3659%206.656C10.3659%206.53844%2010.2699%206.44279%2010.152%206.44279Z'%20fill='white'/%3e%3cpath%20d='M6.05791%207.72227C6.05791%207.71643%206.05836%207.71035%206.05864%207.70435C6.18243%207.215%206.62563%206.85287%207.15344%206.85287C7.68764%206.85287%208.13489%207.2239%208.25235%207.72227H6.05791ZM8.689%207.682C8.59709%207.24697%208.35895%206.88964%207.99626%206.66016C7.46613%206.32358%206.76607%206.3422%206.25401%206.70635C5.83632%207.00349%205.59521%207.48958%205.59521%207.9903C5.59521%208.11586%205.61035%208.24256%205.64186%208.3673C5.79957%208.98778%206.33294%209.45741%206.96885%209.53525C7.15754%209.55814%207.34122%209.54715%207.53141%209.49794C7.69485%209.45818%207.85299%209.39189%207.99871%209.29851C8.14993%209.20128%208.27628%209.07304%208.39864%208.9196C8.40116%208.9168%208.40361%208.91428%208.40613%208.91134C8.49104%208.80599%208.47529%208.65619%208.38198%208.58465C8.30323%208.52438%208.17107%208.49988%208.06712%208.63309C8.04472%208.66487%208.0198%208.69763%207.99238%208.73039C7.90969%208.82181%207.80712%208.91029%207.6842%208.97896C7.52779%209.06254%207.34955%209.11028%207.16006%209.11133C6.53986%209.1044%206.20799%208.67152%206.08993%208.36254C6.06932%208.30479%206.05342%208.24494%206.04234%208.18334C6.0409%208.17179%206.03983%208.16066%206.0394%208.15044C6.16763%208.15044%208.26501%208.15009%208.26501%208.15009C8.57014%208.14365%208.73436%207.92828%208.689%207.682Z'%20fill='white'/%3e%3c/g%3e%3c/svg%3e\"","import type { CSSProperties } from 'react';\nimport { cn } from '@/utils';\nimport { CountryFlag } from '../country-flag';\nimport '@/styles/index.css';\nimport './style.css';\n\nimport browserChrome from '@/assets/icons/general/browser-chrome.svg';\nimport caretDown from '@/assets/icons/general/caret-down.svg';\nimport check from '@/assets/icons/general/check.svg';\nimport close from '@/assets/icons/general/close.svg';\nimport dotsVertical from '@/assets/icons/general/dots-vertical.svg';\nimport edit from '@/assets/icons/general/edit.svg';\nimport eyeOff from '@/assets/icons/general/eye-off.svg';\nimport eyeOn from '@/assets/icons/general/eye-on.svg';\nimport key from '@/assets/icons/general/key.svg';\nimport label from '@/assets/icons/general/label.svg';\nimport logo from '@/assets/icons/general/logo.svg';\nimport logoRed from '@/assets/icons/general/logo-red.svg';\nimport mail from '@/assets/icons/general/mail.svg';\nimport onePassword from '@/assets/icons/general/one-password.svg';\nimport passkey from '@/assets/icons/general/passkey.svg';\nimport phone from '@/assets/icons/general/phone.svg';\nimport search from '@/assets/icons/general/search.svg';\nimport trash from '@/assets/icons/general/trash.svg';\nimport warning from '@/assets/icons/general/warning.svg';\nimport apple from '@/assets/icons/providers/apple.svg';\nimport atlassian from '@/assets/icons/providers/atlassian.svg';\nimport bitbucket from '@/assets/icons/providers/bitbucket.svg';\nimport discord from '@/assets/icons/providers/discord.svg';\nimport dropbox from '@/assets/icons/providers/dropbox.svg';\nimport facebook from '@/assets/icons/providers/facebook.svg';\nimport github from '@/assets/icons/providers/github.svg';\nimport gitlab from '@/assets/icons/providers/gitlab.svg';\nimport google from '@/assets/icons/providers/google.svg';\nimport hubspot from '@/assets/icons/providers/hubspot.svg';\nimport linear from '@/assets/icons/providers/linear.svg';\nimport linkedin from '@/assets/icons/providers/linkedin.svg';\nimport microsoft from '@/assets/icons/providers/microsoft.svg';\nimport notion from '@/assets/icons/providers/notion.svg';\nimport slack from '@/assets/icons/providers/slack.svg';\nimport tiktok from '@/assets/icons/providers/tiktok.svg';\nimport twitch from '@/assets/icons/providers/twitch.svg';\nimport twitter from '@/assets/icons/providers/twitter.svg';\nimport xero from '@/assets/icons/providers/xero.svg';\n\ntype TIcon = {\n type: 'general' | 'providers' | 'flags';\n id: string;\n size: 'small' | 'medium' | 'big' | 'large';\n className?: string;\n decorative?: boolean;\n matchTextColor?: boolean;\n};\n\ntype IconMaskStyle = CSSProperties & {\n '--passflow-icon-mask': string;\n};\n\nexport const Icon = ({ type, id, size, className = '', decorative = false, matchTextColor = false }: TIcon) => {\n const styles = {\n 'passflow-icon--small': size === 'small',\n 'passflow-icon--medium': size === 'medium',\n 'passflow-icon--big': size === 'big',\n 'passflow-icon--large': size === 'large',\n };\n\n const icons: Record<'providers' | 'general', Record<string, string>> = {\n general: {\n logo,\n 'logo-red': logoRed,\n warning,\n mail,\n edit,\n 'eye-on': eyeOn,\n 'eye-off': eyeOff,\n search,\n 'caret-down': caretDown,\n label,\n close,\n check,\n key,\n phone,\n 'one-password': onePassword,\n 'browser-chrome': browserChrome,\n passkey,\n 'dots-vertical': dotsVertical,\n trash,\n },\n providers: {\n google,\n gitlab,\n apple,\n atlassian,\n bitbucket,\n discord,\n dropbox,\n facebook,\n github,\n hubspot,\n linear,\n linkedin,\n linledin: linkedin,\n microsoft,\n notion,\n slack,\n tiktok,\n twitch,\n twitter,\n xero,\n },\n };\n\n if (matchTextColor && type === 'general') {\n const style: IconMaskStyle = {\n '--passflow-icon-mask': `url(\"${icons.general[id]}\")`,\n };\n\n return (\n <span\n className={cn('passflow-icon passflow-icon--match-text', styles, className)}\n style={style}\n role={decorative ? undefined : 'img'}\n aria-label={decorative ? undefined : id}\n aria-hidden={decorative || undefined}\n />\n );\n }\n\n if (type !== 'flags') {\n return <img className={cn('passflow-icon', styles, className)} src={icons[type][id]} alt={decorative ? '' : id} />;\n }\n\n return (\n <div className={cn('passflow-icon', styles, className)}>\n <CountryFlag iso2={id} />\n </div>\n );\n};\n","import type { FC, PropsWithChildren } from 'react';\nimport { useEffect, useRef } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport type { LoginScreenNotice as LoginScreenNoticeProps } from './types';\nimport './login-screen.css';\n\n/** `error` is the default; `info` is a neutral note that is not announced as an alert. */\nexport const LoginAlert: FC<{ message?: string | null; id?: string; tone?: 'error' | 'info' }> = ({\n message,\n id,\n tone = 'error',\n}) => {\n if (!message) return null;\n\n if (tone === 'info') {\n return (\n <div id={id} className='passflow-login-screen-note' role='status'>\n {message}\n </div>\n );\n }\n\n return (\n <div id={id} className='passflow-form-error' role='alert'>\n <Icon size='small' id='warning' type='general' className='icon-warning' decorative />\n <span className='passflow-form-error-text'>{message}</span>\n </div>\n );\n};\n\n/** For a code input locked while a request is in flight: gives focus back when the request ends. */\nexport const useFocusAfterBusy = (busy: boolean) => {\n const inputRef = useRef<HTMLInputElement>(null);\n const wasBusy = useRef(busy);\n\n useEffect(() => {\n if (wasBusy.current && !busy) inputRef.current?.focus();\n wasBusy.current = busy;\n }, [busy]);\n\n return inputRef;\n};\n\nexport const LoginDivider: FC<{ label: string }> = ({ label }) => (\n <div className='passflow-form-divider' aria-hidden='true'>\n <div className='passflow-form-divider__line-left' />\n <span className='passflow-form-divider__text'>{label}</span>\n <div className='passflow-form-divider__line-right' />\n </div>\n);\n\nexport const LoginActionStack: FC<PropsWithChildren> = ({ children }) => (\n <div className='passflow-login-screen-actions'>{children}</div>\n);\n\nexport const LoginProgress: FC<{ message: string; onCancel?: () => void }> = ({ message, onCancel }) => {\n const status = (\n <div className='passflow-login-screen-status' role='status' aria-live='polite'>\n <div className='passflow-login-screen-spinner passflow-login-screen-spinner--small' aria-hidden='true' />\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>{message}</p>\n </div>\n );\n if (!onCancel) return status;\n return (\n <div className='passflow-login-screen-progress'>\n {status}\n <Button size='small' variant='link' type='button' onClick={onCancel}>\n Cancel\n </Button>\n </div>\n );\n};\n\nexport const LoginScreenNotice: FC<LoginScreenNoticeProps> = ({ code, appName, message, codeTestId, appNameTestId }) => (\n <div className='passflow-login-screen-notice' role='note'>\n {code ? (\n <div className='passflow-login-screen-code' data-testid={codeTestId}>\n {code}\n </div>\n ) : null}\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n <span className='passflow-login-screen-app-name' data-testid={appNameTestId}>\n {appName}\n </span>{' '}\n {message}\n </p>\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useState } from 'react';\nimport { Button } from '../button';\nimport { FieldText } from '../fields/field-text';\nimport { LoginAlert, LoginProgress } from './shared';\nimport type { LoginCodeEntryState } from './types';\n\nexport const LoginCodeEntry: FC<LoginCodeEntryState> = ({\n label = 'Code',\n initialCode = '',\n error,\n busy = false,\n submitLabel = 'Continue',\n testId,\n onSubmit,\n}) => {\n const [code, setCode] = useState(initialCode);\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const normalizedCode = code.trim();\n if (normalizedCode) onSubmit(normalizedCode);\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container'>\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label htmlFor='device-user-code' className='passflow-field-label'>\n {label}\n </label>\n </div>\n <FieldText\n id='device-user-code'\n name='user_code'\n type='text'\n autoCapitalize='characters'\n autoComplete='off'\n autoCorrect='off'\n spellCheck={false}\n inputMode='text'\n className='passflow-login-screen-code-input'\n value={code}\n disabled={busy}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? 'device-user-code-error' : undefined}\n isError={Boolean(error)}\n onChange={(event) => setCode(event.target.value)}\n />\n </div>\n <LoginAlert id='device-user-code-error' message={error} />\n </div>\n {busy ? <LoginProgress message='Checking the code…' /> : null}\n <Button size='big' variant='primary' type='submit' disabled={busy || code.trim().length === 0}>\n {busy ? 'Checking…' : submitLabel}\n </Button>\n </form>\n );\n};\n","import { type ChangeEvent, type FC, useId } from 'react';\nimport { cn } from '@/utils';\n\ntype TSwitch = {\n label: string;\n checked: boolean;\n disabled?: boolean;\n /**\n * Overrides the generated input id. Only needed when something outside this\n * component has to point at the input (`aria-describedby`, a test hook, a\n * label rendered elsewhere).\n *\n * The default is a `useId()` value rather than a constant, because a constant\n * breaks the moment a screen renders more than one Switch: duplicate DOM ids\n * are invalid, and every `<label htmlFor>` would resolve to the FIRST input,\n * so clicking row three would toggle row one. The consent screen renders one\n * Switch per requested scope, so this is load-bearing, not hygiene.\n */\n id?: string;\n onChange: (event: ChangeEvent<HTMLInputElement>) => void;\n};\n\nexport const Switch: FC<TSwitch> = ({ label, checked, disabled = false, id, onChange }) => {\n const generatedId = useId();\n const inputId = id ?? generatedId;\n\n return (\n <label className={cn('passflow-switch-wrapper', { 'passflow-switch-wrapper--disabled': disabled })} htmlFor={inputId}>\n <span className='passflow-switch-label'>{label}</span>\n <input\n id={inputId}\n type='checkbox'\n className='passflow-switch-input'\n checked={checked}\n disabled={disabled}\n onChange={onChange}\n />\n <div className='passflow-switch-track' />\n </label>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Switch } from '../switch';\nimport { LoginAlert, LoginProgress, LoginScreenNotice } from './shared';\nimport type { LoginConsentState } from './types';\n\n/**\n * The OIDC consent screen: which scopes an application is asking for, and the\n * two decisions a user can make about them.\n *\n * Every scope starts granted and can be switched off individually — the Allow\n * button submits the subset that is still on, so \"Allow\" never grants more than\n * what is visible on screen. Deny is a peer of Allow, not a hidden link: a\n * consent screen where refusing is harder than accepting is a dark pattern.\n * For the same reason neither button takes initial focus: a bare Enter on a\n * freshly loaded screen must not grant every requested scope.\n */\nexport const LoginConsent: FC<LoginConsentState> = ({\n appName,\n scopes,\n prompt = 'wants to access your account.',\n busy = false,\n error,\n allowLabel = 'Allow',\n denyLabel = 'Deny',\n busyLabel = 'Submitting…',\n testId,\n allowTestId,\n denyTestId,\n appNameTestId,\n onToggleScope,\n onAllow,\n onDeny,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <LoginScreenNotice appName={appName} message={prompt} appNameTestId={appNameTestId} />\n\n <div className='passflow-form-container'>\n <LoginAlert message={error} />\n\n {scopes.length ? (\n <ul className='passflow-consent-scopes'>\n {scopes.map((item) => (\n <li key={item.scope} className='passflow-consent-scope' data-testid={`consent-scope-${item.scope}`}>\n <Switch label={item.label} checked={item.granted} disabled={busy} onChange={() => onToggleScope(item.scope)} />\n {item.description ? <p className='passflow-consent-scope-description'>{item.description}</p> : null}\n </li>\n ))}\n </ul>\n ) : (\n <p className='passflow-login-screen-hint'>This application is not requesting access to any of your data.</p>\n )}\n </div>\n\n {busy ? <LoginProgress message={busyLabel} /> : null}\n\n <div className='passflow-consent-actions'>\n <Button size='big' variant='primary' type='button' data-testid={allowTestId} disabled={busy} onClick={onAllow}>\n {allowLabel}\n </Button>\n <Button size='big' variant='outlined' type='button' data-testid={denyTestId} disabled={busy} onClick={onDeny}>\n {denyLabel}\n </Button>\n </div>\n </div>\n);\n","/* eslint-disable react/jsx-props-no-spreading */\nimport type { FC, MouseEvent, PropsWithChildren } from 'react';\nimport { useNavigation } from '@/hooks';\nimport '@/styles/index.css';\n\ntype LinkProps = PropsWithChildren<{\n to: string;\n search?: string;\n replace?: boolean;\n className?: string;\n onClick?: (e: MouseEvent<HTMLAnchorElement>) => void;\n}>;\n\nexport const Link: FC<LinkProps> = ({ to, search, replace = false, children, className, onClick, ...props }) => {\n const { navigate } = useNavigation();\n\n const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n\n if (onClick) {\n onClick(e);\n }\n\n navigate({ to, search, replace });\n };\n\n const getHref = (): string => {\n const searchParam = search ? (search.startsWith('?') ? search : `?${search}`) : '';\n return `${to}${searchParam}`;\n };\n\n return (\n <a href={getHref()} onClick={handleClick} className={className} {...props}>\n {children}\n </a>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport '@/styles/index.css';\nimport type { Providers } from '@passflow/core';\nimport { cn } from '@/utils';\n\ntype TProvidersBox = {\n providers: Providers[];\n onClick: (provider: Providers) => void;\n className?: string;\n};\n\nexport const ProvidersBox: FC<TProvidersBox> = ({ providers, onClick, className = '' }) => {\n const styles = {\n 'passflow-providers-box--grid': providers.length > 1,\n };\n\n return (\n <div className={cn('passflow-providers-box', styles, className)}>\n {providers.map((provider) => (\n <Button\n onClick={() => onClick(provider)}\n size='big'\n variant='provider'\n type='button'\n key={provider}\n withIcon\n className='passflow-provider-item'\n >\n <Icon size='small' type='providers' id={provider} decorative={providers.length <= 2} />\n {providers.length <= 2 && <p className='passflow-provider-text'>{provider}</p>}\n </Button>\n ))}\n </div>\n );\n};\n","import { phone } from 'phone';\nimport type { FC } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { Controller, useForm } from 'react-hook-form';\nimport type { DefaultMethod } from '@/types';\nimport { cn, emailRegex, passwordValidation } from '@/utils';\nimport { Button } from '../button';\nimport { FieldPassword } from '../fields/field-password';\nimport { FieldPhone } from '../fields/field-phone';\nimport { FieldText } from '../fields/field-text';\nimport { Icon } from '../icon';\nimport { Link } from '../link';\nimport { ProvidersBox } from '../providers-box';\nimport { Switch } from '../switch';\nimport { LoginActionStack, LoginAlert, LoginDivider, LoginProgress, LoginScreenNotice } from './shared';\nimport type { LoginCredentialsState, LoginCredentialsValues } from './types';\n\ntype LoginFormValues = {\n email_or_username: string;\n phone: string;\n password: string;\n};\n\nconst initialValues: LoginFormValues = {\n email_or_username: '',\n phone: '',\n password: '',\n};\n\nconst getDefaultMethod = (state: LoginCredentialsState): DefaultMethod | null => {\n if (state.initialMethod !== undefined && state.methods.identities.some((method) => method.id === state.initialMethod)) {\n return state.initialMethod;\n }\n return state.methods.identities[0]?.id ?? null;\n};\n\nexport const LoginCredentials: FC<LoginCredentialsState> = (state) => {\n const { methods } = state;\n const computedDefaultMethod = getDefaultMethod(state);\n const [defaultMethod, setDefaultMethod] = useState<DefaultMethod | null>(computedDefaultMethod);\n const [passkeyOnly, setPasskeyOnly] = useState(Boolean(state.forcePasskey));\n const previousComputedMethod = useRef(computedDefaultMethod);\n const previousForcePasskey = useRef(Boolean(state.forcePasskey));\n const {\n control,\n getValues,\n reset,\n trigger,\n watch,\n formState: { errors, isDirty, isValid, isSubmitted, touchedFields },\n handleSubmit,\n } = useForm<LoginFormValues>({\n defaultValues: initialValues,\n mode: 'onChange',\n });\n\n useEffect(() => {\n if (previousComputedMethod.current === computedDefaultMethod) return;\n previousComputedMethod.current = computedDefaultMethod;\n setDefaultMethod(computedDefaultMethod);\n reset(initialValues);\n }, [computedDefaultMethod, reset]);\n\n useEffect(() => {\n const nextForcePasskey = Boolean(state.forcePasskey);\n if (previousForcePasskey.current === nextForcePasskey) return;\n previousForcePasskey.current = nextForcePasskey;\n setPasskeyOnly(nextForcePasskey);\n }, [state.forcePasskey]);\n\n const currentIdentity = methods.identities.find((method) => method.id === defaultMethod);\n const hasPassword = Boolean(currentIdentity?.password);\n const hasPasswordless = Boolean(currentIdentity?.passwordlessLabel);\n const hasPasskey = methods.passkey;\n const hasIdentity = Boolean(currentIdentity);\n const showCredentialFields = !passkeyOnly && hasIdentity;\n const showStandalonePasskey = hasPasskey && (passkeyOnly || !hasIdentity);\n const hasCredentialActions = hasPassword || hasPasswordless || hasPasskey;\n const controlsDisabled = Boolean(state.busy || state.disabled);\n const errorScope = state.error?.scope;\n const hasIdentityError = errorScope === 'identity' || errorScope === 'credentials';\n const hasPasswordError = errorScope === 'password' || errorScope === 'credentials';\n const isNewPassword = state.credentialPurpose === 'sign-up';\n // The identity is checked on every keystroke so the submit button can enable, but a half-typed address is not an\n // error yet: its message waits until the user leaves the field or submits.\n const identityError = touchedFields.email_or_username || isSubmitted ? errors.email_or_username : undefined;\n\n const validatePassword = (value: string) => {\n if (!isNewPassword) return true;\n\n try {\n passwordValidation(state.passwordPolicy).validateSync(value);\n return true;\n } catch (error) {\n const validationError = error as { errors?: string[] };\n return validationError.errors?.join(', ') ?? 'Password does not meet the requirements';\n }\n };\n\n const toCredentials = (values: LoginFormValues): LoginCredentialsValues => ({\n method: defaultMethod,\n emailOrUsername: values.email_or_username,\n phone: values.phone,\n password: values.password,\n });\n\n const handleReset = () => {\n reset(initialValues);\n state.onReset?.();\n };\n\n const handleMethodChange = (method: DefaultMethod) => {\n setDefaultMethod(method);\n handleReset();\n };\n\n const handlePasskeyExperienceChange = (checked: boolean) => {\n setPasskeyOnly(checked);\n handleReset();\n };\n\n const submitCurrentMethod = handleSubmit((values) => {\n if (hasPassword) {\n state.onPassword?.(toCredentials(values));\n return;\n }\n if (hasPasswordless) state.onPasswordless?.(toCredentials(values));\n });\n\n const submitPasswordless = async () => {\n if (!defaultMethod || !state.onPasswordless) return;\n const identityField = defaultMethod === 'phone' ? 'phone' : 'email_or_username';\n if (!(await trigger(identityField))) return;\n state.onPasswordless(toCredentials(getValues()));\n };\n const selectedIdentityValue = defaultMethod === 'phone' ? watch('phone') : watch('email_or_username');\n const alternateIdentity = methods.identities.find((method) => method.id !== defaultMethod);\n const formAlert =\n state.error?.startAgain && state.onStartAgain ? (\n <div className='passflow-login-screen-alert-row'>\n <LoginAlert message={state.error.message} />\n <Button size='small' variant='link' type='button' disabled={controlsDisabled} onClick={state.onStartAgain}>\n Start again\n </Button>\n </div>\n ) : (\n <LoginAlert message={state.error?.message} />\n );\n\n return (\n <>\n {state.notice ? <LoginScreenNotice {...state.notice} /> : null}\n {state.allowPasskeyToggle && hasPasskey && hasIdentity && (hasPassword || hasPasswordless) ? (\n <div className='passflow-form-switch'>\n <Switch\n label='Passwordless experience'\n checked={passkeyOnly}\n disabled={controlsDisabled}\n onChange={(event) => handlePasskeyExperienceChange(event.target.checked)}\n />\n </div>\n ) : null}\n <form\n className='passflow-form'\n data-testid={state.testId}\n aria-busy={controlsDisabled && Boolean(state.busy)}\n onSubmit={submitCurrentMethod}\n >\n {state.busy ? <LoginProgress message={state.primaryLabel ?? 'Signing in…'} onCancel={state.onCancel} /> : null}\n {showCredentialFields ? (\n <>\n <div className='passflow-form-container'>\n {defaultMethod === 'email_or_username' ? (\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label\n htmlFor='email_or_username'\n className={cn('passflow-field-label', {\n 'passflow-field-label--error': hasIdentityError || Boolean(identityError),\n })}\n >\n {currentIdentity?.label}\n </label>\n {alternateIdentity ? (\n <Button\n size='small'\n variant='clean'\n type='button'\n className='passflow-field-label-button'\n disabled={controlsDisabled}\n onClick={() => handleMethodChange(alternateIdentity.id)}\n >\n {alternateIdentity.selectLabel}\n </Button>\n ) : null}\n </div>\n <Controller\n name='email_or_username'\n control={control}\n rules={{\n required: currentIdentity?.requiredMessage ?? 'Identity is required',\n ...(currentIdentity?.format === 'email'\n ? { pattern: { value: emailRegex, message: 'Invalid email' } }\n : undefined),\n }}\n render={({ field }) => (\n <FieldText\n {...field}\n id='email_or_username'\n type={currentIdentity?.format === 'email' ? 'email' : 'text'}\n autoComplete={currentIdentity?.format === 'email' ? 'email' : 'username'}\n aria-invalid={Boolean(identityError)}\n aria-describedby={identityError ? 'email_or_username-error' : undefined}\n isError={hasIdentityError || Boolean(identityError)}\n disabled={controlsDisabled}\n />\n )}\n />\n {identityError?.message ? <LoginAlert id='email_or_username-error' message={identityError.message} /> : null}\n </div>\n ) : null}\n\n {defaultMethod === 'phone' ? (\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label\n htmlFor='phone'\n className={cn('passflow-field-label', {\n 'passflow-field-label--error': hasIdentityError || Boolean(errors.phone),\n })}\n >\n Phone number\n </label>\n {alternateIdentity ? (\n <Button\n size='small'\n variant='clean'\n type='button'\n className='passflow-field-label-button'\n disabled={controlsDisabled}\n onClick={() => handleMethodChange(alternateIdentity.id)}\n >\n {alternateIdentity.selectLabel}\n </Button>\n ) : null}\n </div>\n <Controller\n name='phone'\n control={control}\n rules={{\n required: 'Phone number is required',\n validate: (value) => phone(value).isValid || 'Invalid phone number',\n }}\n render={({ field }) => (\n <FieldPhone\n id='phone'\n name='phone'\n onChange={field.onChange}\n aria-describedby={errors.phone ? 'phone-error' : undefined}\n isError={hasIdentityError || Boolean(errors.phone)}\n disabled={controlsDisabled}\n ref={null}\n />\n )}\n />\n {errors.phone?.message ? <LoginAlert id='phone-error' message={errors.phone.message} /> : null}\n </div>\n ) : null}\n\n {hasPassword ? (\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label\n htmlFor='password'\n className={cn('passflow-field-label', {\n 'passflow-field-label--error': hasPasswordError || Boolean(errors.password),\n })}\n >\n Password\n </label>\n {state.forgotPassword ? (\n <Link\n to={state.forgotPassword.to}\n search={state.forgotPassword.getSearch?.(defaultMethod)}\n className='passflow-field-label-button'\n >\n Forgot Password?\n </Link>\n ) : null}\n </div>\n <Controller\n name='password'\n control={control}\n rules={{ required: 'Password is required', validate: validatePassword }}\n render={({ field }) => (\n <FieldPassword\n {...field}\n id='password'\n name='password'\n aria-invalid={Boolean(errors.password)}\n aria-describedby={errors.password && !isNewPassword ? 'password-error' : undefined}\n isError={hasPasswordError || Boolean(errors.password)}\n passwordPolicy={state.passwordPolicy}\n withMessages={isNewPassword}\n validationErrors={\n isNewPassword && errors.password?.message ? errors.password.message.split(', ') : undefined\n }\n autoComplete={isNewPassword ? 'new-password' : 'current-password'}\n disabled={controlsDisabled}\n />\n )}\n />\n {!isNewPassword && errors.password?.message ? (\n <LoginAlert id='password-error' message={errors.password.message} />\n ) : null}\n </div>\n ) : null}\n\n {formAlert}\n </div>\n\n <LoginActionStack>\n {hasPassword && state.onPassword ? (\n <Button\n size='big'\n variant='primary'\n type='submit'\n disabled={controlsDisabled || !isDirty || !isValid}\n className='passflow-button-signin'\n data-testid={state.primaryTestId}\n >\n {state.primaryLabel ?? 'Sign In'}\n </Button>\n ) : null}\n {hasPasswordless && state.onPasswordless ? (\n <Button\n size='big'\n variant={hasPassword ? 'outlined' : 'primary'}\n type='button'\n className={cn('passflow-button-passwordless', {\n 'passflow-button-passwordless--active': hasPassword,\n })}\n disabled={controlsDisabled || selectedIdentityValue.trim().length === 0}\n onClick={() => void submitPasswordless()}\n >\n {state.passwordlessLabelPrefix ?? 'Sign In with'} {currentIdentity?.passwordlessLabel}\n </Button>\n ) : null}\n {hasPasskey && state.onPasskey ? (\n <Button\n size='big'\n variant='dark'\n type='button'\n className='passflow-button-passkey'\n withIcon\n disabled={controlsDisabled}\n onClick={state.onPasskey}\n >\n <Icon\n id='key'\n size='small'\n type='general'\n className='passflow-button-passkey-icon'\n decorative\n matchTextColor\n />\n {state.passkeyLabel ?? 'Sign In with a Passkey'}\n </Button>\n ) : null}\n </LoginActionStack>\n </>\n ) : null}\n\n {showStandalonePasskey ? (\n <>\n {formAlert}\n {state.onPasskey ? (\n <LoginActionStack>\n <Button\n size='big'\n variant='dark'\n type='button'\n className='passflow-button-passkey'\n withIcon\n disabled={controlsDisabled}\n onClick={state.onPasskey}\n >\n <Icon\n id='key'\n size='small'\n type='general'\n className='passflow-button-passkey-icon'\n decorative\n matchTextColor\n />\n {state.passkeyLabel ?? 'Sign In with a Passkey'}\n </Button>\n </LoginActionStack>\n ) : null}\n </>\n ) : null}\n\n {state.footer ? (\n <div className={cn('passflow-form-actions', { 'passflow-form-actions--top-space': hasCredentialActions })}>\n <p className='passflow-dont-have-account'>\n {state.footer.prompt}{' '}\n <Link to={state.footer.to} search={state.footer.search} className='passflow-link'>\n {state.footer.label}\n </Link>\n </p>\n </div>\n ) : null}\n\n {methods.providers.length > 0 && state.onProvider ? (\n <div className='passflow-form-providers'>\n {hasCredentialActions ? <LoginDivider label='Or continue with' /> : null}\n <ProvidersBox providers={methods.providers} onClick={state.onProvider} />\n </div>\n ) : null}\n </form>\n </>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginAlert, LoginProgress, LoginScreenNotice } from './shared';\nimport type { LoginDeviceApprovalState } from './types';\n\nexport const LoginDeviceApproval: FC<LoginDeviceApprovalState> = ({\n appName,\n code,\n identity,\n busy = false,\n error,\n actionLabel = 'Approve this device',\n busyLabel = 'Approving…',\n testId,\n actionTestId,\n codeTestId,\n appNameTestId,\n onApprove,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <LoginScreenNotice\n code={code}\n appName={appName}\n message='requested this sign-in. Confirm that the code matches your terminal.'\n codeTestId={codeTestId}\n appNameTestId={appNameTestId}\n />\n <div className='passflow-form-container passflow-login-screen-centered'>\n <div className='passflow-login-screen-success' role='status' aria-live='polite'>\n <Icon size='small' id='check' type='general' className='icon-success' decorative />\n <p className='passflow-login-screen-text'>\n {identity ? (\n <>\n Signed in as <strong className='passflow-login-screen-app-name'>{identity}</strong>.\n </>\n ) : (\n 'Signed in successfully.'\n )}\n </p>\n </div>\n <p className='passflow-login-screen-hint'>Approve this request to finish signing in on the device.</p>\n <LoginAlert message={error} />\n </div>\n {busy ? <LoginProgress message={busyLabel} /> : null}\n <Button\n size='big'\n variant='primary'\n type='button'\n autoFocus={!busy}\n data-testid={actionTestId}\n disabled={busy}\n onClick={onApprove}\n >\n {busy ? busyLabel : actionLabel}\n </Button>\n </div>\n);\n","import type { FC } from 'react';\nimport './visually-hidden.css';\n\nexport type VisuallyHiddenProps = {\n /** Referenced by a control's `aria-labelledby` or `aria-describedby`. */\n id: string;\n /** The text read by assistive technology. Plain text only. */\n children: string;\n};\n\n/**\n * Text that screen readers announce and sighted users do not see.\n *\n * For a control whose purpose the screen already shows another way, for\n * example a row of code boxes under a \"We sent a code\" subtitle, so it still\n * has an accessible name. Prefer pointing the control at visible text when\n * the screen has some.\n */\nexport const VisuallyHidden: FC<VisuallyHiddenProps> = ({ id, children }) => (\n <span id={id} className='passflow-visually-hidden'>\n {children}\n </span>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { Button } from '../button';\nimport { FieldOtp, type FieldOtpState } from '../fields/field-otp';\nimport { VisuallyHidden } from '../visually-hidden';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginEmailCodeResend, LoginEmailCodeState } from './types';\n\nconst PROMPT_ID = 'email-code-prompt';\nconst INPUT_ID = 'email-code';\nconst ERROR_ID = 'email-code-error';\nconst RESEND_HINT_ID = 'email-code-resend-hint';\nconst DEFAULT_LENGTH = 6;\nconst DEFAULT_COOLDOWN_SECONDS = 30;\n\ntype EmailCodeResendButtonProps = LoginEmailCodeResend & {\n /** Locked by the step itself, while a verify is in flight. */\n locked: boolean;\n};\n\n/**\n * Resend, with its own cooldown. The countdown is drawn in the label but hidden\n * from assistive technology, so the name stays `Resend code` and is not re-read\n * every second. While it counts down, the button is `aria-disabled`: it keeps\n * focus after a press instead of dropping the keyboard user.\n *\n * The step remounts it (`key`) when `restartKey` changes, which restarts the\n * cooldown for a code the server sent again.\n */\nexport const EmailCodeResendButton: FC<EmailCodeResendButtonProps> = ({\n cooldownSeconds = DEFAULT_COOLDOWN_SECONDS,\n busy = false,\n label = 'Resend code',\n locked,\n onResend,\n}) => {\n const [remaining, setRemaining] = useState(cooldownSeconds);\n\n useEffect(() => {\n if (remaining <= 0) return undefined;\n const timer = setTimeout(() => setRemaining((seconds) => seconds - 1), 1000);\n return () => clearTimeout(timer);\n }, [remaining]);\n\n const coolingDown = remaining > 0;\n const unavailable = coolingDown || busy || locked;\n\n const handleResend = () => {\n if (unavailable) return;\n setRemaining(cooldownSeconds);\n onResend();\n };\n\n return (\n <>\n <Button\n size='big'\n variant='clean'\n type='button'\n aria-disabled={unavailable}\n aria-describedby={coolingDown ? RESEND_HINT_ID : undefined}\n onClick={handleResend}\n >\n {busy ? 'Sending…' : label}\n {coolingDown && !busy ? <span aria-hidden='true'>{`\\u00A0(${remaining})`}</span> : null}\n </Button>\n {coolingDown ? (\n <VisuallyHidden id={RESEND_HINT_ID}>A new code can be requested when the countdown ends.</VisuallyHidden>\n ) : null}\n </>\n );\n};\n\n/**\n * The emailed verification code step: the server's prompt names a row of code\n * boxes; six digits submit by themselves. A failed verify or a resend clears the\n * typed code. While a verify is in flight the code, Resend and the way back are\n * locked, and focus returns to the code when it ends.\n */\nexport const LoginEmailCode: FC<LoginEmailCodeState> = ({\n message,\n length = DEFAULT_LENGTH,\n error,\n busy = false,\n submitLabel = 'Verify',\n resend,\n secondaryAction,\n testId,\n onSubmit,\n}) => {\n const [code, setCode] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n const wasBusy = useRef(busy);\n\n // A verify or resend that ended with an error clears the code, so the user types\n // the next one into empty boxes. Compared during render, not in an effect, so the\n // stale code is never drawn next to the error.\n const [seenOutcome, setSeenOutcome] = useState({ busy, error });\n if (seenOutcome.busy !== busy || seenOutcome.error !== error) {\n setSeenOutcome({ busy, error });\n if (!busy && error) setCode('');\n }\n\n // A new code was sent: the old one is no longer worth keeping.\n const restartKey = resend?.restartKey;\n const [seenRestartKey, setSeenRestartKey] = useState(restartKey);\n if (seenRestartKey !== restartKey) {\n setSeenRestartKey(restartKey);\n setCode('');\n }\n\n // The locked input loses focus; give it back once the verify ends.\n useEffect(() => {\n if (wasBusy.current && !busy) inputRef.current?.focus();\n wasBusy.current = busy;\n }, [busy]);\n\n const submit = (value: string) => {\n if (busy || value.length !== length) return;\n onSubmit(value);\n };\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submit(code);\n };\n\n const fieldState: FieldOtpState = busy ? 'disabled' : error ? 'error' : 'default';\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <p id={PROMPT_ID} className='passflow-login-screen-text passflow-login-screen-centered-text'>\n {message}\n </p>\n <FieldOtp\n ref={inputRef}\n id={INPUT_ID}\n name='otp'\n length={length}\n value={code}\n onChange={setCode}\n onComplete={submit}\n charset='numeric'\n state={fieldState}\n labelledBy={PROMPT_ID}\n describedBy={error ? ERROR_ID : undefined}\n autoFocus\n />\n <LoginAlert id={ERROR_ID} message={error} />\n </div>\n {busy ? <LoginProgress message='Checking the code…' /> : null}\n <LoginActionStack>\n <Button size='big' variant='primary' type='submit' disabled={busy || code.length !== length}>\n {busy ? 'Verifying…' : submitLabel}\n </Button>\n {resend ? (\n <EmailCodeResendButton\n key={restartKey}\n {...resend}\n locked={busy}\n onResend={() => {\n setCode('');\n resend.onResend();\n }}\n />\n ) : null}\n {secondaryAction ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={secondaryAction.onClick}>\n {secondaryAction.label}\n </Button>\n ) : null}\n </LoginActionStack>\n </form>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport type { LoginGeneralErrorState } from './types';\n\nexport const LoginGeneralError: FC<LoginGeneralErrorState> = ({\n message,\n detail = 'Go back to start again.',\n actionLabel = 'Go back',\n testId,\n onAction,\n}) => (\n <div className='passflow-error-container' data-testid={testId}>\n <div className='passflow-error-container-text-wrapper' role='alert' aria-live='assertive'>\n {message ? <h1 className='passflow-error-container-text'>{message}</h1> : null}\n <p className='passflow-error-container-text-secondary'>{detail}</p>\n </div>\n <Button size='big' type='button' variant='primary' onClick={onAction} className='passflow-button-go-back-error'>\n {actionLabel}\n </Button>\n </div>\n);\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginInvitationState } from './types';\n\nexport const LoginInvitation: FC<LoginInvitationState> = ({\n identity,\n inviterName,\n busy = false,\n error,\n acceptLabel = 'Accept invitation',\n busyLabel = 'Accepting invitation…',\n switchAccountLabel = 'Switch account',\n createAccountLabel = 'Create a new account',\n testId,\n acceptTestId,\n onAccept,\n onSwitchAccount,\n onCreateAccount,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n {inviterName ? (\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n <strong className='passflow-login-screen-app-name'>{inviterName}</strong> sent this invitation.\n </p>\n ) : null}\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n {identity ? (\n <>\n You&apos;re signed in as <strong className='passflow-login-screen-app-name'>{identity}</strong>.\n </>\n ) : (\n 'You’re already signed in.'\n )}\n </p>\n <p className='passflow-login-screen-hint'>Continue with this account, or switch accounts?</p>\n <LoginAlert message={error} />\n </div>\n {busy ? <LoginProgress message={busyLabel} /> : null}\n <LoginActionStack>\n <Button\n size='big'\n variant='primary'\n type='button'\n autoFocus={!busy}\n data-testid={acceptTestId}\n disabled={busy}\n onClick={onAccept}\n >\n {busy ? busyLabel : acceptLabel}\n </Button>\n <Button size='big' variant='outlined' type='button' disabled={busy} onClick={onSwitchAccount}>\n {switchAccountLabel}\n </Button>\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={onCreateAccount}>\n {createAccountLabel}\n </Button>\n </LoginActionStack>\n </div>\n);\n","import type { FC } from 'react';\nimport { Controller, useForm } from 'react-hook-form';\nimport { cn, passwordValidation } from '@/utils';\nimport { Button } from '../button';\nimport { FieldPassword } from '../fields/field-password';\nimport { LoginAlert, LoginProgress } from './shared';\nimport type { LoginNewPasswordState } from './types';\n\ntype NewPasswordValues = { password: string };\n\nconst ERROR_ID = 'new-password-error';\nconst VALIDATION_ERROR_ID = 'new-password-validation-error';\n\n/**\n * Choosing a new password, checked against the app's password policy as it is\n * typed: for a reset, or to finish an account started by email. The field keeps\n * `id=\"password\"`, and the button the `passflow-button-reset-password` class, so an\n * app's custom CSS still finds them.\n */\nexport const LoginNewPassword: FC<LoginNewPasswordState> = ({\n passwordPolicy,\n label = 'New password',\n hint = 'Enter your new password below.',\n error,\n busy = false,\n submitLabel = 'Save new password',\n testId,\n onSubmit,\n}) => {\n const {\n control,\n handleSubmit,\n formState: { errors, isDirty, isValid },\n } = useForm<NewPasswordValues>({\n defaultValues: { password: '' },\n mode: 'onChange',\n });\n\n const validatePassword = (value: string) => {\n try {\n passwordValidation(passwordPolicy).validateSync(value);\n return true;\n } catch (validationError) {\n const { errors: messages } = validationError as { errors?: string[] };\n return messages?.join(', ') ?? 'Password does not meet the requirements';\n }\n };\n\n const submit = handleSubmit((values) => {\n if (!busy) onSubmit(values.password);\n });\n\n const validationMessage = errors.password?.message;\n // With a policy, FieldPassword lists what is missing; without one, say it in an alert.\n const showValidationAlert = !passwordPolicy && Boolean(validationMessage);\n const describedBy = [error ? ERROR_ID : null, showValidationAlert ? VALIDATION_ERROR_ID : null].filter(Boolean).join(' ');\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={submit}>\n {hint ? <p className='passflow-login-screen-hint'>{hint}</p> : null}\n <div className='passflow-form-container'>\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label htmlFor='password' className={cn('passflow-field-label', { 'passflow-field-label--error': Boolean(error) })}>\n {label}\n </label>\n </div>\n <Controller\n name='password'\n control={control}\n rules={{ required: 'Password is required', validate: validatePassword }}\n render={({ field }) => (\n <FieldPassword\n {...field}\n id='password'\n name='password'\n autoComplete='new-password'\n aria-invalid={Boolean(error) || Boolean(validationMessage)}\n aria-describedby={describedBy || undefined}\n isError={Boolean(error)}\n passwordPolicy={passwordPolicy}\n withMessages\n validationErrors={validationMessage ? validationMessage.split(', ') : undefined}\n disabled={busy}\n />\n )}\n />\n {showValidationAlert ? <LoginAlert id={VALIDATION_ERROR_ID} message={validationMessage} /> : null}\n </div>\n <LoginAlert id={ERROR_ID} message={error} />\n </div>\n {busy ? <LoginProgress message='Saving your password…' /> : null}\n <Button\n size='big'\n variant='primary'\n type='submit'\n disabled={busy || !isDirty || !isValid}\n className='passflow-button-reset-password'\n >\n {busy ? 'Saving…' : submitLabel}\n </Button>\n </form>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginAlert } from './shared';\nimport type { LoginPasskeyProgressState } from './types';\n\nexport const LoginPasskeyProgress: FC<LoginPasskeyProgressState> = ({\n working,\n message,\n actionLabel = 'Continue with a passkey',\n error,\n recoverable = false,\n retryLabel = 'Try again',\n testId,\n onAction,\n onRetry,\n}) => (\n <div className='passflow-form' data-testid={testId}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <div className='passflow-login-screen-status' role='status'>\n {working ? <div className='passflow-login-screen-spinner' aria-hidden='true' /> : null}\n <p className='passflow-login-screen-text'>{message}</p>\n </div>\n <LoginAlert message={error} />\n </div>\n {!working && onAction ? (\n <Button size='big' variant='dark' type='button' className='passflow-button-passkey' withIcon onClick={onAction}>\n <Icon id='key' size='small' type='general' className='icon-white passflow-button-passkey-icon' decorative />\n {actionLabel}\n </Button>\n ) : !working && error && recoverable && onRetry ? (\n <Button size='big' variant='dark' type='button' className='passflow-button-passkey' withIcon onClick={onRetry}>\n <Icon id='key' size='small' type='general' className='icon-white passflow-button-passkey-icon' decorative />\n {retryLabel}\n </Button>\n ) : null}\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { Button } from '../button';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginPasswordlessApprovalFormState, LoginPasswordlessApprovalState } from './types';\n\n/**\n * Approving a sign-in started on any device, in one click. The request details are shown, and the two answers are\n * equally prominent. While an answer is in flight both are locked.\n */\nconst LoginPasswordlessApprovalForm: FC<LoginPasswordlessApprovalFormState> = ({\n appName,\n browser,\n os,\n location,\n requestedAt,\n error,\n busy = false,\n testId,\n onApprove,\n onDeny,\n}) => {\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!busy) onApprove();\n };\n\n const details = [\n { label: 'Application', value: appName },\n { label: 'Browser', value: browser },\n { label: 'Operating system', value: os },\n { label: 'Location', value: location },\n { label: 'Time', value: requestedAt },\n ];\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <dl className='passflow-login-screen-details'>\n {details.map(({ label, value }) =>\n value ? (\n <div key={label} className='passflow-login-screen-details-row'>\n <dt className='passflow-login-screen-details-label'>{label}</dt>\n <dd className='passflow-login-screen-details-value'>{value}</dd>\n </div>\n ) : null,\n )}\n </dl>\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n Choose Sign in only if you just started signing in. If you didn't, choose This wasn't me.\n </p>\n <LoginAlert message={error} />\n </div>\n {busy ? <LoginProgress message='Sending your answer…' /> : null}\n <LoginActionStack>\n <Button size='big' variant='primary' type='submit' disabled={busy}>\n Sign in\n </Button>\n <Button size='big' variant='warning' type='button' disabled={busy} onClick={onDeny}>\n This wasn't me\n </Button>\n </LoginActionStack>\n </form>\n );\n};\n\nexport const LoginPasswordlessApproval: FC<LoginPasswordlessApprovalState> = (state) =>\n state.loading ? (\n <div className='passflow-form'>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <LoginProgress message='Loading the sign-in request…' />\n </div>\n </div>\n ) : (\n <LoginPasswordlessApprovalForm {...state} />\n );\n","import type { FC } from 'react';\nimport { EmailCodeResendButton } from './email-code';\nimport { LoginActionStack, LoginAlert } from './shared';\nimport type { LoginPasswordlessWaitingState } from './types';\n\nexport const LoginPasswordlessWaiting: FC<LoginPasswordlessWaitingState> = ({ error, resend, testId }) => (\n <div className='passflow-form' data-testid={testId}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n <div className='passflow-login-screen-notice' role='status'>\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>\n Open the link we sent on any device and choose Sign in.\n </p>\n </div>\n <LoginAlert message={error} />\n </div>\n {resend ? (\n <LoginActionStack>\n <EmailCodeResendButton key={resend.restartKey} label='Resend email' {...resend} locked={false} />\n </LoginActionStack>\n ) : null}\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useState } from 'react';\nimport { Button } from '../button';\nimport { FieldText } from '../fields/field-text';\nimport { LoginAlert, LoginProgress } from './shared';\nimport type { LoginSecondFactorMethod, LoginSecondFactorState } from './types';\n\n/** The words for each factor, matching the sign-in's own two-factor screens. */\nconst METHOD_COPY: Record<LoginSecondFactorMethod, { label: string; hint: string; switchLabel: string }> = {\n totp: {\n label: 'Authenticator code',\n hint: 'Enter the code from your authenticator app.',\n switchLabel: 'Use authenticator app',\n },\n recovery_codes: {\n label: 'Recovery code',\n hint: 'Enter one of your recovery codes.',\n switchLabel: 'Use recovery code',\n },\n};\n\nexport const LoginSecondFactor: FC<LoginSecondFactorState> = ({\n methods,\n identity,\n busy = false,\n error,\n submitLabel = 'Verify',\n testId,\n onSubmit,\n onMethodChange,\n}) => {\n const [method, setMethod] = useState<LoginSecondFactorMethod>(methods[0] ?? 'totp');\n const [code, setCode] = useState('');\n const alternate = methods.find((m) => m !== method);\n const copy = METHOD_COPY[method];\n const isTOTP = method === 'totp';\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const normalizedCode = code.trim();\n if (normalizedCode) onSubmit(method, normalizedCode);\n };\n\n const switchTo = (next: LoginSecondFactorMethod) => {\n setMethod(next);\n setCode('');\n onMethodChange?.();\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container'>\n {identity ? (\n <p className='passflow-login-screen-hint'>\n Signed in as <strong className='passflow-login-screen-app-name'>{identity}</strong>.\n </p>\n ) : null}\n <div className='passflow-form-field'>\n <div className='passflow-form-field__header'>\n <label htmlFor='second-factor-code' className='passflow-field-label'>\n {copy.label}\n </label>\n {alternate ? (\n <Button\n size='small'\n variant='clean'\n type='button'\n className='passflow-field-label-button'\n disabled={busy}\n onClick={() => switchTo(alternate)}\n >\n {METHOD_COPY[alternate].switchLabel}\n </Button>\n ) : null}\n </div>\n <FieldText\n id='second-factor-code'\n name={isTOTP ? 'otp' : 'recovery_code'}\n type='text'\n autoComplete={isTOTP ? 'one-time-code' : 'off'}\n autoCapitalize={isTOTP ? 'off' : 'characters'}\n autoCorrect='off'\n spellCheck={false}\n inputMode={isTOTP ? 'numeric' : 'text'}\n autoFocus\n className='passflow-login-screen-code-input'\n value={code}\n disabled={busy}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? 'second-factor-code-error' : 'second-factor-code-hint'}\n isError={Boolean(error)}\n onChange={(event) => setCode(event.target.value)}\n />\n <p id='second-factor-code-hint' className='passflow-login-screen-hint'>\n {copy.hint}\n </p>\n </div>\n <LoginAlert id='second-factor-code-error' message={error} />\n </div>\n {busy ? <LoginProgress message='Checking the code…' /> : null}\n <Button size='big' variant='primary' type='submit' disabled={busy || code.trim().length === 0}>\n {busy ? 'Checking…' : submitLabel}\n </Button>\n </form>\n );\n};\n","import type { FC, PropsWithChildren } from 'react';\nimport { cn } from '@/utils';\nimport { Icon } from '../icon';\nimport '@/styles/index.css';\nimport './login-screen.css';\n\nexport type LoginScreenShellProps = PropsWithChildren & {\n iconId?: string;\n title?: string;\n subtitle?: string;\n className?: string;\n customCss?: string;\n customLogo?: string;\n customLogoAlt?: string;\n removeBranding?: boolean;\n};\n\nexport const LoginScreenShell: FC<LoginScreenShellProps> = ({\n iconId = 'logo',\n title = '',\n subtitle = '',\n className = '',\n children,\n customCss,\n customLogo,\n customLogoAlt = 'Application logo',\n removeBranding = false,\n}) => (\n <div id='passflow-wrapper' className='passflow-wrapper'>\n {/*\n * The app's custom CSS (login theme `custom_css`), rendered inline as the\n * last layer so it overrides the kit's styles. Only when there is some.\n */}\n {customCss ? (\n <style className='psfw-custom-styles' data-passflow-style-layer='custom'>\n {customCss}\n </style>\n ) : null}\n <main className={cn('passflow-form-main-wrapper', className)}>\n <div className='passflow-form-main-container'>\n {customLogo ? (\n <img src={customLogo} alt={customLogoAlt} className='passflow-form-main-container-logo' />\n ) : (\n <Icon id={iconId} size='large' type='general' decorative />\n )}\n {title ? (\n <div className='passflow-form-header'>\n <h1 className='passflow-form-title'>{title}</h1>\n {subtitle ? <span className='passflow-form-subtitle'>{subtitle}</span> : null}\n </div>\n ) : null}\n </div>\n {children}\n </main>\n {!removeBranding ? (\n <footer className='passflow-branding'>\n <p className='passflow-branding-text'>\n Secured by <span className='passflow-branding-text-secondary passflow-secondary-font'>PASSFLOW</span>\n </p>\n </footer>\n ) : null}\n </div>\n);\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginActionStack, LoginAlert, LoginProgress } from './shared';\nimport type { LoginStatusState } from './types';\n\nexport const LoginStatus: FC<LoginStatusState> = ({\n tone,\n message,\n detail,\n error,\n recoverable = false,\n retryLabel = 'Try again',\n testId,\n onRetry,\n primaryAction,\n secondaryAction,\n}) => {\n const busy = primaryAction?.busy ?? false;\n const canRetry = !primaryAction && tone === 'error' && recoverable && Boolean(onRetry);\n\n return (\n <div className='passflow-form' data-testid={testId} aria-busy={busy || undefined}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n {tone === 'working' ? (\n <LoginProgress message={message} />\n ) : tone === 'success' ? (\n <div className='passflow-login-screen-success' role='status'>\n <Icon size='small' id='check' type='general' className='icon-success' decorative />\n <span className='passflow-login-screen-success-text'>{message}</span>\n </div>\n ) : tone === 'info' ? (\n <div className='passflow-login-screen-info' role='status'>\n <Icon size='big' id='mail' type='general' className='passflow-login-screen-info-icon' matchTextColor decorative />\n <p className='passflow-login-screen-text passflow-login-screen-centered-text'>{message}</p>\n </div>\n ) : (\n <LoginAlert message={message} />\n )}\n {detail ? <p className='passflow-login-screen-hint'>{detail}</p> : null}\n <LoginAlert message={error} />\n </div>\n {primaryAction || canRetry || secondaryAction ? (\n <LoginActionStack>\n {primaryAction ? (\n <Button size='big' variant='primary' type='button' disabled={busy} onClick={primaryAction.onClick}>\n {primaryAction.label}\n </Button>\n ) : canRetry ? (\n <Button size='big' variant='primary' type='button' onClick={onRetry}>\n {retryLabel}\n </Button>\n ) : null}\n {secondaryAction ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={secondaryAction.onClick}>\n {secondaryAction.label}\n </Button>\n ) : null}\n </LoginActionStack>\n ) : null}\n </div>\n );\n};\n","import type { FC, FormEvent } from 'react';\nimport { useId } from 'react';\nimport { cn } from '@/utils';\nimport { Button } from '../button';\nimport { FieldOtp } from '../fields/field-otp';\nimport { FieldText } from '../fields/field-text';\nimport { Switch } from '../switch';\nimport { LoginActionStack, LoginAlert, useFocusAfterBusy } from './shared';\nimport type { LoginTwoFactorCodeState } from './types';\n\n/**\n * Asking for a second factor at sign-in: authenticator boxes or a recovery code field, with the trust switch above\n * them when the state offers it. The screen owns no code: a submit on the last digit belongs to the caller's\n * `onCodeChange`.\n */\nexport const LoginTwoFactorCode: FC<LoginTwoFactorCodeState> = ({\n factor,\n label,\n code,\n trustDevice,\n busy = false,\n canSubmit,\n locked = false,\n alert,\n submitLabel,\n busyLabel,\n alternate,\n secondaryAction,\n autoFocus = false,\n testId,\n onCodeChange,\n onSubmit,\n}) => {\n const inputId = useId();\n const alertId = `${inputId}-alert`;\n const inputRef = useFocusAfterBusy(busy);\n const disabled = busy || locked;\n const isError = alert?.tone === 'error';\n const describedBy = alert ? alertId : undefined;\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (canSubmit && !disabled) onSubmit();\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container'>\n {/* Above the code: the code can submit itself on its last digit. */}\n {trustDevice ? (\n <div className='passflow-form-field'>\n <Switch\n label={trustDevice.label}\n checked={trustDevice.checked}\n disabled={disabled}\n onChange={(event) => trustDevice.onChange(event.target.checked)}\n />\n </div>\n ) : null}\n {factor.type === 'totp' ? (\n <div className='passflow-verify-otp-wrapper'>\n <FieldOtp\n ref={inputRef}\n id={inputId}\n name='code'\n length={factor.digits}\n value={code}\n onChange={onCodeChange}\n state={disabled ? 'disabled' : isError ? 'error' : 'default'}\n label={label}\n describedBy={describedBy}\n autoFocus={autoFocus && !disabled}\n />\n </div>\n ) : (\n <div className='passflow-form-field'>\n <label htmlFor={inputId} className={cn('passflow-field-label', isError && 'passflow-field-label--error')}>\n {label}\n </label>\n <FieldText\n ref={inputRef}\n id={inputId}\n name='recovery_code'\n autoCapitalize='characters'\n autoComplete='off'\n autoCorrect='off'\n spellCheck={false}\n placeholder={factor.placeholder}\n className='passflow-login-screen-code-input'\n value={code}\n disabled={disabled}\n autoFocus={autoFocus && !disabled}\n aria-invalid={isError}\n aria-describedby={describedBy}\n isError={isError}\n onChange={(event) => onCodeChange(event.target.value)}\n />\n </div>\n )}\n <LoginAlert id={alertId} message={alert?.message} tone={alert?.tone} />\n </div>\n {!locked || secondaryAction ? (\n <LoginActionStack>\n {locked ? null : (\n <Button size='big' variant='primary' type='submit' disabled={busy || !canSubmit}>\n {busy ? busyLabel : submitLabel}\n </Button>\n )}\n {secondaryAction ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={secondaryAction.onClick}>\n {secondaryAction.label}\n </Button>\n ) : null}\n </LoginActionStack>\n ) : null}\n {alternate && !locked ? (\n <div className='passflow-form-actions'>\n <p className='passflow-dont-have-account'>\n {alternate.prompt}{' '}\n <Button size='small' variant='link' type='button' disabled={busy} onClick={alternate.onClick}>\n {alternate.label}\n </Button>\n </p>\n </div>\n ) : null}\n </form>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { LoginActionStack, LoginAlert } from './shared';\nimport type { LoginTwoFactorRecoveryCodesState } from './types';\n\n/** The recovery codes, shown once. They stay on screen through a failed `onContinue`, so they are not lost. */\nexport const LoginTwoFactorRecoveryCodes: FC<LoginTwoFactorRecoveryCodesState> = ({\n warning,\n codes,\n copyLabel,\n continueLabel,\n busyLabel,\n busy = false,\n error,\n testId,\n onCopy,\n onContinue,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n <div className='passflow-form-container'>\n <div className='passflow-2fa-warning' role='note'>\n <Icon size='small' id='warning' type='general' className='icon-warning' decorative />\n <span className='passflow-2fa-warning-text'>{warning}</span>\n </div>\n <ul className='passflow-2fa-recovery-codes'>\n {codes.map((code) => (\n <li key={code}>\n <code className='passflow-2fa-recovery-code'>{code}</code>\n </li>\n ))}\n </ul>\n <LoginAlert message={error} />\n </div>\n <LoginActionStack>\n <Button size='big' variant='secondary' type='button' onClick={onCopy}>\n {copyLabel}\n </Button>\n <Button size='big' variant='primary' type='button' disabled={busy} onClick={onContinue}>\n {busy ? busyLabel : continueLabel}\n </Button>\n </LoginActionStack>\n </div>\n);\n","import type { FC, FormEvent } from 'react';\nimport { useId, useState } from 'react';\nimport { Button } from '../button';\nimport { FieldOtp } from '../fields/field-otp';\nimport { LoginActionStack, LoginAlert, useFocusAfterBusy } from './shared';\nimport type {\n LoginScreenAction,\n LoginTwoFactorSetupCodeState,\n LoginTwoFactorSetupStartState,\n LoginTwoFactorSetupState,\n} from './types';\n\nconst SecondaryAction: FC<{ action?: LoginScreenAction; busy: boolean }> = ({ action, busy }) =>\n action ? (\n <Button size='big' variant='clean' type='button' disabled={busy} onClick={action.onClick}>\n {action.label}\n </Button>\n ) : null;\n\nconst LoginTwoFactorSetupStart: FC<LoginTwoFactorSetupStartState> = ({\n startLabel,\n busyLabel,\n busy = false,\n error,\n secondaryAction,\n testId,\n onStart,\n}) => (\n <div className='passflow-form' data-testid={testId} aria-busy={busy}>\n {error ? (\n <div className='passflow-form-container passflow-login-screen-centered'>\n <LoginAlert message={error} />\n </div>\n ) : null}\n <LoginActionStack>\n <Button size='big' variant='primary' type='button' disabled={busy} onClick={onStart}>\n {busy ? busyLabel : startLabel}\n </Button>\n <SecondaryAction action={secondaryAction} busy={busy} />\n </LoginActionStack>\n </div>\n);\n\n/** The caller shows a new secret by passing it: `LoginTwoFactorSetup` remounts this step, so the typed code clears. */\nconst LoginTwoFactorSetupCode: FC<LoginTwoFactorSetupCodeState> = ({\n qrCode,\n qrAlt,\n secret,\n secretLabel,\n showSecretLabel,\n hideSecretLabel,\n digits,\n codeLabel,\n submitLabel,\n busyLabel,\n busy = false,\n alert,\n secondaryAction,\n testId,\n onSubmit,\n}) => {\n const [code, setCode] = useState('');\n const [secretShown, setSecretShown] = useState(false);\n const inputId = useId();\n const alertId = `${inputId}-alert`;\n const inputRef = useFocusAfterBusy(busy);\n const canSubmit = code.length === digits;\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (canSubmit && !busy) onSubmit(code);\n };\n\n return (\n <form className='passflow-form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit}>\n <div className='passflow-form-container passflow-login-screen-centered'>\n {qrCode ? (\n <>\n <div className='passflow-2fa-qr-container'>\n <img src={`data:image/png;base64,${qrCode}`} alt={qrAlt} className='passflow-2fa-qr-image' />\n </div>\n <p className='passflow-login-screen-hint'>\n <Button size='small' variant='link' type='button' onClick={() => setSecretShown((shown) => !shown)}>\n {secretShown ? hideSecretLabel : showSecretLabel}\n </Button>\n </p>\n </>\n ) : null}\n {secretShown || !qrCode ? (\n <div className='passflow-2fa-secret'>\n <p className='passflow-login-screen-hint'>{secretLabel}</p>\n <code className='passflow-2fa-secret-code'>{secret}</code>\n </div>\n ) : null}\n <FieldOtp\n ref={inputRef}\n id={inputId}\n name='code'\n length={digits}\n value={code}\n onChange={setCode}\n state={busy ? 'disabled' : alert?.tone === 'error' ? 'error' : 'default'}\n label={codeLabel}\n describedBy={alert ? alertId : undefined}\n autoFocus={!busy}\n />\n <LoginAlert id={alertId} message={alert?.message} tone={alert?.tone} />\n </div>\n <LoginActionStack>\n <Button size='big' variant='primary' type='submit' disabled={busy || !canSubmit}>\n {busy ? busyLabel : submitLabel}\n </Button>\n <SecondaryAction action={secondaryAction} busy={busy} />\n </LoginActionStack>\n </form>\n );\n};\n\nexport const LoginTwoFactorSetup: FC<LoginTwoFactorSetupState> = (state) =>\n state.step === 'start' ? <LoginTwoFactorSetupStart {...state} /> : <LoginTwoFactorSetupCode key={state.secret} {...state} />;\n","import type { FC } from 'react';\nimport { LoginCodeEntry } from './code-entry';\nimport { LoginConsent } from './consent';\nimport { LoginCredentials } from './credentials';\nimport { LoginDeviceApproval } from './device-approval';\nimport { LoginEmailCode } from './email-code';\nimport { LoginGeneralError } from './general-error';\nimport { LoginInvitation } from './invitation';\nimport { LoginNewPassword } from './new-password';\nimport { LoginPasskeyProgress } from './passkey-progress';\nimport { LoginPasswordlessApproval } from './passwordless-approval';\nimport { LoginPasswordlessWaiting } from './passwordless-waiting';\nimport { LoginSecondFactor } from './second-factor';\nimport { LoginScreenShell } from './shell';\nimport { LoginStatus } from './status';\nimport { LoginTwoFactorCode } from './two-factor-code';\nimport { LoginTwoFactorRecoveryCodes } from './two-factor-recovery-codes';\nimport { LoginTwoFactorSetup } from './two-factor-setup';\nimport type { LoginScreenProps } from './types';\n\nexport const LoginScreen: FC<LoginScreenProps> = ({ chrome, state }) => {\n const content = (() => {\n switch (state.kind) {\n case 'credentials':\n return <LoginCredentials {...state} />;\n case 'code-entry':\n return <LoginCodeEntry {...state} />;\n case 'email-code':\n return <LoginEmailCode {...state} />;\n case 'passwordless-waiting':\n return <LoginPasswordlessWaiting {...state} />;\n case 'passwordless-approval':\n return <LoginPasswordlessApproval {...state} />;\n case 'new-password':\n return <LoginNewPassword {...state} />;\n case 'passkey-progress':\n return <LoginPasskeyProgress {...state} />;\n case 'device-approval':\n return <LoginDeviceApproval {...state} />;\n case 'second-factor':\n return <LoginSecondFactor {...state} />;\n case 'two-factor-code':\n return <LoginTwoFactorCode {...state} />;\n case 'two-factor-setup':\n return <LoginTwoFactorSetup {...state} />;\n case 'two-factor-recovery-codes':\n return <LoginTwoFactorRecoveryCodes {...state} />;\n case 'invitation':\n return <LoginInvitation {...state} />;\n case 'general-error':\n return <LoginGeneralError {...state} />;\n case 'consent':\n return <LoginConsent {...state} />;\n case 'status':\n return <LoginStatus {...state} />;\n }\n })();\n const isError = state.kind === 'general-error' || (state.kind === 'status' && state.tone === 'error');\n const className =\n state.kind === 'general-error'\n ? 'passflow-error-wrapper'\n : chrome.variant === 'sign-in'\n ? 'passflow-signin-wrapper'\n : chrome.variant === 'reset-password'\n ? 'passflow-reset-password-wrapper'\n : undefined;\n\n return (\n <LoginScreenShell\n iconId={isError ? 'logo-red' : 'logo'}\n title={chrome.title}\n subtitle={chrome.subtitle}\n className={className}\n customCss={chrome.customCss}\n customLogo={chrome.customLogo}\n customLogoAlt={chrome.customLogoAlt}\n removeBranding={chrome.removeBranding}\n >\n {content}\n </LoginScreenShell>\n );\n};\n","import type { FC } from 'react';\nimport { Button } from '../button';\nimport type { UpgradeDialogFactor, UpgradeFactorType } from './types';\n\ntype UpgradeFactorListProps = {\n factors: readonly UpgradeDialogFactor[];\n selected: UpgradeFactorType;\n disabled?: boolean;\n label?: string;\n onSelect: (factor: UpgradeFactorType) => void;\n};\n\n/**\n * The \"use another way\" alternatives. Selecting one reports the user's choice;\n * it never navigates.\n *\n * Each row is `Button variant='option'`: the two-line geometry and the pressed\n * look belong to that variant in the button library, not to this list. The list\n * contributes layout only.\n */\nexport const UpgradeFactorList: FC<UpgradeFactorListProps> = ({\n factors,\n selected,\n disabled = false,\n label = 'Other verification methods',\n onSelect,\n}) => (\n <ul className='passflow-upgrade-dialog__alternatives' aria-label={label}>\n {factors.map((factor) => (\n <li key={factor.type} className='passflow-upgrade-dialog__alternative'>\n <Button\n size='big'\n variant='option'\n type='button'\n disabled={disabled}\n pressed={factor.type === selected}\n description={factor.hint}\n data-testid={`upgrade-dialog-factor-${factor.type}`}\n onClick={() => onSelect(factor.type)}\n >\n {factor.label}\n </Button>\n </li>\n ))}\n </ul>\n);\n","import { type FC, type FormEvent, useRef, useState } from 'react';\nimport { Button } from '../button';\nimport { FieldText } from '../fields/field-text';\nimport { LoginAlert } from '../login-screen';\nimport { UpgradeFactorList } from './factor-list';\nimport type { UpgradeDialogChallengeState, UpgradeFactorType } from './types';\n\nconst CODE_FIELD_ID = 'passflow-upgrade-code';\nconst CODE_ERROR_ID = 'passflow-upgrade-code-error';\n\n/**\n * The collecting view: the suggested factor, its input affordance, the\n * alternatives toggle, and the two terminal controls.\n *\n * Selection is reported through `onSelectFactor` before `onSubmit` ever fires —\n * architecture §13.2's late-join boundary is factor selection, not submission,\n * so the controller must learn of the choice while the user is still typing.\n */\nexport const UpgradeChallengeView: FC<UpgradeDialogChallengeState> = ({\n factors,\n selected,\n busy = false,\n error,\n showAlternatives = false,\n submitLabel = 'Verify',\n cancelLabel = 'Cancel',\n alternativesLabel = 'Use another way',\n testId,\n onSelectFactor,\n onToggleAlternatives,\n onSubmit,\n onCancel,\n}) => {\n const [code, setCode] = useState('');\n const reported = useRef<UpgradeFactorType | null>(null);\n\n const active = factors.find((factor) => factor.type === selected) ?? factors[0];\n // The code contract travels WITH the factor (§H12): length, charset and\n // autofill are the factor's own statement, never this component's guess. A\n // six-character cap applied to every factor truncated a 12-character recovery\n // code into a guaranteed rejection.\n const codeContract = active?.input === 'code' ? active.code : undefined;\n const needsCode = codeContract !== undefined;\n const hasAlternatives = factors.length > 1;\n\n const report = (factor: UpgradeFactorType) => {\n if (reported.current === factor) return;\n reported.current = factor;\n onSelectFactor(factor);\n };\n\n const choose = (factor: UpgradeFactorType) => {\n setCode('');\n report(factor);\n };\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!active) return;\n const trimmed = code.trim();\n if (needsCode && trimmed.length === 0) return;\n report(active.type);\n onSubmit(needsCode ? trimmed : undefined);\n };\n\n return (\n <form className='passflow-upgrade-dialog__form' data-testid={testId} aria-busy={busy} onSubmit={handleSubmit} noValidate>\n {active ? (\n <div className='passflow-upgrade-dialog__factor'>\n <span className='passflow-upgrade-dialog__factor-label'>{active.label}</span>\n {active.hint ? <span className='passflow-upgrade-dialog__factor-hint'>{active.hint}</span> : null}\n </div>\n ) : null}\n\n {codeContract ? (\n <div className='passflow-upgrade-dialog__field'>\n <label htmlFor={CODE_FIELD_ID} className='passflow-field-label'>\n Verification code\n </label>\n <FieldText\n id={CODE_FIELD_ID}\n name='upgrade_code'\n type='text'\n inputMode={codeContract.inputMode}\n autoComplete={codeContract.autoComplete}\n autoCorrect='off'\n autoCapitalize={codeContract.autoCapitalize}\n spellCheck={false}\n maxLength={codeContract.maxLength}\n value={code}\n disabled={busy}\n isError={Boolean(error)}\n aria-invalid={Boolean(error)}\n aria-describedby={error ? CODE_ERROR_ID : undefined}\n data-testid='upgrade-dialog-code'\n onChange={(event) => setCode(event.target.value)}\n />\n </div>\n ) : null}\n\n <LoginAlert id={CODE_ERROR_ID} message={error} />\n\n <div className='passflow-upgrade-dialog__actions'>\n <Button\n size='big'\n variant='primary'\n type='submit'\n disabled={busy || !active || (needsCode && code.trim().length === 0)}\n data-testid='upgrade-dialog-submit'\n >\n {busy ? 'Verifying…' : submitLabel}\n </Button>\n {hasAlternatives ? (\n <Button\n size='big'\n variant='clean'\n type='button'\n disabled={busy}\n aria-expanded={showAlternatives}\n data-testid='upgrade-dialog-alternatives'\n onClick={onToggleAlternatives}\n >\n {alternativesLabel}\n </Button>\n ) : null}\n {showAlternatives && hasAlternatives ? (\n <UpgradeFactorList factors={factors} selected={selected} disabled={busy} onSelect={choose} />\n ) : null}\n <Button size='big' variant='clean' type='button' data-testid='upgrade-dialog-cancel' onClick={onCancel}>\n {cancelLabel}\n </Button>\n </div>\n </form>\n );\n};\n","/**\n * Pure mapping from the controller's prompt request plus local UI state to the\n * dialog's rendering union. No React, no DOM, no styling — architecture §10.2\n * classifies this as non-visual state mapping, which is why it is the one file\n * in this folder a Vitest spec may cover.\n *\n * The inputs are declared structurally — `UpgradePromptSnapshot` is the shape of\n * `UpgradePromptRequest` that the dialog actually reads — but the one judgement\n * that is NOT structural is which kind of failure an error is: that belongs to\n * `@passflow/core`, which raises the errors, and is imported from it.\n */\n\nimport { classifyUpgradeError, type UpgradeErrorKind } from '@passflow/core';\nimport type {\n AssuranceBar,\n UpgradeDialogFactor,\n UpgradeDialogState,\n UpgradeFactorCodeContract,\n UpgradeFactorInput,\n UpgradeFactorType,\n} from './types';\n\nexport type UpgradeChallengeSnapshot = {\n requiredLevel?: number;\n acrValues?: string;\n maxAge?: number;\n};\n\nexport type UpgradeFactorSnapshot = {\n type: UpgradeFactorType;\n input: UpgradeFactorInput;\n};\n\nexport type UpgradePromptSnapshot = {\n challenge: UpgradeChallengeSnapshot;\n /** Already ranked by `selectFactors`; index 0 is the suggested factor. */\n factors: readonly UpgradeFactorSnapshot[];\n previousError?: unknown;\n};\n\nexport type UpgradeDialogLabels = Partial<Record<UpgradeFactorType, { label: string; hint?: string }>>;\n\n/** How the flight ended, as the controller's outcome summary reports it (§13.4). */\nexport type UpgradeDialogOutcome =\n | { kind: 'elevated' }\n | { kind: 'insufficient'; obtained: AssuranceBar; required: AssuranceBar }\n | { kind: 'cancelled' }\n | { kind: 'failed'; error: unknown };\n\nexport type UpgradeDialogUiState = {\n selected?: UpgradeFactorType | null;\n busy?: boolean;\n showAlternatives?: boolean;\n};\n\nexport type UpgradeDialogHandlers = {\n onSelectFactor: (factor: UpgradeFactorType) => void;\n onToggleAlternatives: () => void;\n onSubmit: (code?: string) => void;\n onCancel: () => void;\n onDismiss: () => void;\n onRetry?: () => void;\n /** Sends the user to sign in again, from a state that offers it. */\n onSignIn?: () => void;\n};\n\nexport type ToDialogStateInput = {\n prompt: UpgradePromptSnapshot | null;\n outcome?: UpgradeDialogOutcome;\n ui?: UpgradeDialogUiState;\n labels?: UpgradeDialogLabels;\n handlers: UpgradeDialogHandlers;\n testId?: string;\n};\n\n/**\n * How an elevation failure reads to the user. `rejected` is the retryable\n * wrong-answer case, which keeps the dialog open on the challenge.\n */\nexport type UpgradeDialogErrorKind =\n | 'rejected'\n | 'cancelled'\n | 'exhausted'\n | 'unsatisfiable'\n | 'unavailable'\n | 'transport'\n | 'insufficient'\n | 'session-changed'\n | 'rate-limited'\n | 'sign-in-required';\n\nexport const DEFAULT_FACTOR_LABELS: Record<UpgradeFactorType, { label: string; hint?: string }> = {\n totp: { label: 'Authenticator app', hint: 'Enter the code from your authenticator app' },\n passkey: { label: 'Passkey', hint: 'Confirm with your device' },\n recovery_codes: { label: 'Recovery code', hint: 'Enter one of your single-use recovery codes' },\n email_otp: { label: 'Email code', hint: 'Enter the code we emailed you' },\n sms_otp: { label: 'SMS code', hint: 'Enter the code we texted you' },\n};\n\nconst CHALLENGE_REASON = 'This action needs extra verification';\n\n/** No factor of this account reaches the bar. A fresh sign-in would not either, so nothing offers one. */\nexport const UPGRADE_UNSATISFIABLE_DETAIL =\n \"This account can't reach the security level this app asks for. Add a passkey on this device, or contact the app.\";\n\nconst countOf = (count: number, unit: string): string => `${count} ${unit}${count === 1 ? '' : 's'}`;\n\n/**\n * A wait in seconds in the largest unit it reaches once rounded up: `90` is \"2 minutes\", and `3599`, which rounds up\n * to 60 minutes, is \"1 hour\".\n */\nconst waitDuration = (seconds: number): string => {\n if (seconds < 60) return countOf(seconds, 'second');\n const minutes = Math.ceil(seconds / 60);\n if (minutes < 60) return countOf(minutes, 'minute');\n const hours = Math.ceil(seconds / 3600);\n if (hours < 24) return countOf(hours, 'hour');\n return countOf(Math.ceil(seconds / 86400), 'day');\n};\n\n/** What the rate limit asks for: the wait, when the server named one, else its own text. */\nexport const upgradeRateLimitedMessage = (retryAfter: number | undefined, serverText: string | undefined): string =>\n retryAfter !== undefined\n ? `Too many attempts. Try again in ${waitDuration(retryAfter)}.`\n : (serverText ?? 'Too many attempts. Try again later.');\n\n/** A six-digit numeric one-time code — the two OTP transports. */\nconst OTP_CODE_CONTRACT: UpgradeFactorCodeContract = Object.freeze({\n maxLength: 6,\n inputMode: 'numeric',\n autoComplete: 'one-time-code',\n autoCapitalize: 'off',\n});\n\n/** An authenticator code: six or eight digits, so the cap is eight and a six-digit code simply types shorter. */\nconst TOTP_CODE_CONTRACT: UpgradeFactorCodeContract = Object.freeze({ ...OTP_CODE_CONTRACT, maxLength: 8 });\n\n/**\n * Per-factor code contracts, keyed by the factor type, which is the only thing\n * about a factor the protocol guarantees.\n *\n * `recovery_codes` is the reason this table exists. The server generates them\n * at `DefaultRecoveryCodeLength` (12) from a 32-character alphanumeric charset,\n * 8 codes by default, and accepts a configured length anywhere in 10..16, so the cap is the server's\n * MAXIMUM — capping at the default would reject a valid code on a deployment\n * that raised it, and capping at six (the old single hardcoded number) rejected\n * every code on every deployment. A shorter configured code simply types\n * shorter; a cap can only ever do harm by being too small.\n *\n * `null` means the factor collects nothing typed: its proof comes from the\n * ceremony, so there is no field and no contract to state.\n */\nexport const UPGRADE_FACTOR_CODE_CONTRACTS: Readonly<{\n totp: UpgradeFactorCodeContract;\n email_otp: UpgradeFactorCodeContract;\n sms_otp: UpgradeFactorCodeContract;\n recovery_codes: UpgradeFactorCodeContract;\n passkey: null;\n}> = Object.freeze({\n totp: TOTP_CODE_CONTRACT,\n email_otp: OTP_CODE_CONTRACT,\n sms_otp: OTP_CODE_CONTRACT,\n recovery_codes: Object.freeze({\n maxLength: 16,\n inputMode: 'text',\n autoComplete: 'off',\n autoCapitalize: 'characters',\n }),\n passkey: null,\n});\n\n/**\n * The contract for a factor that collects a typed answer. A `'code'` factor the\n * table has no entry for falls back to the OTP shape rather than to no cap at\n * all, so an unknown future code factor is merely sub-optimal, never broken.\n */\nconst codeContractFor = (type: UpgradeFactorType): UpgradeFactorCodeContract =>\n UPGRADE_FACTOR_CODE_CONTRACTS[type] ?? OTP_CODE_CONTRACT;\n\n/** Index 0 stays index 0: `selectFactors` already ranked the list, and ranking is not filtering. */\nexport const toDialogFactors = (\n factors: readonly UpgradeFactorSnapshot[],\n labels?: UpgradeDialogLabels,\n): UpgradeDialogFactor[] =>\n factors.map((factor) => {\n const fallback = DEFAULT_FACTOR_LABELS[factor.type];\n const override = labels?.[factor.type];\n const base = {\n type: factor.type,\n label: override?.label ?? fallback.label,\n hint: override?.hint ?? fallback.hint,\n };\n return factor.input === 'code'\n ? { ...base, input: 'code' as const, code: codeContractFor(factor.type) }\n : { ...base, input: 'none' as const };\n });\n\nconst readString = (value: unknown): string | undefined => (typeof value === 'string' && value ? value : undefined);\n\nconst readRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n\n/**\n * Every kind `@passflow/core` can classify, mapped to the panel the user sees.\n *\n * **The table routes by `kind`, never by `code`, and its totality is the\n * point.** Every classified transport failure carries the same fixed literal\n * `code === 'upgrade_transport'`, so routing by `code` would swallow the kinds\n * with their own route: a mistyped code (`wrong_code`, retryable) would land on\n * a terminal panel. Routing by `kind` through a `Record<UpgradeErrorKind, …>`\n * needs no catch-all and makes a missing route a TYPE error: a new kind added\n * to core cannot compile here until someone decides where it goes.\n *\n * `attempts_exhausted` is terminal. It is the controller's local attempt\n * budget being spent, so the challenge the server holds will never be accepted\n * again; routing it with the retryable kinds would re-prompt forever. It shares\n * the `exhausted` panel with the server's own `challenge_too_many_attempts`,\n * which settles the challenge the same way.\n */\nconst DIALOG_KIND_BY_UPGRADE_KIND: Readonly<Record<UpgradeErrorKind, UpgradeDialogErrorKind>> = Object.freeze({\n // Retryable: the user answers again, the prompt stays open (§3.3, §13.3).\n wrong_code: 'rejected',\n challenge_spent: 'rejected',\n not_registered: 'rejected',\n prepare_not_required: 'rejected',\n // Terminal.\n exhausted: 'exhausted',\n attempts_exhausted: 'exhausted',\n rate_limited: 'rate-limited',\n unavailable: 'unavailable',\n session_changed: 'session-changed',\n fatal: 'transport',\n protocol: 'transport',\n network: 'transport',\n});\n\nconst isUpgradeErrorKind = (value: string | undefined): value is UpgradeErrorKind =>\n value !== undefined && Object.hasOwn(DIALOG_KIND_BY_UPGRADE_KIND, value);\n\n/**\n * Whether the value carries enough HTTP fact for core's classifier to say\n * anything at all. Without one of these, `classifyUpgradeError` would read the\n * value as a network failure, so a stray non-protocol object would be reported\n * to the user as a transport outcome it has no evidence for.\n */\nconst hasTransportFacts = (record: Record<string, unknown>): boolean =>\n typeof record.status === 'number' || typeof record.id === 'string' || readRecord(record.response) !== undefined;\n\n/**\n * The kind, as core determines it. The dialog states no kinds of its own.\n *\n * The already-tagged `kind` is read FIRST, and that order is load-bearing:\n * `classifyUpgradeError` passes a `UpgradeTransportError` through by\n * `instanceof`, which fails across a duplicated bundle or a structured clone,\n * and re-classifying an already-classified error by its bare status re-buckets\n * a `wrong_code` 401 into `session_changed`. The string is validated against\n * the route table, so a kind core does not know still falls through to the\n * classifier.\n */\nconst upgradeKindOf = (error: unknown, record: Record<string, unknown>): UpgradeErrorKind | undefined => {\n const tagged = readString(record.kind);\n if (isUpgradeErrorKind(tagged)) return tagged;\n if (!hasTransportFacts(record)) return undefined;\n // `'refresh'` is the commit round: the dialog only ever sees a failure that\n // already travelled through a flight, and the one round-dependent id\n // (`token.invalid`) means a session change there, which is the terminal\n // reading and the safe one for an un-tagged error.\n return classifyUpgradeError(error, 'refresh').kind;\n};\n\n/**\n * How a failure reads to the user, as the dialog's own vocabulary.\n *\n * Named `dialogOutcomeFromError`, not `classifyUpgradeError`: that name belongs\n * to `@passflow/core`, and holding it here shadowed core's symbol in the\n * package's own star exports, which made the real classifier unreachable to\n * consumers. This function decides nothing about what the error IS — core's\n * classifier does — only which panel that kind is shown on.\n *\n * The dedicated error classes are matched before the kind table because they\n * are not transport failures at all: they carry no `kind`, and core's\n * classifier has nothing to say about them.\n */\nexport const dialogOutcomeFromError = (error: unknown): UpgradeDialogErrorKind => {\n const record = readRecord(error);\n if (!record) return 'rejected';\n const code = readString(record.code);\n const name = readString(record.name);\n\n if (code === 'upgrade_cancelled' || name === 'UpgradeCancelledError' || record.cancelled === true) return 'cancelled';\n if (code === 'upgrade_sign_in_required' || name === 'UpgradeSignInRequiredError') return 'sign-in-required';\n if (code === 'upgrade_unsatisfiable' || name === 'UpgradeUnsatisfiableError') return 'unsatisfiable';\n if (code === 'upgrade_unavailable' || name === 'UpgradeUnavailableError') return 'unavailable';\n if (code === 'upgrade_exhausted' || name === 'UpgradeExhaustedError') return 'exhausted';\n if (code === 'upgrade_insufficient' || name === 'UpgradeInsufficientError') return 'insufficient';\n if (code === 'upgrade_session_changed' || name === 'UpgradeSessionChangedError') return 'session-changed';\n\n const kind = upgradeKindOf(error, record);\n // Nothing identifiable: keep the prompt open rather than inventing a terminal\n // outcome. The controller's attempt budget bounds the re-prompting.\n return kind === undefined ? 'rejected' : DIALOG_KIND_BY_UPGRADE_KIND[kind];\n};\n\nexport const readAssuranceBar = (value: unknown): AssuranceBar | undefined => {\n const record = readRecord(value);\n if (!record) return undefined;\n const bar: AssuranceBar = {};\n if (typeof record.acrValues === 'string') bar.acrValues = record.acrValues;\n if (typeof record.level === 'number') bar.level = record.level;\n if (typeof record.maxAge === 'number') bar.maxAge = record.maxAge;\n return bar.acrValues === undefined && bar.level === undefined && bar.maxAge === undefined ? undefined : bar;\n};\n\n/** Human wording for a bar, on whichever axis it constrains. */\nexport const describeAssuranceBar = (bar?: AssuranceBar): string => {\n if (!bar) return 'an unknown level';\n const parts: string[] = [];\n if (bar.level !== undefined) parts.push(`AAL${bar.level}`);\n else if (bar.acrValues) parts.push(`acr ${bar.acrValues}`);\n if (bar.maxAge !== undefined) parts.push(`verified within ${bar.maxAge}s`);\n return parts.length > 0 ? parts.join(', ') : 'an unknown level';\n};\n\nconst challengeBar = (challenge: UpgradeChallengeSnapshot): AssuranceBar | undefined =>\n readAssuranceBar({\n acrValues: challenge.acrValues,\n level: challenge.requiredLevel,\n maxAge: challenge.maxAge,\n });\n\nconst errorMessage = (error: unknown, fallback: string): string => {\n const record = readRecord(error);\n return readString(record?.message) ?? fallback;\n};\n\nconst terminalFromError = (input: ToDialogStateInput, error: unknown): UpgradeDialogState => {\n const { handlers, testId } = input;\n switch (dialogOutcomeFromError(error)) {\n case 'cancelled':\n return {\n kind: 'cancelled',\n message: 'Verification cancelled',\n detail: 'The action that needed extra verification was not completed.',\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'exhausted':\n return {\n kind: 'exhausted',\n message: 'Too many attempts',\n detail: errorMessage(error, 'No attempts are left for this verification. Start the action again to retry.'),\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'unsatisfiable':\n return {\n kind: 'unsatisfiable',\n message: 'No usable verification method',\n detail: UPGRADE_UNSATISFIABLE_DETAIL,\n required: input.prompt ? challengeBar(input.prompt.challenge) : undefined,\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'rate-limited': {\n const record = readRecord(error);\n const retryAfter = typeof record?.retryAfter === 'number' ? record.retryAfter : undefined;\n return {\n kind: 'exhausted',\n message: upgradeRateLimitedMessage(retryAfter, readString(record?.message)),\n testId,\n onDismiss: handlers.onDismiss,\n };\n }\n case 'sign-in-required':\n // `UpgradeProvider` shows no dialog for it: it sends the user to sign in.\n return {\n kind: 'cancelled',\n message: 'Sign in again to continue',\n detail: 'Only a fresh sign-in can verify this action.',\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'unavailable':\n return {\n kind: 'unavailable',\n message: 'Verification is unavailable',\n detail: errorMessage(error, 'This deployment cannot raise your assurance level right now.'),\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'session-changed':\n return {\n kind: 'cancelled',\n message: 'Verification stopped',\n detail: errorMessage(error, 'Your session changed while verifying, so the request was abandoned.'),\n testId,\n onDismiss: handlers.onDismiss,\n };\n case 'insufficient': {\n const record = readRecord(error);\n return {\n kind: 'insufficient',\n message: errorMessage(error, 'Verified, but not enough for this action'),\n obtained: readAssuranceBar(record?.obtained) ?? {},\n required: readAssuranceBar(record?.required) ?? {},\n testId,\n onSignIn: handlers.onSignIn,\n onDismiss: handlers.onDismiss,\n };\n }\n default:\n return {\n kind: 'transport',\n message: 'Verification could not be completed',\n detail: errorMessage(error, 'The verification request failed before it reached the server.'),\n retryable: readRecord(error)?.retryable === true,\n testId,\n onRetry: handlers.onRetry,\n onDismiss: handlers.onDismiss,\n };\n }\n};\n\n/**\n * The single projection. A terminal `outcome` always wins over an open prompt;\n * an empty offered factor list is the `no usable factor` outcome; a `busy`\n * ceremony with no code to type is `working`; everything else is the challenge.\n */\nexport const toDialogState = (input: ToDialogStateInput): UpgradeDialogState => {\n const { prompt, outcome, ui, labels, handlers, testId } = input;\n\n if (outcome) {\n switch (outcome.kind) {\n case 'elevated':\n return {\n kind: 'success',\n message: 'Verification complete',\n detail: 'Your request is continuing.',\n testId,\n // The happy path must clear itself: §13.4's \"reports success and\n // closes\". Without this the modal's focus trap covers the app after\n // every elevation.\n onDismiss: handlers.onDismiss,\n };\n case 'insufficient':\n return {\n kind: 'insufficient',\n message: `Verified to ${describeAssuranceBar(outcome.obtained)}; this action requires ${describeAssuranceBar(outcome.required)}`,\n obtained: outcome.obtained,\n required: outcome.required,\n detail: 'The elevation succeeded but the action was challenged again. Nothing was completed.',\n testId,\n onSignIn: handlers.onSignIn,\n onDismiss: handlers.onDismiss,\n };\n case 'cancelled':\n return {\n kind: 'cancelled',\n message: 'Verification cancelled',\n detail: 'The action that needed extra verification was not completed.',\n testId,\n onDismiss: handlers.onDismiss,\n };\n default:\n return terminalFromError(input, outcome.error);\n }\n }\n\n if (!prompt) {\n return {\n kind: 'working',\n message: 'Preparing verification…',\n testId,\n onCancel: handlers.onCancel,\n };\n }\n\n const previousKind = prompt.previousError === undefined ? undefined : dialogOutcomeFromError(prompt.previousError);\n if (previousKind !== undefined && previousKind !== 'rejected') {\n return terminalFromError(input, prompt.previousError);\n }\n\n const factors = toDialogFactors(prompt.factors, labels);\n const required = challengeBar(prompt.challenge);\n const suggested = factors[0];\n\n if (suggested === undefined) {\n return {\n kind: 'unsatisfiable',\n message: 'No usable verification method',\n detail: UPGRADE_UNSATISFIABLE_DETAIL,\n required,\n testId,\n onDismiss: handlers.onDismiss,\n };\n }\n\n const selected = factors.find((factor) => factor.type === ui?.selected)?.type ?? suggested.type;\n const active = factors.find((factor) => factor.type === selected);\n const busy = ui?.busy === true;\n\n if (busy && active?.input === 'none') {\n return {\n kind: 'working',\n message: 'Waiting for your passkey…',\n detail: 'Follow the prompt from your device to confirm it is you.',\n testId,\n onCancel: handlers.onCancel,\n };\n }\n\n return {\n kind: 'challenge',\n factors,\n selected,\n reason: CHALLENGE_REASON,\n busy,\n error: previousKind === 'rejected' ? errorMessage(prompt.previousError, 'That code was not accepted. Try again.') : null,\n showAlternatives: ui?.showAlternatives === true,\n testId,\n onSelectFactor: handlers.onSelectFactor,\n onToggleAlternatives: handlers.onToggleAlternatives,\n onSubmit: handlers.onSubmit,\n onCancel: handlers.onCancel,\n };\n};\n\n/**\n * What Escape and an overlay click mean in each state. Cancellation must reach\n * the controller or the caller's promise hangs (§8.1), so this is never a bare\n * close; `success` has nothing to cancel, so it closes instead of cancelling —\n * returning `undefined` there made Escape and the overlay inert on the one\n * state every user reaches.\n */\nexport const upgradeDialogDismissHandler = (state: UpgradeDialogState): (() => void) | undefined => {\n switch (state.kind) {\n case 'challenge':\n return state.onCancel;\n case 'working':\n return state.onCancel;\n default:\n return state.onDismiss;\n }\n};\n","import type { FC } from 'react';\nimport { cn } from '@/utils';\nimport './spinner.css';\n\nexport type SpinnerSize = 'small' | 'medium';\n\nexport type SpinnerProps = {\n /** `small` sits inline beside a line of text; `medium` stands alone. */\n size?: SpinnerSize;\n /**\n * The accessible name. Omit it when a sibling already announces the busy\n * state — the ring is then decorative and hidden from assistive technology,\n * which is what a status region with its own live text wants.\n */\n label?: string;\n};\n\n/**\n * The indeterminate activity ring.\n *\n * It exists as a primitive so its diameter and stroke live in one place rather\n * than in each consuming component's stylesheet. The upgrade dialog uses it;\n * the login screen still draws its own identical ring in\n * `login-screen.css` and should be migrated onto this when that file is next\n * touched.\n */\nexport const Spinner: FC<SpinnerProps> = ({ size = 'medium', label }) => (\n <span\n className={cn('passflow-spinner', { 'passflow-spinner--small': size === 'small' })}\n role={label === undefined ? undefined : 'status'}\n aria-label={label}\n aria-hidden={label === undefined ? true : undefined}\n />\n);\n","import { type FC, useEffect } from 'react';\nimport { Button } from '../button';\nimport { Icon } from '../icon';\nimport { Spinner } from '../spinner';\nimport { describeAssuranceBar } from './state-mapping';\nimport type { AssuranceBar, UpgradeDialogState } from './types';\n\n/** Every state that is not the collecting challenge. */\nexport type UpgradeStatusState = Exclude<UpgradeDialogState, { kind: 'challenge' }>;\n\ntype Tone = 'working' | 'success' | 'problem' | 'neutral';\n\nconst TONE: Record<UpgradeStatusState['kind'], Tone> = {\n working: 'working',\n success: 'success',\n insufficient: 'problem',\n unsatisfiable: 'problem',\n unavailable: 'problem',\n exhausted: 'problem',\n transport: 'problem',\n cancelled: 'neutral',\n};\n\n/**\n * How long `success` stays on screen before it closes itself (§13.4: \"reports\n * success and closes\"). Long enough to be read, short enough that the app is\n * never held behind a modal the user cannot see a reason for.\n */\nexport const UPGRADE_SUCCESS_AUTO_CLOSE_MS = 1800;\n\nconst BarRow: FC<{ term: string; bar: AssuranceBar }> = ({ term, bar }) => (\n <div className='passflow-upgrade-dialog__bar'>\n <span className='passflow-upgrade-dialog__bar-term'>{term}</span>\n <span className='passflow-upgrade-dialog__bar-value'>{describeAssuranceBar(bar)}</span>\n </div>\n);\n\n/**\n * The non-collecting views: `working`, `success` and the six terminal outcomes\n * of §13.3's settlement table.\n *\n * `insufficient` is deliberately rendered in the problem tone with both bars\n * shown: the elevation succeeded and the action still did not, and the dialog\n * must not report success when the replay was re-challenged (§13.4).\n *\n * `success` owns its own exit: a Done control and an auto-close timer, both\n * calling the state's `onDismiss`. The affordance lives here rather than in the\n * provider because a modal that cannot be closed is a property of this\n * component, and the Storybook story for the state has to show the way out.\n */\nexport const UpgradeStatus: FC<UpgradeStatusState> = (state) => {\n const tone = TONE[state.kind];\n const { detail } = state;\n\n const autoClose = state.kind === 'success' ? (state.autoCloseMs ?? UPGRADE_SUCCESS_AUTO_CLOSE_MS) : 0;\n const autoDismiss = state.kind === 'success' ? state.onDismiss : undefined;\n\n useEffect(() => {\n if (autoDismiss === undefined || autoClose <= 0) return;\n const timer = setTimeout(autoDismiss, autoClose);\n return () => clearTimeout(timer);\n }, [autoClose, autoDismiss]);\n\n return (\n <div className='passflow-upgrade-dialog__status' data-testid={state.testId} data-upgrade-state={state.kind}>\n <div\n className={`passflow-upgrade-dialog__status-head passflow-upgrade-dialog__status-head--${tone}`}\n role={tone === 'problem' ? 'alert' : 'status'}\n aria-live={tone === 'problem' ? 'assertive' : 'polite'}\n >\n {tone === 'working' ? <Spinner size='small' /> : null}\n {tone === 'success' ? <Icon size='small' id='check' type='general' className='icon-success' decorative /> : null}\n {tone === 'problem' ? <Icon size='small' id='warning' type='general' className='icon-warning' decorative /> : null}\n <span className='passflow-upgrade-dialog__status-message'>{state.message}</span>\n </div>\n\n {detail ? <p className='passflow-upgrade-dialog__status-detail'>{detail}</p> : null}\n\n {state.kind === 'insufficient' ? (\n <div className='passflow-upgrade-dialog__bars' data-testid='upgrade-dialog-bars'>\n <BarRow term='Verified' bar={state.obtained} />\n <BarRow term='Required' bar={state.required} />\n </div>\n ) : null}\n\n {state.kind === 'unsatisfiable' && state.required ? (\n <div className='passflow-upgrade-dialog__bars' data-testid='upgrade-dialog-bars'>\n <BarRow term='Required' bar={state.required} />\n </div>\n ) : null}\n\n <div className='passflow-upgrade-dialog__actions'>\n {state.kind === 'insufficient' && state.onSignIn ? (\n <Button size='big' variant='primary' type='button' data-testid='upgrade-dialog-sign-in' onClick={state.onSignIn}>\n {state.signInLabel ?? 'Sign in again'}\n </Button>\n ) : null}\n {state.kind === 'transport' && state.retryable && state.onRetry ? (\n <Button size='big' variant='primary' type='button' data-testid='upgrade-dialog-retry' onClick={state.onRetry}>\n {state.retryLabel ?? 'Try again'}\n </Button>\n ) : null}\n {state.kind === 'working' && state.onCancel ? (\n <Button size='big' variant='clean' type='button' data-testid='upgrade-dialog-cancel' onClick={state.onCancel}>\n Cancel\n </Button>\n ) : null}\n {state.kind !== 'working' ? (\n <Button size='big' variant='clean' type='button' data-testid='upgrade-dialog-dismiss' onClick={state.onDismiss}>\n {state.dismissLabel ?? (state.kind === 'success' ? 'Done' : 'Close')}\n </Button>\n ) : null}\n </div>\n </div>\n );\n};\n","import type { FC } from 'react';\nimport { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../dialog';\nimport { UpgradeChallengeView } from './challenge';\nimport { upgradeDialogDismissHandler } from './state-mapping';\nimport { UpgradeStatus } from './status';\nimport type { UpgradeDialogProps } from './types';\nimport './upgrade-dialog.css';\n\nconst DESCRIPTION_ID = 'passflow-upgrade-dialog-description';\n\n/**\n * The assurance-upgrade modal. A switch over `state.kind`, modelled on\n * `LoginScreen`: one discriminated union, one view per state, no transitions of\n * its own.\n *\n * Escape and an overlay click route to the state's cancel or dismiss callback,\n * never to a bare close — cancellation must reach the controller or the\n * caller's promise never settles (§8.1).\n */\nexport const UpgradeDialog: FC<UpgradeDialogProps> = ({ open, title = 'Extra verification required', state }) => {\n const dismiss = upgradeDialogDismissHandler(state);\n const description = state.kind === 'challenge' ? state.reason : undefined;\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) dismiss?.();\n }}\n >\n <DialogContent\n className='passflow-upgrade-dialog'\n data-testid='upgrade-dialog'\n aria-describedby={description ? DESCRIPTION_ID : undefined}\n >\n <DialogHeader className='passflow-upgrade-dialog__header'>\n <DialogTitle>{title}</DialogTitle>\n {description ? <DialogDescription id={DESCRIPTION_ID}>{description}</DialogDescription> : null}\n </DialogHeader>\n {state.kind === 'challenge' ? <UpgradeChallengeView {...state} /> : <UpgradeStatus {...state} />}\n </DialogContent>\n </Dialog>\n );\n};\n","/**\n * `UpgradeProvider` — the React side of the assurance-upgrade flow (§8.3).\n *\n * It owns the controller (through `passflow.upgrade`, or the `facade` it is\n * given), bridges the\n * promise-returning `UpgradePromptHandler` to React state, and mounts the\n * dialog from `src/components/ui/upgrade-dialog`. It selects a state and maps\n * domain data onto that component's props; it renders no UI of its own and\n * styles nothing, per the project's component-library boundary.\n *\n * Three properties fall out of the shipped controller, and they are why this\n * is small:\n *\n * 1. **The wrong-code loop needs no plumbing.** The controller catches the\n * recoverable failure, sets `previousError` and calls `prompt()` again, so\n * the provider simply receives a new request and the dialog re-renders with\n * the error, still open.\n * 2. **Attempt budgeting needs no plumbing.** `maxAttempts` bounds the loop in\n * the controller and then fails the flight, which arrives here as the\n * `exhausted` terminal state.\n * 3. **Passkey has no code field.** `factors[i].input === 'none'` submits with\n * no code and the dialog shows `working` while the platform authenticator\n * runs.\n *\n * **The anti-leak rule is the single most important line in this file.** On\n * unmount, on teardown and on a session change, the pending prompt is resolved\n * `{ type: 'cancel' }`. A dangling `resolve` is an Observer leak wearing a\n * promise: the controller awaits forever, the elevation never settles, and\n * every request that joined the single flight hangs.\n *\n * **The session-change reset.** A challenge is server-bound to the session, so\n * an abandoned flight must never elevate a NEW session. The core discards its\n * controller on `SignIn` / `SignOut`; this provider discards its view of it in\n * the same breath, and the waiter that was mid-flight settles as\n * `session changed`, which the hook reports as `idle` — nothing that did not\n * happen is reported as though it had. The hosted step-up\n * (`passflow.hostedUpgrade`) is bound to the hosted session cookie instead, so\n * the instance's `SignIn` / `SignOut` leave its prompt open.\n */\n\nimport {\n type AssuranceBar,\n PassflowEvent,\n type PassflowSubscriber,\n type ReplayPolicy,\n requiredAcrLevel,\n type UpgradeChallenge,\n type UpgradeDiagnosticSink,\n type UpgradeFacade,\n type UpgradeFactor,\n type UpgradeFactorType,\n type UpgradeFlightSummary,\n type UpgradePromptHandler,\n type UpgradePromptResult,\n type UpgradeReplayInfo,\n type Waiter,\n} from '@passflow/core';\nimport { type FC, type ReactElement, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { UpgradeDialogLabels, UpgradeDialogOutcome, UpgradeDialogProps } from '@/components/ui/upgrade-dialog';\nimport { dialogOutcomeFromError, readAssuranceBar, toDialogState, UpgradeDialog } from '@/components/ui/upgrade-dialog';\nimport {\n UpgradeContext,\n type UpgradeContextValue,\n type UpgradeElevateOptions,\n type UpgradeErrorStatusKind,\n type UpgradeHookState,\n type UpgradePromptView,\n type UpgradeSettledState,\n} from '@/context/upgrade-context';\nimport { useIsomorphicLayoutEffect } from '@/hooks/use-isomorphic-layout-effect';\nimport { usePassflow } from '@/hooks/use-passflow';\nimport { startHostedSignIn } from '@/utils/hosted-sign-in';\nimport { registerUpgradeAuthInstance, upgradeAuthInstance } from '@/utils/upgrade-auth';\n\nexport type UpgradeProviderProps = {\n children?: ReactNode;\n /** Default `true`. `false` installs nothing and leaves the hook inert. */\n enabled?: boolean;\n /**\n * The upgrade facade to install and elevate through. Defaults to\n * `passflow.upgrade`. The hosted login passes `passflow.hostedUpgrade`, which\n * proves factors against the hosted session cookie instead of stored tokens.\n */\n facade?: UpgradeFacade;\n /**\n * Where the customer's own API is — domain 2 (§13.5). Nothing outside this\n * and Passflow's own API is ever observed, and there is no allow-all opt-in.\n */\n backend?: string | string[];\n /**\n * Patches `globalThis.fetch` through the core's registry. **Off by default**,\n * and a different decision from enabling the UI: one prop for both would\n * bundle \"show me the verification prompt\" with \"patch the global\", and only\n * the second has the blast radius.\n */\n interceptFetch?: boolean;\n /** Requires the RFC 9470 channel. The body is then never read for a challenge. */\n requireChallengeChannel?: 'header';\n /** NARROWING ONLY: `false` excludes an admitted URL; `true` cannot widen. */\n shouldIntercept?: (url: string) => boolean;\n replay?: ReplayPolicy;\n /** The fetch surface's only cancellation option. Default `'resolve-original'`. */\n onCancel?: 'resolve-original' | 'reject';\n onUpgradeDiagnostic?: UpgradeDiagnosticSink;\n factors?: readonly UpgradeFactor[];\n maxAttempts?: number;\n relyingPartyId?: string;\n /** Per-factor wording for the dialog. */\n labels?: UpgradeDialogLabels;\n title?: string;\n /**\n * Where a step-up that only a fresh sign-in can meet sends the user, and the \"Sign in again\" action of an\n * insufficient one. Called once, with the dialog closed; nothing is retried. Default: `startHostedSignIn(passflow)`.\n */\n onSignInRequired?: () => void;\n /**\n * Who shows how a failed step-up ended. `'dialog'` (default): the dialog's own panels, and sign-in required calls\n * `onSignInRequired`. `'caller'`: the dialog closes and the caller of `elevate` shows it from the rejection, as the\n * hosted login page does.\n */\n failures?: 'dialog' | 'caller';\n /**\n * FR5's render-prop override. It receives the **exact** props the built-in\n * dialog would render — a typed, constrained override with no `className` or\n * `style` leak.\n *\n * It carries the same obligations as the built-in dialog, the selection\n * signal included: the `challenge` state's `onSelectFactor` must be called\n * when the user picks a factor, because that is the only thing that reports\n * §13.2's selection boundary to the controller. An override that never calls\n * it leaves the controller `collecting` for the whole ceremony, so a late\n * join re-ranks mid-entry — degraded, not silent.\n */\n renderDialog?: (props: UpgradeDialogProps) => ReactElement | null;\n};\n\ntype PendingResolve = ((result: UpgradePromptResult) => void) | undefined;\n\n/** §13.3's settlement table, hook column, for a flight that produced no proof. */\nconst errorStateOf = (error: Error): UpgradeSettledState => {\n switch (dialogOutcomeFromError(error)) {\n case 'cancelled':\n case 'session-changed':\n // Cancellation is not a status (§13.3): it is `elevate()` resolving null.\n return { status: 'idle' };\n case 'insufficient':\n return {\n status: 'insufficient',\n obtained: readAssuranceBar((error as { obtained?: unknown }).obtained) ?? {},\n required: readAssuranceBar((error as { required?: unknown }).required) ?? {},\n };\n case 'exhausted':\n return { status: 'error', kind: 'exhausted', error };\n case 'unsatisfiable':\n return { status: 'error', kind: 'unsatisfiable', error };\n case 'unavailable':\n return { status: 'error', kind: 'unavailable', error };\n case 'rate-limited':\n return { status: 'error', kind: 'rate_limited', error };\n case 'sign-in-required':\n return { status: 'error', kind: 'sign_in_required', error };\n default:\n return { status: 'error', kind: 'transport' satisfies UpgradeErrorStatusKind, error };\n }\n};\n\nconst summaryError = (summary: UpgradeFlightSummary): Error =>\n summary.error ??\n (summary.proof.status === 'failed' ? summary.proof.reason : undefined) ??\n new Error('The verification flight failed without reporting a reason.');\n\n/** One terminal state per flight, taken from the controller's summary (§13.4). */\nconst summaryToState = (summary: UpgradeFlightSummary): UpgradeSettledState => {\n if (summary.terminal === 'success') return { status: 'success' };\n if (summary.terminal === 'insufficient') {\n return {\n status: 'insufficient',\n obtained: summary.insufficient?.obtained ?? {},\n required: summary.insufficient?.required ?? {},\n };\n }\n return errorStateOf(summaryError(summary));\n};\n\nconst summaryToOutcome = (summary: UpgradeFlightSummary): UpgradeDialogOutcome => {\n if (summary.terminal === 'success') return { kind: 'elevated' };\n if (summary.terminal === 'insufficient') {\n return {\n kind: 'insufficient',\n obtained: summary.insufficient?.obtained ?? {},\n required: summary.insufficient?.required ?? {},\n };\n }\n return { kind: 'failed', error: summaryError(summary) };\n};\n\nconst asError = (value: unknown): Error => (value instanceof Error ? value : new Error(String(value)));\n\nconst statedBar = (options?: UpgradeElevateOptions): AssuranceBar | undefined => {\n if (options === undefined) return undefined;\n const bar = readAssuranceBar({\n acrValues: options.acrValues,\n level: requiredAcrLevel(options.acrValues),\n maxAge: options.maxAge,\n });\n return bar;\n};\n\n/**\n * The imperative seam's challenge. A caller asking for a bar states it here;\n * the parsing of `acrValues` is the core's `requiredAcrLevel`, never a second\n * reading of the ACR list.\n */\nconst imperativeChallenge = (options?: UpgradeElevateOptions): UpgradeChallenge => ({\n acrValues: options?.acrValues,\n requiredLevel: requiredAcrLevel(options?.acrValues),\n maxAge: options?.maxAge,\n status: 403,\n channels: [],\n});\n\n/**\n * Value identity for `factors`, so a fresh array literal with the same factors\n * does not tear down and reinstall the interceptors (H13).\n *\n * The factor TYPE is the identity: everything else on an `UpgradeFactor` is the\n * `assert` implementation, and the registry is keyed by type. A caller who\n * swaps one type's implementation for another keeps the installed one until the\n * type list itself changes — the same trade the `backend` join already makes,\n * and the alternative is an unconditional reinstall on every render.\n */\nconst factorsSignature = (factors?: readonly UpgradeFactor[]): string =>\n factors === undefined ? '\\u0000default' : factors.map((factor) => factor.type).join('\\u0000');\n\n/**\n * Value identity for `replay` (H13). The policy is a union, so each arm gets\n * its own comparable signature:\n *\n * - a mode string compares as itself;\n * - a limits object compares by its two fields;\n * - a PREDICATE compares as the constant `fn`, because a function's identity is\n * never stable across renders. The current closure is reached through a ref\n * and called by a stable proxy, which is the same pattern `shouldIntercept`\n * and `onUpgradeDiagnostic` already use here.\n */\nconst replaySignature = (replay?: ReplayPolicy): string => {\n if (replay === undefined) return 'none';\n if (typeof replay === 'string') return `mode:${replay}`;\n if (typeof replay === 'function') return 'fn';\n return `limits:${replay.maxBodyBytes ?? ''}:${replay.allowStreamingBody ?? ''}`;\n};\n\nexport const UpgradeProvider: FC<UpgradeProviderProps> = ({\n children,\n enabled = true,\n facade,\n backend,\n interceptFetch = false,\n requireChallengeChannel,\n shouldIntercept,\n replay,\n onCancel,\n onUpgradeDiagnostic,\n factors,\n maxAttempts,\n relyingPartyId,\n labels,\n title,\n onSignInRequired,\n failures = 'dialog',\n renderDialog,\n}) => {\n const passflow = usePassflow();\n const upgradeFacade = facade ?? passflow.upgrade;\n\n const [prompt, setPrompt] = useState<UpgradePromptView | null>(null);\n const [state, setState] = useState<UpgradeHookState>({ status: 'idle' });\n const [selectedFactor, setSelectedFactor] = useState<UpgradeFactorType | null>(null);\n const [busy, setBusy] = useState(false);\n const [showAlternatives, setShowAlternatives] = useState(false);\n const [outcome, setOutcome] = useState<UpgradeDialogOutcome | undefined>(undefined);\n const [installed, setInstalled] = useState(false);\n\n /** The open prompt's resolver. Cleared the instant it is used — H3's \"once\". */\n const resolveRef = useRef<PendingResolve>(undefined);\n /** The open request, so the selection signal reaches the controller. */\n const requestRef = useRef<Parameters<UpgradePromptHandler>[0] | null>(null);\n /** Whether this prompt already reported a selection (§13.2 T3 fires once). */\n const reportedSelectionRef = useRef(false);\n /** Set by `cancel()`: the user closed the dialog, so no terminal panel is shown. */\n const userCancelledRef = useRef(false);\n /**\n * H11 — cancellation is STICKY for the rest of the flight.\n *\n * After a submit the prompt's resolver is already spent, so `cancel()` has\n * nothing to answer and the cancellation was simply lost: the flight ran on,\n * and the controller re-prompted the user it had just been told to stop\n * asking. The intent is recorded here and answered at the first boundary the\n * controller offers — its next `prompt()` call — which settles the flight as\n * `UpgradeCancelledError` and so puts every surface on §13.3's asymmetric\n * contract (fetch resolves the untouched 401/403, axios and the imperative\n * seam reject, `useUpgrade().elevate` resolves `null`). Cleared when the\n * flight settles, so it can never leak into the next one.\n *\n * It cannot abort a request already on the wire: the core exposes no abort\n * channel for a round in progress, and inventing one here would be a second\n * lifecycle authority beside the controller (§13.2).\n */\n const cancelRequestedRef = useRef(false);\n\n // Callback props are read through refs so that re-rendering with a new inline\n // closure never tears down and reinstalls the interceptors.\n const shouldInterceptRef = useRef(shouldIntercept);\n const diagnosticRef = useRef(onUpgradeDiagnostic);\n shouldInterceptRef.current = shouldIntercept;\n diagnosticRef.current = onUpgradeDiagnostic;\n\n const signInRef = useRef<() => void>(() => undefined);\n signInRef.current = onSignInRequired ?? (() => void startHostedSignIn(passflow).catch(() => undefined));\n const failuresRef = useRef(failures);\n failuresRef.current = failures;\n\n // H13: `factors` and `replay` are compared by VALUE in the install effect's\n // dependencies (see `factorsSignature` / `replaySignature`) and read through\n // these refs, so an inline array or an inline predicate no longer reinstalls\n // the interceptors on every render. `onCancel` needs neither: it is a string\n // union, so it already compares by value.\n const factorsRef = useRef(factors);\n const replayRef = useRef(replay);\n factorsRef.current = factors;\n replayRef.current = replay;\n\n /**\n * The stable stand-in for a caller-supplied replay PREDICATE. The non-function\n * arms are passed through untouched; this is only ever installed when the\n * policy is a function, and a change of arm changes the signature and\n * reinstalls, which is why the fallback is unreachable rather than a decision.\n */\n const replayPredicate = useCallback((info: UpgradeReplayInfo): boolean => {\n const policy = replayRef.current;\n return typeof policy === 'function' ? policy(info) : true;\n }, []);\n\n /** Resolves a pending prompt exactly once. The anti-leak primitive. */\n const settlePrompt = useCallback((result: UpgradePromptResult): boolean => {\n const resolve = resolveRef.current;\n if (resolve === undefined) return false;\n resolveRef.current = undefined;\n resolve(result);\n return true;\n }, []);\n\n const clearPromptView = useCallback(() => {\n requestRef.current = null;\n reportedSelectionRef.current = false;\n setPrompt(null);\n setSelectedFactor(null);\n setShowAlternatives(false);\n setBusy(false);\n }, []);\n\n const promptHandler = useCallback<UpgradePromptHandler>(\n (request) =>\n new Promise<UpgradePromptResult>((resolve) => {\n // H11: the user cancelled after submitting and the controller came back\n // for another answer. Answer the cancellation instead of re-opening a\n // dialog they already closed.\n if (cancelRequestedRef.current) {\n resolve({ type: 'cancel' });\n return;\n }\n\n // Branch 2's channel (§13.2 T2): the controller pushes a raised bar and\n // a re-ranked list into the OPEN prompt, which updates without\n // resolving. Subscribed synchronously, before anything is awaited.\n request.onRequirementRaised = (next) => {\n setPrompt({ challenge: next.challenge, factors: next.factors, previousError: request.previousError });\n setState({ status: 'challenged', challenge: next.challenge, factors: next.factors.map((f) => f.type) });\n };\n\n resolveRef.current = resolve;\n requestRef.current = request;\n reportedSelectionRef.current = false;\n userCancelledRef.current = false;\n setOutcome(undefined);\n setSelectedFactor(null);\n setShowAlternatives(false);\n setBusy(false);\n setPrompt({ challenge: request.challenge, factors: request.factors, previousError: request.previousError });\n setState({\n status: 'challenged',\n challenge: request.challenge,\n factors: request.factors.map((factor) => factor.type),\n });\n }),\n [],\n );\n\n const handleFlightSettled = useCallback(\n (summary: UpgradeFlightSummary) => {\n cancelRequestedRef.current = false;\n setState(summaryToState(summary));\n clearPromptView();\n const signInRequired =\n summary.terminal === 'failed' && dialogOutcomeFromError(summaryError(summary)) === 'sign-in-required';\n // Cleared here as well as when a prompt opens: a flight can settle without ever prompting, and a cancel from an\n // earlier flight must not hide its outcome.\n const userCancelled = userCancelledRef.current;\n userCancelledRef.current = false;\n if (userCancelled || (failuresRef.current === 'caller' && summary.terminal !== 'success')) {\n setOutcome(undefined);\n } else if (signInRequired) {\n setOutcome(undefined);\n signInRef.current();\n } else {\n setOutcome(summaryToOutcome(summary));\n }\n },\n [clearPromptView],\n );\n\n // A layout effect, so the facade is enabled in the commit that brings it. The hosted login elevates through the\n // facade from an awaited network answer, which can run between a commit and its passive effects; a facade that is\n // not enabled yet rejects that elevation as unavailable.\n useIsomorphicLayoutEffect(() => {\n if (!enabled) {\n setInstalled(false);\n return;\n }\n\n const teardown = upgradeFacade.enable({\n prompt: promptHandler,\n backend,\n interceptFetch,\n requireChallengeChannel,\n shouldIntercept: shouldIntercept === undefined ? undefined : (url) => shouldInterceptRef.current?.(url) !== false,\n replay: typeof replayRef.current === 'function' ? replayPredicate : replayRef.current,\n onCancel,\n onUpgradeDiagnostic: onUpgradeDiagnostic === undefined ? undefined : (d) => diagnosticRef.current?.(d),\n factors: factorsRef.current,\n maxAttempts,\n relyingPartyId,\n onFlightSettled: handleFlightSettled,\n });\n setInstalled(true);\n\n return () => {\n // The anti-leak rule: never leave the controller awaiting an answer.\n settlePrompt({ type: 'cancel' });\n teardown();\n setInstalled(false);\n };\n // `backend` is compared by value so a fresh array literal does not reinstall.\n }, [\n upgradeFacade,\n enabled,\n Array.isArray(backend) ? backend.join('\\u0000') : backend,\n interceptFetch,\n requireChallengeChannel,\n shouldIntercept === undefined,\n onUpgradeDiagnostic === undefined,\n // H13: compared by value, never by identity — an inline policy object, an\n // inline predicate or a fresh factor array must not reinstall.\n replaySignature(replay),\n replayPredicate,\n onCancel,\n factorsSignature(factors),\n maxAttempts,\n relyingPartyId,\n promptHandler,\n handleFlightSettled,\n settlePrompt,\n ]);\n\n /**\n * Publishes this provider's instance to the free-function adapters, twice,\n * for two different reasons — and both are load-bearing.\n *\n * **The render-phase write** exists because React runs a child's effects\n * before the parent's in the same commit, so the documented\n * `useEffect(() => attachAuth(api), [])` in a child would otherwise reach\n * `requireInstance` with nothing registered and throw — and a throw inside an\n * effect unmounts the tree. Publishing in render makes attach order\n * irrelevant. It is guarded and idempotent, so a re-render or a discarded\n * Strict-Mode render changes nothing.\n *\n * **The effect re-registers and releases through the same call**, so the pair\n * is symmetric: `registerUpgradeAuthInstance` returns the release for its own\n * registration, and that release is deferred by a microtask and cancelled by\n * any registration in the meantime (see `utils/upgrade-auth`). React Strict\n * Mode mounts, unmounts and remounts effects in development, and a cleanup\n * that released immediately would leave the registry empty for the remount —\n * render does not run again, and the child-before-parent effect order holds\n * on the remount pass as well, so the re-registration here cannot be early\n * enough on its own. Measured, not assumed: with an immediate release the\n * remounting child's `attachAuth` throws.\n *\n * A ref cannot be the publication channel, which is why this is not the ref\n * shape: the free functions are bare module imports called by code that never\n * sees this component's context or refs, so the module-level registry is the\n * only channel children can read.\n */\n if (upgradeAuthInstance() !== passflow) registerUpgradeAuthInstance(passflow);\n useEffect(() => registerUpgradeAuthInstance(passflow), [passflow]);\n\n /**\n * The session-change reset. The core discards its controller here; the view\n * of it must go with it, or a dialog from the old session would collect an\n * answer that can only elevate the new one.\n *\n * Not for the hosted step-up: it elevates the hosted session cookie, which a\n * sign-in or sign-out of the instance's stored tokens leaves as it was.\n */\n const elevatesHostedSession = upgradeFacade === passflow.hostedUpgrade;\n useEffect(() => {\n if (elevatesHostedSession) return;\n const subscriber: PassflowSubscriber = {\n onAuthChange: () => {\n cancelRequestedRef.current = false;\n settlePrompt({ type: 'cancel' });\n clearPromptView();\n setOutcome(undefined);\n setState({ status: 'idle' });\n },\n };\n const events = [PassflowEvent.SignIn, PassflowEvent.SignOut];\n passflow.subscribe(subscriber, events);\n return () => passflow.unsubscribe(subscriber, events);\n }, [passflow, elevatesHostedSession, settlePrompt, clearPromptView]);\n\n const selectFactor = useCallback((factor: UpgradeFactorType) => {\n setSelectedFactor(factor);\n // §13.2 T3: the selection boundary, reported before any answer is\n // submitted. `selected` is defined off this call and off nothing else.\n requestRef.current?.onFactorSelected(factor);\n reportedSelectionRef.current = true;\n }, []);\n\n const submit = useCallback(\n (code?: string) => {\n const request = requestRef.current;\n if (request === null || resolveRef.current === undefined) return;\n const factor = selectedFactor ?? request.factors[0]?.type;\n if (factor === undefined) return;\n if (!reportedSelectionRef.current) {\n // A submit that skipped the picker still selected a factor — the\n // suggested one — and the controller must hear it before the ceremony.\n request.onFactorSelected(factor);\n reportedSelectionRef.current = true;\n }\n setBusy(true);\n setState({ status: 'submitting' });\n settlePrompt({ type: 'submit', factor, code });\n },\n [selectedFactor, settlePrompt],\n );\n\n const cancel = useCallback(() => {\n userCancelledRef.current = true;\n cancelRequestedRef.current = true;\n if (!settlePrompt({ type: 'cancel' })) {\n // Nothing was pending: either a terminal panel is on screen, or an answer\n // is in flight. Close it either way — the sticky flag answers the\n // controller's next prompt, and leaving a busy dialog open would ask the\n // user to wait for a flight they have abandoned.\n setOutcome(undefined);\n }\n clearPromptView();\n setState({ status: 'idle' });\n }, [settlePrompt, clearPromptView]);\n\n const dismiss = useCallback(() => {\n setOutcome(undefined);\n }, []);\n\n const signInAgain = useCallback(() => {\n setOutcome(undefined);\n signInRef.current();\n }, []);\n\n const toggleAlternatives = useCallback(() => {\n setShowAlternatives((shown) => !shown);\n }, []);\n\n const elevate = useCallback(\n async (options?: UpgradeElevateOptions): Promise<UpgradeSettledState | null> => {\n const requested = statedBar(options);\n const waiter: Waiter = requested === undefined ? { kind: 'imperative' } : { kind: 'imperative', requested };\n try {\n await upgradeFacade.elevate(imperativeChallenge(options), waiter);\n return { status: 'success' };\n } catch (error) {\n // The one surface where cancellation resolves `null`: there the\n // cancellation IS the whole value (§13.3).\n if (dialogOutcomeFromError(error) === 'cancelled') return null;\n return errorStateOf(asError(error));\n }\n },\n [upgradeFacade],\n );\n\n const value = useMemo<UpgradeContextValue>(\n () => ({\n enabled: enabled && installed,\n state,\n prompt,\n selectedFactor,\n selectFactor,\n submit,\n cancel,\n dismiss,\n elevate,\n }),\n [enabled, installed, state, prompt, selectedFactor, selectFactor, submit, cancel, dismiss, elevate],\n );\n\n const dialogState = toDialogState({\n prompt:\n prompt === null ? null : { challenge: prompt.challenge, factors: prompt.factors, previousError: prompt.previousError },\n outcome,\n ui: { selected: selectedFactor, busy, showAlternatives },\n labels,\n handlers: {\n onSelectFactor: selectFactor,\n onToggleAlternatives: toggleAlternatives,\n onSubmit: submit,\n onCancel: cancel,\n onDismiss: dismiss,\n onSignIn: signInAgain,\n },\n });\n\n const dialogProps: UpgradeDialogProps = {\n open: prompt !== null || outcome !== undefined,\n title,\n state: dialogState,\n };\n\n return (\n <UpgradeContext.Provider value={value}>\n {children}\n {/* Mounted after `children` so it overlays them. */}\n {renderDialog === undefined ? <UpgradeDialog {...dialogProps} /> : renderDialog(dialogProps)}\n </UpgradeContext.Provider>\n );\n};\n","import type { Passflow } from '@passflow/core';\nimport { useEffect, useRef } from 'react';\n\ntype Disposable = Pick<Passflow, 'dispose'>;\n\ntype PendingDispose = {\n instance: Disposable;\n timer: ReturnType<typeof setTimeout>;\n};\n\n/**\n * Disposes a Passflow instance once it is replaced (a new `useMemo` value) or the\n * provider unmounts. Each instance owns refresh timers, a BroadcastChannel and Web\n * Locks; one left undisposed keeps acting as an extra tab.\n *\n * Why the dispose is deferred: React StrictMode runs effect cleanup and setup again\n * for the same instance in one commit, while `useMemo` keeps that instance live. An\n * immediate dispose in cleanup would kill the instance the app keeps using, and core\n * forbids using an instance after `dispose()`. So cleanup only schedules the dispose\n * (`setTimeout(0)`); a setup that sees the same instance cancels it. A different\n * instance or a real unmount leaves the timer to fire.\n */\nexport function useDisposeOnReplace(instance: Disposable): void {\n const pending = useRef<PendingDispose | null>(null);\n\n useEffect(() => {\n const scheduled = pending.current;\n if (scheduled) {\n if (scheduled.instance === instance) clearTimeout(scheduled.timer);\n pending.current = null;\n }\n\n return () => {\n const timer = setTimeout(() => instance.dispose(), 0);\n pending.current = { instance, timer };\n };\n }, [instance]);\n}\n","import {\n type ErrorPayload,\n FETCH_PRIORITY_OIDC,\n Passflow,\n type PassflowConfig,\n PassflowEvent,\n type PassflowEventPayload,\n type PassflowSubscriber,\n parseUpgradeChallenge,\n registerFetchMiddleware,\n} from '@passflow/core';\nimport React, { type FC, type ReactNode, useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { UpgradeProvider, type UpgradeProviderProps } from '@/components/provider/upgrade-provider';\nimport { useDisposeOnReplace } from '@/components/provider/use-dispose-on-replace';\nimport { ContinuingStatus } from '@/components/ui/continuing-status';\nimport { LoginScreen } from '@/components/ui/login-screen';\nimport {\n dialogOutcomeFromError,\n UPGRADE_UNSATISFIABLE_DETAIL,\n upgradeRateLimitedMessage,\n} from '@/components/ui/upgrade-dialog/state-mapping';\nimport {\n AuthProvider,\n addressBarSearch,\n defaultNavigate,\n type FederatedLandingOutcome,\n type HandOff,\n initialState,\n type NavigateFunction,\n NavigationContext,\n PassflowContext,\n type PassflowState,\n passflowReducer,\n type RouterType,\n routes,\n} from '@/context';\nimport { useHydrated } from '@/hooks/use-hydrated';\nimport { passwordlessSignInFailedMessage } from '@/utils/auth-error';\nimport { submitFormPost } from '@/utils/form-post';\nimport { startHostedSignIn, takeReturnPath } from '@/utils/hosted-sign-in';\nimport { signInSearch, twoFactorTokenAppId, urlCarriesAccessToken, urlCarriesTwoFactorToken } from '@/utils/second-factor';\nimport { readParentChallengeIdFromURL } from '@/utils/url-params';\nimport '@/styles/index.css';\n\nexport { readParentChallengeIdFromURL };\n\n/** A hosted sign-in return this tab refused, such as one whose state is not its sign-in. */\nconst SignInReturnFailed: FC<{ onSignInAgain: () => void }> = ({ onSignInAgain }) => (\n <LoginScreen\n chrome={{ title: 'We could not sign you in' }}\n state={{\n kind: 'status',\n tone: 'error',\n message: passwordlessSignInFailedMessage,\n testId: 'sign-in-return-failed',\n primaryAction: { label: 'Sign in again', onClick: onSignInAgain },\n }}\n />\n);\n\n/** A hosted session the exchange could not step up, with why: the page shows it instead of the sign-in form. */\nconst StepUpFailed: FC<{ message: string; testId: string }> = ({ message, testId }) => (\n <LoginScreen chrome={{ title: 'Extra verification required' }} state={{ kind: 'status', tone: 'error', message, testId }} />\n);\n\n/**\n * The assurance-upgrade options a consumer may set on `PassflowProvider`.\n *\n * `children`, `enabled` and `backend` are owned by `PassflowProvider` itself:\n * `backend` is a top-level prop (§13.5 — \"where your API is\" is the headline\n * act, not a nested detail) and `enabled` is derived from `upgrade`/`backend`\n * below, so there is exactly one source for each.\n */\nexport type PassflowUpgradeOptions = Omit<UpgradeProviderProps, 'children' | 'enabled' | 'backend' | 'failures'>;\n\ntype PassflowProviderProps = PassflowConfig & {\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n keyStoragePrefix?: PassflowConfig['keyStoragePrefix'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n tokenExchange?: PassflowConfig['tokenExchange'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n platform?: PassflowConfig['platform'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n refreshCoordination?: PassflowConfig['refreshCoordination'];\n /** See `PassflowConfig`. Read once, when the provider mounts. */\n refreshStrikes?: PassflowConfig['refreshStrikes'];\n children: ReactNode;\n navigate?: NavigateFunction;\n router?: RouterType;\n /**\n * Where the customer's own API is — domain 2 of §13.5's two-domain\n * interception model. Nothing outside this and Passflow's own API is ever\n * observed, and there is no allow-all opt-in. `string | string[]`, an origin\n * or a same-origin path prefix (`'/api'`).\n */\n backend?: string | string[];\n /**\n * Automatic assurance upgrade (step-up). `undefined` ⇒ **off**, so no\n * existing consumer changes behaviour on upgrade. `true` ⇒ on with\n * defaults; an object ⇒ on with those options; `false` ⇒ off even when\n * `backend` is declared.\n *\n * Declaring `backend` also turns it on: naming where your API is has no\n * other meaning, and §13.5's acceptance configuration is `backend` plus one\n * attached client. The global `window.fetch` patch is a separate, explicit\n * act (`upgrade={{ interceptFetch: true }}`) and stays off by default.\n */\n upgrade?: boolean | PassflowUpgradeOptions;\n /**\n * Where to send a sign-in that lands on this page owing its second factor:\n * a federated redirect on a non-PKCE app comes back with `#tfa_token=` and\n * no tokens. A mounted `PassflowFlow` registers its own (prefixed) route,\n * which wins; set this when the landing page renders no flow, or the flow\n * is mounted elsewhere. Defaults to `routes.two_factor_verify.path`.\n */\n twoFactorVerifyPath?: string;\n /**\n * For the hosted login: the scopes and `state` the app that sent the user here asked for. They decide what goes\n * back to the app after sign-in; unset `scopes` are filled from the app's configuration, else `openid profile id`.\n * Read once, when the provider mounts. Leave unset when the flow is embedded in the app itself.\n */\n handOff?: HandOff;\n};\n\n/**\n * Passflow auth-endpoint regex used by the OIDC interceptor below.\n * Matches every endpoint that takes credentials + an optional\n * parent_challenge_id so the SDK can inject the parent on outbound\n * POSTs and follow `redirect_url` on responses.\n *\n * The set is canonical with the server's AuthFlow dispatcher; if a\n * new credential endpoint lands server-side, it must be added here.\n *\n * - /auth/login — password login\n * - /auth/register — password sign-up\n * - /auth/passwordless/start|complete — OTP / magic-link; the status and\n * approval calls take no parent\n * - /auth/passkey/* — passkey registration/auth\n * - /auth/2fa/* — second-factor verify\n * - /auth/validate — emailed sign-up / sign-in code\n * - /auth/federated/start — federated start (callback is server)\n * - /auth/session/exchange — RFC 8693-style session exchange\n * (ADR-2; activated on Leg 2 of\n * OIDC two-step flows)\n */\nexport const AUTH_ENDPOINT_PATTERN =\n /\\/auth\\/(login|register|passwordless\\/(start|complete)|passkey|2fa|validate|session\\/exchange)\\b|\\/auth\\/federated\\/start\\b/;\n\n/**\n * The passwordless status poll. Under a parent, the approved answer is `{ redirect_url }`, which the interceptor\n * follows. It is follow-only: the poll takes no parent, so its request body is never rewritten.\n */\nexport const PASSWORDLESS_STATUS_PATTERN = /\\/auth\\/passwordless\\/status\\b/;\n\n// Captured at module evaluation — before React mounts and before any\n// consumer-side router can rewrite the URL. The provider's mount-time\n// read stays primary (a consumer could mount the SDK long after boot,\n// on a different URL); this is the fallback that makes the OIDC opt-in\n// immune to mount-vs-navigation timing. Observed in the field: the\n// OIDF conformance login intermittently proceeded as a plain\n// first-party login (tokens in the response, no redirect_url) because\n// the whole OIDC layer keyed off a single mount-time read.\nconst bootParentChallengeId = readParentChallengeIdFromURL();\n\n/**\n * The RFC 8628 device verification page (`/oidc/device`) is the ONE auth surface\n * that must never silently exchange an existing session. A device grant is\n * approved only through the explicit authenticate → user_code confirmation →\n * approve path (see `useDeviceVerify` + src/web/oidc/device_verify.go). Letting\n * the exchange-on-mount probe solve a device parent would approve a grant with\n * no §5.4 code check — the STORM-2372 device-code phishing attack. The server\n * now refuses this at `/auth/session/exchange` too; this is the client half of\n * the same guard, so the probe never even fires here.\n */\nconst isDeviceVerificationURL = (): boolean => typeof window !== 'undefined' && window.location.pathname === '/oidc/device';\n\n/**\n * Set once the OIDC interceptor has started following a server-issued\n * `redirect_url`. Module-level on purpose: it is read by the credential forms,\n * which are siblings of the provider rather than children of a context it could\n * publish through, and its lifetime is exactly one page — the navigation it\n * records is what ends that page.\n */\nlet oidcRedirectFollowed = false;\n\n/**\n * Has the OIDC interceptor already taken ownership of the post-login navigation?\n *\n * A credential form MUST NOT navigate after a successful login when this is\n * true. Two navigations do not queue — the second cancels the first, and the\n * first is the one that completes the OIDC flow:\n *\n * 1. The interceptor calls `window.location.assign(redirect_url)` to hand the\n * authorization code back to the RP (a CLI's `127.0.0.1:<port>/callback`,\n * a web RP's `redirect_uri`, …).\n * 2. `window.location.assign` does not halt script execution, so the form's\n * success handler keeps running and sets `window.location.href` to the\n * app's default post-login page.\n * 3. The browser drops the in-flight request from (1) and goes to (2).\n *\n * Whether (1) has already been delivered when (2) lands is pure scheduling, so\n * this presents as a flake rather than a clean break. Measured against the CLI\n * loopback flow (RFC 8252 §7.3): roughly a third of real browser sign-ins had\n * the GET to the CLI's loopback port aborted mid-flight, and the CLI then sat\n * waiting for a callback that had already been cancelled until it timed out.\n */\nexport const hasFollowedOIDCRedirect = (): boolean => oidcRedirectFollowed;\n\n/**\n * Install the global OIDC AuthFlow interceptor on `fetch` and\n * `XMLHttpRequest`. The interceptor:\n *\n * 1. Injects `parent_challenge_id` on every Passflow auth POST\n * body (when one is present on the SDK's host URL).\n * 2. Watches Passflow auth responses for a JSON answer and executes\n * it: `{ redirect_url: \"...\" }` is followed with\n * `window.location.assign(redirect_url)`, and\n * `{ form_post: { action, fields } }` is submitted as a hidden POST\n * form (OIDC response_mode=form_post).\n *\n * Why both fetch and XHR: `@passflow/core` uses axios, which on the\n * browser delegates to XMLHttpRequest. Other consumer code (and the\n * SDK's own `/oidc/requests/{id}` GET) uses fetch. Patching both\n * keeps the interceptor uniform.\n *\n * No-op when `parent_challenge_id` is absent from the URL.\n *\n * Implementation note: previously this hook lived in the bundled\n * login-app at `login-app/src/App.tsx::useAuthFlowInterceptor`.\n * Moved into the SDK so any Passflow consumer that mounts\n * `<PassflowProvider>` gets full OIDC RP integration automatically.\n */\nconst useOIDCInterceptor = (parentChallengeId: string | undefined): void => {\n useEffect(() => {\n if (!parentChallengeId || typeof window === 'undefined') {\n return;\n }\n\n const isAuthURL = (url: string): boolean => AUTH_ENDPOINT_PATTERN.test(url);\n const followsAnswer = (url: string): boolean => isAuthURL(url) || PASSWORDLESS_STATUS_PATTERN.test(url);\n\n const injectParentChallenge = (raw: string | null | undefined): string | undefined => {\n if (!raw) return undefined;\n try {\n const obj = JSON.parse(raw) as Record<string, unknown>;\n if ('parent_challenge_id' in obj) return undefined;\n obj.parent_challenge_id = parentChallengeId;\n return JSON.stringify(obj);\n } catch {\n return undefined;\n }\n };\n\n const followRedirectURL = (raw: string | null | undefined): void => {\n if (!raw) return;\n try {\n const obj = JSON.parse(raw) as {\n redirect_url?: unknown;\n form_post?: { action?: unknown; fields?: unknown } | null;\n };\n // Claim the navigation BEFORE starting it. `assign` and `submit` do not\n // stop JavaScript: the credential form's own success handler runs right\n // after this and would otherwise navigate on top of us. See\n // `hasFollowedOIDCRedirect` for why that is fatal, not cosmetic.\n const formPost = obj.form_post;\n if (\n typeof formPost === 'object' &&\n formPost !== null &&\n typeof formPost.action === 'string' &&\n formPost.action &&\n typeof formPost.fields === 'object' &&\n formPost.fields !== null\n ) {\n // response_mode=form_post: the RP takes the code as a POST body.\n oidcRedirectFollowed = true;\n submitFormPost(formPost.action, formPost.fields as Record<string, string>);\n return;\n }\n if (typeof obj.redirect_url === 'string' && obj.redirect_url) {\n oidcRedirectFollowed = true;\n window.location.assign(obj.redirect_url);\n }\n } catch {\n // Non-JSON — ignore.\n }\n };\n\n // fetch() interceptor (covers code paths that use the platform fetch API).\n //\n // Installed through the core's fetch registry rather than by assigning\n // `window.fetch` here. Two features that each capture and restore the\n // global compose as `A(B(native))`, and whichever cleanup runs first\n // restores a fetch that predates the other patch — so one interceptor\n // disappears non-deterministically (architecture §13.5, \"the OIDC\n // collision: 'untouched' is withdrawn\"). The registry owns the single\n // patch, reference-counts it, and never restores over a foreign patch.\n //\n // Priority matters behaviourally: OIDC is the OUTER layer\n // (`FETCH_PRIORITY_OIDC` = 10, outside `FETCH_PRIORITY_UPGRADE` = 20) so it\n // still observes the response the caller actually receives — including a\n // replayed one — which is what it reads `redirect_url` from. The logic\n // below is unchanged from the hand-rolled patch: `next` stands exactly\n // where the captured `originalFetch` stood.\n const unregisterFetchMiddleware = registerFetchMiddleware(\n async (next, input, init) => {\n let url = '';\n if (typeof input === 'string') url = input;\n else if (input instanceof URL) url = input.toString();\n else if (input instanceof Request) url = input.url;\n\n const method = init?.method?.toUpperCase() ?? 'GET';\n let outInit = init;\n if (method === 'POST' && isAuthURL(url) && typeof init?.body === 'string') {\n const rewritten = injectParentChallenge(init.body);\n if (rewritten !== undefined) outInit = { ...init, body: rewritten };\n }\n\n const response = await next(input, outInit);\n\n if (response.ok && followsAnswer(url)) {\n try {\n const cloned = response.clone();\n const text = await cloned.text();\n followRedirectURL(text);\n } catch {\n // ignore\n }\n }\n\n return response;\n },\n { priority: FETCH_PRIORITY_OIDC, name: 'passflow-oidc-authflow' },\n );\n\n // XMLHttpRequest interceptor — `@passflow/core` uses axios, which in\n // the browser uses XHR under the hood. The fetch interceptor above\n // does NOT catch those calls.\n const OriginalXHROpen = XMLHttpRequest.prototype.open;\n const OriginalXHRSend = XMLHttpRequest.prototype.send;\n\n // `isAuth` gates the parent injection; `follows` gates following `redirect_url` in the answer.\n type XHRTracker = { method?: string; url?: string; isAuth?: boolean; follows?: boolean };\n const tracker = new WeakMap<XMLHttpRequest, XHRTracker>();\n\n XMLHttpRequest.prototype.open = function (\n this: XMLHttpRequest,\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ): void {\n const urlStr = typeof url === 'string' ? url : url.toString();\n tracker.set(this, {\n method: method?.toUpperCase(),\n url: urlStr,\n isAuth: isAuthURL(urlStr),\n follows: followsAnswer(urlStr),\n });\n this.addEventListener('load', () => {\n const meta = tracker.get(this);\n if (!meta?.follows) return;\n if (this.status >= 200 && this.status < 300) {\n // Server returns 200 + JSON body { redirect_url } or\n // { form_post: { action, fields } } when an AuthFlow parent\n // (OIDC, federated) needs the SPA to navigate.\n followRedirectURL(typeof this.responseText === 'string' ? this.responseText : null);\n }\n });\n // @ts-expect-error spread into open's varargs signature\n OriginalXHROpen.call(this, method, url, ...rest);\n };\n\n XMLHttpRequest.prototype.send = function (this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null): void {\n const meta = tracker.get(this);\n let outBody: Document | XMLHttpRequestBodyInit | null | undefined = body;\n if (meta?.isAuth && meta.method === 'POST' && typeof body === 'string') {\n const rewritten = injectParentChallenge(body);\n if (rewritten !== undefined) outBody = rewritten;\n }\n OriginalXHRSend.call(this, outBody as Document | XMLHttpRequestBodyInit | null);\n };\n\n return () => {\n // Fetch teardown is the registry's: it removes the one patch on the last\n // registration's removal and declines to restore over a stranger's patch.\n // Nothing here captures or restores `window.fetch`.\n unregisterFetchMiddleware();\n XMLHttpRequest.prototype.open = OriginalXHROpen;\n XMLHttpRequest.prototype.send = OriginalXHRSend;\n };\n }, [parentChallengeId]);\n};\n\n/**\n * Parent-challenge metadata returned by GET /oidc/requests/{id}.\n * Subset used by the SDK's exchange-on-mount probe.\n */\ntype ParentChallengeMeta = {\n request_id: string;\n app_name?: string;\n client_id?: string;\n redirect_uri?: string;\n state?: string;\n response_mode?: string;\n // The OIDC directives the parent carries. `prompt=login` and `max_age` are\n // enforced by the server at /auth/session/exchange, which answers 403 when\n // the hosted session does not satisfy them; `prompt=none` is the SDK's to\n // honour, because only the SDK can decide not to render a form.\n oidc_prompt_login?: boolean;\n oidc_prompt_none?: boolean;\n max_age?: number;\n};\n\n/**\n * Where the exchange-on-mount probe stands.\n *\n * - `idle`: nothing attempted yet (no parent, or the app id is unknown).\n * - `exchanging`: the exchange is in flight, or it answered and the browser is\n * on its way back to the relying party.\n * - `upgrade_required`: the hosted session needs a step-up before it can be\n * exchanged, and the step-up dialog is open.\n * - `fallback_to_login`: no usable hosted session; the sign-in form renders.\n * - `unsatisfiable`: no factor of this account reaches the level; the page says so, with no form.\n * - `rate_limited`: the step-up hit the server's rate limit; the page says how long to wait, with no form.\n */\ntype ExchangeState = 'idle' | 'exchanging' | 'upgrade_required' | 'fallback_to_login' | 'unsatisfiable' | 'rate_limited';\n\n/** An OIDC error sent back to the relying party instead of rendering a form. */\ntype RelyingPartyError = 'login_required' | 'interaction_required' | 'unmet_authentication_requirements';\n\nconst relyingPartyErrorDescriptions: Record<RelyingPartyError, string> = {\n login_required: 'user is not authenticated',\n interaction_required: 'user interaction is required',\n unmet_authentication_requirements: 'the authentication requirements could not be met',\n};\n\n/**\n * Sends an OIDC error to the parent's `redirect_uri`, in the parent's\n * `response_mode`: a hidden POST form for `form_post`, a query-string\n * navigation otherwise. Returns false when the metadata has no `redirect_uri`\n * (its fetch failed), leaving the caller to render the form.\n */\nconst answerRelyingParty = (meta: ParentChallengeMeta | undefined, error: RelyingPartyError): boolean => {\n if (!meta?.redirect_uri) return false;\n const fields: Record<string, string> = { error, error_description: relyingPartyErrorDescriptions[error] };\n if (meta.state) fields.state = meta.state;\n if (meta.response_mode === 'form_post') {\n submitFormPost(meta.redirect_uri, fields);\n return true;\n }\n const dest = new URL(meta.redirect_uri);\n for (const [key, value] of Object.entries(fields)) dest.searchParams.set(key, value);\n window.location.assign(dest.toString());\n return true;\n};\n\n/**\n * Does a 200 from the exchange carry an answer the OIDC interceptor executes\n * (`redirect_url` or `form_post`)? The interceptor is the sole owner of that\n * navigation: it reads the response before this hook does, and a second\n * navigation from here would re-present the single-use authorization code.\n */\nconst carriesAnswer = async (res: Response): Promise<boolean> => {\n try {\n const body = (await res.json()) as { redirect_url?: unknown; form_post?: unknown };\n return Boolean(body.redirect_url) || Boolean(body.form_post);\n } catch {\n return false;\n }\n};\n\nconst readBody = async (res: Response): Promise<unknown> => {\n try {\n return await res.json();\n } catch {\n return undefined;\n }\n};\n\n/**\n * Exchange-on-mount: when a parent challenge is on the URL, ask\n * /auth/session/exchange whether the hosted session cookie can answer it\n * without a sign-in form. The request carries the cookie only\n * (`credentials: 'include'`), never stored tokens; the server is the sole judge\n * of the session, including `prompt=login` and `max_age`.\n *\n * The answers:\n *\n * - 200 `{ redirect_url }` or `{ form_post }` → the OIDC interceptor executes\n * it; the hook stays `exchanging` so no form flashes while the page leaves.\n * A 200 with neither renders the form.\n * - 401 / 400 → no usable hosted session: the form, or `login_required` to\n * the relying party under `prompt=none`.\n * - 403 → the session falls short. Under `prompt=none` that is\n * `interaction_required` to the relying party. Otherwise the body is read\n * with core's `parseUpgradeChallenge`, `available_factors` and\n * `sign_in_required` included:\n * - `sign_in_required: true`, or a body naming neither `acr_values` nor\n * `max_age` → the form, with no step-up.\n * - Otherwise the step-up dialog opens through `passflow.hostedUpgrade`\n * (`upgrade_required`), offering exactly the server's factors.\n * - Step-up succeeds → exactly one more exchange. A 200 answer completes;\n * a 401 renders the form; anything else sends\n * `unmet_authentication_requirements` to the relying party.\n * - Step-up ends in sign-in required (an older server's empty\n * `available_factors`) or insufficient → the form.\n * - Unsatisfiable (no factor of this account reaches the level) →\n * `unsatisfiable`: the page says why. No form, since a fresh sign-in\n * would not meet it either, and nothing goes to the relying party.\n * - Rate limited → `rate_limited`: the page says how long to wait.\n * - Cancelled or any other failure → when the refusal named `acr_values`\n * the relying party gets `unmet_authentication_requirements`; when it\n * named only `max_age`, the form renders so the user can sign in again.\n * - Any other status, or a network error → the form.\n *\n * An error for the relying party needs the parent's `redirect_uri`; without\n * it the form renders instead.\n */\nconst useSessionExchangeOnMount = (\n parentChallengeId: string | undefined,\n landedWithTwoFactorToken: boolean,\n // Read at call time: the provider replaces its instance while the exchange runs, and only the current one steps up.\n currentPassflow: () => Passflow,\n baseUrl: string | undefined,\n appId: string | undefined,\n): { exchangeState: ExchangeState; parentMeta?: ParentChallengeMeta; stepUpFailure?: string } => {\n const [exchangeState, setExchangeState] = useState<ExchangeState>('idle');\n const [stepUpFailure, setStepUpFailure] = useState<string | undefined>(undefined);\n const [parentMeta, setParentMeta] = useState<ParentChallengeMeta | undefined>(undefined);\n const attemptedRef = useRef(false);\n\n useEffect(() => {\n // A landing that owes its second factor finishes that sign-in: the 2FA screen, not an exchange of another session.\n if (!parentChallengeId || landedWithTwoFactorToken || attemptedRef.current) {\n return;\n }\n // Never auto-exchange on the device verification page — that would approve\n // a device grant with no user_code check (see isDeviceVerificationURL).\n if (isDeviceVerificationURL()) {\n return;\n }\n // Wait until appId has been discovered before attempting the\n // exchange — otherwise the request 400s on \"Application ID is\n // missing from request\".\n if (!appId) {\n return;\n }\n attemptedRef.current = true;\n\n const base = baseUrl ?? '';\n\n const exchange = (): Promise<Response> =>\n fetch(`${base}/auth/session/exchange`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n // App middleware reads X-Passflow-ClientID; without it the\n // request gets 400 \"Application ID is missing from request\".\n 'X-Passflow-ClientID': appId,\n },\n body: JSON.stringify({ parent_challenge_id: parentChallengeId }),\n });\n\n const run = async () => {\n // The parent's metadata: where an error for the relying party goes\n // (`redirect_uri`, `state`, `response_mode`), whether it asked for\n // `prompt=none`, and the app name for the continuing status.\n let meta: ParentChallengeMeta | undefined;\n try {\n const res = await fetch(`${base}/oidc/requests/${encodeURIComponent(parentChallengeId)}`);\n if (res.ok) {\n meta = (await res.json()) as ParentChallengeMeta;\n setParentMeta(meta);\n }\n } catch {\n // Network error fetching the parent: no relying-party answer is\n // possible, but the exchange still decides between leaving and the form.\n }\n\n const showForm = () => setExchangeState('fallback_to_login');\n const answerOrShowForm = (error: RelyingPartyError) => {\n if (!answerRelyingParty(meta, error)) showForm();\n };\n\n setExchangeState('exchanging');\n try {\n const res = await exchange();\n if (res.ok) {\n if (!(await carriesAnswer(res))) showForm();\n return;\n }\n if (res.status === 401 || res.status === 400) {\n if (meta?.oidc_prompt_none) answerOrShowForm('login_required');\n else showForm();\n return;\n }\n if (res.status !== 403) {\n showForm();\n return;\n }\n if (meta?.oidc_prompt_none) {\n answerOrShowForm('interaction_required');\n return;\n }\n\n const challenge = parseUpgradeChallenge(403, (name) => res.headers.get(name), await readBody(res));\n if (\n !challenge ||\n challenge.signInRequired === true ||\n (challenge.acrValues === undefined && challenge.maxAge === undefined)\n ) {\n showForm();\n return;\n }\n\n setExchangeState('upgrade_required');\n try {\n await currentPassflow().hostedUpgrade.elevate(challenge, { kind: 'imperative' });\n } catch (error) {\n const outcome = dialogOutcomeFromError(error);\n if (outcome === 'sign-in-required' || outcome === 'insufficient') {\n showForm();\n } else if (outcome === 'unsatisfiable') {\n setStepUpFailure(UPGRADE_UNSATISFIABLE_DETAIL);\n setExchangeState('unsatisfiable');\n } else if (outcome === 'rate-limited') {\n const { retryAfter, message } = error as { retryAfter?: number; message?: string };\n setStepUpFailure(upgradeRateLimitedMessage(retryAfter, message || undefined));\n setExchangeState('rate_limited');\n } else if (challenge.acrValues !== undefined) {\n answerOrShowForm('unmet_authentication_requirements');\n } else {\n showForm();\n }\n return;\n }\n\n setExchangeState('exchanging');\n const retry = await exchange();\n if (retry.ok) {\n if (!(await carriesAnswer(retry))) showForm();\n return;\n }\n if (retry.status === 401) {\n showForm();\n return;\n }\n answerOrShowForm('unmet_authentication_requirements');\n } catch {\n showForm();\n }\n };\n\n void run();\n }, [parentChallengeId, baseUrl, appId]);\n\n return { exchangeState, parentMeta, stepUpFailure };\n};\n\n/**\n * Context surface exposed to children so the SDK's own components\n * (or consumer code) can read the OIDC parent-challenge state.\n */\nexport type OIDCExchangeContextValue = {\n parentChallengeId?: string;\n parentMeta?: ParentChallengeMeta;\n exchangeState: ExchangeState;\n};\n\n/**\n * Sends a landing that owes its second factor to the 2FA screen.\n *\n * A federated sign-in on a non-PKCE app comes back to its redirect URL with\n * the 2FA token in the fragment and no tokens. Core adopts it as it is\n * constructed (`parseQueryParams`, on by default) and strips the fragment;\n * with that off, the token is adopted here through `handleTokensRedirect()`.\n *\n * The navigation runs one render after mount, not in the mount effect: the\n * flow's router and its 2FA route register themselves in their own mount\n * effects, which run before this one, and their state lands in the next\n * render. Navigating at mount would go through the default full-page\n * navigation to the unprefixed route. App-id discovery would hold the flow back\n * the same way, so a `#tfa_token=` landing on the hosted login never runs it: the\n * app comes from the token. That app goes onto the URL here, where the hosted login\n * reads it after a reload.\n *\n * A PKCE federated landing (`?code=&user_state=`) is taken here too, from an\n * effect: the instance is built during render, and StrictMode throws one away\n * without running its effects, so core must not take the landing in its\n * constructor. So is the landing of a hosted sign-in in SDK mode (`?code=&state=`,\n * started by `authRedirect()` in this tab), which core takes after the federated\n * one. Taking either can end in that same 2FA navigation; returned is how it\n * ended otherwise, and a refused landing is `'failed'`.\n *\n * Under an OIDC parent the 2FA landing goes on even with a stored session: the\n * parent's sign-in is the one owing the factor.\n *\n * Tokens in the URL (`access_token=`) are taken from an effect for the same\n * reason, and only once the app id is known: core verifies them against it in\n * the background, and an instance with no app id would reject and strip them.\n * The outcome arrives as `SignIn` with source `tokens-in-url`, or as `Error`\n * with operation `tokens.from-url`, after which the sign-in form shows.\n */\nconst useSecondFactorLanding = (\n landedWithTwoFactorToken: boolean,\n passflow: Passflow,\n navigate: NavigateFunction,\n twoFactorVerifyPath: string,\n appIdFromToken: string | undefined,\n takeTokensFromUrl: boolean,\n isDiscoveringAppId: boolean,\n parentChallengeId: string | undefined,\n): { federatedLandingOutcome?: FederatedLandingOutcome; signInReturnFailed: boolean } => {\n const [pending, setPending] = useState(false);\n const [federatedLandingOutcome, setFederatedLandingOutcome] = useState<FederatedLandingOutcome>();\n const [signInReturnFailed, setSignInReturnFailed] = useState(false);\n\n const takenRef = useRef(false);\n const currentPassflowRef = useRef(passflow);\n currentPassflowRef.current = passflow;\n const navigateRef = useRef(navigate);\n navigateRef.current = navigate;\n\n // A hosted sign-in returns to the app root; this takes the user on to the page it started on.\n // A fragment cannot travel through `navigate`, so a page with one is loaded in full.\n const returnToStartPage = () => {\n const to = takeReturnPath();\n const { pathname, search, hash } = window.location;\n if (to === undefined || to === pathname + search + hash) return;\n const url = new URL(to, window.location.origin);\n if (url.hash) window.location.replace(to);\n else navigateRef.current({ to: url.pathname, search: url.search || undefined, replace: true });\n };\n\n // Deps `[passflow]`: under app-id discovery the first instance has no app id\n // and leaves the landing to the next one. The ref makes StrictMode's replay a\n // no-op. No cleanup on purpose: settings can replace the instance while its\n // exchange runs, and the events still fire on the store of the one that took\n // the landing. The listener removes itself on its first outcome.\n useEffect(() => {\n if (takenRef.current) return;\n\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.TwoFactorRequired) {\n passflow.unsubscribe(subscriber);\n setPending(true);\n } else if (eventType === PassflowEvent.Error) {\n const operation = (payload as ErrorPayload | undefined)?.operation;\n if (operation !== 'federated.redirect' && operation !== 'oidc.redirect') return;\n passflow.unsubscribe(subscriber);\n setFederatedLandingOutcome('failed');\n // Core reports a refused hosted sign-in return only as this event: the provider shows it.\n if (operation === 'oidc.redirect') setSignInReturnFailed(true);\n } else if (eventType === PassflowEvent.SignIn) {\n const signIn = payload as PassflowEventPayload[PassflowEvent.SignIn] | undefined;\n if (signIn?.source !== 'federated-landing' && signIn?.source !== 'oidc-landing') return;\n passflow.unsubscribe(subscriber);\n // A replaced instance's session start is a no-op, and the current one\n // read storage before these tokens existed.\n const current = currentPassflowRef.current;\n if (current !== passflow && signIn.tokens) current.setTokens(signIn.tokens);\n setFederatedLandingOutcome('signed-in');\n if (signIn.source === 'oidc-landing') returnToStartPage();\n }\n },\n };\n\n passflow.subscribe(subscriber, [PassflowEvent.TwoFactorRequired, PassflowEvent.SignIn, PassflowEvent.Error]);\n if (passflow.completeFederatedLanding()) takenRef.current = true;\n else passflow.unsubscribe(subscriber);\n }, [passflow]);\n\n // Same shape as the federated landing above: once, on the instance that has\n // the app id (or the last one, if discovery failed), with no cleanup.\n const tokensTakenRef = useRef(false);\n useEffect(() => {\n if (!takeTokensFromUrl || isDiscoveringAppId || tokensTakenRef.current) return;\n tokensTakenRef.current = true;\n\n const subscriber: PassflowSubscriber = {\n onAuthChange: (eventType, payload) => {\n if (eventType === PassflowEvent.Error) {\n if ((payload as ErrorPayload | undefined)?.operation !== 'tokens.from-url') return;\n passflow.unsubscribe(subscriber);\n } else if (eventType === PassflowEvent.SignIn) {\n const signIn = payload as PassflowEventPayload[PassflowEvent.SignIn] | undefined;\n if (signIn?.source !== 'tokens-in-url') return;\n passflow.unsubscribe(subscriber);\n const current = currentPassflowRef.current;\n if (current !== passflow && signIn.tokens) current.setTokens(signIn.tokens);\n setFederatedLandingOutcome('tokens-in-url');\n returnToStartPage();\n }\n },\n };\n\n passflow.subscribe(subscriber, [PassflowEvent.SignIn, PassflowEvent.Error]);\n passflow.handleTokensRedirect();\n }, [passflow, takeTokensFromUrl, isDiscoveringAppId]);\n\n // Once, on mount — the landing is a property of the page load. A hydrated page waits for the render after\n // hydration: the flow mounts its routes only then, and the navigation must come one render after them.\n const hydrated = useHydrated();\n const landingTakenRef = useRef(false);\n useEffect(() => {\n if (!hydrated || landingTakenRef.current) return;\n landingTakenRef.current = true;\n if (!landedWithTwoFactorToken) return;\n // A signed-in user owes no factor: a `#tfa_token=` link is not theirs to answer. Under an OIDC parent it is the\n // parent's sign-in that owes it.\n if (passflow.isAuthenticated() && !parentChallengeId) return;\n if (!passflow.isTwoFactorVerificationRequired()) passflow.handleTokensRedirect();\n if (passflow.isTwoFactorVerificationRequired()) setPending(true);\n }, [hydrated]);\n\n useEffect(() => {\n if (!pending) return;\n setPending(false);\n const search = new URLSearchParams(signInSearch(addressBarSearch.read()));\n if (appIdFromToken) search.set('appid', appIdFromToken);\n navigate({ to: twoFactorVerifyPath, search: search.toString() || undefined, replace: true });\n }, [pending, navigate, twoFactorVerifyPath, appIdFromToken]);\n\n return { federatedLandingOutcome, signInReturnFailed };\n};\n\nexport const OIDCExchangeContext = React.createContext<OIDCExchangeContextValue>({\n exchangeState: 'idle',\n});\n\nexport const PassflowProvider: FC<PassflowProviderProps> = ({\n children,\n navigate: initialNavigate,\n router = 'default',\n backend,\n upgrade,\n twoFactorVerifyPath,\n // `backend` and `upgrade` are destructured out on purpose: they are\n // interception policy, not client-wide configuration, and §13.5 keeps them\n // off `PassflowConfig` — which is what `config` is spread into below.\n ...config\n}) => {\n // Read before core is constructed: core adopts `#tfa_token=` and strips it.\n const [appIdFromToken] = useState(() => (config.appId ? undefined : twoFactorTokenAppId(config.url)));\n\n // If appId is not provided, set isDiscoveringAppId to true to signal\n // that auto-discovery should happen (prevents showing error before discovery)\n const needsDiscovery = !config.appId && !appIdFromToken;\n\n const [state, dispatch] = useReducer(passflowReducer, {\n ...initialState,\n ...config,\n appId: config.appId || appIdFromToken,\n isDiscoveringAppId: needsDiscovery,\n });\n\n // A new `appId` prop is another app: the instance below is rebuilt for it and reads only that app's tokens.\n // Everything the old app's settings wrote goes back to the props or the initial state, so the new app's settings\n // are fetched and fill it again.\n const appIdPropRef = useRef(config.appId);\n const [mountHandOff] = useState(config.handOff);\n useEffect(() => {\n if (!config.appId || config.appId === appIdPropRef.current) return;\n appIdPropRef.current = config.appId;\n dispatch({\n type: 'SET_PASSFLOW_STATE',\n payload: {\n appId: config.appId,\n appSettings: initialState.appSettings,\n passwordPolicy: initialState.passwordPolicy,\n hasSettingsError: initialState.hasSettingsError,\n scopes: config.scopes,\n createTenantForNewUser: config.createTenantForNewUser,\n handOff: mountHandOff,\n },\n });\n }, [config.appId]);\n\n const [navigate, setNavigate] = useState<NavigateFunction>(() => {\n if (initialNavigate) {\n return initialNavigate;\n }\n return defaultNavigate;\n });\n\n // Read before core is constructed: core adopts `#tfa_token=` and strips it.\n const [landedWithTwoFactorToken] = useState(urlCarriesTwoFactorToken);\n const [landedWithAccessToken] = useState(urlCarriesAccessToken);\n const takeTokensFromUrl = landedWithAccessToken && config.parseQueryParams !== false;\n\n // Read once, at mount, like every other prop that seeds the reducer.\n const [fixedConfig] = useState<PassflowConfig>(() => ({\n keyStoragePrefix: config.keyStoragePrefix,\n tokenExchange: config.tokenExchange,\n platform: config.platform,\n refreshCoordination: config.refreshCoordination,\n refreshStrikes: config.refreshStrikes,\n }));\n\n // OIDC AuthFlow integration: the interceptor injects\n // parent_challenge_id on outbound auth POSTs + follows\n // server-returned redirect_url; the exchange-on-mount probe decides\n // whether to render login form vs auto-exchange. See ADR-2.\n const parentChallengeId = useMemo(() => readParentChallengeIdFromURL() ?? bootParentChallengeId, []);\n useOIDCInterceptor(parentChallengeId);\n // Assigned below in every render, before any effect reads it.\n const passflowRef = useRef<Passflow | undefined>(undefined);\n const currentPassflow = useCallback(() => passflowRef.current as Passflow, []);\n const { exchangeState, parentMeta, stepUpFailure } = useSessionExchangeOnMount(\n parentChallengeId,\n landedWithTwoFactorToken,\n currentPassflow,\n config.url,\n state.appId,\n );\n\n // The fields core reads. While the step-up dialog is open they stay as they were: the dialog is the current\n // instance's hosted step-up, and replacing the instance would cancel it. What arrived meanwhile, such as the app's\n // settings, applies once the dialog closes.\n const liveInstanceConfig = {\n url: state.url,\n appId: state.appId,\n scopes: state.scopes,\n createTenantForNewUser: state.createTenantForNewUser,\n parseQueryParams: state.parseQueryParams,\n };\n const instanceConfigRef = useRef(liveInstanceConfig);\n if (exchangeState !== 'upgrade_required') instanceConfigRef.current = liveInstanceConfig;\n const instanceConfig = instanceConfigRef.current;\n\n // Rebuilt only when a field core reads changes. Settings arriving, discovery ending or an equal scopes array keep\n // the instance, and with it core's cached settings read.\n const scopesKey = instanceConfig.scopes?.join(' ');\n const passflow = useMemo(\n () =>\n new Passflow({\n ...fixedConfig,\n ...instanceConfig,\n parseQueryParams: landedWithAccessToken ? false : instanceConfig.parseQueryParams,\n deferFederatedLanding: true,\n }),\n [\n fixedConfig,\n instanceConfig.url,\n instanceConfig.appId,\n scopesKey,\n instanceConfig.createTenantForNewUser,\n instanceConfig.parseQueryParams,\n landedWithAccessToken,\n ],\n );\n passflowRef.current = passflow;\n useDisposeOnReplace(passflow);\n\n // Auto-discover appId from /settings endpoint if not provided\n const discoveryAttemptedRef = useRef(false);\n useEffect(() => {\n if (needsDiscovery && !discoveryAttemptedRef.current && state.isDiscoveringAppId) {\n discoveryAttemptedRef.current = true;\n\n const discoverAppId = async () => {\n // Try relative path first (works with dev server proxy and same-origin production)\n // Then fall back to absolute URL if configured\n const urlsToTry = ['/settings'];\n if (config.url) {\n urlsToTry.push(`${config.url}/settings`);\n }\n\n for (const url of urlsToTry) {\n try {\n const response = await fetch(url);\n if (response.ok) {\n const settings = await response.json();\n const discoveredAppId = settings.login_app?.app_id || settings.appId;\n\n if (discoveredAppId) {\n passflow.setAppId(discoveredAppId);\n // Only what discovery found: a field it did not find keeps whatever is in the state now.\n const discovered: Partial<PassflowState> = { appId: discoveredAppId, isDiscoveringAppId: false };\n const scopes = settings.login_app?.scopes || settings.scopes;\n // Under a hand-off the sign-in scopes follow the hand-off scopes rule, applied by the reducer.\n if (state.handOff) dispatch({ type: 'SET_FOUND_SCOPES', found: scopes });\n else if (scopes) discovered.scopes = scopes;\n const createTenant = settings.login_app?.create_tenant_for_new_user ?? settings.createTenantForNewUser;\n if (createTenant !== undefined) discovered.createTenantForNewUser = createTenant;\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: discovered });\n return;\n }\n }\n } catch (error) {}\n }\n\n // All URLs failed\n console.warn('Failed to discover appId from /settings');\n dispatch({ type: 'SET_PASSFLOW_STATE', payload: { isDiscoveringAppId: false } });\n };\n\n void discoverAppId();\n }\n }, [needsDiscovery, state.isDiscoveringAppId, config.url, passflow]);\n\n const passflowValue = useMemo(() => ({ state, dispatch, passflow }), [state, passflow]);\n\n const handleSetNavigate = useCallback((newNavigate: NavigateFunction | null) => {\n setNavigate(() => newNavigate || defaultNavigate);\n }, []);\n\n const [flowTwoFactorVerifyPath, setFlowTwoFactorVerifyPath] = useState<string | null>(null);\n const resolvedTwoFactorVerifyPath = flowTwoFactorVerifyPath ?? twoFactorVerifyPath ?? routes.two_factor_verify.path;\n const [flowSignInPath, setFlowSignInPath] = useState<string | null>(null);\n const { federatedLandingOutcome, signInReturnFailed } = useSecondFactorLanding(\n landedWithTwoFactorToken,\n passflow,\n navigate,\n resolvedTwoFactorVerifyPath,\n appIdFromToken,\n takeTokensFromUrl,\n state.isDiscoveringAppId === true,\n parentChallengeId,\n );\n\n const navigationValue = useMemo(\n () => ({\n navigate,\n setNavigate: handleSetNavigate,\n router,\n twoFactorVerifyPath: resolvedTwoFactorVerifyPath,\n setTwoFactorVerifyPath: setFlowTwoFactorVerifyPath,\n signInPath: flowSignInPath ?? routes.signin.path,\n setSignInPath: setFlowSignInPath,\n federatedLandingOutcome,\n }),\n [navigate, handleSetNavigate, router, resolvedTwoFactorVerifyPath, flowSignInPath, federatedLandingOutcome],\n );\n\n const oidcExchangeValue = useMemo<OIDCExchangeContextValue>(\n () => ({ parentChallengeId, parentMeta, exchangeState }),\n [parentChallengeId, parentMeta, exchangeState],\n );\n\n // `undefined` ⇒ off, so no existing consumer changes behaviour. `false`\n // forces it off even when a `backend` is declared; declaring a `backend` is\n // itself an opt-in, since naming where your API is has no other meaning.\n //\n // Under a parent challenge (the hosted login) it is on, through\n // `passflow.hostedUpgrade`: the exchange-on-mount probe steps the hosted\n // session up through that facade. The facade is chosen once, from mount, and\n // the global fetch is never patched there — the exchange reads its own 403.\n const hosted = parentChallengeId !== undefined;\n const upgradeEnabled = upgrade === false ? false : upgrade !== undefined || backend !== undefined || hosted;\n const upgradeOptions = useMemo<PassflowUpgradeOptions>(\n () => (typeof upgrade === 'object' && upgrade !== null ? upgrade : {}),\n [upgrade],\n );\n // A step-up only a fresh sign-in can meet: the app's own sign-in route when a mounted flow registered one, else the\n // hosted login. The hosted login page itself shows its sign-in form from the exchange instead.\n const signInForStepUp = useCallback(() => {\n if (flowSignInPath) navigate({ to: flowSignInPath });\n else void startHostedSignIn(passflow).catch(() => undefined);\n }, [flowSignInPath, navigate, passflow]);\n\n // Render the continuing status while the exchange is in flight or the\n // step-up dialog is open over it. Once it resolves (either via navigation\n // or by falling through), children mount as normal.\n const showContinuing = exchangeState === 'exchanging' || exchangeState === 'upgrade_required';\n return (\n <PassflowContext.Provider value={passflowValue}>\n <NavigationContext.Provider value={navigationValue}>\n <OIDCExchangeContext.Provider value={oidcExchangeValue}>\n <AuthProvider>\n {/* Mounted outside the exchange branch so a state change does not\n tear down and reinstall the upgrade interceptors. */}\n <UpgradeProvider\n {...upgradeOptions}\n facade={hosted ? passflow.hostedUpgrade : undefined}\n interceptFetch={hosted ? false : upgradeOptions.interceptFetch}\n onSignInRequired={upgradeOptions.onSignInRequired ?? signInForStepUp}\n failures={hosted ? 'caller' : 'dialog'}\n enabled={upgradeEnabled}\n backend={backend}\n >\n {signInReturnFailed ? (\n <SignInReturnFailed onSignInAgain={() => void startHostedSignIn(passflow).catch(() => undefined)} />\n ) : (exchangeState === 'unsatisfiable' || exchangeState === 'rate_limited') && stepUpFailure ? (\n <StepUpFailed message={stepUpFailure} testId={`exchange-${exchangeState.replace('_', '-')}`} />\n ) : showContinuing ? (\n <ContinuingStatus appName={parentMeta?.app_name} />\n ) : (\n children\n )}\n </UpgradeProvider>\n </AuthProvider>\n </OIDCExchangeContext.Provider>\n </NavigationContext.Provider>\n </PassflowContext.Provider>\n );\n};\n","import { SERVICE_UNAVAILABLE_ERROR_ID } from '@passflow/core';\nimport { useContext, useRef, useState } from 'react';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport { PassflowContext } from '@/context';\nimport { getUrlWithTokens, isSameOriginPath, isSignInPage } from '@/utils';\nimport { useNavigation } from './use-navigation';\nimport { usePassflow } from './use-passflow';\n\nconst REDIRECT_NOT_REGISTERED = 'error.app.redirect.url.not.registered';\n\nexport type SignInEnding = 'none' | 'checking' | 'signed-in' | 'refused' | 'unavailable' | 'service-unavailable';\n\n/**\n * How every sign-in ends once the user holds tokens, in this order:\n * 1. With no target, or a target that is the sign-in page itself, the user stays and is told they are signed in.\n * 2. A path on this page's origin is a plain navigation. It carries no tokens.\n * 3. Anything else is left for. A target that came with the request (a prop, the URL, a token or a response) is\n * validated by the server first and the user goes to the address it returns. If the server refuses, fails, or\n * Passflow cannot be reached at all, nothing is sent: `ending` says which, and `retry` asks again. The app's own\n * default redirect is its operator's configuration and is not checked. The source decides, not the value.\n * 4. Tokens go in the URL only for an app in Simple mode; in SDK mode the user goes to the address with nothing, and\n * the app's SDK starts the sign-in. If the app's mode cannot be read, nothing is sent and `ending` is\n * `unavailable`.\n */\nexport const useSignInEnding = () => {\n const passflow = usePassflow();\n const handOff = useContext(PassflowContext)?.state.handOff;\n const { navigate, signInPath } = useNavigation();\n const [ending, setEnding] = useState<SignInEnding>('none');\n // The external ending last started, for `retry`: a requested target is checked again, the app default is not.\n const lastEnding = useRef<{ target: string; checked: boolean } | null>(null);\n // A screen that starts its request on mount holds this render's closure, from before the flow registered its path.\n const latestSignInPath = useRef(signInPath);\n latestSignInPath.current = signInPath;\n\n const handOver = async (address: string) => {\n setEnding('checking');\n let pkceEnabled: boolean | undefined;\n try {\n pkceEnabled = (await passflow.getAppSettings())?.pkce_enabled;\n } catch {\n setEnding('unavailable');\n return;\n }\n // Only a mode positively known to be Simple gets tokens in the URL.\n window.location.href = pkceEnabled === false ? await getUrlWithTokens(passflow, address, 'hash', handOff) : address;\n };\n\n const leaveFor = async (target: string) => {\n setEnding('checking');\n let address: string;\n try {\n address = await passflow.checkRedirectUrl(target);\n } catch (error) {\n const id = (error as { id?: string } | undefined)?.id;\n if (id === REDIRECT_NOT_REGISTERED) setEnding('refused');\n else if (id === SERVICE_UNAVAILABLE_ERROR_ID) setEnding('service-unavailable');\n else setEnding('unavailable');\n return;\n }\n await handOver(address);\n };\n\n const finishSignIn = async (requested?: string | null, appDefault?: string | null) => {\n // An OIDC parent's redirect is already under way: a second navigation would break it.\n if (hasFollowedOIDCRedirect()) return;\n const target = requested || appDefault;\n if (!target || isSignInPage(target, latestSignInPath.current)) {\n setEnding('signed-in');\n } else if (isSameOriginPath(target)) {\n navigate({ to: target });\n } else if (requested) {\n lastEnding.current = { target: requested, checked: true };\n await leaveFor(requested);\n } else {\n lastEnding.current = { target, checked: false };\n await handOver(target);\n }\n };\n\n const retry = () => {\n const last = lastEnding.current;\n if (!last) return;\n void (last.checked ? leaveFor(last.target) : handOver(last.target));\n };\n\n return { ending, retry, finishSignIn };\n};\n","import type {\n PassflowPasskeyAuthenticateStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignInPayload,\n} from '@passflow/core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { AuthOperation, AuthUiError } from '@/types';\nimport {\n authErrorFor,\n authErrorFrom,\n passwordChangeRequiredErrorId,\n passwordChangeRequiredMessage,\n serverErrorIdFrom,\n serverMessageFor,\n} from '@/utils';\nimport { type UseEmailCodeStep, useEmailCodeStep } from './use-email-code-step';\nimport { usePassflow } from './use-passflow';\n\n/**\n * How a password or passkey sign-in ended. `'two-factor-required'` means core holds a pending sign-in that still owes\n * a second factor: there is no session yet.\n */\nexport type SignInOutcome = 'signed-in' | 'two-factor-required';\n\nexport type UseSignInOptions = {\n /**\n * Called when the server refuses the sign-in until the password is changed. `fetch` then resolves `false` and sets\n * no form error; send the user to the password reset. `notice` is the server's message for the user. Without this\n * option, the same message shows as the form error.\n */\n onPasswordChangeRequired?: (notice: string) => void;\n};\n\nexport type UseSignInProps = (options?: UseSignInOptions) => {\n /**\n * Resolves a {@link SignInOutcome} for a password or passkey sign-in, the server's answer for a passwordless one,\n * and `false` when the request failed, was superseded, or entered the emailed-code step.\n */\n fetch: (\n payload: PassflowPasskeyAuthenticateStartPayload | PassflowSignInPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ) => Promise<false | SignInOutcome | PassflowPasswordlessResponse>;\n isLoading: boolean;\n isError: boolean;\n error: AuthUiError | null;\n reset: () => void;\n /** Abandons the passkey request in flight: the form returns with a cancelled error, and this hook ignores the request's late result. core may still finish a sign-in that completes later. */\n cancelPasskey: () => void;\n /** The sign-in method whose request is in flight, `null` when none is. */\n pendingOperation: AuthOperation | null;\n /**\n * The emailed-code step. A password request the server answers with a code (or a link) enters it, and `fetch`\n * resolves `false`: there is no session yet.\n */\n emailCode: UseEmailCodeStep;\n};\n\nexport const useSignIn: UseSignInProps = ({ onPasswordChangeRequired } = {}) => {\n const passflow = usePassflow();\n const onPasswordChangeRequiredRef = useRef(onPasswordChangeRequired);\n onPasswordChangeRequiredRef.current = onPasswordChangeRequired;\n // The password request is kept only to repeat it for \"Resend code\"; never rendered, logged or stored.\n const lastPasswordPayloadRef = useRef<PassflowSignInPayload | null>(null);\n const resendPasswordRequest = useCallback(async () => {\n const payload = lastPasswordPayloadRef.current;\n if (!payload) throw new Error('Nothing to resend');\n return passflow.signIn(payload);\n }, [passflow]);\n const emailCode = useEmailCodeStep({\n resend: resendPasswordRequest,\n onRelease: () => {\n lastPasswordPayloadRef.current = null;\n },\n });\n\n useEffect(\n () => () => {\n lastPasswordPayloadRef.current = null;\n },\n [],\n );\n const [error, setError] = useState<AuthUiError | null>(null);\n const [isError, setIsError] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [pendingOperation, setPendingOperation] = useState<AuthOperation | null>(null);\n const attemptRef = useRef(0);\n\n const fetch = useCallback(\n async (\n payload: PassflowPasskeyAuthenticateStartPayload | PassflowSignInPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ): Promise<false | SignInOutcome | PassflowPasswordlessResponse> => {\n attemptRef.current += 1;\n const attempt = attemptRef.current;\n const isCurrent = () => attempt === attemptRef.current;\n setIsLoading(true);\n setPendingOperation(type);\n setIsError(false);\n setError(null);\n\n try {\n if (type === 'password') {\n const answer = await passflow.signIn(payload as PassflowSignInPayload);\n if (!isCurrent()) return false;\n // Held before entering: a link answer releases it at once, a code answer keeps it for resend.\n lastPasswordPayloadRef.current = payload as PassflowSignInPayload;\n if (emailCode.enter(answer)) return false;\n lastPasswordPayloadRef.current = null;\n } else if (type === 'passkey') {\n await passflow.passkeyAuthenticate(payload as PassflowPasskeyAuthenticateStartPayload);\n } else {\n const answer = await passflow.passwordlessSignIn(payload as PassflowPasswordlessSignInPayload);\n return isCurrent() ? answer : false;\n }\n if (!isCurrent()) return false;\n return passflow.isTwoFactorVerificationRequired() ? 'two-factor-required' : 'signed-in';\n } catch (error) {\n if (!isCurrent()) return false;\n const handlePasswordChange = onPasswordChangeRequiredRef.current;\n if (handlePasswordChange && serverErrorIdFrom(error) === passwordChangeRequiredErrorId) {\n handlePasswordChange(serverMessageFor(error) ?? passwordChangeRequiredMessage);\n return false;\n }\n console.error(`[passflow] ${type} sign-in failed`, error);\n setIsError(true);\n setError(authErrorFrom(error, 'sign-in', type));\n return false;\n } finally {\n if (isCurrent()) {\n setIsLoading(false);\n setPendingOperation(null);\n }\n }\n },\n [\n passflow.passkeyAuthenticate,\n passflow.passwordlessSignIn,\n passflow.signIn,\n passflow.isTwoFactorVerificationRequired,\n emailCode.enter,\n ],\n );\n\n const reset = () => {\n setIsError(false);\n setError(null);\n setIsLoading(false);\n setPendingOperation(null);\n };\n\n const cancelPasskey = useCallback(() => {\n attemptRef.current += 1;\n setIsLoading(false);\n setPendingOperation(null);\n setIsError(true);\n setError({ message: 'Passkey sign-in was cancelled.', scope: authErrorFor('sign-in', 'passkey').scope });\n }, []);\n\n return { fetch, isLoading, isError, error, reset, cancelPasskey, pendingOperation, emailCode } as const;\n};\n","import type {\n PassflowPasskeyRegisterStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignUpPayload,\n} from '@passflow/core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { AuthOperation, AuthUiError } from '@/types';\nimport { authErrorFrom } from '@/utils';\nimport { type UseEmailCodeStep, useEmailCodeStep } from './use-email-code-step';\nimport { usePassflow } from './use-passflow';\nimport type { SignInOutcome } from './use-signin';\n\nexport type UseSignUpProps = () => {\n /**\n * Resolves a {@link SignInOutcome} for a password or passkey sign-up, the server's answer for a passwordless one,\n * and `false` when the request failed or entered the emailed-code step.\n */\n fetch: (\n payload: PassflowPasskeyRegisterStartPayload | PassflowSignUpPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ) => Promise<false | SignInOutcome | PassflowPasswordlessResponse>;\n isLoading: boolean;\n isError: boolean;\n error: AuthUiError | null;\n reset: () => void;\n /**\n * The emailed-code step. A password request the server answers with a code (or a link) enters it, and `fetch`\n * resolves `false`: there is no session yet.\n */\n emailCode: UseEmailCodeStep;\n};\n\nexport const useSignUp: UseSignUpProps = () => {\n const passflow = usePassflow();\n // The password request is kept only to repeat it for \"Resend code\"; never rendered, logged or stored.\n const lastPasswordPayloadRef = useRef<PassflowSignUpPayload | null>(null);\n const resendPasswordRequest = useCallback(async () => {\n const payload = lastPasswordPayloadRef.current;\n if (!payload) throw new Error('Nothing to resend');\n return passflow.signUp(payload);\n }, [passflow]);\n const emailCode = useEmailCodeStep({\n resend: resendPasswordRequest,\n onRelease: () => {\n lastPasswordPayloadRef.current = null;\n },\n });\n\n useEffect(\n () => () => {\n lastPasswordPayloadRef.current = null;\n },\n [],\n );\n const [isError, setIsError] = useState(false);\n const [error, setError] = useState<AuthUiError | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n\n const fetch = useCallback(\n async (\n payload: PassflowPasskeyRegisterStartPayload | PassflowSignUpPayload | PassflowPasswordlessSignInPayload,\n type: AuthOperation,\n ): Promise<false | SignInOutcome | PassflowPasswordlessResponse> => {\n setIsLoading(true);\n setIsError(false);\n setError(null);\n const cleanup = () => setIsLoading(false);\n\n try {\n if (type === 'password') {\n const answer = await passflow.signUp(payload as PassflowSignUpPayload);\n // Held before entering: a link answer releases it at once, a code answer keeps it for resend.\n lastPasswordPayloadRef.current = payload as PassflowSignUpPayload;\n if (emailCode.enter(answer)) return false;\n lastPasswordPayloadRef.current = null;\n } else if (type === 'passkey') {\n await passflow.passkeyRegister(payload as PassflowPasskeyRegisterStartPayload);\n } else {\n const passwordlessResponse = await passflow.passwordlessSignIn(payload as PassflowPasswordlessSignInPayload);\n cleanup();\n return passwordlessResponse;\n }\n cleanup();\n return passflow.isTwoFactorVerificationRequired() ? 'two-factor-required' : 'signed-in';\n } catch (error) {\n console.error(`[passflow] ${type} sign-up failed`, error);\n setIsError(true);\n setError(authErrorFrom(error, 'sign-up', type));\n cleanup();\n return false;\n } finally {\n cleanup();\n }\n },\n [\n passflow.signUp,\n passflow.passkeyRegister,\n passflow.passwordlessSignIn,\n passflow.isTwoFactorVerificationRequired,\n emailCode.enter,\n ],\n );\n\n const reset = () => {\n setIsError(false);\n setError(null);\n setIsLoading(false);\n };\n\n return { fetch, isLoading, isError, error, reset, emailCode } as const;\n};\n","import type { TwoFactorTrustedDevice } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTrustedDevicesProps = () => {\n /** The devices the signed-in user trusted to skip the second factor on this app. */\n data: TwoFactorTrustedDevice[];\n refetch: () => Promise<TwoFactorTrustedDevice[] | null>;\n /**\n * Revokes one device; its next sign-in asks for the second factor again.\n * On success the device leaves `data` without a refetch.\n *\n * @returns true when the server revoked it\n */\n revoke: (deviceId: string) => Promise<boolean>;\n isLoading: boolean;\n isError: boolean;\n errorMessage: string;\n};\n\n/**\n * Hook to list and revoke the signed-in user's trusted devices\n */\nexport const useTrustedDevices: UseTrustedDevicesProps = () => {\n const passflow = usePassflow();\n const [data, setData] = useState<TwoFactorTrustedDevice[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [errorMessage, setErrorMessage] = useState<string>('');\n\n const fail = useCallback((e: unknown) => {\n setIsError(true);\n setErrorMessage((e as Error).message);\n }, []);\n\n const fetch = useCallback(async (): Promise<TwoFactorTrustedDevice[] | null> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n const devices = await passflow.getTrustedDevices();\n setData(devices);\n return devices;\n } catch (e) {\n fail(e);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [passflow, fail]);\n\n const revoke = useCallback(\n async (deviceId: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n await passflow.revokeTrustedDevice(deviceId);\n setData((devices) => devices.filter((device) => device.id !== deviceId));\n return true;\n } catch (e) {\n fail(e);\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, fail],\n );\n\n useIsomorphicLayoutEffect(() => {\n void fetch();\n }, [fetch]);\n\n return {\n data,\n refetch: fetch,\n revoke,\n isLoading,\n isError,\n errorMessage,\n };\n};\n","import type { TwoFactorChallengeResponse, TwoFactorMethod, TwoFactorVerifyResponseV2 } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorChallengeReturn = {\n challenge: TwoFactorChallengeResponse | null;\n isLoading: boolean;\n error: Error | null;\n requestChallenge: (firstFactorMethod?: string) => Promise<void>;\n verify: (response: string, trustDevice?: boolean) => Promise<TwoFactorVerifyResponseV2 | null>;\n switchMethod: (method: TwoFactorMethod) => Promise<void>;\n selectedMethod: TwoFactorMethod | null;\n reset: () => void;\n};\n\n/**\n * Hook to manage the v2 two-factor challenge flow with multi-method support\n */\nexport const useTwoFactorChallenge = (): UseTwoFactorChallengeReturn => {\n const passflow = usePassflow();\n const [challenge, setChallenge] = useState<TwoFactorChallengeResponse | null>(null);\n const [selectedMethod, setSelectedMethod] = useState<TwoFactorMethod | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const requestChallenge = useCallback(\n async (firstFactorMethod?: string): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const response = await passflow.twoFactor.requestChallenge({\n first_factor_method: firstFactorMethod,\n });\n setChallenge(response);\n setSelectedMethod(response.method);\n } catch (e) {\n setError(e as Error);\n setChallenge(null);\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const verify = useCallback(\n async (response: string, trustDevice = false): Promise<TwoFactorVerifyResponseV2 | null> => {\n if (!challenge?.challenge_id) {\n setError(new Error('No active challenge session'));\n return null;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const result = await passflow.twoFactor.verifyV2({\n challenge_id: challenge.challenge_id,\n method: selectedMethod || challenge.method,\n response,\n trust_device: trustDevice,\n });\n return result;\n } catch (e) {\n setError(e as Error);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, challenge, selectedMethod],\n );\n\n const switchMethod = useCallback(\n async (method: TwoFactorMethod): Promise<void> => {\n if (!challenge?.challenge_id) {\n setError(new Error('No active challenge session'));\n return;\n }\n\n setIsLoading(true);\n setError(null);\n\n try {\n const response = await passflow.twoFactor.switchToAlternative({\n challenge_id: challenge.challenge_id,\n method,\n });\n setChallenge(response);\n setSelectedMethod(method);\n } catch (e) {\n setError(e as Error);\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, challenge],\n );\n\n const reset = useCallback(() => {\n setChallenge(null);\n setSelectedMethod(null);\n setError(null);\n setIsLoading(false);\n }, []);\n\n return {\n challenge,\n isLoading,\n error,\n requestChallenge,\n verify,\n switchMethod,\n selectedMethod,\n reset,\n };\n};\n","import type { TwoFactorRegenerateResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorManageProps = () => {\n recoveryCodes: string[];\n disable: (code: string) => Promise<boolean>;\n regenerateCodes: (code: string) => Promise<TwoFactorRegenerateResponse | null>;\n reset: () => void;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\n/**\n * Hook to manage 2FA (disable, regenerate codes)\n */\nexport const useTwoFactorManage: UseTwoFactorManageProps = () => {\n const passflow = usePassflow();\n const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [error, setError] = useState<string>('');\n\n const disable = useCallback(\n async (code: string): Promise<boolean> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n await passflow.disableTwoFactor(code);\n return true;\n } catch (e) {\n setIsError(true);\n const err = e as Error;\n setError(err.message);\n return false;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const regenerateCodes = useCallback(\n async (code: string): Promise<TwoFactorRegenerateResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n const response = await passflow.regenerateTwoFactorRecoveryCodes(code);\n setRecoveryCodes(response.recovery_codes);\n return response;\n } catch (e) {\n setIsError(true);\n const err = e as Error;\n setError(err.message);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const reset = useCallback(() => {\n setRecoveryCodes([]);\n setIsError(false);\n setError('');\n }, []);\n\n return {\n recoveryCodes,\n disable,\n regenerateCodes,\n reset,\n isLoading,\n isError,\n error,\n };\n};\n","import type { RegisteredTwoFactorMethod, TwoFactorMethod } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorMethodsReturn = {\n availableMethods: TwoFactorMethod[];\n registeredMethods: RegisteredTwoFactorMethod[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n removeMethod: (methodId: string) => Promise<void>;\n};\n\n/**\n * Hook to manage two-factor authentication methods\n */\nexport const useTwoFactorMethods = (): UseTwoFactorMethodsReturn => {\n const passflow = usePassflow();\n const [availableMethods, setAvailableMethods] = useState<TwoFactorMethod[]>([]);\n const [registeredMethods, setRegisteredMethods] = useState<RegisteredTwoFactorMethod[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async (): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const methods = await passflow.twoFactor.getRegisteredMethods();\n setRegisteredMethods(methods);\n\n // Extract available methods from registered methods\n const available = methods.map((m) => m.method);\n setAvailableMethods(available);\n } catch (e) {\n setError(e as Error);\n setRegisteredMethods([]);\n setAvailableMethods([]);\n } finally {\n setIsLoading(false);\n }\n }, [passflow]);\n\n const removeMethod = useCallback(\n async (methodId: string): Promise<void> => {\n setIsLoading(true);\n setError(null);\n\n try {\n // Call remove method API (needs to be implemented in @passflow/core)\n // For now, this is a placeholder\n await passflow.twoFactor.removeMethod?.(methodId);\n\n // Refresh the methods list after removal\n await refresh();\n } catch (e) {\n setError(e as Error);\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, refresh],\n );\n\n return {\n availableMethods,\n registeredMethods,\n isLoading,\n error,\n refresh,\n removeMethod,\n };\n};\n","import type { TwoFactorConfirmResponse, TwoFactorSetupResponse } from '@passflow/core';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { enrollmentFailureFrom, twoFactorRateLimitedMessage, twoFactorWrongCodeMessage } from '@/utils/auth-error';\nimport { useHydrated } from './use-hydrated';\nimport { usePassflow } from './use-passflow';\n\n/** `checking` reads whether a signed-in user is enrolled; `enrolled` is a user with two-factor authentication on. */\nexport type TwoFactorSetupStep = 'checking' | 'idle' | 'setup' | 'complete' | 'enrolled';\n\nexport type UseTwoFactorSetupProps = () => {\n setupData: TwoFactorSetupResponse | null;\n recoveryCodes: string[];\n step: TwoFactorSetupStep;\n beginSetup: () => Promise<TwoFactorSetupResponse | null>;\n confirmSetup: (code: string) => Promise<TwoFactorConfirmResponse | null>;\n reset: () => void;\n /** The user saved the codes, or there were none: the step becomes `enrolled`. */\n finish: () => void;\n isLoading: boolean;\n isError: boolean;\n error: string;\n};\n\n/** A rate limit on the link page's confirm is a 400 with an id, so the status alone cannot tell. */\nconst setupErrorMessage = (e: unknown): string => {\n const failure = enrollmentFailureFrom(e);\n if (failure === 'rate_limited') return twoFactorRateLimitedMessage;\n if (failure === 'wrong_code') return twoFactorWrongCodeMessage;\n return (e as Error).message;\n};\n\n/**\n * Hook to handle 2FA setup flow (enable 2FA)\n */\nexport const useTwoFactorSetup: UseTwoFactorSetupProps = () => {\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const [setupData, setSetupData] = useState<TwoFactorSetupResponse | null>(null);\n const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [error, setError] = useState<string>('');\n // Signed out, as in a setup link or a sign-in waiting on its second factor, there is no status to read.\n const [step, setStep] = useState<TwoFactorSetupStep>(() => (passflow.isAuthenticated() ? 'checking' : 'idle'));\n\n const checkedRef = useRef(false);\n useEffect(() => {\n if (step !== 'checking' || checkedRef.current) return;\n checkedRef.current = true;\n const read = async () => {\n let enabled = false;\n try {\n enabled = (await passflow.getTwoFactorStatus()).enabled;\n } catch {\n // Unread, the user can still start: the server refuses a second enrolment.\n }\n setStep((current) => (current === 'checking' ? (enabled ? 'enrolled' : 'idle') : current));\n };\n void read();\n }, [passflow, step]);\n\n const beginSetup = useCallback(async (): Promise<TwoFactorSetupResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n const response = await passflow.beginTwoFactorSetup();\n setSetupData(response);\n setStep('setup');\n return response;\n } catch (e) {\n setIsError(true);\n setError(setupErrorMessage(e));\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [passflow]);\n\n const confirmSetup = useCallback(\n async (code: string): Promise<TwoFactorConfirmResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n try {\n const response = await passflow.confirmTwoFactorSetup(code);\n // The answer may carry no codes: an empty list, null or no field.\n setRecoveryCodes(response.recovery_codes ?? []);\n setStep('complete');\n return response;\n } catch (e) {\n setIsError(true);\n setError(setupErrorMessage(e));\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow],\n );\n\n const reset = useCallback(() => {\n setSetupData(null);\n setRecoveryCodes([]);\n setIsError(false);\n setError('');\n setStep('idle');\n }, []);\n\n const finish = useCallback(() => setStep('enrolled'), []);\n\n return {\n setupData,\n recoveryCodes,\n // Hydration renders what the signed-out server rendered.\n step: hydrated ? step : 'idle',\n beginSetup,\n confirmSetup,\n reset,\n finish,\n isLoading,\n isError,\n error,\n };\n};\n","import type { TwoFactorSetupMagicLinkError, TwoFactorSetupMagicLinkErrorCode } from '@passflow/core';\nimport { useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { PassflowContext } from '@/context';\nimport { usePassflow } from './use-passflow';\n\nconst knownErrorCodes: readonly TwoFactorSetupMagicLinkErrorCode[] = [\n 'INVALID_TOKEN',\n 'EXPIRED_TOKEN',\n 'REVOKED_TOKEN',\n 'ALREADY_USED',\n 'RATE_LIMITED',\n 'SERVER_ERROR',\n];\n\n/**\n * Return type for useTwoFactorSetupMagicLink hook\n */\nexport type UseTwoFactorSetupMagicLinkReturn = {\n /** True during validation */\n isLoading: boolean;\n /** True during retry attempt */\n isRetrying: boolean;\n /** True if token validated successfully */\n isValidated: boolean;\n /** Error details if validation failed */\n error: TwoFactorSetupMagicLinkError | null;\n /** Session token if validated */\n sessionToken: string | null;\n /** User ID if validated */\n userId: string | null;\n /** App ID if validated (may be null) */\n appId: string | null;\n /** Session expiration in seconds */\n expiresIn: number | null;\n /** Manual retry function for transient errors */\n retry: () => Promise<void>;\n};\n\n/**\n * Hook to validate magic link token for 2FA setup\n *\n * This hook:\n * - Validates once per token on mount (StrictMode included), after app id discovery ends: the session lives in memory\n * on the Passflow instance, and discovery replaces the instance\n * - Provides loading, error, and success states\n * - Allows manual retry for transient failures\n * - Cleans up conditionally on unmount (only if validation failed or not validated)\n *\n * Usage:\n * ```tsx\n * const { isLoading, isValidated, error, retry } = useTwoFactorSetupMagicLink(token);\n *\n * if (isLoading) return <Loading />;\n * if (error) return <ErrorUI error={error} onRetry={retry} />;\n * if (isValidated) return <TwoFactorSetupForm />;\n * ```\n */\nexport const useTwoFactorSetupMagicLink = (token: string): UseTwoFactorSetupMagicLinkReturn => {\n const passflow = usePassflow();\n const isDiscovering = useContext(PassflowContext)?.state.isDiscoveringAppId ?? false;\n\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [isRetrying, setIsRetrying] = useState<boolean>(false);\n const [isValidated, setIsValidated] = useState<boolean>(false);\n const [error, setError] = useState<TwoFactorSetupMagicLinkError | null>(null);\n const [sessionToken, setSessionToken] = useState<string | null>(null);\n const [userId, setUserId] = useState<string | null>(null);\n const [appId, setAppId] = useState<string | null>(null);\n const [expiresIn, setExpiresIn] = useState<number | null>(null);\n\n // The token the mount effect already validated: its guard, and only its guard.\n const validatedOnMount = useRef<string | null>(null);\n\n // Ref to track if we should clear session on unmount\n const shouldClearOnUnmount = useRef<boolean>(true);\n\n const validateToken = useCallback(async () => {\n try {\n const response = await passflow.validateTwoFactorSetupMagicLink(token);\n\n if (response.success && response.sessionToken && response.userId) {\n // Cleared only here: a retry keeps its error screen, with the busy button, until the answer comes.\n setError(null);\n setSessionToken(response.sessionToken);\n setUserId(response.userId);\n setAppId(response.appId ?? null);\n setExpiresIn(response.expiresIn ?? null);\n setIsValidated(true);\n // Don't clear session on unmount if validation succeeded\n shouldClearOnUnmount.current = false;\n } else if (response.error) {\n // Core copies a raw 429's body `error` into `code`, and only that path gives an unknown code.\n setError(knownErrorCodes.includes(response.error.code) ? response.error : { ...response.error, code: 'RATE_LIMITED' });\n setIsValidated(false);\n shouldClearOnUnmount.current = true;\n }\n } catch (err) {\n // Unexpected error (shouldn't happen - SDK catches errors)\n setError({\n code: 'SERVER_ERROR',\n message: err instanceof Error ? err.message : 'An unexpected error occurred',\n });\n setIsValidated(false);\n shouldClearOnUnmount.current = true;\n } finally {\n setIsLoading(false);\n setIsRetrying(false);\n }\n }, [token, passflow]);\n\n /**\n * Manual retry for transient errors: it skips the mount guard\n */\n const retry = useCallback(async () => {\n setIsRetrying(true);\n await validateToken();\n }, [validateToken]);\n\n /**\n * Validate on mount or when token changes\n */\n useEffect(() => {\n if (!token) {\n setError({\n code: 'INVALID_TOKEN',\n message: 'No token provided',\n });\n setIsLoading(false);\n return;\n }\n\n if (isDiscovering || validatedOnMount.current === token) return;\n validatedOnMount.current = token;\n setIsLoading(true);\n void validateToken();\n }, [token, isDiscovering, validateToken]);\n\n /**\n * Cleanup on unmount - conditional based on validation state\n * Per review feedback: Only clear if validation failed or user navigated away before validation\n */\n useEffect(() => {\n return () => {\n // Only clear magic link session if validation failed or wasn't validated\n // If isValidated=true, let the form handle session clearing after confirm\n if (shouldClearOnUnmount.current) {\n passflow.clearMagicLinkSession();\n }\n };\n }, [passflow]);\n\n return {\n isLoading,\n isRetrying,\n isValidated,\n error,\n sessionToken,\n userId,\n appId,\n expiresIn,\n retry,\n };\n};\n","import type { TwoFactorStatusResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorStatusProps = () => {\n data: TwoFactorStatusResponse | null;\n refetch: () => Promise<TwoFactorStatusResponse | null>;\n isLoading: boolean;\n isError: boolean;\n errorMessage: string;\n};\n\n/**\n * Hook to get the current 2FA enrollment status\n */\nexport const useTwoFactorStatus: UseTwoFactorStatusProps = () => {\n const passflow = usePassflow();\n const [data, setData] = useState<TwoFactorStatusResponse | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [errorMessage, setErrorMessage] = useState<string>('');\n\n const fetch = useCallback(async (): Promise<TwoFactorStatusResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setErrorMessage('');\n try {\n const response = await passflow.getTwoFactorStatus();\n setData(response);\n return response;\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [passflow]);\n\n useIsomorphicLayoutEffect(() => {\n void fetch();\n }, [fetch]);\n\n return {\n data,\n refetch: fetch,\n isLoading,\n isError,\n errorMessage,\n };\n};\n","import type { TwoFactorCompletionOptions, TwoFactorRecoveryResponse, TwoFactorVerifyResponse } from '@passflow/core';\nimport { useCallback, useState } from 'react';\nimport type { TwoFactorError, TwoFactorErrorType } from '@/types/two-factor-errors';\nimport { classifyTwoFactorError } from '@/utils/classify-two-factor-error';\nimport { usePassflow } from './use-passflow';\n\nexport type UseTwoFactorVerifyProps = () => {\n isVerificationRequired: () => boolean;\n /** `options.trustDevice` asks the server to trust this device for later sign-ins. */\n verify: (code: string, options?: TwoFactorCompletionOptions) => Promise<TwoFactorVerifyResponse | null>;\n /** `options.trustDevice` asks the server to trust this device for later sign-ins. */\n useRecoveryCode: (code: string, options?: TwoFactorCompletionOptions) => Promise<TwoFactorRecoveryResponse | null>;\n reset: () => void;\n isLoading: boolean;\n isError: boolean;\n error: string;\n errorType: TwoFactorErrorType | null;\n errorDetails: TwoFactorError | null;\n};\n\n/**\n * Hook to verify 2FA code during login with error classification\n */\nexport const useTwoFactorVerify: UseTwoFactorVerifyProps = () => {\n const passflow = usePassflow();\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [isError, setIsError] = useState<boolean>(false);\n const [error, setError] = useState<string>('');\n const [errorType, setErrorType] = useState<TwoFactorErrorType | null>(null);\n const [errorDetails, setErrorDetails] = useState<TwoFactorError | null>(null);\n\n const isVerificationRequired = useCallback((): boolean => {\n return passflow.isTwoFactorVerificationRequired();\n }, [passflow]);\n\n const handleError = useCallback((e: unknown) => {\n const classified = classifyTwoFactorError(e);\n\n setIsError(true);\n setError(classified.message);\n setErrorType(classified.type);\n setErrorDetails(classified);\n }, []);\n\n const verify = useCallback(\n async (code: string, options?: TwoFactorCompletionOptions): Promise<TwoFactorVerifyResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n setErrorType(null);\n setErrorDetails(null);\n\n try {\n const response = await passflow.verifyTwoFactor(code, options);\n return response;\n } catch (e) {\n handleError(e);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, handleError],\n );\n\n const useRecoveryCode = useCallback(\n async (code: string, options?: TwoFactorCompletionOptions): Promise<TwoFactorRecoveryResponse | null> => {\n setIsLoading(true);\n setIsError(false);\n setError('');\n setErrorType(null);\n setErrorDetails(null);\n\n try {\n const response = await passflow.useTwoFactorRecoveryCode(code, options);\n return response;\n } catch (e) {\n handleError(e);\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [passflow, handleError],\n );\n\n const reset = useCallback(() => {\n setIsError(false);\n setError('');\n setErrorType(null);\n setErrorDetails(null);\n }, []);\n\n return {\n isVerificationRequired,\n verify,\n useRecoveryCode,\n reset,\n isLoading,\n isError,\n error,\n errorType,\n errorDetails,\n };\n};\n","/**\n * `useUpgrade` — the read side of the assurance-upgrade flow (§8.2, §13.3).\n *\n * It **reads `UpgradeContext` and installs nothing**. Installation belongs to\n * `UpgradeProvider` and only to it: two hooks each installing a prompt handler\n * would open two prompts and defeat single-flight.\n *\n * Outside an `UpgradeProvider` it returns `status: 'idle'` with no-op actions\n * rather than throwing (§9.5 H8).\n */\n\nimport type { AssuranceBar, UpgradeChallenge, UpgradeFactor, UpgradeFactorType } from '@passflow/core';\nimport { useContext, useMemo } from 'react';\nimport {\n INERT_UPGRADE_CONTEXT,\n UpgradeContext,\n type UpgradeContextValue,\n type UpgradeElevateOptions,\n type UpgradeErrorStatusKind,\n type UpgradeHookState,\n type UpgradePromptView,\n type UpgradeSettledState,\n} from '@/context/upgrade-context';\n\nexport type UseUpgradeResult = {\n /** True when an `UpgradeProvider` installed a prompt handler. */\n enabled: boolean;\n /** The whole state, as the discriminated union (§13.5's `UpgradeHookState`). */\n state: UpgradeHookState;\n /** The discriminant, for the common `status === 'challenged'` read. */\n status: UpgradeHookState['status'];\n /** What the server demanded — the MERGED requirement when challenges joined. */\n challenge: UpgradeChallenge | null;\n /** Usable factors, already ranked; index 0 is the suggested one. */\n factors: readonly UpgradeFactor[];\n /** The ranked factor types, which is what `UpgradeHookState.challenged` carries. */\n factorTypes: readonly UpgradeFactorType[];\n selectedFactor: UpgradeFactorType | null;\n /**\n * Elevated, and still not enough: the replay was re-challenged (§13.4).\n * Non-null **only** in the `insufficient` state, and it never coexists with\n * `status === 'success'` — this must not read as success.\n */\n insufficient: { obtained: AssuranceBar; required: AssuranceBar } | null;\n /** The terminal failure, in the `error` state only. */\n error: Error | null;\n /** Which failure class, in the `error` state only. */\n errorKind: UpgradeErrorStatusKind | null;\n /** The previous attempt's failure while the prompt is re-shown (a wrong code). */\n previousError: Error | null;\n /** True while a ceremony is on the wire. */\n busy: boolean;\n /** The factor-selection signal — §13.2's late-join boundary (T3). */\n selectFactor: (factor: UpgradeFactorType) => void;\n submit: (code?: string) => void;\n cancel: () => void;\n dismiss: () => void;\n /** Resolves `null` on cancellation; otherwise the flight's terminal state. */\n elevate: (options?: UpgradeElevateOptions) => Promise<UpgradeSettledState | null>;\n};\n\nconst EMPTY_FACTORS: readonly UpgradeFactor[] = [];\n\nconst readPromptFactors = (prompt: UpgradePromptView | null): readonly UpgradeFactor[] =>\n prompt === null ? EMPTY_FACTORS : prompt.factors;\n\nexport const useUpgrade = (): UseUpgradeResult => {\n const context: UpgradeContextValue = useContext(UpgradeContext) ?? INERT_UPGRADE_CONTEXT;\n const { enabled, state, prompt, selectedFactor, selectFactor, submit, cancel, dismiss, elevate } = context;\n\n return useMemo<UseUpgradeResult>(() => {\n const factors = readPromptFactors(prompt);\n\n return {\n enabled,\n state,\n status: state.status,\n challenge: state.status === 'challenged' ? state.challenge : (prompt?.challenge ?? null),\n factors,\n factorTypes: state.status === 'challenged' ? state.factors : factors.map((factor) => factor.type),\n selectedFactor,\n insufficient: state.status === 'insufficient' ? { obtained: state.obtained, required: state.required } : null,\n error: state.status === 'error' ? state.error : null,\n errorKind: state.status === 'error' ? state.kind : null,\n previousError: prompt?.previousError ?? null,\n busy: state.status === 'submitting',\n selectFactor,\n submit,\n cancel,\n dismiss,\n elevate,\n };\n }, [enabled, state, prompt, selectedFactor, selectFactor, submit, cancel, dismiss, elevate]);\n};\n","import { type ParsedTokens, type Passflow, PassflowEvent, type PassflowSubscriber } from '@passflow/core';\nimport { useEffect, useState } from 'react';\nimport { useHydrated } from './use-hydrated';\nimport { usePassflow } from './use-passflow';\n\n/** The signed-in user, from the tokens. Every field is absent when no one is signed in. */\nexport type PassflowUser = {\n /** The user id, the tokens' `sub`. */\n id?: string;\n email?: string;\n phone?: string;\n};\n\nconst USER_EVENTS = [\n PassflowEvent.SignIn,\n PassflowEvent.Register,\n PassflowEvent.Refresh,\n PassflowEvent.SignOut,\n PassflowEvent.SessionExpired,\n];\n\nconst claim = (tokens: ParsedTokens, read: (token: NonNullable<ParsedTokens['id_token']>) => string | undefined) => {\n const fromId = tokens.id_token ? read(tokens.id_token) : undefined;\n return fromId || (tokens.access_token ? read(tokens.access_token) : undefined) || undefined;\n};\n\n// The hosted code flow puts `email` in the access token and the embedded flow in the id token, so the id token is read\n// first and the access token fills what it lacks.\nconst readUser = (passflow: Passflow): PassflowUser => {\n const tokens = passflow.isAuthenticated() ? passflow.getParsedTokens() : undefined;\n if (!tokens) return {};\n return {\n id: claim(tokens, (token) => token.sub),\n email: claim(tokens, (token) => token.email),\n phone: claim(tokens, (token) => token.phonenumber),\n };\n};\n\nconst signedOut: PassflowUser = {};\n\nconst sameUser = (a: PassflowUser, b: PassflowUser) => a.id === b.id && a.email === b.email && a.phone === b.phone;\n\n/** The signed-in user's id, email and phone. Re-renders on sign-in, sign-up, refresh, sign-out and session expiry. */\nexport const useUser = (): PassflowUser => {\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const [user, setUser] = useState<PassflowUser>(() => readUser(passflow));\n\n useEffect(() => {\n const update = () => {\n const next = readUser(passflow);\n setUser((current) => (sameUser(current, next) ? current : next));\n };\n // The session may have changed between the first render and this subscription.\n update();\n const subscriber: PassflowSubscriber = { onAuthChange: update };\n passflow.subscribe(subscriber, USER_EVENTS);\n return () => passflow.unsubscribe(subscriber, USER_EVENTS);\n }, [passflow]);\n\n return hydrated ? user : signedOut;\n};\n","import type { PassflowUserPasskey } from '@passflow/core';\nimport { useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\nimport { usePassflow } from './use-passflow';\n\nexport type UseUserPasskeysProps = () => {\n data: PassflowUserPasskey[];\n createUserPasskey: (relaingPartyId: string) => Promise<void>;\n editUserPasskey: (newName: string, passkeyId: string) => Promise<void>;\n deleteUserPasskey: (passkeyId: string) => Promise<void>;\n isLoading: boolean;\n isError: boolean;\n errorMessage: string;\n};\n\nexport const useUserPasskeys: UseUserPasskeysProps = () => {\n const passflow = usePassflow();\n const [data, setData] = useState<PassflowUserPasskey[]>([]);\n const [isError, setIsError] = useState<boolean>(false);\n const [errorMessage, setErrorMessage] = useState<string>('');\n const [isLoading, setIsLoading] = useState<boolean>(false);\n\n useIsomorphicLayoutEffect(() => {\n const fetch = async (): Promise<void> => {\n setIsLoading(true);\n try {\n const response = await passflow.getUserPasskeys();\n setData(response as unknown as PassflowUserPasskey[]);\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n void fetch();\n }, [passflow]);\n\n const createUserPasskey = async (\n relyingPartyId: string,\n passkeyUsername?: string,\n passkeyDisplayName?: string,\n ): Promise<void> => {\n setIsLoading(true);\n try {\n await passflow.addUserPasskey({ relyingPartyId, passkeyUsername, passkeyDisplayName });\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n const editUserPasskey = async (newName: string, passkeyId: string): Promise<void> => {\n setIsLoading(true);\n try {\n const editUserPasskeyStatus = await passflow.renameUserPasskey(newName, passkeyId);\n if (editUserPasskeyStatus) {\n const userPasskeys = await passflow.getUserPasskeys();\n setData(userPasskeys as unknown as PassflowUserPasskey[]);\n }\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n const deleteUserPasskey = async (passkeyId: string): Promise<void> => {\n setIsLoading(true);\n try {\n const deleteUserPasskeyStatus = await passflow.deleteUserPasskey(passkeyId);\n if (deleteUserPasskeyStatus) {\n const userPasskeys = await passflow.getUserPasskeys();\n setData(userPasskeys as unknown as PassflowUserPasskey[]);\n }\n } catch (e) {\n setIsError(true);\n const error = e as Error;\n setErrorMessage(error.message);\n } finally {\n setIsLoading(false);\n }\n };\n\n return {\n data,\n createUserPasskey,\n editUserPasskey,\n deleteUserPasskey,\n isLoading,\n isError,\n errorMessage,\n };\n};\n","import { getCountryForTimezone } from 'countries-and-timezones';\nimport {\n type ChangeEvent,\n type FC,\n type InputHTMLAttributes,\n type KeyboardEvent,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { type CountryIso2, defaultCountries, parseCountry, usePhoneInput } from 'react-international-phone';\nimport { useOutsideClick } from '@/hooks';\nimport { cn } from '@/utils';\nimport { Button, CountryFlag, Icon } from '..';\n\nimport '@/styles/index.css';\nimport 'react-international-phone/style.css';\n\ntype TFieldPhone = InputHTMLAttributes<HTMLInputElement> & {\n id: string;\n onChange: (event: ChangeEvent<HTMLInputElement>) => void;\n isError?: boolean;\n className?: string;\n // eslint-disable-next-line react/no-unused-prop-types\n ref?: null;\n};\n\nexport const FieldPhone: FC<TFieldPhone> = ({\n id,\n name,\n onChange,\n isError = false,\n className = '',\n disabled = false,\n value,\n ...inputProps\n}) => {\n // The number the field opens with; after that the input owns what is typed.\n const [startingValue] = useState(typeof value === 'string' ? value : '');\n const [show, setShow] = useState(false);\n const [filterValue, setFilterValue] = useState('');\n const [isFocused, setIsFocused] = useState(false);\n const refWrapper = useRef<HTMLDivElement>(null);\n const searchInputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (show) searchInputRef.current?.focus();\n }, [show]);\n\n useOutsideClick(refWrapper, () => {\n setShow(false);\n setFilterValue('');\n });\n\n const userTZ = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const userCountry = getCountryForTimezone(userTZ);\n // Set while a country switch is in flight: the hook resets the number to the new dial code, and the form must hear\n // about it. Typed changes already reach the form through the input's own change event.\n const countrySwitchRef = useRef(false);\n const { inputValue, country, setCountry, handlePhoneValueChange, inputRef } = usePhoneInput({\n defaultCountry: userCountry?.id.toLocaleLowerCase() || 'us',\n value: startingValue,\n onChange: ({ inputValue: nextValue }) => {\n if (!countrySwitchRef.current) return;\n countrySwitchRef.current = false;\n // The tel input is not mounted while the country list is open, so the change is reported without it.\n onChange({ target: { name, value: nextValue } } as ChangeEvent<HTMLInputElement>);\n },\n });\n\n const handlePhoneChange = (event: ChangeEvent<HTMLInputElement>) => {\n countrySwitchRef.current = false;\n handlePhoneValueChange(event);\n onChange(event);\n };\n\n const filteredCountries = useMemo(\n () =>\n defaultCountries.filter((defCountry) => {\n const { name: countryName } = parseCountry(defCountry);\n return countryName.toLowerCase().includes(filterValue.toLowerCase());\n }),\n [filterValue],\n );\n\n const preferredCountries = useMemo(\n () =>\n defaultCountries.filter((defCountry) => {\n const { iso2 } = parseCountry(defCountry);\n return iso2 === userCountry?.id.toLocaleLowerCase();\n }),\n [userCountry?.id],\n );\n\n const allCountries = useMemo(() => {\n if (filterValue) return filteredCountries;\n const preferredIso = new Set(preferredCountries.map((defCountry) => parseCountry(defCountry).iso2));\n return filteredCountries.filter((defCountry) => !preferredIso.has(parseCountry(defCountry).iso2));\n }, [filterValue, filteredCountries, preferredCountries]);\n\n const restoreCountryButtonFocus = () => {\n refWrapper.current?.querySelector<HTMLButtonElement>('.passflow-button-show-country')?.focus();\n };\n\n const handleShow = () => setShow(true);\n\n const handleClose = (restoreFocus = false) => {\n setShow(false);\n setFilterValue('');\n if (restoreFocus) restoreCountryButtonFocus();\n };\n\n const handleChangeCountry = (iso2: CountryIso2) => {\n countrySwitchRef.current = true;\n setCountry(iso2);\n handleClose(true);\n };\n\n const handleOptionKeyDown = (event: KeyboardEvent<HTMLDivElement>, iso2: CountryIso2) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n handleChangeCountry(iso2);\n return;\n }\n\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;\n event.preventDefault();\n const options = Array.from(refWrapper.current?.querySelectorAll<HTMLElement>('[role=\"option\"]') ?? []);\n const currentIndex = options.indexOf(event.currentTarget);\n const nextIndex =\n event.key === 'ArrowDown' ? Math.min(currentIndex + 1, options.length - 1) : Math.max(currentIndex - 1, 0);\n options[nextIndex]?.focus();\n };\n\n const renderCountry = (defCountry: (typeof defaultCountries)[number]) => {\n const { name: countryName, dialCode, iso2 } = parseCountry(defCountry);\n return (\n <div\n key={iso2}\n role='option'\n aria-selected={iso2 === country.iso2}\n tabIndex={0}\n title={countryName}\n onClick={() => handleChangeCountry(iso2)}\n onKeyDown={(event) => handleOptionKeyDown(event, iso2)}\n className='passflow-country-search-item'\n >\n <CountryFlag iso2={iso2} className='passflow-country-search-flag' />\n <span className='passflow-country-search-name'>{countryName}</span>\n <span className='passflow-country-search-code'>+{dialCode}</span>\n </div>\n );\n };\n\n return (\n <div\n ref={refWrapper}\n className={cn(\n 'passflow-field-phone-wrapper',\n { 'passflow-field-phone-wrapper--focus': isFocused, 'passflow-field-phone-wrapper--error': isError },\n className,\n )}\n >\n <Button\n type='button'\n variant='clean'\n onClick={() => (show ? handleClose(true) : handleShow())}\n size='big'\n className='passflow-button-show-country'\n disabled={disabled}\n aria-label={`Select country, current ${country.iso2.toUpperCase()}`}\n aria-haspopup='listbox'\n aria-expanded={show}\n aria-controls='passflow-country-options'\n >\n <CountryFlag iso2={country.iso2} />\n <Icon type='general' id='caret-down' size='small' />\n </Button>\n\n {!show ? (\n <input\n {...inputProps}\n id={id}\n name={name}\n ref={inputRef}\n type='tel'\n value={inputValue}\n disabled={disabled}\n aria-invalid={isError}\n onChange={handlePhoneChange}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n className='passflow-field-phone-input'\n />\n ) : (\n <div className='passflow-field-country-search-wrapper'>\n <input\n ref={searchInputRef}\n role='combobox'\n aria-label='Search countries'\n aria-expanded='true'\n aria-controls='passflow-country-options'\n aria-autocomplete='list'\n value={filterValue}\n onChange={(event) => setFilterValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Escape') handleClose(true);\n if (event.key === 'ArrowDown') {\n event.preventDefault();\n refWrapper.current?.querySelector<HTMLElement>('[role=\"option\"]')?.focus();\n }\n }}\n className='passflow-field-country-search'\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n placeholder='Search for a country'\n />\n <div className='passflow-field-country-search-icon'>\n <Icon type='general' id='search' size='small' />\n </div>\n </div>\n )}\n\n <div\n id='passflow-country-options'\n role='listbox'\n tabIndex={-1}\n aria-label='Countries'\n aria-hidden={!show}\n className={cn('passflow-country-search-wrapper', {\n 'passflow-country-search-wrapper--show': show,\n 'passflow-country-search-wrapper--hidden': !show,\n 'passflow-country-search-wrapper--without-preferred': !!filterValue || preferredCountries.length === 0,\n })}\n >\n {filteredCountries.length > 0 ? (\n <>\n <div role='presentation' aria-hidden='true' className='passflow-country-search-sticky-top' />\n {!filterValue && preferredCountries.length > 0 ? (\n <>\n {preferredCountries.map(renderCountry)}\n <div role='presentation' className='passflow-country-search-divider'>\n All countries\n </div>\n </>\n ) : null}\n {allCountries.map(renderCountry)}\n <div role='presentation' aria-hidden='true' className='passflow-country-search-sticky-bottom' />\n </>\n ) : (\n <div role='presentation' className='passflow-country-search-no-matches'>\n No matches\n </div>\n )}\n </div>\n </div>\n );\n};\n","/**\n * Reads a host app's shadcn/ui colour variables for `appearance=\"shadcn\"`.\n *\n * shadcn themes come in two formats. Older themes store a bare HSL triplet\n * (`--primary: 222.2 47.4% 11.2%`) that the app wraps as `hsl(var(--primary))`;\n * Tailwind v4 themes store a complete colour (`oklch(0.205 0 0)`, a hex, …)\n * used as `var(--primary)`. CSS cannot tell the two apart, so the value is read\n * in script and handed to the stylesheet as a `--passflow-login-button-*`\n * custom property. A missing variable sets nothing and the stylesheet's\n * `--passflow-*` fallback applies.\n */\n\nconst HSL_TRIPLET = /^[+-]?[\\d.]+(deg|rad|grad|turn)?\\s+[+-]?[\\d.]+%\\s+[+-]?[\\d.]+%(\\s*\\/\\s*[+-]?[\\d.]+%?)?$/;\n\n/** A shadcn colour variable's value as a CSS colour, or `undefined` when the variable is missing. */\nexport const toCssColor = (raw: string): string | undefined => {\n const value = raw.trim();\n if (!value) return undefined;\n return HSL_TRIPLET.test(value) ? `hsl(${value})` : value;\n};\n\nconst COLOR_VARIABLES = {\n '--primary': '--passflow-login-button-background',\n '--primary-foreground': '--passflow-login-button-foreground',\n '--ring': '--passflow-login-button-ring',\n} as const;\n\nexport type ShadcnThemeProperties = Partial<Record<(typeof COLOR_VARIABLES)[keyof typeof COLOR_VARIABLES], string>>;\n\n/** The login button custom properties for the shadcn colour variables that reach `element`. */\nexport const readShadcnTheme = (element: Element): ShadcnThemeProperties => {\n const style = getComputedStyle(element);\n const properties: ShadcnThemeProperties = {};\n for (const [source, target] of Object.entries(COLOR_VARIABLES) as [\n keyof typeof COLOR_VARIABLES,\n (typeof COLOR_VARIABLES)[keyof typeof COLOR_VARIABLES],\n ][]) {\n const color = toCssColor(style.getPropertyValue(source));\n if (color) properties[target] = color;\n }\n return properties;\n};\n","import type { RefObject } from 'react';\nimport { useIsomorphicLayoutEffect } from '@/hooks/use-isomorphic-layout-effect';\nimport { readShadcnTheme } from './shadcn-theme';\n\n/** The attributes a shadcn app switches its theme with, on `<html>` or `<body>`. */\nconst THEME_ATTRIBUTES = ['class', 'style', 'data-theme'];\n\n/**\n * Sets the host's shadcn colours on `ref`'s element as the custom properties\n * its stylesheet reads, and sets them again when the theme switches: a class,\n * style or `data-theme` change on `<html>` or `<body>`, or a change of\n * `prefers-color-scheme`. Does nothing while `enabled` is false.\n */\nexport const useShadcnTheme = (ref: RefObject<HTMLElement | null>, enabled: boolean): void => {\n // A layout effect so the host's colours are in place before the first paint.\n useIsomorphicLayoutEffect(() => {\n const element = ref.current;\n if (!enabled || !element) return;\n\n let applied: string[] = [];\n const clear = () => {\n for (const name of applied) element.style.removeProperty(name);\n };\n const apply = () => {\n clear();\n const theme = readShadcnTheme(element);\n applied = Object.keys(theme);\n for (const [name, value] of Object.entries(theme)) element.style.setProperty(name, value);\n };\n apply();\n\n const observer = new MutationObserver(apply);\n for (const target of [document.documentElement, document.body]) {\n observer.observe(target, { attributes: true, attributeFilter: THEME_ATTRIBUTES });\n }\n const colorScheme = window.matchMedia?.('(prefers-color-scheme: dark)');\n colorScheme?.addEventListener('change', apply);\n\n return () => {\n observer.disconnect();\n colorScheme?.removeEventListener('change', apply);\n clear();\n };\n }, [ref, enabled]);\n};\n","import { cloneElement, type FC, type MouseEvent, type ReactElement, type ReactNode, useId, useRef } from 'react';\nimport { cn } from '@/utils';\nimport '@/styles/index.css';\nimport { VisuallyHidden } from '../visually-hidden';\nimport { useShadcnTheme } from './use-shadcn-theme';\nimport './login-button.css';\n\n/**\n * `passflow` is the Passflow look. `shadcn` takes the colours, radius, focus\n * ring and font from the host app's shadcn/ui variables (`--primary`,\n * `--primary-foreground`, `--radius`, `--ring`, `--font-sans`), in either the\n * HSL-triplet or the complete-colour format, and falls back to the Passflow\n * tokens for any that are missing.\n */\nexport type LoginButtonAppearance = 'passflow' | 'shadcn';\n\n/** `signing-out` is the signed-in button while the sign-out is in flight: disabled and busy. */\nexport type LoginButtonViewState = 'signed-out' | 'signed-in' | 'signing-out';\n\nexport type LoginButtonViewProps = {\n state: LoginButtonViewState;\n /** The visible content of the default button. Ignored when `children` is given. */\n label: ReactNode;\n /** Read by assistive technology after the name while signed in, since clicking signs out. */\n signOutDescription?: string;\n appearance?: LoginButtonAppearance;\n /** The sign-in or sign-out. Not called when a wrapped child's own `onClick` calls `preventDefault()`. */\n onClick: () => void;\n /**\n * The app's own element to use as the button instead of the default one. It\n * is cloned with a click handler and otherwise left as it is: its props,\n * content and look are its own, and no label is injected. While signing out\n * it also gets `disabled` and `aria-busy`; when idle those stay as the app\n * passed them.\n */\n children?: ReactElement;\n};\n\ntype ClickableProps = { onClick?: (event?: MouseEvent<HTMLElement>) => void };\ntype ChildProps = ClickableProps & { disabled?: boolean; 'aria-busy'?: boolean };\n\n/**\n * The sign-in / sign-out button. It renders a state and calls `onClick`; the\n * `LoginButton` runtime component decides the state and does the sign-in or\n * sign-out.\n */\nexport const LoginButtonView: FC<LoginButtonViewProps> = ({\n state,\n label,\n signOutDescription = 'Sign out',\n appearance = 'passflow',\n onClick,\n children,\n}) => {\n const buttonRef = useRef<HTMLButtonElement>(null);\n const descriptionId = useId();\n useShadcnTheme(buttonRef, appearance === 'shadcn' && !children);\n\n const busy = state === 'signing-out';\n\n if (children) {\n const own = (children.props as ClickableProps).onClick;\n return cloneElement(children as ReactElement<ChildProps>, {\n // Some UI libraries call `onClick()` with no event; then there is nothing to have been prevented.\n onClick: (event?: MouseEvent<HTMLElement>) => {\n own?.(event);\n if (!event?.defaultPrevented) onClick();\n },\n // Set only while busy, so an idle child keeps its own `disabled` and `aria-busy`.\n ...(busy ? { disabled: true, 'aria-busy': true } : {}),\n });\n }\n\n const signedIn = state !== 'signed-out';\n\n // The description is a sibling, not a child: inside the button it would join the button's name.\n return (\n <>\n <button\n ref={buttonRef}\n type='button'\n className={cn('passflow-login-button', {\n 'passflow-login-button--shadcn': appearance === 'shadcn',\n })}\n disabled={busy}\n aria-busy={busy || undefined}\n aria-describedby={signedIn ? descriptionId : undefined}\n onClick={onClick}\n >\n {label}\n </button>\n {signedIn ? <VisuallyHidden id={descriptionId}>{signOutDescription}</VisuallyHidden> : null}\n </>\n );\n};\n","import * as PopoverPrimitive from '@radix-ui/react-popover';\nimport { type ComponentPropsWithoutRef, type ElementRef, forwardRef } from 'react';\nimport { cn } from '@/utils';\n\nconst Popover = PopoverPrimitive.Root;\n\nconst PopoverTrigger = PopoverPrimitive.Trigger;\n\nconst PopoverAnchor = PopoverPrimitive.Anchor;\n\nconst PopoverContent = forwardRef<\n ElementRef<typeof PopoverPrimitive.Content>,\n ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n ref={ref}\n align={align}\n sideOffset={sideOffset}\n className={cn('passflow-popover-content', className)}\n {...props}\n />\n </PopoverPrimitive.Portal>\n));\nPopoverContent.displayName = PopoverPrimitive.Content.displayName;\n\nexport { Popover, PopoverAnchor, PopoverContent, PopoverTrigger };\n","/* eslint-disable react/jsx-props-no-spreading */\nimport type { ComponentType, FC } from 'react';\nimport { useHydrated } from '@/hooks/use-hydrated';\n\n/**\n * Renders `Component` only once the page has hydrated. The URL and the session exist only in the browser, so a screen\n * that reads either during render renders nothing on the server and in the hydration render, and its content from\n * the next render. A render that is not a hydration shows the screen at once.\n */\nexport const withHydration = <P extends object>(Component: ComponentType<P>): FC<P> => {\n const Hydrated: FC<P> = (props) => {\n const hydrated = useHydrated();\n if (!hydrated) return null;\n return <Component {...props} />;\n };\n Hydrated.displayName = Component.displayName ?? Component.name;\n return Hydrated;\n};\n","import type { LoginScreenProps } from '@/components/ui';\nimport type { UseConsentProps } from '@/hooks/use-consent';\n\n/**\n * Maps consent state onto the shared LoginScreen. Pure — every visual decision\n * lives in LoginScreen, every protocol decision lives in useConsent, and this\n * file is only the translation between them.\n */\nexport const getConsentLoginScreenProps = (consent: UseConsentProps): LoginScreenProps | null => {\n if (consent.status === 'loading') return null;\n\n if (consent.status === 'invalid') {\n return {\n chrome: {\n title: consent.error?.message ?? 'Consent request unavailable',\n },\n state: {\n kind: 'general-error',\n message: consent.error?.message,\n detail: consent.error?.description,\n actionLabel: 'Back to login',\n testId: 'consent-invalid',\n onAction: () => {\n window.location.href = '/web';\n },\n },\n };\n }\n\n if (consent.status === 'redirecting') {\n return {\n chrome: {\n title: 'Taking you back',\n subtitle: `Returning you to ${consent.info?.app_name || 'the application'}.`,\n },\n state: {\n kind: 'status',\n tone: 'success',\n message: 'Decision recorded',\n detail: 'You can close this page if it does not continue on its own.',\n testId: 'consent-redirecting',\n },\n };\n }\n\n const info = consent.info;\n if (!info) return null;\n\n const appName = info.app_name || info.client_id;\n const busy = consent.status === 'working';\n\n return {\n chrome: {\n title: `Allow ${appName} to access your account?`,\n subtitle: 'Choose what this application may use, then allow or deny.',\n // The app's own logo replaces the Passflow mark, which is what makes this\n // read as \"THIS app is asking\" rather than a generic Passflow screen.\n customLogo: info.app_logo_url || undefined,\n customLogoAlt: `${appName} logo`,\n },\n state: {\n kind: 'consent',\n appName,\n scopes: info.requested_scopes.map((scope) => {\n const meta = consent.scopeMetadata(scope);\n return {\n scope,\n label: meta.label || scope,\n description: meta.description || undefined,\n granted: consent.grantedScopes.includes(scope),\n };\n }),\n busy,\n error: consent.error?.message,\n allowLabel: 'Allow',\n denyLabel: 'Deny',\n busyLabel: 'Submitting…',\n testId: 'consent-screen',\n allowTestId: 'consent-allow',\n denyTestId: 'consent-deny',\n appNameTestId: 'consent-app-name',\n onToggleScope: consent.toggleScope,\n onAllow: () => void consent.allow(),\n onDeny: () => void consent.deny(),\n },\n };\n};\n","import type { FC } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useConsent } from '@/hooks/use-consent';\nimport { getConsentLoginScreenProps } from './screen';\n\n/**\n * OIDC consent controller, mounted by the host app on `/web/consent`.\n *\n * Standalone by design: it needs no PassflowProvider. The staged request is\n * addressed by `consent_challenge_id` on the URL and read with a same-origin\n * cookie, so there is no SDK client, no app settings lookup, and no token to\n * hold — which is also why mounting it inside the provider would be actively\n * wrong, since the provider's session-exchange probe would fire against a\n * challenge that is waiting for a human decision.\n */\nconst ConsentFlowScreen: FC = () => {\n const consent = useConsent();\n const screen = getConsentLoginScreenProps(consent);\n\n return screen ? <LoginScreen {...screen} /> : null;\n};\n\nexport const ConsentFlow = withHydration(ConsentFlowScreen);\n","import type { LoginMethodConfig, LoginScreenProps } from '@/components/ui';\nimport type { UseDeviceVerifyProps } from '@/hooks/use-device-verify';\nimport type { AuthUiError, DeviceError } from '@/types';\nimport { deviceErrorOfType } from '@/utils';\n\nconst getDeviceLoginMethods = (device: UseDeviceVerifyProps): LoginMethodConfig => ({\n identities: device.info?.methods.password\n ? [\n {\n id: 'email_or_username',\n label: 'Email',\n selectLabel: 'Use email',\n requiredMessage: 'Email is required',\n format: 'email',\n password: true,\n },\n ]\n : [],\n passkey: Boolean(device.info?.methods.passkey),\n providers: [],\n});\n\nconst toCredentialsError = (error: DeviceError | null): AuthUiError | null => {\n if (!error) return null;\n\n return {\n message: error.message,\n scope: error.type === 'bad_credentials' || error.type === 'missing_credentials' ? 'credentials' : 'form',\n };\n};\n\nconst deviceNotice = (device: UseDeviceVerifyProps) => {\n if (!device.info) return undefined;\n\n return {\n code: device.info.user_code,\n appName: device.info.app_name,\n message: \"requested this sign-in. Confirm that the code matches your terminal. If it doesn't, close this page.\",\n codeTestId: 'device-consent-user-code',\n appNameTestId: 'device-consent-app-name',\n };\n};\n\nexport const getDeviceLoginScreenProps = (device: UseDeviceVerifyProps): LoginScreenProps | null => {\n if (device.status === 'loading') return null;\n\n if (device.status === 'code_entry') {\n return {\n chrome: {\n title: 'Enter the code',\n subtitle: 'Type the code shown on your device.',\n },\n state: {\n kind: 'code-entry',\n error: device.error?.message,\n testId: 'device-code-entry',\n onSubmit: device.submitCode,\n },\n };\n }\n\n if (device.status === 'done') {\n return {\n chrome: {\n title: device.info?.app_name ? `You're signed in to ${device.info.app_name}` : \"You're signed in\",\n subtitle: \"Head back to your terminal — it's ready to go.\",\n },\n state: {\n kind: 'status',\n tone: 'success',\n message: 'This device is approved',\n detail: 'You can close this page.',\n testId: device.info?.mode === 'passkey' ? 'device-auto-passkey-done' : 'device-done',\n },\n };\n }\n\n if (device.status === 'refused') {\n const error = device.error ?? deviceErrorOfType('mode_disabled');\n return {\n chrome: {\n title: \"Sign-in isn't available this way\",\n },\n state: {\n kind: 'status',\n tone: 'disabled',\n message: error.message,\n detail: 'Nothing was approved, and nothing was sent to the device that showed you this code.',\n testId: 'device-mode-disabled',\n },\n };\n }\n\n if (device.status === 'failed') {\n const error = device.error ?? deviceErrorOfType('generic');\n return {\n chrome: {\n title: \"That didn't work\",\n },\n state: {\n kind: 'status',\n tone: 'error',\n message: error.message,\n recoverable: error.isRecoverable,\n testId: 'device-failed',\n onRetry: error.isRecoverable ? () => device.submitCode('') : undefined,\n },\n };\n }\n\n if (!device.info) return null;\n\n // Every mode asks for the second factor the same way, before its approval.\n if (device.status === 'second_factor' || (device.status === 'working' && device.isSecondFactorPending)) {\n return {\n chrome: {\n title: 'Two-Factor Authentication',\n subtitle: `One more step to approve ${device.info.app_name}.`,\n },\n state: {\n kind: 'second-factor',\n methods: device.secondFactorMethods,\n identity: device.email,\n busy: device.status === 'working',\n error: device.error?.message,\n testId: 'device-second-factor',\n onSubmit: (method, code) => void device.submitSecondFactor(method, code),\n onMethodChange: device.clearError,\n },\n };\n }\n\n if (device.info.mode === 'passkey') {\n const working = (device.status === 'ready' || device.status === 'working') && !device.error;\n return {\n chrome: {\n title: `Sign in to ${device.info.app_name}`,\n subtitle: 'Confirm with your passkey to finish this device sign-in.',\n },\n state: {\n kind: 'passkey-progress',\n working,\n message: device.error\n ? \"Passkey sign-in couldn't continue.\"\n : 'Waiting for your passkey — follow the prompt on your device.',\n error: device.error?.message,\n recoverable: device.error?.isRecoverable,\n testId: 'device-auto-passkey',\n onRetry: device.error?.isRecoverable ? () => void device.confirmWithPasskey() : undefined,\n },\n };\n }\n\n const busy = device.status === 'working';\n const authenticated = device.isAuthenticated || device.status === 'signed_in';\n const methods = getDeviceLoginMethods(device);\n const notice = deviceNotice(device);\n\n if (device.info.mode === 'full_login') {\n if (authenticated) {\n return {\n chrome: {\n title: `Approve sign-in to ${device.info.app_name}`,\n subtitle: 'Confirm that the code matches your terminal before approving.',\n },\n state: {\n kind: 'device-approval',\n appName: device.info.app_name,\n code: device.info.user_code,\n identity: device.email,\n busy,\n error: device.error?.message,\n testId: 'device-full-login-approval',\n actionTestId: 'device-confirm',\n codeTestId: 'device-consent-user-code',\n appNameTestId: 'device-consent-app-name',\n onApprove: () => void device.approve(),\n },\n };\n }\n\n return {\n chrome: {\n title: `Sign in to approve ${device.info.app_name}`,\n subtitle: 'Confirm the code, then sign in to continue.',\n variant: 'sign-in',\n },\n state: {\n kind: 'credentials',\n methods,\n passwordPolicy: null,\n notice,\n busy,\n error: toCredentialsError(device.error),\n primaryLabel: busy ? 'Signing in…' : 'Sign In',\n passkeyLabel: 'Sign In with a Passkey',\n testId: 'device-full-login',\n onPassword: (values) => void device.signInWithPassword(values.emailOrUsername, values.password),\n onPasskey: () => void device.signInWithPasskey(),\n },\n };\n }\n\n return {\n chrome: {\n title: `Approve sign-in to ${device.info.app_name}`,\n subtitle: 'Confirm the code, then sign in to approve this request.',\n variant: 'sign-in',\n },\n state: {\n kind: 'credentials',\n methods,\n passwordPolicy: null,\n notice,\n busy,\n error: toCredentialsError(device.error),\n primaryLabel: busy ? 'Approving…' : 'Approve',\n primaryTestId: 'device-confirm',\n passkeyLabel: 'Approve with a Passkey',\n testId: 'device-consent',\n onPassword: (values) => void device.confirmWithPassword(values.emailOrUsername, values.password),\n onPasskey: () => void device.confirmWithPasskey(),\n },\n };\n};\n","import type { FC } from 'react';\nimport { useEffect, useRef } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useDeviceVerify } from '@/hooks/use-device-verify';\nimport { getDeviceLoginScreenProps } from './screen';\n\n/**\n * RFC 8628 device verification controller.\n *\n * The server selects consent, full-login, or passkey mode. This component owns\n * the state transition and automatic passkey attempt; the Storybook-backed\n * LoginScreen owns every visual state.\n */\nconst DeviceVerifyFlowScreen: FC = () => {\n const device = useDeviceVerify();\n const attemptedPasskeyChallenge = useRef<string | null>(null);\n const { confirmWithPasskey } = device;\n const challengeKey = device.info?.csrf_token ?? null;\n const isAutomaticPasskeyReady = device.info?.mode === 'passkey' && device.status === 'ready' && !device.error;\n\n useEffect(() => {\n if (!isAutomaticPasskeyReady || !challengeKey || attemptedPasskeyChallenge.current === challengeKey) return;\n\n attemptedPasskeyChallenge.current = challengeKey;\n void confirmWithPasskey();\n }, [challengeKey, confirmWithPasskey, isAutomaticPasskeyReady]);\n\n const screen = getDeviceLoginScreenProps(device);\n return screen ? <LoginScreen {...screen} /> : null;\n};\n\nexport const DeviceVerifyFlow = withHydration(DeviceVerifyFlowScreen);\n","import type { TwoFactorSetupResponse } from '@passflow/core';\nimport type { LoginScreenAction, LoginScreenProps } from '@/components/ui';\n\nconst DEFAULT_DIGITS = 6;\n\ntype SetupScreenStatus = {\n busy: boolean;\n error?: string | null;\n};\n\ntype StartScreenProps = SetupScreenStatus & {\n secondaryAction?: LoginScreenAction;\n onStart: () => void;\n};\n\ntype CodeScreenProps = SetupScreenStatus & {\n data: TwoFactorSetupResponse;\n /** Used when the server named no digit count. */\n fallbackDigits?: number;\n /** Tells the user something without marking the code invalid. An `error` takes its place. */\n notice?: string;\n secondaryAction?: LoginScreenAction;\n onSubmit: (code: string) => void;\n};\n\ntype RecoveryCodesScreenProps = SetupScreenStatus & {\n codes: string[];\n onContinue: () => void;\n};\n\n/** Direct enrolment and the setup link page share these, so both look the same. */\nexport const getTwoFactorSetupStartScreen = ({\n busy,\n error,\n secondaryAction,\n onStart,\n}: StartScreenProps): LoginScreenProps => ({\n chrome: {\n title: 'Enable Two-Factor Authentication',\n subtitle: 'Add an extra layer of security to your account',\n },\n state: {\n kind: 'two-factor-setup',\n step: 'start',\n startLabel: 'Get Started',\n busyLabel: 'Loading...',\n busy,\n error,\n secondaryAction,\n testId: 'two-factor-setup-start',\n onStart,\n },\n});\n\n/** A user with two-factor authentication on: shown instead of the start step. */\nexport const getTwoFactorSetupEnrolledScreen = (): LoginScreenProps => ({\n chrome: { title: 'Two-Factor Authentication' },\n state: {\n kind: 'status',\n tone: 'success',\n message: 'Two-factor authentication is on for your account.',\n detail: 'You will be asked for a code from your authenticator app when you sign in.',\n testId: 'two-factor-setup-enrolled',\n },\n});\n\nexport const getTwoFactorSetupCodeScreen = ({\n data,\n fallbackDigits = DEFAULT_DIGITS,\n notice,\n busy,\n error,\n secondaryAction,\n onSubmit,\n}: CodeScreenProps): LoginScreenProps => {\n const digits = data.totp_digits ?? fallbackDigits;\n\n return {\n chrome: data.qr_code\n ? {\n title: 'Scan QR Code',\n subtitle: 'Scan this code with your authenticator app (Google Authenticator, Authy, etc.)',\n }\n : {\n title: 'Add Your Authenticator',\n subtitle: 'Add this key to your authenticator app (Google Authenticator, Authy, etc.)',\n },\n state: {\n kind: 'two-factor-setup',\n step: 'code',\n qrCode: data.qr_code,\n qrAlt: '2FA QR Code',\n secret: data.secret,\n secretLabel: 'Enter this key in your authenticator app.',\n showSecretLabel: \"Can't scan? Enter code manually\",\n hideSecretLabel: 'Hide manual code',\n digits,\n codeLabel: `Enter the ${digits}-digit code from your app to confirm:`,\n submitLabel: 'Confirm & Enable',\n busyLabel: 'Confirming...',\n busy,\n alert: error ? { message: error, tone: 'error' } : notice ? { message: notice, tone: 'info' } : undefined,\n secondaryAction,\n testId: 'two-factor-setup-code',\n onSubmit,\n },\n };\n};\n\nexport const getTwoFactorRecoveryCodesScreen = ({\n codes,\n busy,\n error,\n onContinue,\n}: RecoveryCodesScreenProps): LoginScreenProps => ({\n chrome: {\n title: 'Save Your Recovery Codes',\n subtitle: \"Store these codes in a safe place. You'll need them if you lose access to your authenticator.\",\n },\n state: {\n kind: 'two-factor-recovery-codes',\n warning: 'These codes will only be shown once. Make sure to save them!',\n codes,\n copyLabel: 'Copy to Clipboard',\n continueLabel: \"I've Saved These Codes\",\n busyLabel: 'Finishing sign-in...',\n busy,\n error,\n testId: 'two-factor-recovery-codes',\n onCopy: () => void navigator.clipboard.writeText(codes.join('\\n')),\n onContinue,\n },\n});\n","import { type FC, useEffect, useRef } from 'react';\nimport { LoginScreen, type LoginScreenAction } from '@/components/ui';\nimport { useTwoFactorSetup } from '@/hooks';\nimport { twoFactorBackToSignInLabel } from '@/utils';\nimport {\n getTwoFactorRecoveryCodesScreen,\n getTwoFactorSetupCodeScreen,\n getTwoFactorSetupEnrolledScreen,\n getTwoFactorSetupStartScreen,\n} from './setup-screen';\n\nimport '@/styles/index.css';\n\ntype TwoFactorSetupFormProps = {\n onComplete?: (recoveryCodes: string[]) => void;\n /** The way out of the first step only. */\n onCancel?: () => void;\n /** The way out of the first step and the code step, labelled Back to sign in. */\n onBackToSignIn?: () => void;\n numInputs?: number;\n};\n\nexport const TwoFactorSetupForm: FC<TwoFactorSetupFormProps> = ({ onComplete, onCancel, onBackToSignIn, numInputs }) => {\n const { setupData, recoveryCodes, step, beginSetup, confirmSetup, finish, isLoading, isError, error } = useTwoFactorSetup();\n const shownError = isError ? error : null;\n const backToSignIn: LoginScreenAction | undefined = onBackToSignIn\n ? { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn }\n : undefined;\n const cancel: LoginScreenAction | undefined = onCancel ? { label: 'Cancel', onClick: onCancel } : undefined;\n\n const handleComplete = () => {\n // A caller that gets `onComplete` owns the next step: its session may be gone, so the form stays on the codes.\n if (onComplete) onComplete(recoveryCodes);\n else finish();\n };\n\n // No codes to save: the codes screen is skipped.\n const skipsCodes = step === 'complete' && recoveryCodes.length === 0;\n const skipCodesRef = useRef(handleComplete);\n skipCodesRef.current = handleComplete;\n useEffect(() => {\n if (skipsCodes) skipCodesRef.current();\n }, [skipsCodes]);\n\n if (step === 'enrolled' || skipsCodes) return <LoginScreen {...getTwoFactorSetupEnrolledScreen()} />;\n\n if (step === 'idle' || step === 'checking') {\n return (\n <LoginScreen\n {...getTwoFactorSetupStartScreen({\n busy: isLoading || step === 'checking',\n error: shownError,\n secondaryAction: backToSignIn ?? cancel,\n onStart: () => void beginSetup(),\n })}\n />\n );\n }\n\n if (step === 'setup' && setupData) {\n return (\n <LoginScreen\n {...getTwoFactorSetupCodeScreen({\n data: setupData,\n fallbackDigits: numInputs,\n busy: isLoading,\n error: shownError,\n secondaryAction: backToSignIn,\n onSubmit: (code) => void confirmSetup(code),\n })}\n />\n );\n }\n\n if (step === 'complete') {\n return (\n <LoginScreen {...getTwoFactorRecoveryCodesScreen({ codes: recoveryCodes, busy: false, onContinue: handleComplete })} />\n );\n }\n\n return null;\n};\n","import type { FC } from 'react';\nimport { useEffect, useState } from 'react';\nimport { TwoFactorSetupForm } from '@/components/form/two-factor-setup';\nimport { routes } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useNavigation, usePassflow } from '@/hooks';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { TwoFactorLoopPrevention } from '@/utils';\n\nimport '@/styles/index.css';\n\nexport type TwoFactorSetupFlowProps = {\n successAuthRedirect?: SuccessAuthRedirect;\n twoFactorVerifyPath?: string;\n signInPath?: string;\n};\n\nconst TwoFactorSetupFlowScreen: FC<TwoFactorSetupFlowProps> = ({\n twoFactorVerifyPath = routes.two_factor_verify.path,\n signInPath = routes.signin.path,\n}) => {\n const [shouldBlockRender, setShouldBlockRender] = useState(false);\n const { navigate } = useNavigation();\n const passflow = usePassflow();\n\n // Handle initial verification requirement check\n // User must be in partial auth state (have tfa_token) to access setup\n useEffect(() => {\n if (!passflow.isTwoFactorVerificationRequired()) {\n // Not in partial auth state - redirect to sign-in\n if (TwoFactorLoopPrevention.canRedirect()) {\n TwoFactorLoopPrevention.incrementRedirect();\n navigate({ to: signInPath });\n setShouldBlockRender(true);\n } else {\n // Loop detected - let component handle gracefully\n setShouldBlockRender(false);\n }\n }\n }, [passflow, navigate, signInPath]);\n\n const handleSetupComplete = () => {\n // After setup is complete, redirect back to verify flow\n // User now has 2FA enabled and needs to verify with a code\n navigate({ to: twoFactorVerifyPath });\n };\n\n const handleCancel = () => {\n // User cancelled setup - reset loop prevention and go back to sign-in\n TwoFactorLoopPrevention.reset();\n navigate({ to: signInPath });\n };\n\n // Don't render if we're redirecting\n if (shouldBlockRender) {\n return null;\n }\n\n // Don't render if verification not required and no loop detected\n if (!passflow.isTwoFactorVerificationRequired() && TwoFactorLoopPrevention.canRedirect()) {\n return null;\n }\n\n return <TwoFactorSetupForm onComplete={handleSetupComplete} onCancel={handleCancel} />;\n};\n\nexport const TwoFactorSetupFlow = withHydration(TwoFactorSetupFlowScreen);\n","import type { FC } from 'react';\nimport { useEffect } from 'react';\nimport { TwoFactorSetupForm } from '@/components/form/two-factor-setup';\nimport { LoginScreen, type LoginStatusState } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { type UseTwoFactorSetupMagicLinkReturn, useNavigation, useTwoFactorSetupMagicLink } from '@/hooks';\nimport {\n signInSearch,\n twoFactorBackToSignInLabel,\n twoFactorLinkAlreadyUsedMessage,\n twoFactorRateLimitedMessage,\n twoFactorSignInLabel,\n} from '@/utils';\n\nimport '@/styles/index.css';\n\n/**\n * Error type for magic link validation\n */\ntype MagicLinkError = NonNullable<UseTwoFactorSetupMagicLinkReturn['error']>;\n\n/**\n * Props for TwoFactorSetupMagicLinkFlow component\n */\nexport type TwoFactorSetupMagicLinkFlowProps = {\n /**\n * The magic-link token. Leave it out and it is read from the URL: the path\n * segment after `/two-factor-setup-magic-link/` (or the same after `#`).\n */\n token?: string;\n /** Callback after successful setup */\n onSuccess?: () => void;\n /** Callback on validation error */\n onError?: (error: MagicLinkError) => void;\n /** Whether to redirect after setup (default: true) */\n redirectOnSuccess?: boolean;\n /** Path to sign-in page (default: /signin) */\n signInPath?: string;\n};\n\nconst MAGIC_LINK_SEGMENT = /\\/two-factor-setup-magic-link\\/([^/?#]+)/;\n\n/** The token in the current URL's path, or after `#` for hash routing; '' when there is none. */\nconst tokenFromUrl = (): string => {\n const found = MAGIC_LINK_SEGMENT.exec(window.location.pathname) ?? MAGIC_LINK_SEGMENT.exec(window.location.hash);\n if (!found?.[1]) return '';\n try {\n return decodeURIComponent(found[1]);\n } catch {\n return found[1];\n }\n};\n\nconst ERROR_SUBTITLES: Partial<Record<MagicLinkError['code'], string>> = {\n EXPIRED_TOKEN: 'This link has expired',\n INVALID_TOKEN: 'This link is invalid',\n REVOKED_TOKEN: 'This link has been revoked',\n SERVER_ERROR: 'Something went wrong',\n};\n\ntype ErrorStateOptions = {\n isRetrying: boolean;\n onRetry: () => void;\n onSignIn: () => void;\n};\n\nconst errorState = (error: MagicLinkError, { isRetrying, onRetry, onSignIn }: ErrorStateOptions): LoginStatusState => {\n const base = { kind: 'status', tone: 'error', testId: 'two-factor-link-error' } as const;\n const signIn = { label: twoFactorSignInLabel, onClick: onSignIn };\n const backToSignIn = { label: twoFactorBackToSignInLabel, onClick: onSignIn };\n\n switch (error.code) {\n case 'ALREADY_USED':\n return { ...base, message: twoFactorLinkAlreadyUsedMessage, primaryAction: signIn };\n case 'RATE_LIMITED':\n return { ...base, message: twoFactorRateLimitedMessage, primaryAction: signIn };\n case 'SERVER_ERROR':\n return {\n ...base,\n message: error.message,\n primaryAction: { label: isRetrying ? 'Retrying...' : 'Try Again', busy: isRetrying, onClick: onRetry },\n secondaryAction: backToSignIn,\n };\n default:\n return {\n ...base,\n message: error.message,\n detail: 'Please contact your administrator to request a new magic link.',\n secondaryAction: backToSignIn,\n };\n }\n};\n\n/**\n * Flow component for magic link 2FA setup\n *\n * This component:\n * 1. Takes the token from its `token` prop, or from the URL\n * 2. Validates token via useTwoFactorSetupMagicLink hook\n * 3. Shows loading state during validation\n * 4. Shows error UI if validation fails\n * 5. Renders TwoFactorSetupForm if validation succeeds\n * 6. Redirects to sign-in after successful setup\n *\n * Route: /two-factor-setup-magic-link/:token\n */\nconst TwoFactorSetupMagicLinkFlowScreen: FC<TwoFactorSetupMagicLinkFlowProps> = ({\n token: tokenProp,\n onSuccess,\n onError,\n redirectOnSuccess = true,\n signInPath = routes.signin.path,\n}) => {\n const token = tokenProp ?? tokenFromUrl();\n const { navigate } = useNavigation();\n const searchSource = useSearchSource();\n\n const { isLoading, isRetrying, isValidated, error, retry } = useTwoFactorSetupMagicLink(token);\n\n useEffect(() => {\n if (error) {\n onError?.(error);\n }\n }, [error, onError]);\n\n const goToSignIn = () => navigate({ to: signInPath, search: signInSearch(searchSource.read()) });\n\n const handleSetupComplete = () => {\n onSuccess?.();\n if (redirectOnSuccess) goToSignIn();\n };\n\n if (isLoading) {\n return (\n <LoginScreen\n chrome={{ title: 'Validating Magic Link', subtitle: 'Please wait while we verify your link...' }}\n state={{ kind: 'status', tone: 'working', message: 'Validating your magic link...', testId: 'two-factor-link-loading' }}\n />\n );\n }\n\n if (error) {\n return (\n <LoginScreen\n chrome={{ title: 'We could not open this link', subtitle: ERROR_SUBTITLES[error.code] }}\n state={errorState(error, { isRetrying, onRetry: () => void retry(), onSignIn: goToSignIn })}\n />\n );\n }\n\n if (isValidated) {\n return <TwoFactorSetupForm onComplete={handleSetupComplete} onBackToSignIn={goToSignIn} />;\n }\n\n // Fallback (should not reach here)\n return null;\n};\n\nexport const TwoFactorSetupMagicLinkFlow = withHydration(TwoFactorSetupMagicLinkFlowScreen);\n","import { SERVICE_UNAVAILABLE_MESSAGE } from '@passflow/core';\nimport type { FC } from 'react';\nimport { LoginScreen, type LoginScreenProps } from '@/components/ui';\nimport { useAppSettings } from '@/hooks';\nimport type { SignInEnding } from '@/hooks/use-sign-in-ending';\n\nexport const SIGNED_IN_MESSAGE = \"You're signed in\";\n\nconst COULD_NOT_FINISH = 'We could not finish your sign-in';\n\nconst screens: Record<\n Exclude<SignInEnding, 'none'>,\n (onRetry: () => void) => Pick<LoginScreenProps, 'state'> & { title: string }\n> = {\n checking: () => ({\n title: 'Finishing your sign-in',\n state: { kind: 'status', tone: 'working', message: 'One moment.', testId: 'sign-in-checking' },\n }),\n 'signed-in': () => ({\n title: SIGNED_IN_MESSAGE,\n state: { kind: 'status', tone: 'success', message: 'You can close this page.', testId: 'signed-in' },\n }),\n refused: () => ({\n title: COULD_NOT_FINISH,\n state: {\n kind: 'status',\n tone: 'error',\n message: 'This app does not allow the address it was asked to return to. Contact your administrator.',\n testId: 'sign-in-refused',\n },\n }),\n unavailable: (onRetry) => ({\n title: COULD_NOT_FINISH,\n state: {\n kind: 'status',\n tone: 'error',\n message: 'We could not check where to send you. Try again.',\n recoverable: true,\n retryLabel: 'Try again',\n onRetry,\n testId: 'sign-in-unavailable',\n },\n }),\n 'service-unavailable': (onRetry) => ({\n title: COULD_NOT_FINISH,\n state: {\n kind: 'status',\n tone: 'error',\n message: SERVICE_UNAVAILABLE_MESSAGE,\n recoverable: true,\n retryLabel: 'Try again',\n onRetry,\n testId: 'sign-in-service-unavailable',\n },\n }),\n};\n\n/** How a sign-in ended, when that is not a redirect. See `useSignInEnding`. */\nexport const SignInEndingScreen: FC<{ ending: Exclude<SignInEnding, 'none'>; onRetry: () => void }> = ({ ending, onRetry }) => {\n const { currentStyles, loginAppTheme } = useAppSettings();\n const { title, state } = screens[ending](onRetry);\n\n return (\n <LoginScreen\n chrome={{\n title,\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={state}\n />\n );\n};\n","import { type FC, useEffect, useRef, useState } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { useTwoFactorVerify } from '@/hooks';\nimport {\n getUserFriendlyErrorMessage,\n isTerminalTwoFactorError,\n twoFactorBackToSignInLabel,\n twoFactorWrongRecoveryCodeMessage,\n} from '@/utils';\n\nimport '@/styles/index.css';\n\ntype TwoFactorRecoveryFormProps = {\n onSuccess?: () => void;\n onBack?: () => void;\n /** The server ended the sign-in, or locked it for too many attempts. The form still shows why when this is not handled. */\n onEnded?: (type: 'expired' | 'rate_limited') => void;\n /** The way out once no further code can be taken. */\n onBackToSignIn?: () => void;\n title?: string;\n subtitle?: string;\n /** Label of the \"trust this device\" option, unticked by default. */\n trustDeviceLabel?: string;\n /** The server's `device_trust_available` for this sign-in. Only `false` hides the option; absent shows it. */\n deviceTrustAvailable?: boolean;\n};\n\n/** Only a ticked box asks for trust; an unticked one sends no option at all. */\nconst completionOptions = (trustDevice: boolean) => (trustDevice ? { trustDevice: true } : undefined);\n\nexport const TwoFactorRecoveryForm: FC<TwoFactorRecoveryFormProps> = ({\n onSuccess,\n onBack,\n onEnded,\n onBackToSignIn,\n title = 'Use Recovery Code',\n subtitle = 'Enter one of your recovery codes',\n trustDeviceLabel = 'Trust this device',\n deviceTrustAvailable,\n}) => {\n const [code, setCode] = useState('');\n const [trustDevice, setTrustDevice] = useState(false);\n const { useRecoveryCode: redeemRecoveryCode, isLoading, isError, errorDetails, reset } = useTwoFactorVerify();\n const errorType = errorDetails?.type;\n\n // Once per error, whatever the caller's callback identity does.\n const onEndedRef = useRef(onEnded);\n onEndedRef.current = onEnded;\n useEffect(() => {\n if (errorType === 'expired' || errorType === 'rate_limited') onEndedRef.current?.(errorType);\n }, [errorType]);\n\n const handleCodeChange = (value: string) => {\n reset();\n // Normalize: uppercase and remove spaces\n setCode(value.toUpperCase().replace(/\\s/g, ''));\n };\n\n const handleSubmit = async () => {\n const result = await redeemRecoveryCode(code, completionOptions(trustDevice));\n if (result) onSuccess?.();\n };\n\n const locked = isTerminalTwoFactorError(errorType);\n const errorMessage = errorDetails\n ? errorType === 'invalid_code'\n ? twoFactorWrongRecoveryCodeMessage\n : getUserFriendlyErrorMessage(errorDetails)\n : '';\n\n return (\n <LoginScreen\n chrome={{ title, subtitle }}\n state={{\n kind: 'two-factor-code',\n factor: { type: 'recovery', placeholder: 'XXXX-XXXX-XXXX' },\n label: 'Recovery Code',\n code,\n trustDevice:\n deviceTrustAvailable === false\n ? undefined\n : { label: trustDeviceLabel, checked: trustDevice, onChange: setTrustDevice },\n busy: isLoading,\n canSubmit: code.length >= 8,\n locked,\n alert:\n isError && errorDetails ? { message: errorMessage, tone: errorType === 'expired' ? 'info' : 'error' } : undefined,\n submitLabel: 'Verify',\n busyLabel: 'Verifying...',\n alternate: onBack ? { prompt: 'Have your device?', label: 'Use authenticator code', onClick: onBack } : undefined,\n secondaryAction: locked && onBackToSignIn ? { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn } : undefined,\n testId: 'two-factor-recovery',\n onCodeChange: handleCodeChange,\n onSubmit: () => void handleSubmit(),\n }}\n />\n );\n};\n","import { type FC, useEffect, useRef, useState } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { usePassflow, useTwoFactorVerify } from '@/hooks';\nimport { getUserFriendlyErrorMessage, isTerminalTwoFactorError, twoFactorBackToSignInLabel } from '@/utils';\n\nimport '@/styles/index.css';\n\ntype TwoFactorVerifyFormProps = {\n onSuccess?: () => void;\n onUseRecovery?: () => void;\n /** The server ended the sign-in, or locked it for too many attempts. The form still shows why when this is not handled. */\n onEnded?: (type: 'expired' | 'rate_limited') => void;\n /** The way out once no further code can be taken. */\n onBackToSignIn?: () => void;\n title?: string;\n subtitle?: string;\n numInputs?: number;\n shouldAutoFocus?: boolean;\n /** Label of the \"trust this device\" option, unticked by default. */\n trustDeviceLabel?: string;\n /** The server's `device_trust_available` for this sign-in. Only `false` hides the option; absent shows it. */\n deviceTrustAvailable?: boolean;\n};\n\n/** Only a ticked box asks for trust; an unticked one sends no option at all. */\nconst completionOptions = (trustDevice: boolean) => (trustDevice ? { trustDevice: true } : undefined);\n\nconst TwoFactorVerifyFormScreen: FC<TwoFactorVerifyFormProps> = ({\n onSuccess,\n onUseRecovery,\n onEnded,\n onBackToSignIn,\n title = 'Two-Factor Authentication',\n subtitle,\n numInputs,\n shouldAutoFocus = true,\n trustDeviceLabel = 'Trust this device',\n deviceTrustAvailable,\n}) => {\n const [code, setCode] = useState('');\n const [trustDevice, setTrustDevice] = useState(false);\n const passflow = usePassflow();\n const { verify, isLoading, isError, errorDetails, reset } = useTwoFactorVerify();\n const errorType = errorDetails?.type;\n\n // An explicit numInputs wins; otherwise core's digit count for the pending sign-in.\n const totpDigits = numInputs ?? passflow.getTotpDigits();\n\n // Compute subtitle dynamically based on totpDigits\n const computedSubtitle = subtitle ?? `Enter the ${totpDigits}-digit code from your authenticator app`;\n\n // Once per error, whatever the caller's callback identity does.\n const onEndedRef = useRef(onEnded);\n onEndedRef.current = onEnded;\n useEffect(() => {\n if (errorType === 'expired' || errorType === 'rate_limited') onEndedRef.current?.(errorType);\n }, [errorType]);\n\n const submit = async (value: string) => {\n const result = await verify(value, completionOptions(trustDevice));\n if (result) onSuccess?.();\n };\n\n // Auto-submit when code is complete\n const handleCodeChange = (value: string) => {\n reset();\n setCode(value);\n if (value.length === totpDigits) void submit(value);\n };\n\n const locked = isTerminalTwoFactorError(errorType);\n\n return (\n <LoginScreen\n chrome={{ title, subtitle: computedSubtitle }}\n state={{\n kind: 'two-factor-code',\n factor: { type: 'totp', digits: totpDigits },\n label: 'Verification code',\n code,\n trustDevice:\n deviceTrustAvailable === false\n ? undefined\n : { label: trustDeviceLabel, checked: trustDevice, onChange: setTrustDevice },\n busy: isLoading,\n canSubmit: code.length === totpDigits,\n locked,\n alert:\n isError && errorDetails\n ? { message: getUserFriendlyErrorMessage(errorDetails), tone: errorType === 'expired' ? 'info' : 'error' }\n : undefined,\n submitLabel: 'Verify',\n busyLabel: 'Verifying...',\n alternate: onUseRecovery\n ? { prompt: 'Lost your device?', label: 'Use recovery code', onClick: onUseRecovery }\n : undefined,\n secondaryAction: locked && onBackToSignIn ? { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn } : undefined,\n autoFocus: shouldAutoFocus,\n testId: 'two-factor-verify',\n onCodeChange: handleCodeChange,\n onSubmit: () => void submit(code),\n }}\n />\n );\n};\n\nexport const TwoFactorVerifyForm = withHydration(TwoFactorVerifyFormScreen);\n","import type { TwoFactorEnrollmentResponse, TwoFactorSetupResponse } from '@passflow/core';\nimport { useContext, useEffect, useRef, useState } from 'react';\nimport { PassflowContext } from '@/context';\nimport {\n enrollmentFailureFrom,\n serverErrorStatusFrom,\n twoFactorRateLimitedMessage,\n twoFactorSendFailedMessage,\n twoFactorSetupCodeChangedMessage,\n twoFactorSetupSavedNewCodeMessage,\n twoFactorSetupSavedSignInMessage,\n twoFactorSignInOverMessage,\n twoFactorTryAgainMessage,\n twoFactorWrongCodeMessage,\n} from '@/utils/auth-error';\nimport { usePassflow } from './use-passflow';\n\n/** Send taps on the email link screen: send, begin and challenge share 3 requests per 5 minutes on the server. */\nexport const TWO_FACTOR_LINK_MAX_SENDS = 3;\n\nexport type TwoFactorEnrollmentScreen =\n | { kind: 'loading' }\n | { kind: 'verify'; notice?: string; digits?: number; deviceTrustAvailable?: boolean }\n | { kind: 'email_link'; sent: boolean; sends: number; busy: boolean; error?: string }\n | {\n kind: 'direct';\n step: 'start' | 'code' | 'codes';\n data: TwoFactorSetupResponse | null;\n codes: string[];\n busy: boolean;\n error?: string;\n /** Shown on the code step until the next confirm. */\n notice?: string;\n }\n | { kind: 'unavailable' }\n | { kind: 'ended'; message: string }\n | { kind: 'read_failed' }\n | { kind: 'finished' };\n\nexport type UseTwoFactorEnrollmentProps = {\n /** The sign-in is finished, by the enrolment's verify or by `complete`. */\n onFinished?: () => void;\n};\n\nexport type UseTwoFactorEnrollmentReturn = {\n screen: TwoFactorEnrollmentScreen;\n /** Reads the state. It has no guard, so Try again and the `not_allowed` re-read work. */\n read: () => Promise<void>;\n sendLink: () => Promise<void>;\n begin: () => Promise<void>;\n confirm: (code: string) => Promise<void>;\n /** \"I've saved these codes\": finishes the sign-in with the code that confirmed. */\n finish: () => Promise<void>;\n /** The verify or recovery form ended the sign-in. */\n end: (type: 'expired' | 'rate_limited') => void;\n /** The verify or recovery form finished the sign-in. */\n complete: () => void;\n};\n\nconst screenFor = ({\n enrollment,\n totp_digits: digits,\n device_trust_available: deviceTrustAvailable,\n}: TwoFactorEnrollmentResponse): TwoFactorEnrollmentScreen => {\n switch (enrollment) {\n case 'verify':\n return { kind: 'verify', digits, deviceTrustAvailable };\n case 'email_link':\n return { kind: 'email_link', sent: false, sends: 0, busy: false };\n case 'direct':\n return { kind: 'direct', step: 'start', data: null, codes: [], busy: false };\n case 'unavailable':\n return { kind: 'unavailable' };\n default:\n return { kind: 'read_failed' };\n }\n};\n\n/**\n * What the verify screen shows for a pending sign-in, as the server decides it. Nothing that spends budget runs on\n * mount: only the state is read, once, and the link send and begin wait for a tap.\n */\nexport const useTwoFactorEnrollment = ({ onFinished }: UseTwoFactorEnrollmentProps = {}): UseTwoFactorEnrollmentReturn => {\n const passflow = usePassflow();\n const isDiscovering = useContext(PassflowContext)?.state.isDiscoveringAppId ?? false;\n const [screen, setScreen] = useState<TwoFactorEnrollmentScreen>({ kind: 'loading' });\n\n const readOnMount = useRef(false);\n const notAllowedReread = useRef(false);\n const beganAgain = useRef(false);\n // The code that confirmed. Verify cannot run before the codes show: the OIDC interceptor follows `redirect_url`\n // on `/auth/2fa/*` immediately, and the codes would vanish.\n const heldCode = useRef<string | null>(null);\n // The state read's `device_trust_available`, for the code screen that follows an enrolment here.\n const deviceTrustAvailable = useRef<boolean | undefined>(undefined);\n\n const updateDirect = (patch: Partial<Extract<TwoFactorEnrollmentScreen, { kind: 'direct' }>>) =>\n setScreen((current) => (current.kind === 'direct' ? { ...current, ...patch } : current));\n\n const endSignIn = () =>\n setScreen({\n kind: 'ended',\n message: heldCode.current === null ? twoFactorSignInOverMessage : twoFactorSetupSavedSignInMessage,\n });\n\n const handleFailure = (error: unknown, stay: (message: string) => void) => {\n const failure = enrollmentFailureFrom(error);\n if (failure === 'over') {\n endSignIn();\n } else if (failure === 'rate_limited') {\n setScreen({ kind: 'ended', message: twoFactorRateLimitedMessage });\n } else if (failure === 'unavailable') {\n setScreen({ kind: 'unavailable' });\n } else if (failure === 'not_allowed' && !notAllowedReread.current) {\n notAllowedReread.current = true;\n void read();\n } else if (failure === 'send_failed') {\n stay(twoFactorSendFailedMessage);\n } else {\n stay(twoFactorTryAgainMessage);\n }\n };\n\n const read = async () => {\n setScreen({ kind: 'loading' });\n try {\n const response = await passflow.getTwoFactorEnrollment();\n deviceTrustAvailable.current = response.device_trust_available;\n setScreen(screenFor(response));\n } catch (error) {\n if (serverErrorStatusFrom(error) === 401) endSignIn();\n else handleFailure(error, () => setScreen({ kind: 'read_failed' }));\n }\n };\n\n useEffect(() => {\n if (isDiscovering || readOnMount.current) return;\n readOnMount.current = true;\n if (passflow.isTwoFactorVerificationRequired()) void read();\n else setScreen({ kind: 'verify' });\n }, [isDiscovering, passflow]);\n\n const sendLink = async () => {\n if (screen.kind !== 'email_link' || screen.busy || screen.sends >= TWO_FACTOR_LINK_MAX_SENDS) return;\n const { sent } = screen;\n const sends = screen.sends + 1;\n const stay = (error: string) => setScreen({ kind: 'email_link', sent, sends, busy: false, error });\n\n setScreen({ kind: 'email_link', sent, sends, busy: true });\n try {\n const { email_sent: emailSent } = await passflow.sendTwoFactorSetupLink();\n if (emailSent) setScreen({ kind: 'email_link', sent: true, sends, busy: false });\n else stay(twoFactorSendFailedMessage);\n } catch (error) {\n handleFailure(error, stay);\n }\n };\n\n const beginEnrollment = async (notice?: string) => {\n updateDirect({ busy: true, error: undefined });\n try {\n const data = await passflow.beginTwoFactorEnrollment();\n updateDirect({ step: 'code', data, busy: false, notice });\n } catch (error) {\n handleFailure(error, (message) => updateDirect({ busy: false, error: message }));\n }\n };\n\n const confirm = async (code: string) => {\n updateDirect({ busy: true, error: undefined, notice: undefined });\n let codes: string[];\n try {\n // The answer may carry no codes: an empty list, null or no field.\n codes = (await passflow.confirmTwoFactorEnrollment(code)).recovery_codes ?? [];\n heldCode.current = code;\n } catch (error) {\n const failure = enrollmentFailureFrom(error);\n if (failure === 'wrong_code') {\n updateDirect({ busy: false, error: twoFactorWrongCodeMessage });\n } else if (failure === 'setup_incomplete' && !beganAgain.current) {\n beganAgain.current = true;\n await beginEnrollment(twoFactorSetupCodeChangedMessage);\n } else {\n handleFailure(error, (message) => updateDirect({ busy: false, error: message }));\n }\n return;\n }\n // No codes to save: the sign-in finishes with the code that confirmed.\n if (codes.length > 0) updateDirect({ step: 'codes', codes, busy: false });\n else await verifyHeldCode(code, screen.kind === 'direct' ? screen.data?.totp_digits : undefined);\n };\n\n const complete = () => {\n setScreen({ kind: 'finished' });\n onFinished?.();\n };\n\n const finish = async () => {\n if (screen.kind !== 'direct' || heldCode.current === null) return;\n await verifyHeldCode(heldCode.current, screen.data?.totp_digits);\n };\n\n const verifyHeldCode = async (code: string, digits?: number) => {\n updateDirect({ busy: true, error: undefined });\n try {\n await passflow.verifyTwoFactor(code);\n complete();\n } catch (error) {\n // The held code goes stale after about 30-60 seconds on the codes: a common case, so it gets its own screen.\n if (enrollmentFailureFrom(error) === 'wrong_code') {\n setScreen({\n kind: 'verify',\n notice: twoFactorSetupSavedNewCodeMessage,\n digits,\n deviceTrustAvailable: deviceTrustAvailable.current,\n });\n } else {\n handleFailure(error, (message) => updateDirect({ busy: false, error: message }));\n }\n }\n };\n\n const end = (type: 'expired' | 'rate_limited') => {\n if (type === 'rate_limited') setScreen({ kind: 'ended', message: twoFactorRateLimitedMessage });\n else endSignIn();\n };\n\n return { screen, read, sendLink, begin: () => beginEnrollment(), confirm, finish, end, complete };\n};\n","import { SIGNED_IN_MESSAGE } from '@/components/form/signed-in';\nimport {\n getTwoFactorRecoveryCodesScreen,\n getTwoFactorSetupCodeScreen,\n getTwoFactorSetupStartScreen,\n} from '@/components/form/two-factor-setup/setup-screen';\nimport type { LoginScreenAction, LoginScreenProps } from '@/components/ui';\nimport { TWO_FACTOR_LINK_MAX_SENDS, type UseTwoFactorEnrollmentReturn } from '@/hooks/use-two-factor-enrollment';\nimport { twoFactorBackToSignInLabel, twoFactorSignInLabel } from '@/utils';\n\nconst TITLE = 'Two-Factor Authentication';\n\n/** The screen for the enrolment state; null on `verify`, which the verify and recovery forms draw. */\nexport const getTwoFactorEnrollmentScreenProps = (\n enrollment: UseTwoFactorEnrollmentReturn,\n onBackToSignIn: () => void,\n): LoginScreenProps | null => {\n const { screen } = enrollment;\n const backToSignIn: LoginScreenAction = { label: twoFactorBackToSignInLabel, onClick: onBackToSignIn };\n\n switch (screen.kind) {\n case 'verify':\n return null;\n\n case 'loading':\n return {\n chrome: { title: TITLE },\n state: { kind: 'status', tone: 'working', message: 'Checking your sign-in...', testId: 'two-factor-loading' },\n };\n\n case 'email_link':\n return {\n chrome: { title: 'Set Up Two-Factor Authentication' },\n state: {\n kind: 'status',\n tone: 'info',\n message: screen.sent\n ? 'Check your email for a link to set up two-factor authentication. After you set it up, sign in again.'\n : 'Your account needs two-factor authentication. We can email you a link to set it up.',\n error: screen.error,\n testId: 'two-factor-email-link',\n primaryAction:\n screen.busy || screen.sends < TWO_FACTOR_LINK_MAX_SENDS\n ? {\n label: screen.busy ? 'Sending...' : screen.sent ? 'Send again' : 'Email me a setup link',\n busy: screen.busy,\n onClick: () => void enrollment.sendLink(),\n }\n : undefined,\n secondaryAction: backToSignIn,\n },\n };\n\n case 'direct':\n if (screen.step === 'codes') {\n return getTwoFactorRecoveryCodesScreen({\n codes: screen.codes,\n busy: screen.busy,\n error: screen.error,\n onContinue: () => void enrollment.finish(),\n });\n }\n if (screen.step === 'code' && screen.data) {\n return getTwoFactorSetupCodeScreen({\n data: screen.data,\n notice: screen.notice,\n busy: screen.busy,\n error: screen.error,\n secondaryAction: backToSignIn,\n onSubmit: (code) => void enrollment.confirm(code),\n });\n }\n return getTwoFactorSetupStartScreen({\n busy: screen.busy,\n error: screen.error,\n secondaryAction: backToSignIn,\n onStart: () => void enrollment.begin(),\n });\n\n case 'unavailable':\n return {\n chrome: { title: TITLE },\n state: {\n kind: 'status',\n tone: 'disabled',\n message: 'Two-factor authentication cannot be set up for your account here. Contact your administrator.',\n testId: 'two-factor-unavailable',\n secondaryAction: backToSignIn,\n },\n };\n\n case 'ended':\n return {\n chrome: { title: TITLE },\n state: {\n kind: 'status',\n tone: 'error',\n message: screen.message,\n testId: 'two-factor-ended',\n primaryAction: { label: twoFactorSignInLabel, onClick: onBackToSignIn },\n },\n };\n\n case 'read_failed':\n return {\n chrome: { title: TITLE },\n state: {\n kind: 'status',\n tone: 'error',\n message: 'We could not continue your sign-in. Try again.',\n recoverable: true,\n testId: 'two-factor-read-failed',\n onRetry: () => void enrollment.read(),\n secondaryAction: backToSignIn,\n },\n };\n\n case 'finished':\n return {\n chrome: { title: TITLE },\n state: { kind: 'status', tone: 'success', message: SIGNED_IN_MESSAGE, testId: 'two-factor-finished' },\n };\n }\n};\n","import type { FC } from 'react';\nimport { useCallback, useEffect, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { TwoFactorRecoveryForm, TwoFactorVerifyForm } from '@/components/form/two-factor-verify';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport { LoginScreen } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useNavigation, usePassflow, useSignInEnding } from '@/hooks';\nimport { useTwoFactorEnrollment } from '@/hooks/use-two-factor-enrollment';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { signInSearch } from '@/utils';\nimport { getTwoFactorEnrollmentScreenProps } from './screen';\n\nimport '@/styles/index.css';\n\nexport type TwoFactorVerifyFlowProps = {\n successAuthRedirect?: SuccessAuthRedirect;\n signInPath?: string;\n};\n\nconst TwoFactorVerifyFlowScreen: FC<TwoFactorVerifyFlowProps> = ({ successAuthRedirect, signInPath = routes.signin.path }) => {\n const [mode, setMode] = useState<'verify' | 'recovery'>('verify');\n const { navigate } = useNavigation();\n const passflow = usePassflow();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n // Read once: a screen must not blank when core's 5 minute pending state expires under it.\n const [pendingOnLanding] = useState(() => passflow.isTwoFactorVerificationRequired());\n\n const goToSignIn = useCallback(\n () => navigate({ to: signInPath, search: signInSearch(searchSource.read()) }),\n [navigate, signInPath, searchSource],\n );\n\n const continueSignIn = async () => {\n // `/auth/2fa/*` is an interceptor-matched endpoint, so an OIDC login that\n // required a second factor has already been dispatched back to the RP by\n // the time this runs. Navigating again would cancel that in flight — see\n // `hasFollowedOIDCRedirect`.\n if (hasFollowedOIDCRedirect()) return;\n\n try {\n // With nowhere to go the user stays: the screen is already the finished one, which says they are signed in.\n await finishSignIn(\n successAuthRedirect,\n successAuthRedirect ? undefined : (await passflow.getAppSettings()).defaults?.redirect,\n );\n } catch {\n // No target to go to: as above.\n }\n };\n\n const enrollment = useTwoFactorEnrollment({ onFinished: () => void continueSignIn() });\n\n // This cannot loop: the sign-in screen sends the user back here only with a pending sign-in.\n useEffect(() => {\n if (!pendingOnLanding) goToSignIn();\n }, [pendingOnLanding, goToSignIn]);\n\n if (!pendingOnLanding) return null;\n\n // The finished screen already says the user is signed in; only a target that could not be used needs its own.\n if (ending === 'checking' || ending === 'refused' || ending === 'unavailable' || ending === 'service-unavailable')\n return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const screenProps = getTwoFactorEnrollmentScreenProps(enrollment, goToSignIn);\n if (screenProps) return <LoginScreen {...screenProps} />;\n\n const { screen } = enrollment;\n const deviceTrustAvailable = screen.kind === 'verify' ? screen.deviceTrustAvailable : undefined;\n\n return mode === 'verify' ? (\n <TwoFactorVerifyForm\n subtitle={screen.kind === 'verify' ? screen.notice : undefined}\n numInputs={screen.kind === 'verify' ? screen.digits : undefined}\n deviceTrustAvailable={deviceTrustAvailable}\n onSuccess={enrollment.complete}\n onUseRecovery={() => setMode('recovery')}\n onEnded={enrollment.end}\n onBackToSignIn={goToSignIn}\n />\n ) : (\n <TwoFactorRecoveryForm\n deviceTrustAvailable={deviceTrustAvailable}\n onSuccess={enrollment.complete}\n onBack={() => setMode('verify')}\n onEnded={enrollment.end}\n onBackToSignIn={goToSignIn}\n />\n );\n};\n\nexport const TwoFactorVerifyFlow = withHydration(TwoFactorVerifyFlowScreen);\n","import type { PassflowSendPasswordResetEmailPayload } from '@passflow/core';\nimport { phone } from 'phone';\n/* eslint-disable max-len */\n/* eslint-disable react/jsx-props-no-spreading */\n/* eslint-disable complexity */\n/* eslint-disable jsx-a11y/label-has-associated-control */\nimport { type FC, useMemo } from 'react';\nimport { Controller, useForm } from 'react-hook-form';\nimport * as Yup from 'yup';\nimport { Button, FieldPhone, FieldText, Icon, Link, LoginAlert } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useForgotPassword, useNavigation } from '@/hooks';\nimport {\n cn,\n emailRegex,\n getAuthMethods,\n getIdentityLabel,\n passwordChangeRequiredMessage,\n passwordChangeRequiredReason,\n useUrlParams,\n} from '@/utils';\nimport { Wrapper } from '../wrapper';\n\nimport '@/styles/index.css';\nimport queryString from 'query-string';\n\nconst searchParamsForgotPasswordSchema = Yup.object().shape({\n defaultMethod: Yup.string().oneOf(['email_or_username', 'phone']).required(),\n});\n\ntype TForgotPassword = {\n successResetRedirect?: string;\n signInPath?: string;\n forgotPasswordSuccessPath?: string;\n};\n\nconst ForgotPasswordScreen: FC<TForgotPassword> = ({\n successResetRedirect,\n signInPath = routes.signin.path,\n forgotPasswordSuccessPath = routes.forgot_password_success.path,\n}) => {\n const { get } = useUrlParams({\n default_method: '',\n email: '',\n username: '',\n phone: '',\n });\n\n const {\n getValues,\n control,\n formState: { errors, isValid },\n } = useForm({\n defaultValues: {\n email_or_username: get('email') || get('username') || '',\n phone: get('phone') ?? '',\n },\n });\n\n const { appSettings, currentStyles, isError: isErrorApp, error: errorApp, loginAppTheme } = useAppSettings();\n\n if (isErrorApp) throw new Error(errorApp);\n\n const authMethods = useMemo(() => getAuthMethods(appSettings?.auth_strategies), [appSettings]);\n const { navigate } = useNavigation();\n const searchSource = useSearchSource();\n\n const params = {\n defaultMethod: get('default_method'),\n };\n const showPasswordChangeNotice = get('reason') === passwordChangeRequiredReason;\n\n try {\n searchParamsForgotPasswordSchema.validateSync(params, { abortEarly: false });\n } catch (err) {\n throw new Error('Invalid default method param');\n }\n\n const { defaultMethod } = params;\n\n const { fetch, error, isError, isLoading } = useForgotPassword();\n\n const onSubmitHanlder = async () => {\n const values = getValues();\n // Only the field on screen is sent: the URL may prefill the other one, which the user never sees.\n const usesPhone = defaultMethod === 'phone';\n const isEmail = !usesPhone && values.email_or_username.match(emailRegex);\n const isUsername = !usesPhone && !isEmail && values.email_or_username.length > 0;\n const validatedPhone = phone(values.phone);\n const isPhone = usesPhone && validatedPhone.isValid;\n\n const payload = {\n ...(isEmail && { email: values.email_or_username }),\n ...(isUsername && { username: values.email_or_username }),\n ...(isPhone && { phone: validatedPhone.phoneNumber }),\n ...(successResetRedirect && { redirect_url: successResetRedirect }),\n } as PassflowSendPasswordResetEmailPayload;\n\n const status = await fetch(payload);\n\n if (status) {\n const currentSearchParams = new URLSearchParams(searchSource.read());\n for (const name of ['redirect_url', 'email', 'phone', 'username']) currentSearchParams.delete(name);\n const newParams = queryString.stringify({\n ...Object.fromEntries(currentSearchParams.entries()),\n ...payload,\n });\n navigate({ to: forgotPasswordSuccessPath, search: newParams });\n }\n };\n\n // if (!state)\n // return (\n // <Navigate\n // to={{\n // pathname: signInPath ?? routes.signin.path,\n // search: window.location.search,\n // }}\n // replace\n // />\n // );\n\n const currentSubtitle =\n defaultMethod === 'email_or_username'\n ? 'Enter the email address you used when you joined and we’ll send you instructions to reset your password.'\n : 'Enter the mobile phone number you used when you joined and we’ll send you the reset link.';\n\n const currentSubscriptions =\n defaultMethod === 'email_or_username'\n ? 'For security reasons, we do NOT store your password. So rest assured that we will never send your password via email.'\n : 'For security reasons, we do NOT store your password. So rest assured that we will never send your password via SMS.';\n\n return (\n <Wrapper\n title='Forgot password?'\n subtitle={currentSubtitle}\n className='passflow-forgot-password-wrapper'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <span className='passflow-form-subscriptions'>{currentSubscriptions}</span>\n <form onSubmit={(e) => e.preventDefault()} className='passflow-form'>\n {showPasswordChangeNotice && <LoginAlert tone='info' message={passwordChangeRequiredMessage} />}\n <div className='passflow-form-container'>\n <div className='passflow-form-field'>\n {defaultMethod === 'email_or_username' && (\n <>\n <div className='passflow-form-field__header'>\n <label htmlFor='identity' className={cn('passflow-field-label', { 'passflow-field-label--error': isError })}>\n {getIdentityLabel(authMethods, 'label')}\n </label>\n </div>\n <Controller\n name='email_or_username'\n control={control}\n rules={{ required: 'Email is required' }}\n render={({ field }) => (\n <FieldText\n {...field}\n isError={isError || Object.hasOwn(errors, 'email_or_username')}\n id='email_or_username'\n type='text'\n name='email_or_username'\n />\n )}\n />\n </>\n )}\n {defaultMethod === 'phone' && (\n <>\n <div className='passflow-form-field__header'>\n <label htmlFor='phone' className={cn('passflow-field-label', { 'passflow-field-label--error': isError })}>\n Phone\n </label>\n </div>\n <Controller\n name='phone'\n control={control}\n rules={{\n required: 'Phone is required',\n validate: (value) => {\n const validatePhone = phone(value);\n if (validatePhone.isValid) return true;\n return 'Invalid phone number';\n },\n }}\n render={({ field }) => (\n <FieldPhone\n {...field}\n onChange={(e) => field.onChange(e)}\n id='phone'\n name='phone'\n isError={isError || Object.hasOwn(errors, 'phone')}\n ref={null}\n />\n )}\n />\n </>\n )}\n {isError && (\n <div className='passflow-form-error'>\n <Icon size='small' id='warning' type='general' className='icon-warning' />\n <span className='passflow-form-error-text'>{error}</span>\n </div>\n )}\n </div>\n </div>\n <div className='passflow-send-reset-wrapper'>\n <Button\n size='big'\n variant='primary'\n type='button'\n disabled={!isValid || isLoading}\n className='passflow-button-send-reset-password'\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onClick={onSubmitHanlder}\n >\n Send reset instructions\n </Button>\n <p className='passflow-remember-password'>\n Remember your password?{' '}\n <Link to={signInPath ?? routes.signin.path} className='passflow-link'>\n Sign In\n </Link>{' '}\n </p>\n </div>\n </form>\n </Wrapper>\n );\n};\n\nexport const ForgotPassword = withHydration(ForgotPasswordScreen);\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable complexity */\nimport * as Yup from 'yup';\nimport { Button } from '@/components/ui';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useForgotPassword } from '@/hooks';\nimport { Wrapper } from '../wrapper';\nimport '@/styles/index.css';\nimport type { PassflowSendPasswordResetEmailPayload } from '@passflow/core';\nimport { useUrlParams, verificationLinkErrorMessage } from '@/utils';\n\nconst searchParamsForgotPasswordSuccessSchema = Yup.object().shape({\n identity: Yup.string().oneOf(['email', 'phone', 'username']).required(),\n identityValue: Yup.string().required(),\n redirectUrl: Yup.string().nullable(),\n});\n\nconst ForgotPasswordSuccessScreen = () => {\n const { currentStyles, loginAppTheme } = useAppSettings();\n const { fetch: refetch } = useForgotPassword();\n const { get } = useUrlParams();\n\n const params = {\n identity: get('email') ? 'email' : get('phone') ? 'phone' : get('username') ? 'username' : null,\n identityValue: get('email') || get('phone') || get('username') || null,\n redirectUrl: get('redirect_url'),\n };\n\n try {\n searchParamsForgotPasswordSuccessSchema.validateSync(params, { abortEarly: false });\n } catch (error) {\n console.error('[passflow] invalid password-reset confirmation link', error);\n throw new Error(verificationLinkErrorMessage);\n }\n\n const onClickResendHandler = async () => {\n const resendPayload = {\n ...(params.identity === 'email' ? { email: params.identityValue } : undefined),\n ...(params.identity === 'phone' ? { phone: params.identityValue } : undefined),\n ...(params.identity === 'username' ? { username: params.identityValue } : undefined),\n ...(params.redirectUrl ? { redirect_url: params.redirectUrl } : {}),\n };\n\n await refetch(resendPayload as PassflowSendPasswordResetEmailPayload);\n };\n\n return (\n <Wrapper\n title={`Check your ${params.identity === 'phone' ? 'phone' : 'email'}`}\n className='passflow-forgot-password-success-wrapper'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <div className='passflow-forgot-password-success-container'>\n <p className='passflow-forgot-password-success-text'>\n We sent a link to{' '}\n {params.identity === 'phone'\n ? 'phone number'\n : params.identity === 'email'\n ? 'email address'\n : 'the email address for'}{' '}\n <strong className='passflow-forgot-password-success-text--strong'>{params.identityValue}</strong>. Click the link to\n reset your password.\n </p>\n <Button\n size='big'\n variant='secondary'\n type='button'\n className='passflow-button-resend-reset-password'\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onClick={onClickResendHandler}\n >\n Resend {params.identity === 'phone' ? 'SMS' : 'email'}\n </Button>\n </div>\n </Wrapper>\n );\n};\n\nexport const ForgotPasswordSuccess = withHydration(ForgotPasswordSuccessScreen);\n","import type { FC } from 'react';\nimport { LoginScreen } from '@/components/ui';\nimport { useAppSettings, useNavigation } from '@/hooks';\nimport { isSameOriginPath } from '@/utils';\n\nexport type TError = {\n goBackRedirectTo: string;\n error?: string;\n};\n\nconst defaultErrorMessage = 'Something went wrong';\n\nexport const ErrorComponent: FC<TError> = ({ error = defaultErrorMessage, goBackRedirectTo }) => {\n const { navigate } = useNavigation();\n const { currentStyles, loginAppTheme } = useAppSettings();\n\n // The target can come from the request, so this only ever follows a path on this origin.\n const handleGoBack = () => navigate({ to: isSameOriginPath(goBackRedirectTo) ? goBackRedirectTo : '/' });\n\n return (\n <LoginScreen\n chrome={{\n title: '',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={{\n kind: 'general-error',\n message: error,\n onAction: handleGoBack,\n }}\n />\n );\n};\n","/* eslint-disable react/prop-types */\n/* eslint-disable react/jsx-props-no-spreading */\nimport { type ComponentType, useContext } from 'react';\nimport { ErrorBoundary, type FallbackProps } from 'react-error-boundary';\nimport type { TError } from '@/components/error';\nimport type { PassflowProps } from '@/components/flow/passflow';\nimport type { TInvitationJoinFlow, TSignIn, TSignUp } from '@/components/form';\nimport { PassflowContext } from '@/context';\nimport { useHydrated } from '@/hooks/use-hydrated';\n\ntype UnionType = TSignIn | TSignUp | TInvitationJoinFlow | PassflowProps;\n// react-error-boundary 6 types the caught value as unknown: anything can be thrown.\nconst toErrorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));\n\nconst excludeRoutes = ['verify-challenge-otp', 'password/reset', 'two-factor-verify', 'two-factor-recovery'];\n\nexport const withError =\n <P extends UnionType>(Component: ComponentType<P>, ErrorComponent: ComponentType<TError>) =>\n (props: P) => {\n const context = useContext(PassflowContext);\n const hydrated = useHydrated();\n const { successAuthRedirect } = props;\n\n // The URL exists only in the browser: render nothing on the server and in the hydration render.\n if (!hydrated) return null;\n\n const { pathname } = window.location;\n\n // Allow excluded routes to render without checking appId\n if (excludeRoutes.some((route) => pathname.includes(route))) {\n return (\n <ErrorBoundary\n // eslint-disable-next-line react/no-unstable-nested-components\n FallbackComponent={({ error }: FallbackProps) => (\n <ErrorComponent goBackRedirectTo={successAuthRedirect ?? '/'} error={toErrorMessage(error)} />\n )}\n >\n <Component {...props} />\n </ErrorBoundary>\n );\n }\n\n // If we're still discovering the appId, don't show error yet\n if (context?.state.isDiscoveringAppId) {\n return null; // Or render a loading spinner if desired\n }\n\n // After discovery is complete, check if we have the required config\n // Only appId is required - URL defaults to current origin if not provided\n if (!context?.state.appId) {\n const errorMessage = 'Missing appId';\n return <ErrorComponent goBackRedirectTo={successAuthRedirect ?? '/'} error={errorMessage} />;\n }\n\n return (\n <ErrorBoundary\n // eslint-disable-next-line react/no-unstable-nested-components\n FallbackComponent={({ error }: FallbackProps) => (\n <ErrorComponent goBackRedirectTo={successAuthRedirect ?? '/'} error={toErrorMessage(error)} />\n )}\n >\n <Component {...props} />\n </ErrorBoundary>\n );\n };\n\nexport default withError;\n","import { type InvitationToken, parseToken } from '@passflow/core';\nimport { type FC, useEffect } from 'react';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { LoginScreen } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withError } from '@/hocs';\nimport { useAppSettings, useJoinInvite, useNavigation, usePassflow, useSignInEnding } from '@/hooks';\nimport { useHydrated } from '@/hooks/use-hydrated';\nimport { invitationLinkErrorMessage, undefinedOnCatch, useUrlParams } from '@/utils';\n\nexport type TInvitationJoinFlow = {\n successAuthRedirect?: string;\n signInPath?: string;\n signUpPath?: string;\n};\n\nconst InvitationJoinFlow: FC<TInvitationJoinFlow> = ({\n signInPath = routes.signin.path,\n signUpPath = routes.signup.path,\n successAuthRedirect,\n}) => {\n const { appSettings, currentStyles, loginAppTheme } = useAppSettings();\n const { navigate } = useNavigation();\n const searchSource = useSearchSource();\n const { get } = useUrlParams();\n const passflow = usePassflow();\n const hydrated = useHydrated();\n const { fetch: joinInvite, isLoading, error, isError } = useJoinInvite();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const invitationToken = get('invite_token');\n const invitationTokenData = invitationToken ? undefinedOnCatch(parseToken)(invitationToken) : undefined;\n const parsedTokenCache = passflow.getParsedTokens();\n const hasAuthenticatedSession = Boolean(parsedTokenCache?.access_token);\n\n useEffect(() => {\n if (invitationTokenData && !hasAuthenticatedSession) {\n navigate({ to: signInPath, search: searchSource.read() });\n }\n }, [hasAuthenticatedSession, invitationTokenData, navigate, searchSource, signInPath]);\n\n if (!invitationTokenData) {\n console.error('[passflow] invitation token could not be parsed');\n throw new Error(invitationLinkErrorMessage);\n }\n // Hydration renders what the signed-out server rendered.\n if (!hasAuthenticatedSession || !hydrated) return null;\n\n const {\n inviter_name: inviterName,\n tenant_name: tenantName,\n redirect_url: redirectUrl,\n } = invitationTokenData as InvitationToken;\n\n const acceptInvitation = async () => {\n if (!invitationToken) return;\n\n const joined = await joinInvite(invitationToken);\n if (!joined) return;\n\n await finishSignIn(redirectUrl ?? successAuthRedirect, appSettings?.defaults?.redirect);\n };\n\n const navigateToSignIn = () => navigate({ to: signInPath, search: searchSource.read() });\n const navigateToSignUp = () => navigate({ to: signUpPath, search: searchSource.read() });\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n return (\n <LoginScreen\n chrome={{\n title: `You've been invited to join ${tenantName}.`,\n subtitle: 'Review the invitation before continuing.',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={{\n kind: 'invitation',\n identity: parsedTokenCache?.id_token?.email,\n inviterName: inviterName || undefined,\n busy: isLoading,\n error: isError ? error : null,\n testId: 'invitation-join',\n acceptTestId: 'invitation-accept',\n onAccept: () => void acceptInvitation(),\n onSwitchAccount: navigateToSignIn,\n onCreateAccount: navigateToSignUp,\n }}\n />\n );\n};\n\nexport const InvitationJoin = withError(InvitationJoinFlow, ErrorComponent);\n","import { parseToken, type Token } from '@passflow/core';\nimport type { FC } from 'react';\nimport * as Yup from 'yup';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport { LoginScreen, type LoginScreenChrome, type LoginScreenState } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useNavigation, usePassflow, useResetPassword, useSignInEnding } from '@/hooks';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { routeToSecondFactor, undefinedOnCatch, useUrlParams } from '@/utils';\nimport '@/styles/index.css';\n\nconst searchParamsResetPasswordSchema = Yup.object().shape({\n token: Yup.string().required(),\n});\n\ntype TResetPassword = {\n successAuthRedirect?: SuccessAuthRedirect;\n twoFactorVerifyPath?: string;\n /** Where `Back to sign in` goes once the password is saved. */\n signInPath?: string;\n};\n\n/**\n * The reset link's claims. A registration continuation link (an account started by email whose code budget ran out)\n * carries `registration_continuation` and no `redirect_url`.\n */\ntype ResetToken = Token & {\n redirect_url?: string;\n registration_continuation?: string;\n};\n\nconst ResetPasswordScreen: FC<TResetPassword> = ({\n successAuthRedirect,\n twoFactorVerifyPath = routes.two_factor_verify.path,\n signInPath = routes.signin.path,\n}) => {\n const passflow = usePassflow();\n const { fetch, error, isError, isLoading, isPasswordSaved, emailCode } = useResetPassword();\n const { navigate } = useNavigation();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n const { get } = useUrlParams();\n const { appSettings, passwordPolicy, currentStyles, isError: isErrorApp, error: errorApp, loginAppTheme } = useAppSettings();\n\n if (isErrorApp) throw new Error(errorApp);\n\n const params = {\n token: get('token'),\n };\n\n try {\n searchParamsResetPasswordSchema.validateSync(params, { abortEarly: false });\n } catch {\n throw new Error('Invalid reset token.');\n }\n\n const { token: resetToken } = params;\n const resetTokenData = resetToken ? (undefinedOnCatch(parseToken)(resetToken) as ResetToken | undefined) : undefined;\n const isContinuation = Boolean(resetTokenData?.registration_continuation);\n\n // A user with 2FA is signed in only once the second factor passes; an OIDC parent's redirect wins over ours.\n const completeSignIn = async (answerRedirectUrl?: string) => {\n if (routeToSecondFactor(passflow, navigate, twoFactorVerifyPath, searchSource.read())) return;\n if (hasFollowedOIDCRedirect()) return;\n await finishSignIn(\n answerRedirectUrl ?? resetTokenData?.redirect_url ?? successAuthRedirect,\n appSettings?.defaults?.redirect,\n );\n };\n\n const savePassword = async (password: string) => {\n // The token goes along explicitly: core would otherwise read it from the address bar, which a hash or memory\n // router does not keep.\n if (await fetch(password, resetToken ?? undefined)) await completeSignIn();\n };\n\n const verifyEmailCode = async (code: string) => {\n const answer = await emailCode.verify(code);\n if (answer) await completeSignIn(answer.redirect_url);\n };\n\n const backToSignIn = () => {\n emailCode.cancel();\n navigate({ to: signInPath });\n };\n\n const chrome: LoginScreenChrome = {\n title: isContinuation ? 'Create your password' : 'Reset password',\n subtitle: isContinuation ? 'Finish creating your account' : 'Let’s get you back in.',\n variant: 'reset-password',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n const { step } = emailCode;\n\n const state: LoginScreenState =\n step.kind === 'code'\n ? {\n // No resend: the reset link is spent once the password is saved.\n kind: 'email-code',\n message: step.message,\n error: emailCode.error,\n busy: emailCode.isVerifying,\n secondaryAction: { label: 'Back to sign in', onClick: backToSignIn },\n onSubmit: (code) => void verifyEmailCode(code),\n }\n : step.kind === 'link'\n ? {\n kind: 'status',\n tone: 'info',\n message: step.message,\n primaryAction: { label: 'Back to sign in', onClick: backToSignIn },\n }\n : isPasswordSaved\n ? {\n kind: 'status',\n tone: 'info',\n message: error,\n primaryAction: { label: 'Back to sign in', onClick: backToSignIn },\n }\n : {\n kind: 'new-password',\n passwordPolicy,\n hint: isContinuation ? 'Choose a password to finish creating your account.' : 'Enter your new password below.',\n error: isError ? error : null,\n busy: isLoading,\n submitLabel: isContinuation ? 'Create account' : 'Save new password',\n onSubmit: (password) => void savePassword(password),\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const heading: Pick<LoginScreenChrome, 'title' | 'subtitle'> =\n step.kind === 'code'\n ? { title: 'Verify your email', subtitle: 'Enter the code to finish signing in' }\n : step.kind === 'link'\n ? { title: 'Check your email', subtitle: undefined }\n : isPasswordSaved\n ? { title: 'Password saved', subtitle: undefined }\n : { title: chrome.title, subtitle: chrome.subtitle };\n\n return <LoginScreen chrome={{ ...chrome, ...heading }} state={state} />;\n};\n\nexport const ResetPassword = withHydration(ResetPasswordScreen);\n","import type {\n PassflowPasskeyAuthenticateStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignInPayload,\n Providers,\n} from '@passflow/core';\nimport { phone } from 'phone';\nimport queryString from 'query-string';\nimport type { FC } from 'react';\nimport { useMemo, useRef } from 'react';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { hasFollowedOIDCRedirect, readParentChallengeIdFromURL } from '@/components/provider/passflow-provider';\nimport {\n type LoginCredentialsValues,\n type LoginMethodConfig,\n LoginScreen,\n type LoginScreenChrome,\n type LoginScreenState,\n} from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withError, withHydration } from '@/hocs';\nimport { useAppSettings, useNavigation, usePassflow, useProvider, useSignIn, useSignInEnding } from '@/hooks';\nimport type { FederatedLanding, SuccessAuthRedirect } from '@/types';\nimport {\n type AuthMethods,\n authRedirectErrorFrom,\n emailRegex,\n getAuthMethods,\n getIdentityLabel,\n getInvitationAuthChrome,\n getPasswordlessData,\n getUrlErrors,\n passwordChangeRequiredReason,\n routeToSecondFactor,\n urlWithoutParentChallenge,\n useUrlParams,\n} from '@/utils';\n\nconst getLoginMethodConfig = (authMethods: AuthMethods): LoginMethodConfig => {\n const identities: LoginMethodConfig['identities'] = [];\n\n if (authMethods.hasSignInEmailMethods || authMethods.hasSignInUsernameMethods) {\n const label = getIdentityLabel(authMethods, 'label') ?? 'Email or username';\n identities.push({\n id: 'email_or_username',\n label,\n selectLabel: getIdentityLabel(authMethods, 'button') ?? 'Use email',\n requiredMessage: `${label} is required`,\n format: authMethods.hasSignInEmailMethods && !authMethods.hasSignInUsernameMethods ? 'email' : undefined,\n password: authMethods.internal.email.password || authMethods.internal.username.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'email_or_username')?.label,\n });\n }\n\n if (authMethods.hasSignInPhoneMethods) {\n identities.push({\n id: 'phone',\n label: 'Phone number',\n selectLabel: 'Use phone',\n requiredMessage: 'Phone number is required',\n password: authMethods.internal.phone.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'phone')?.label,\n });\n }\n\n return {\n identities,\n passkey: authMethods.passkey,\n providers: authMethods.fim.providers,\n };\n};\n\nexport type TSignIn = {\n successAuthRedirect?: SuccessAuthRedirect;\n relyingPartyId?: string;\n federatedDisplayMode?: 'modal' | 'redirect';\n federatedLanding?: FederatedLanding;\n signUpPath?: string;\n verifyOTPPath?: string;\n verifyMagicLinkPath?: string;\n forgotPasswordPath?: string;\n twoFactorVerifyPath?: string;\n};\n\nconst SignInFormScreen: FC<TSignIn> = ({\n successAuthRedirect,\n relyingPartyId = window.location.hostname,\n federatedLanding,\n signUpPath = routes.signup.path,\n verifyOTPPath = routes.verify_otp.path,\n verifyMagicLinkPath = routes.verify_magic_link.path,\n forgotPasswordPath = routes.forgot_password.path,\n twoFactorVerifyPath = routes.two_factor_verify.path,\n}) => {\n const passflow = usePassflow();\n const { navigate } = useNavigation();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n const {\n appSettings,\n scopes,\n createTenantForNewUser,\n passwordPolicy,\n currentStyles,\n isError: isErrorApp,\n error: errorApp,\n loginAppTheme,\n } = useAppSettings();\n const { federatedWithRedirect } = useProvider(successAuthRedirect, createTenantForNewUser, federatedLanding);\n\n if (isErrorApp) throw new Error(errorApp);\n\n const authMethods = useMemo(() => getAuthMethods(appSettings?.auth_strategies), [appSettings]);\n const loginMethods = useMemo(() => getLoginMethodConfig(authMethods), [authMethods]);\n const { error: errorUrl, message: messageUrl } = getUrlErrors();\n\n if (errorUrl) {\n console.error('[passflow] sign-in redirect returned an error', { error: errorUrl, message: messageUrl });\n throw new Error(authRedirectErrorFrom(errorUrl, messageUrl));\n }\n\n const { get } = useUrlParams({ invite_token: '' });\n const inviteToken = get('invite_token');\n const invitationChrome = getInvitationAuthChrome(inviteToken, 'sign-in');\n // The identifier of the password sign-in in flight, carried to forgot-password if the password must change.\n const passwordIdentityRef = useRef<Pick<PassflowSignInPayload, 'email' | 'username' | 'phone'>>({});\n const goToPasswordReset = () => {\n const identity = passwordIdentityRef.current;\n const params = new URLSearchParams(searchSource.read());\n for (const name of ['email', 'username', 'phone']) params.delete(name);\n navigate({\n to: forgotPasswordPath ?? routes.forgot_password.path,\n search: queryString.stringify({\n ...Object.fromEntries(params.entries()),\n ...identity,\n default_method: identity.phone ? 'phone' : 'email_or_username',\n reason: passwordChangeRequiredReason,\n }),\n });\n };\n const { fetch, isError, error, reset, cancelPasskey, isLoading, pendingOperation, emailCode } = useSignIn({\n onPasswordChangeRequired: goToPasswordReset,\n });\n\n const oidcLayerOwnsRedirect = (): boolean => {\n if (hasFollowedOIDCRedirect()) return true;\n if (readParentChallengeIdFromURL()) {\n console.error(\n '[passflow] login took the legacy token path while parent_challenge_id is present on the URL — the OIDC interceptor did not engage and the RP redirect will not happen',\n );\n }\n return false;\n };\n\n const completeAuthentication = async () => {\n if (routeToSecondFactor(passflow, navigate, twoFactorVerifyPath ?? routes.two_factor_verify.path, searchSource.read()))\n return;\n if (oidcLayerOwnsRedirect()) return;\n await finishSignIn(successAuthRedirect, appSettings?.defaults?.redirect);\n };\n\n const submitPassword = async (userPayload: PassflowSignInPayload) => {\n const payload = {\n ...userPayload,\n ...(inviteToken && { invite_token: inviteToken }),\n } as PassflowSignInPayload;\n\n const { email, username, phone: phoneNumber } = userPayload;\n passwordIdentityRef.current = {\n ...(email && { email }),\n ...(username && { username }),\n ...(phoneNumber && { phone: phoneNumber }),\n };\n const status = await fetch(payload, 'password');\n if (status) await completeAuthentication();\n };\n\n const submitPasskey = async (passkeyPayload: PassflowPasskeyAuthenticateStartPayload) => {\n const payload = {\n ...passkeyPayload,\n ...(inviteToken && { invite_token: inviteToken }),\n } as PassflowPasskeyAuthenticateStartPayload;\n\n passwordIdentityRef.current = {};\n const response = await fetch(payload, 'passkey');\n if (response) await completeAuthentication();\n };\n\n const submitPasswordless = async (\n userPayload: Partial<PassflowPasswordlessSignInPayload>,\n method: LoginCredentialsValues['method'],\n ) => {\n const challengeType = getPasswordlessData(authMethods, method)?.challengeType;\n const payload = {\n ...userPayload,\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n ...(successAuthRedirect && { redirect_url: successAuthRedirect }),\n ...(inviteToken && { invite_token: inviteToken }),\n } as PassflowPasswordlessSignInPayload;\n\n passwordIdentityRef.current = {};\n const response = await fetch(payload, 'passwordless');\n if (!response) return;\n\n // The match code is shown only by the tab holding it: it never goes in a URL.\n const { match_code: _matchCode, ...startAnswer } = response as PassflowPasswordlessResponse;\n const params = new URLSearchParams(searchSource.read());\n // The attempt's own address is the one sent at start, not one left on this page's URL.\n params.delete('redirect_url');\n const newParams = queryString.stringify({\n ...Object.fromEntries(params.entries()),\n ...payload,\n ...startAnswer,\n type: 'passwordless',\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n });\n\n if (challengeType === 'otp') navigate({ to: verifyOTPPath ?? routes.verify_otp.path, search: newParams });\n if (challengeType === 'magic_link')\n navigate({ to: verifyMagicLinkPath ?? routes.verify_magic_link.path, search: newParams });\n };\n\n const handlePassword = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const isUsername = values.method === 'email_or_username' && !isEmail && values.emailOrUsername.length > 0;\n const validatedPhone = phone(values.phone);\n const payload = {\n ...(isEmail && { email: values.emailOrUsername }),\n ...(isUsername && { username: values.emailOrUsername }),\n ...(validatedPhone.isValid && { phone: validatedPhone.phoneNumber }),\n scopes,\n password: values.password,\n };\n\n await submitPassword(payload as PassflowSignInPayload);\n };\n\n const handlePasswordless = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const validatedPhone = phone(values.phone);\n const payload = {\n ...(isEmail && { email: values.emailOrUsername }),\n ...(validatedPhone.isValid && { phone: validatedPhone.phoneNumber }),\n scopes,\n };\n\n await submitPasswordless(payload as Partial<PassflowPasswordlessSignInPayload>, values.method);\n };\n\n const handlePasskey = async () => {\n await submitPasskey({ relying_party_id: relyingPartyId, scopes });\n };\n\n const handleProvider = (provider: Providers) => federatedWithRedirect(provider, inviteToken ?? undefined);\n\n // The emailed code answers like a sign-in: the same 2FA, OIDC and redirect path follows.\n const verifyEmailCode = async (code: string) => {\n if (await emailCode.verify(code)) await completeAuthentication();\n };\n\n const resendEmailCode = async () => {\n if (await emailCode.resend()) await completeAuthentication();\n };\n\n // The application name set in the admin panel's Login Appearance.\n const appName = loginAppTheme?.application_name?.trim();\n const chrome: LoginScreenChrome = {\n title: invitationChrome?.title ?? 'Sign In to your account',\n subtitle: invitationChrome?.subtitle ?? (appName ? `To ${appName}` : undefined),\n variant: 'sign-in',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const { step } = emailCode;\n\n if (step.kind !== 'none') {\n // The server does not answer a sign-in with a link today; the state is mapped anyway.\n const stepState: LoginScreenState =\n step.kind === 'code'\n ? {\n kind: 'email-code',\n message: step.message,\n error: emailCode.error,\n busy: emailCode.isVerifying,\n resend: {\n restartKey: step.challengeId,\n busy: emailCode.isResending,\n onResend: () => void resendEmailCode(),\n },\n secondaryAction: { label: 'Use a different account', onClick: emailCode.cancel },\n onSubmit: (code) => void verifyEmailCode(code),\n }\n : {\n kind: 'status',\n tone: 'info',\n message: step.message,\n primaryAction: { label: 'Back to sign in', onClick: emailCode.cancel },\n };\n\n return (\n <LoginScreen\n chrome={{\n ...chrome,\n title: step.kind === 'code' ? 'Verify your email' : 'Check your email',\n subtitle: step.kind === 'code' ? 'Enter the code to finish signing in' : 'Follow the link to finish signing in',\n }}\n state={stepState}\n />\n );\n }\n\n return (\n <LoginScreen\n chrome={chrome}\n state={{\n kind: 'credentials',\n methods: loginMethods,\n passwordPolicy,\n forcePasskey: Boolean(appSettings?.force_passwordless_login && authMethods.passkey),\n allowPasskeyToggle: true,\n busy: isLoading,\n onCancel: isLoading && pendingOperation === 'passkey' ? cancelPasskey : undefined,\n primaryLabel: isLoading ? 'Signing in…' : 'Sign In',\n error: isError ? error : null,\n forgotPassword: {\n to: forgotPasswordPath ?? routes.forgot_password.path,\n getSearch: (method) =>\n queryString.stringify({\n ...queryString.parse(searchSource.read()),\n default_method: method,\n }),\n },\n footer: {\n prompt: \"Don't have an account?\",\n label: 'Sign Up',\n to: signUpPath ?? routes.signup.path,\n search: searchSource.read(),\n },\n onPassword: (values) => void handlePassword(values),\n onPasswordless: (values) => void handlePasswordless(values),\n onPasskey: () => void handlePasskey(),\n onProvider: handleProvider,\n onReset: reset,\n onStartAgain: () => window.location.assign(urlWithoutParentChallenge(window.location.href)),\n }}\n />\n );\n};\n\nexport const SignInForm = withHydration(SignInFormScreen);\n\nexport const SignIn = withError(SignInFormScreen, ErrorComponent);\n","import type {\n PassflowPasskeyRegisterStartPayload,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInPayload,\n PassflowSignUpPayload,\n PassflowUserPayload,\n Providers,\n} from '@passflow/core';\nimport { phone } from 'phone';\nimport queryString from 'query-string';\nimport type { FC } from 'react';\nimport { useMemo } from 'react';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { hasFollowedOIDCRedirect } from '@/components/provider/passflow-provider';\nimport {\n type LoginCredentialsValues,\n type LoginMethodConfig,\n LoginScreen,\n type LoginScreenChrome,\n type LoginScreenState,\n} from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withError, withHydration } from '@/hocs';\nimport { useAppSettings, useNavigation, usePassflow, useProvider, useSignInEnding, useSignUp } from '@/hooks';\nimport type { DefaultMethod, FederatedLanding, SuccessAuthRedirect } from '@/types';\nimport {\n type AuthMethods,\n authRedirectErrorFrom,\n emailRegex,\n getAuthMethods,\n getInvitationAuthChrome,\n getPasswordlessData,\n getUrlErrors,\n routeToSecondFactor,\n urlWithoutParentChallenge,\n useUrlParams,\n} from '@/utils';\n\nconst getSignUpMethodConfig = (authMethods: AuthMethods): LoginMethodConfig => {\n const identities: LoginMethodConfig['identities'] = [];\n\n if (authMethods.hasEmailMethods || authMethods.hasUsernameMethods) {\n const label =\n authMethods.hasEmailMethods && authMethods.hasUsernameMethods\n ? 'Email or username'\n : authMethods.hasUsernameMethods\n ? 'Username'\n : 'Email';\n identities.push({\n id: 'email_or_username',\n label,\n selectLabel: authMethods.hasUsernameMethods && !authMethods.hasEmailMethods ? 'Use username' : 'Use email',\n requiredMessage: `${label} is required`,\n format: authMethods.hasEmailMethods && !authMethods.hasUsernameMethods ? 'email' : undefined,\n password: authMethods.internal.email.password || authMethods.internal.username.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'email_or_username')?.label,\n });\n }\n\n if (authMethods.hasPhoneMethods) {\n identities.push({\n id: 'phone',\n label: 'Phone number',\n selectLabel: 'Use phone',\n requiredMessage: 'Phone number is required',\n password: authMethods.internal.phone.password,\n passwordlessLabel: getPasswordlessData(authMethods, 'phone')?.label,\n });\n }\n\n return {\n identities,\n passkey: authMethods.passkey,\n providers: authMethods.fim.providers,\n };\n};\n\nexport type TSignUp = {\n successAuthRedirect?: SuccessAuthRedirect;\n relyingPartyId?: string;\n federatedDisplayMode?: 'modal' | 'redirect';\n federatedLanding?: FederatedLanding;\n signInPath?: string;\n verifyOTPPath?: string;\n verifyMagicLinkPath?: string;\n twoFactorVerifyPath?: string;\n};\n\nconst SignUpFormScreen: FC<TSignUp> = ({\n successAuthRedirect,\n relyingPartyId = window.location.hostname,\n federatedLanding,\n signInPath = routes.signin.path,\n verifyOTPPath = routes.verify_otp.path,\n verifyMagicLinkPath = routes.verify_magic_link.path,\n twoFactorVerifyPath = routes.two_factor_verify.path,\n}) => {\n const passflow = usePassflow();\n const { navigate } = useNavigation();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const searchSource = useSearchSource();\n const {\n appSettings,\n scopes,\n createTenantForNewUser,\n passwordPolicy,\n currentStyles,\n isError: isErrorApp,\n error: errorApp,\n loginAppTheme,\n } = useAppSettings();\n const { federatedWithRedirect } = useProvider(successAuthRedirect, createTenantForNewUser, federatedLanding);\n\n if (isErrorApp) throw new Error(errorApp);\n\n const authMethods = useMemo(() => getAuthMethods(appSettings?.auth_strategies), [appSettings]);\n const loginMethods = useMemo(() => getSignUpMethodConfig(authMethods), [authMethods]);\n const { error: errorUrl, message: messageUrl } = getUrlErrors();\n\n if (errorUrl) {\n console.error('[passflow] sign-up redirect returned an error', { error: errorUrl, message: messageUrl });\n throw new Error(authRedirectErrorFrom(errorUrl, messageUrl));\n }\n\n const { get } = useUrlParams({ invite_token: '' });\n const inviteToken = get('invite_token');\n const invitationChrome = getInvitationAuthChrome(inviteToken, 'sign-up');\n const { fetch, isError, error, reset, isLoading, emailCode } = useSignUp();\n\n // The server can answer a sign-up with a 2FA token in place of tokens, as it\n // does a sign-in, so the 2FA screen comes before any success redirect.\n const completeRegistration = async ({ oidcMayOwnRedirect = false } = {}) => {\n if (routeToSecondFactor(passflow, navigate, twoFactorVerifyPath ?? routes.two_factor_verify.path, searchSource.read()))\n return;\n if (oidcMayOwnRedirect && hasFollowedOIDCRedirect()) return;\n await finishSignIn(successAuthRedirect, appSettings?.defaults?.redirect);\n };\n\n const submitPassword = async (userPayload: PassflowUserPayload) => {\n const payload = {\n user: userPayload,\n create_tenant: createTenantForNewUser,\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n } as PassflowSignUpPayload;\n\n if (await fetch(payload, 'password')) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n const submitPasskey = async () => {\n const payload = {\n relying_party_id: relyingPartyId,\n create_tenant: createTenantForNewUser,\n redirect_url: successAuthRedirect ?? '',\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n scopes,\n } as PassflowPasskeyRegisterStartPayload;\n\n if (await fetch(payload, 'passkey')) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n const submitPasswordless = async (userPayload: Partial<PassflowPasswordlessSignInPayload>, method: DefaultMethod | null) => {\n const challengeType = getPasswordlessData(authMethods, method)?.challengeType;\n const payload = {\n ...userPayload,\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n ...(successAuthRedirect ? { redirect_url: successAuthRedirect } : {}),\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n } as PassflowPasswordlessSignInPayload;\n\n const response = await fetch(payload, 'passwordless');\n if (!response) return;\n\n // The match code is shown only by the tab holding it: it never goes in a URL.\n const { match_code: _matchCode, ...startAnswer } = response as PassflowPasswordlessResponse;\n const params = new URLSearchParams(searchSource.read());\n // The attempt's own address is the one sent at start, not one left on this page's URL.\n params.delete('redirect_url');\n const newParams = queryString.stringify({\n ...Object.fromEntries(params.entries()),\n ...payload,\n ...startAnswer,\n type: 'passwordless',\n challenge_type: challengeType,\n create_tenant: createTenantForNewUser,\n });\n\n if (challengeType === 'otp') navigate({ to: verifyOTPPath ?? routes.verify_otp.path, search: newParams });\n if (challengeType === 'magic_link')\n navigate({ to: verifyMagicLinkPath ?? routes.verify_magic_link.path, search: newParams });\n };\n\n const handlePassword = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const isUsername = values.method === 'email_or_username' && !isEmail && values.emailOrUsername.length > 0;\n const validatedPhone = phone(values.phone);\n const user = {\n ...(isEmail ? { email: values.emailOrUsername } : {}),\n ...(isUsername ? { username: values.emailOrUsername } : {}),\n ...(validatedPhone.isValid ? { phone_number: validatedPhone.phoneNumber } : {}),\n password: values.password,\n scopes,\n } as PassflowUserPayload;\n\n await submitPassword(user);\n };\n\n const handlePasswordless = async (values: LoginCredentialsValues) => {\n const isEmail = Boolean(values.emailOrUsername.match(emailRegex));\n const validatedPhone = phone(values.phone);\n const payload = {\n ...(isEmail ? { email: values.emailOrUsername } : {}),\n ...(validatedPhone.isValid ? { phone: validatedPhone.phoneNumber } : {}),\n scopes,\n };\n\n await submitPasswordless(payload as Partial<PassflowPasswordlessSignInPayload>, values.method);\n };\n\n const handleProvider = (provider: Providers) => federatedWithRedirect(provider, inviteToken ?? undefined);\n\n // The emailed code answers like a sign-up: the same 2FA, OIDC and redirect path follows.\n const verifyEmailCode = async (code: string) => {\n if (await emailCode.verify(code)) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n const resendEmailCode = async () => {\n if (await emailCode.resend()) await completeRegistration({ oidcMayOwnRedirect: true });\n };\n\n // The application name set in the admin panel's Login Appearance.\n const appName = loginAppTheme?.application_name?.trim();\n const chrome: LoginScreenChrome = {\n title: invitationChrome?.title ?? 'Create your account',\n subtitle: invitationChrome?.subtitle ?? (appName ? `For ${appName}` : undefined),\n variant: 'sign-in',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const { step } = emailCode;\n\n if (step.kind !== 'none') {\n const stepState: LoginScreenState =\n step.kind === 'code'\n ? {\n kind: 'email-code',\n message: step.message,\n error: emailCode.error,\n busy: emailCode.isVerifying,\n resend: {\n restartKey: step.challengeId,\n busy: emailCode.isResending,\n onResend: () => void resendEmailCode(),\n },\n secondaryAction: { label: 'Use a different email', onClick: emailCode.cancel },\n onSubmit: (code) => void verifyEmailCode(code),\n }\n : {\n kind: 'status',\n tone: 'info',\n message: step.message,\n primaryAction: { label: 'Back to sign up', onClick: emailCode.cancel },\n };\n\n return (\n <LoginScreen\n chrome={{\n ...chrome,\n title: 'Check your email',\n subtitle:\n step.kind === 'code' ? 'Enter the code to finish creating your account' : 'Follow the link to finish signing up',\n }}\n state={stepState}\n />\n );\n }\n\n return (\n <LoginScreen\n chrome={chrome}\n state={{\n kind: 'credentials',\n methods: loginMethods,\n passwordPolicy,\n credentialPurpose: 'sign-up',\n forcePasskey: Boolean(appSettings?.force_passwordless_login && authMethods.passkey),\n allowPasskeyToggle: true,\n busy: isLoading,\n primaryLabel: isLoading ? 'Creating account…' : 'Sign Up',\n passwordlessLabelPrefix: 'Sign Up with',\n passkeyLabel: 'Sign Up with a Passkey',\n error: isError ? error : null,\n footer: {\n prompt: 'Already have an account?',\n label: 'Sign In',\n to: signInPath ?? routes.signin.path,\n search: searchSource.read(),\n },\n onPassword: (values) => void handlePassword(values),\n onPasswordless: (values) => void handlePasswordless(values),\n onPasskey: () => void submitPasskey(),\n onProvider: handleProvider,\n onReset: reset,\n onStartAgain: () => window.location.assign(urlWithoutParentChallenge(window.location.href)),\n }}\n />\n );\n};\n\nexport const SignUpForm = withHydration(SignUpFormScreen);\n\nexport const SignUp = withError(SignUpFormScreen, ErrorComponent);\n","import type { TwoFactorMethod } from '@passflow/core';\nimport * as Dialog from '@radix-ui/react-dialog';\nimport type { FC } from 'react';\n\ntype MethodSelectorProps = {\n availableMethods: TwoFactorMethod[];\n currentMethod: TwoFactorMethod;\n onSelectMethod: (method: TwoFactorMethod) => void;\n isOpen: boolean;\n onClose: () => void;\n};\n\nconst methodLabels: Partial<Record<TwoFactorMethod, string>> = {\n totp: 'Authenticator App',\n email_otp: 'Email Code',\n sms_otp: 'SMS Code',\n passkey: 'Passkey',\n recovery_codes: 'Recovery Code',\n push_fcm: 'Push Notification (FCM)',\n push_webpush: 'Push Notification (Web)',\n};\n\nconst methodIcons: Partial<Record<TwoFactorMethod, string>> = {\n totp: '📱',\n email_otp: '✉️',\n sms_otp: '💬',\n passkey: '🔑',\n recovery_codes: '🔒',\n push_fcm: '🔔',\n push_webpush: '🔔',\n};\n\nexport const MethodSelector: FC<MethodSelectorProps> = ({\n availableMethods,\n currentMethod,\n onSelectMethod,\n isOpen,\n onClose,\n}) => {\n const handleSelect = (method: TwoFactorMethod) => {\n onSelectMethod(method);\n onClose();\n };\n\n return (\n <Dialog.Root open={isOpen} onOpenChange={(open) => !open && onClose()}>\n <Dialog.Portal>\n <Dialog.Overlay className='pf-dialog-overlay' />\n <Dialog.Content className='pf-dialog-content pf-method-selector-dialog'>\n <Dialog.Title className='pf-dialog-title'>Choose Verification Method</Dialog.Title>\n <Dialog.Description className='pf-dialog-description'>\n Select an alternative method to verify your identity\n </Dialog.Description>\n\n <div className='pf-method-selector-list'>\n {availableMethods.map((method) => (\n <button\n key={method}\n type='button'\n className={`pf-method-selector-item ${method === currentMethod ? 'pf-method-selector-item-active' : ''}`}\n onClick={() => handleSelect(method)}\n disabled={method === currentMethod}\n >\n <span className='pf-method-icon'>{methodIcons[method] || '🔐'}</span>\n <span className='pf-method-label'>{methodLabels[method] || method}</span>\n {method === currentMethod && <span className='pf-method-current-badge'>Current</span>}\n </button>\n ))}\n </div>\n\n <Dialog.Close asChild>\n <button type='button' className='pf-dialog-close' aria-label='Close'>\n &times;\n </button>\n </Dialog.Close>\n </Dialog.Content>\n </Dialog.Portal>\n </Dialog.Root>\n );\n};\n","import type { TwoFactorMethod } from '@passflow/core';\nimport type { FC } from 'react';\nimport { useEffect, useId, useRef, useState } from 'react';\nimport { FieldOtp } from '@/components/ui';\nimport { usePassflow } from '@/hooks/use-passflow';\nimport { useTwoFactorChallenge } from '@/hooks/use-two-factor-challenge';\nimport { MethodSelector } from './method-selector';\n\ntype TwoFactorChallengeProps = {\n firstFactorMethod?: string;\n onSuccess?: () => void;\n onError?: (error: Error) => void;\n trustDevice?: boolean;\n};\n\nexport const TwoFactorChallenge: FC<TwoFactorChallengeProps> = ({\n firstFactorMethod,\n onSuccess,\n onError,\n trustDevice = false,\n}) => {\n const passflow = usePassflow();\n const { challenge, isLoading, error, requestChallenge, verify, switchMethod, selectedMethod } = useTwoFactorChallenge();\n\n const [otpValue, setOtpValue] = useState('');\n const [isMethodSelectorOpen, setIsMethodSelectorOpen] = useState(false);\n const otpId = useId();\n const otpLabelId = `${otpId}-label`;\n const otpErrorId = `${otpId}-error`;\n\n // Once per method: every request spends budget, so StrictMode's second effect must not send another.\n // Starts at null because `firstFactorMethod` may be undefined and must still request on mount.\n const requested = useRef<string | undefined | null>(null);\n useEffect(() => {\n if (requested.current === firstFactorMethod) return;\n requested.current = firstFactorMethod;\n requestChallenge(firstFactorMethod);\n }, [requestChallenge, firstFactorMethod]);\n\n // Handle errors\n useEffect(() => {\n if (error && onError) {\n onError(error);\n }\n }, [error, onError]);\n\n const handleVerify = async () => {\n if (!otpValue) {\n return;\n }\n\n const result = await verify(otpValue, trustDevice);\n if (result) {\n onSuccess?.();\n }\n };\n\n const handleSwitchMethod = async (method: TwoFactorMethod) => {\n setOtpValue('');\n await switchMethod(method);\n };\n\n // Email and SMS codes carry no length in the challenge, so they stay at six.\n const codeLength = (selectedMethod || challenge?.method) === 'totp' ? passflow.getTotpDigits() : 6;\n\n // A form that is gone must not submit a code typed just before it left.\n const autoSubmitTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n useEffect(() => () => clearTimeout(autoSubmitTimer.current), []);\n\n const handleOtpChange = (value: string) => {\n setOtpValue(value);\n clearTimeout(autoSubmitTimer.current);\n\n // Auto-submit when the code is complete\n if (value.length === codeLength) {\n autoSubmitTimer.current = setTimeout(() => {\n verify(value, trustDevice).then((result) => {\n if (result) {\n onSuccess?.();\n }\n });\n }, 100);\n }\n };\n\n if (!challenge) {\n return (\n <div className='pf-two-factor-challenge pf-loading'>\n <p>Loading challenge...</p>\n </div>\n );\n }\n\n const currentMethod = selectedMethod || challenge.method;\n const availableMethods = [challenge.method, ...(challenge.alternative_methods || [])];\n\n const renderChallengeInput = () => {\n switch (currentMethod) {\n case 'totp':\n case 'email_otp':\n case 'sms_otp':\n return (\n <div className='pf-challenge-input-wrapper'>\n <FieldOtp\n id={otpId}\n name='code'\n length={codeLength}\n value={otpValue}\n onChange={handleOtpChange}\n state={isLoading ? 'disabled' : error ? 'error' : 'default'}\n labelledBy={otpLabelId}\n describedBy={error ? otpErrorId : undefined}\n autoFocus\n />\n {error && (\n <div id={otpErrorId} className='pf-otp-error'>\n {error.message}\n </div>\n )}\n {currentMethod === 'email_otp' && challenge.code_sent_to && (\n <p className='pf-challenge-hint'>Code sent to {challenge.code_sent_to}</p>\n )}\n {currentMethod === 'sms_otp' && challenge.code_sent_to && (\n <p className='pf-challenge-hint'>Code sent to {challenge.code_sent_to}</p>\n )}\n <button\n type='button'\n onClick={handleVerify}\n disabled={isLoading || otpValue.length !== codeLength}\n className='pf-button pf-button-primary'\n >\n {isLoading ? 'Verifying...' : 'Verify'}\n </button>\n </div>\n );\n\n case 'passkey':\n return (\n <div className='pf-challenge-input-wrapper'>\n <button type='button' onClick={handleVerify} disabled={isLoading} className='pf-button pf-button-primary'>\n {isLoading ? 'Verifying...' : 'Use Passkey'}\n </button>\n </div>\n );\n\n case 'recovery_codes':\n return (\n <div className='pf-challenge-input-wrapper'>\n <input\n type='text'\n value={otpValue}\n onChange={(e) => setOtpValue(e.target.value)}\n placeholder='Enter recovery code'\n disabled={isLoading}\n className='pf-input'\n />\n <button\n type='button'\n onClick={handleVerify}\n disabled={isLoading || !otpValue}\n className='pf-button pf-button-primary'\n >\n {isLoading ? 'Verifying...' : 'Verify'}\n </button>\n </div>\n );\n\n default:\n return <p>Unsupported method: {currentMethod}</p>;\n }\n };\n\n return (\n <div className='pf-two-factor-challenge'>\n <div className='pf-challenge-method-info'>\n <h3>Two-Factor Authentication</h3>\n <p id={otpLabelId}>Enter the verification code</p>\n </div>\n\n {renderChallengeInput()}\n\n {availableMethods.length > 1 && (\n <button\n type='button'\n onClick={() => setIsMethodSelectorOpen(true)}\n className='pf-button pf-button-secondary pf-button-switch-method'\n >\n Use different method\n </button>\n )}\n\n <MethodSelector\n availableMethods={availableMethods}\n currentMethod={currentMethod}\n onSelectMethod={handleSwitchMethod}\n isOpen={isMethodSelectorOpen}\n onClose={() => setIsMethodSelectorOpen(false)}\n />\n </div>\n );\n};\n","import { useRef } from 'react';\nimport { routes, useSearchSource } from '@/context';\nimport { routeToSecondFactor } from '@/utils';\nimport { useNavigation } from './use-navigation';\nimport { usePassflow } from './use-passflow';\n\n/**\n * Sends a screen that starts its request on mount to the second factor. That request holds the closure of the first render,\n * from before the flow registered its router and paths, so this reads them when the answer arrives.\n */\nexport const useSecondFactorRoute = (twoFactorVerifyPath?: string) => {\n const passflow = usePassflow();\n const { navigate, twoFactorVerifyPath: registeredPath } = useNavigation();\n const searchSource = useSearchSource();\n const path = twoFactorVerifyPath ?? registeredPath ?? routes.two_factor_verify.path;\n const latest = useRef({ navigate, searchSource, path });\n latest.current = { navigate, searchSource, path };\n\n return () => routeToSecondFactor(passflow, latest.current.navigate, latest.current.path, latest.current.searchSource.read());\n};\n","/* eslint-disable no-nested-ternary */\nimport type { PassflowPasswordlessResponse, PassflowPasswordlessSignInPayload } from '@passflow/core';\nimport { type FC, useEffect, useMemo, useRef, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { Button, LoginScreen } from '@/components/ui';\nimport { routes, useSearchSource } from '@/context';\nimport { withHydration } from '@/hocs/with-hydration';\nimport { useAppSettings, useNavigation, usePassflow, useSignIn, useSignInEnding } from '@/hooks';\nimport { useSecondFactorRoute } from '@/hooks/use-second-factor-route';\nimport { Wrapper } from '../wrapper';\nimport '@/styles/index.css';\nimport {\n passwordlessLinkExpiredMessage,\n passwordlessSignInFailedMessage,\n passwordlessWaitCompletedMessage,\n passwordlessWaitDeniedMessage,\n signInSearch,\n useUrlParams,\n} from '@/utils';\n\nconst challengeTypeFullString = {\n email: 'email address',\n phone: 'phone number',\n};\n\nconst WAIT_FAILURE_MESSAGES = {\n denied: passwordlessWaitDeniedMessage,\n expired: passwordlessLinkExpiredMessage,\n completed: passwordlessWaitCompletedMessage,\n};\n\nconst useResendPayload = () => {\n const { createTenantForNewUser } = useAppSettings();\n const { get } = useUrlParams({\n identity: '',\n identity_value: '',\n challenge_type: '',\n type: '',\n redirect_url: '',\n });\n\n const identity = get('email') ? 'email' : get('phone') ? 'phone' : undefined;\n const identityValue = get('email') ? get('email') : get('phone') ? get('phone') : undefined;\n const redirectUrl = get('redirect_url');\n const inviteToken = get('invite_token');\n\n return {\n identity,\n identityValue,\n redirectUrl,\n type: get('type') as 'passkey' | 'password' | 'passwordless',\n resendPayload: {\n ...(identity === 'email' ? { email: identityValue } : undefined),\n ...(identity === 'phone' ? { phone: identityValue } : undefined),\n challenge_type: get('challenge_type'),\n create_tenant: createTenantForNewUser,\n redirect_url: redirectUrl,\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n } as PassflowPasswordlessSignInPayload,\n };\n};\n\n/** A link was sent and this tab has nothing to wait for: the user follows it. */\nconst MagicLinkSent: FC = () => {\n const { currentStyles, loginAppTheme } = useAppSettings();\n const { fetch: refetch } = useSignIn();\n const { identity, identityValue, type, resendPayload } = useResendPayload();\n\n const onClickResendHandler = async () => {\n await refetch(resendPayload, type);\n };\n\n return (\n <Wrapper\n title='Check your email'\n className='passflow-verify-challenge-magic-link-wrapper'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <div className='passflow-verify-challenge-magic-link-container'>\n <p className='passflow-verify-challenge-magic-link-text'>\n We sent a link to {challengeTypeFullString[identity as keyof typeof challengeTypeFullString]}{' '}\n {identityValue && <strong className='passflow-verify-challenge-magic-link-text--strong'>{identityValue}</strong>}.\n Open the link to continue.\n </p>\n {type === 'passwordless' && (\n <Button\n size='big'\n variant='secondary'\n type='button'\n className='passflow-button-resend-magic-link'\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n onClick={onClickResendHandler}\n >\n Resend email\n </Button>\n )}\n </div>\n </Wrapper>\n );\n};\n\ntype MagicLinkWaitingProps = {\n challengeId: string;\n signInPath: string;\n onResent: (answer: PassflowPasswordlessResponse) => void;\n};\n\n/** This tab started the sign-in and holds its secret: it takes the session once the link is approved on any device. */\nconst MagicLinkWaiting: FC<MagicLinkWaitingProps> = ({ challengeId, signInPath, onResent }) => {\n const passflow = usePassflow();\n const { appSettings, currentStyles, loginAppTheme } = useAppSettings();\n // The wait below starts once, and settings can arrive after it.\n const appDefault = useRef<string | undefined>(undefined);\n appDefault.current = appSettings?.defaults?.redirect;\n const { navigate } = useNavigation();\n const routeToSecondFactor = useSecondFactorRoute();\n const { fetch: refetch, isLoading: isResending, isError: isResendError, error: resendError } = useSignIn();\n const searchSource = useSearchSource();\n const { redirectUrl, type, resendPayload } = useResendPayload();\n const { ending, retry, finishSignIn } = useSignInEnding();\n const [failure, setFailure] = useState<string | null>(null);\n\n useEffect(() => {\n const controller = new AbortController();\n const { signal } = controller;\n\n const wait = async () => {\n try {\n const result = await passflow.waitForPasswordlessSignIn(challengeId, { signal });\n if (signal.aborted) return;\n\n if (result.status === 'signed-in') {\n await finishSignIn(redirectUrl, appDefault.current);\n } else if (result.status === 'second-factor-required') {\n if (!routeToSecondFactor()) setFailure(passwordlessSignInFailedMessage);\n } else {\n setFailure(WAIT_FAILURE_MESSAGES[result.status]);\n }\n } catch (error) {\n if (signal.aborted) return;\n console.error('[passflow] waiting for the passwordless sign-in failed', error);\n setFailure(passwordlessSignInFailedMessage);\n }\n };\n void wait();\n\n return () => controller.abort();\n }, [passflow, challengeId]);\n\n const resend = async () => {\n const answer = await refetch(resendPayload, 'passwordless');\n if (answer) onResent(answer as PassflowPasswordlessResponse);\n };\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const chrome = {\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n };\n\n if (failure) {\n return (\n <LoginScreen\n chrome={{ ...chrome, title: 'Sign-in not completed' }}\n state={{\n kind: 'status',\n tone: 'error',\n message: failure,\n testId: 'passwordless-wait-failure',\n primaryAction: {\n label: 'Start again',\n onClick: () => navigate({ to: signInPath, search: signInSearch(searchSource.read()) }),\n },\n }}\n />\n );\n }\n\n return (\n <LoginScreen\n chrome={{ ...chrome, title: 'Check your email' }}\n state={{\n kind: 'passwordless-waiting',\n error: isResendError ? resendError?.message : null,\n resend:\n type === 'passwordless' ? { restartKey: challengeId, busy: isResending, onResend: () => void resend() } : undefined,\n testId: 'passwordless-waiting',\n }}\n />\n );\n};\n\ntype VerifyChallengeMagicLinkProps = {\n signInPath?: string;\n};\n\nconst VerifyChallengeMagicLinkScreen: FC<VerifyChallengeMagicLinkProps> = ({ signInPath = routes.signin.path }) => {\n const passflow = usePassflow();\n const { get, set } = useUrlParams();\n // The address bar does not re-render on a write, so a resend asks for it.\n const [, setResendCount] = useState(0);\n const challengeId = get('challenge_id');\n\n // A pending record is how this screen knows this tab started the sign-in.\n // Read once per challenge: core drops the record when the wait ends, and the outcome must stay on this screen.\n const pending = useMemo(() => (challengeId ? passflow.getPendingPasswordlessSignIn(challengeId) : undefined), [challengeId]);\n\n if (!challengeId || !pending) return <MagicLinkSent />;\n\n return (\n <MagicLinkWaiting\n challengeId={challengeId}\n signInPath={signInPath}\n onResent={(answer) => {\n set({ challenge_id: answer.challenge_id, expires_at: String(answer.expires_at) });\n setResendCount((count) => count + 1);\n }}\n />\n );\n};\n\nexport const VerifyChallengeMagicLink = withHydration(VerifyChallengeMagicLinkScreen);\n","import type { PasswordlessApprovalInfo } from '@passflow/core';\nimport { type FC, useEffect, useState } from 'react';\nimport { LoginScreen, type LoginScreenState } from '@/components/ui';\nimport { useAppSettings, usePassflow } from '@/hooks';\nimport {\n approvalAlreadyDecidedMessage,\n approvalApprovedMessage,\n approvalDeniedMessage,\n approvalErrorFrom,\n approvalInvalidMessage,\n passwordlessLinkExpiredMessage,\n} from '@/utils';\n\ntype VerifyChallengeApprovalProps = {\n challengeId: string | null;\n otp: string | null;\n};\n\ntype ApprovalView =\n | { kind: 'loading' }\n | { kind: 'form'; info: PasswordlessApprovalInfo }\n | { kind: 'decided'; message: string }\n | { kind: 'terminal'; message: string }\n | { kind: 'load-failed'; message: string };\n\nconst viewFromInfo = (info: PasswordlessApprovalInfo): ApprovalView => {\n if (info.state === 'pending') return { kind: 'form', info };\n if (info.state === 'expired') return { kind: 'terminal', message: passwordlessLinkExpiredMessage };\n return { kind: 'terminal', message: approvalAlreadyDecidedMessage };\n};\n\n/**\n * The device that opened an emailed link on a row only another device can sign in with. Opening it writes nothing: the\n * user reads the request, then signs in or answers that it wasn't them, in one click. Errors from these calls are\n * plain and carry no code, but are not logged here anyway, because this screen holds the OTP.\n */\nexport const VerifyChallengeApproval: FC<VerifyChallengeApprovalProps> = ({ challengeId, otp }) => {\n const passflow = usePassflow();\n const { currentStyles, loginAppTheme } = useAppSettings();\n const [view, setView] = useState<ApprovalView>(\n challengeId && otp ? { kind: 'loading' } : { kind: 'terminal', message: approvalInvalidMessage },\n );\n const [error, setError] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [loadAttempt, setLoadAttempt] = useState(0);\n\n // `loadAttempt` only triggers a retry; `passflow` is left out so a replaced instance does not reload a request on screen.\n useEffect(() => {\n if (!challengeId || !otp) return undefined;\n let left = false;\n\n const load = async () => {\n try {\n const info = await passflow.getPasswordlessApproval(challengeId);\n if (!left) setView(viewFromInfo(info));\n } catch (loadError) {\n if (left) return;\n const { message, terminal } = approvalErrorFrom(loadError);\n setView(terminal ? { kind: 'terminal', message } : { kind: 'load-failed', message });\n }\n };\n void load();\n\n return () => {\n left = true;\n };\n }, [challengeId, otp, loadAttempt]);\n\n const decide = async (approve: boolean) => {\n if (!challengeId || !otp) return;\n setBusy(true);\n setError(null);\n try {\n await passflow.decidePasswordlessApproval(challengeId, otp, approve);\n setView({ kind: 'decided', message: approve ? approvalApprovedMessage : approvalDeniedMessage });\n } catch (decideError) {\n const { message, terminal } = approvalErrorFrom(decideError);\n if (terminal) setView({ kind: 'terminal', message });\n else setError(message);\n } finally {\n setBusy(false);\n }\n };\n\n const screenState = ((): LoginScreenState => {\n switch (view.kind) {\n case 'loading':\n return { kind: 'passwordless-approval', loading: true };\n case 'form': {\n const { info } = view;\n return {\n kind: 'passwordless-approval',\n appName: info.app_name,\n browser: info.browser,\n os: info.os,\n location: info.location ? [info.location.city, info.location.country].filter(Boolean).join(', ') : null,\n requestedAt: new Date(info.requested_at).toLocaleString(),\n error,\n busy,\n testId: 'passwordless-approval',\n onApprove: () => void decide(true),\n onDeny: () => void decide(false),\n };\n }\n case 'decided':\n return { kind: 'status', tone: 'success', message: view.message };\n case 'terminal':\n return { kind: 'status', tone: 'error', message: view.message };\n case 'load-failed':\n return {\n kind: 'status',\n tone: 'error',\n message: view.message,\n recoverable: true,\n onRetry: () => {\n setView({ kind: 'loading' });\n setLoadAttempt((attempt) => attempt + 1);\n },\n };\n }\n })();\n\n return (\n <LoginScreen\n chrome={{\n title: view.kind === 'loading' || view.kind === 'form' ? 'Approve sign-in' : 'Sign-in request',\n customCss: currentStyles?.custom_css,\n customLogo: currentStyles?.logo_url,\n customLogoAlt: `${loginAppTheme?.application_name ?? 'Application'} logo`,\n removeBranding: loginAppTheme?.remove_passflow_logo,\n }}\n state={screenState}\n />\n );\n};\n","import { type FC, type PropsWithChildren, useEffect, useState } from 'react';\nimport { Button } from '@/components/ui';\nimport '@/styles/index.css';\nimport { cn } from '@/utils';\n\ntype TTimerButton = PropsWithChildren & {\n totalSecond: number;\n onClick: () => void;\n className?: string;\n};\n\nexport const TimerButton: FC<TTimerButton> = ({ totalSecond, onClick, className = '', ...props }) => {\n const [seconds, setSeconds] = useState(totalSecond);\n\n useEffect(() => {\n const interval = setInterval(() => {\n if (seconds > 0) {\n setSeconds((prev) => prev - 1);\n }\n }, 1000);\n\n return () => {\n clearInterval(interval);\n };\n }, [seconds]);\n\n const onClickHandler = () => {\n onClick();\n setSeconds(totalSecond);\n };\n\n return (\n <Button\n disabled={seconds > 0}\n size='small'\n variant='clean'\n type='button'\n className={cn(\n 'passflow-button-timer',\n {\n 'passflow-button-timer--active': seconds > 0,\n 'passflow-button-timer--inactive': seconds === 0,\n },\n className,\n )}\n onClick={onClickHandler}\n {...props}\n >\n Resend {seconds > 0 ? `(${seconds})` : ''}\n </Button>\n );\n};\n","import type {\n InternalStrategyChallenge,\n PassflowPasswordlessResponse,\n PassflowPasswordlessSignInCompletePayload,\n PassflowPasswordlessSignInPayload,\n} from '@passflow/core';\n/* eslint-disable no-void */\n/* eslint-disable complexity */\nimport { type FC, useEffect, useId, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { Button, FieldOtp, Icon } from '@/components/ui';\nimport { useAppSettings, useNavigation, usePasswordlessComplete, useSignIn, useSignInEnding } from '@/hooks';\nimport { useSecondFactorRoute } from '@/hooks/use-second-factor-route';\nimport { useUrlParams } from '@/utils';\nimport { Wrapper } from '../wrapper';\nimport { TimerButton } from './timer-button';\n\nimport '@/styles/index.css';\n\ntype VerifyChallengeOTPManualProps = {\n identity: string | null;\n identityValue: string | null;\n challengeType: string | null;\n challengeId: string | null;\n type: 'passwordless' | 'passkey' | null;\n numInputs: number;\n shouldAutoFocus: boolean;\n signUpPath: string;\n successAuthRedirect?: string;\n twoFactorVerifyPath?: string;\n};\n\nconst challengeTypeFullString = {\n email: 'email address',\n phone: 'phone number',\n};\n\nexport const VerifyChallengeOTPManual: FC<VerifyChallengeOTPManualProps> = ({\n identity,\n identityValue,\n challengeType,\n challengeId,\n type,\n numInputs,\n shouldAutoFocus,\n successAuthRedirect,\n signUpPath,\n twoFactorVerifyPath,\n}) => {\n const routeToSecondFactor = useSecondFactorRoute(twoFactorVerifyPath);\n const { createTenantForNewUser, currentStyles, loginAppTheme } = useAppSettings();\n const { navigate } = useNavigation();\n const { fetch: refetch } = useSignIn();\n const { fetch: fetchPasswordlessComplete, isError, error } = usePasswordlessComplete();\n const [valueOTP, setValueOTP] = useState('');\n const [paramsError, setParamsError] = useState<string | null>(null);\n const { ending, retry, finishSignIn } = useSignInEnding();\n const { get, set } = useUrlParams();\n const otpId = useId();\n const otpErrorId = `${otpId}-error`;\n\n const onChangeOTP = (value: string) => setValueOTP(value);\n\n const onClickResendHandler = async () => {\n if (type && identity && identityValue && challengeType) {\n const inviteToken = get('invite_token');\n const payload: PassflowPasswordlessSignInPayload = {\n create_tenant: createTenantForNewUser,\n challenge_type: challengeType as InternalStrategyChallenge,\n redirect_url: successAuthRedirect ?? '',\n ...(identity === 'email' ? { email: identityValue } : { phone: identityValue }),\n ...(inviteToken ? { invite_token: inviteToken } : {}),\n };\n\n const refetchResponse = (await refetch(payload, type)) as PassflowPasswordlessResponse;\n if (refetchResponse) {\n set({ challenge_id: refetchResponse.challenge_id });\n } else {\n setParamsError('Something went wrong. Please try again later.');\n }\n }\n };\n\n useEffect(() => {\n if (valueOTP.length === numInputs && challengeId) {\n const payload: PassflowPasswordlessSignInCompletePayload = {\n challenge_id: challengeId,\n challenge_type: 'otp',\n otp: valueOTP,\n };\n const fetchData = async () => {\n const response = await fetchPasswordlessComplete(payload);\n if (response) {\n // The code completed the first factor only: no tokens yet.\n if (routeToSecondFactor()) return;\n await finishSignIn(response.redirect_url);\n }\n };\n void fetchData();\n }\n }, [valueOTP, numInputs, fetchPasswordlessComplete, challengeId]);\n\n if (paramsError) throw new Error(paramsError);\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n const onClickNavigateBack = () => navigate({ to: signUpPath });\n\n return (\n <Wrapper\n title={`Verify your ${identity}`}\n subtitle={`We sent OTP code to your ${challengeTypeFullString[identity as keyof typeof challengeTypeFullString]}`}\n className='passflow-verify-otp'\n customCss={currentStyles?.custom_css}\n customLogo={currentStyles?.logo_url}\n removeBranding={loginAppTheme?.remove_passflow_logo}\n >\n <div className='passflow-verify-otp-container'>\n {identityValue && (\n <Button\n size='big'\n type='button'\n variant='outlined'\n className='passflow-verify-otp-button'\n withIcon\n onClick={onClickNavigateBack}\n >\n <Icon id={identity === 'email' ? 'mail' : 'phone'} type='general' size='small' />\n {identityValue}\n <Icon id='edit' type='general' size='small' className='passflow-verify-otp-button-icon' />\n </Button>\n )}\n <div id='otp-wrapper' className='passflow-verify-otp-wrapper'>\n <FieldOtp\n id={otpId}\n name='otp'\n length={numInputs}\n value={valueOTP}\n onChange={onChangeOTP}\n state={isError ? 'error' : 'default'}\n label='Verification code'\n describedBy={isError ? otpErrorId : undefined}\n autoFocus={shouldAutoFocus}\n />\n {isError && (\n <div className='passflow-verify-otp-error'>\n <Icon size='small' id='warning' type='general' className='icon-warning' />\n <span id={otpErrorId} className='passflow-verify-otp-error-text'>\n {error}\n </span>\n </div>\n )}\n </div>\n </div>\n {type === 'passwordless' && (\n <p className='passflow-verify-otp-resend'>\n Don&apos;t receive a code?\n <TimerButton totalSecond={30} onClick={() => void onClickResendHandler()} />\n </p>\n )}\n </Wrapper>\n );\n};\n","import { useEffect, useRef, useState } from 'react';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { usePasswordlessComplete, useSignInEnding } from '@/hooks';\nimport { useSecondFactorRoute } from '@/hooks/use-second-factor-route';\nimport { verificationLinkErrorMessage, verificationRequestErrorMessage } from '@/utils';\n\ntype VerifyChallengeOTPRedirectProps = {\n appId: string | null;\n otp: string | null;\n challengeId: string | null;\n twoFactorVerifyPath?: string;\n};\n\nexport const VerifyChallengeOTPRedirect = ({\n otp,\n challengeId,\n appId,\n twoFactorVerifyPath,\n}: VerifyChallengeOTPRedirectProps) => {\n const routeToSecondFactor = useSecondFactorRoute(twoFactorVerifyPath);\n const [paramsError, setParamsError] = useState<string | null>(null);\n const { ending, retry, finishSignIn } = useSignInEnding();\n const { fetch, isError, error } = usePasswordlessComplete();\n const requested = useRef(false);\n\n // Once per opened link: the code is single use, so StrictMode's second effect must not send it again.\n useEffect(() => {\n if (requested.current) return;\n requested.current = true;\n\n const fetchData = async () => {\n if (!appId || !otp || !challengeId) {\n const missingParameters = [!appId && 'app_id', !otp && 'otp', !challengeId && 'challenge_id'].filter(Boolean);\n console.error('[passflow] passwordless verification redirect is missing required parameters', missingParameters);\n setParamsError(verificationLinkErrorMessage);\n return;\n }\n\n const response = await fetch({ otp, challenge_id: challengeId });\n\n if (response) {\n // The link completed the first factor only: no tokens yet.\n if (routeToSecondFactor()) return;\n await finishSignIn(response.redirect_url);\n } else {\n setParamsError(verificationRequestErrorMessage);\n }\n };\n\n void fetchData();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (isError && error) throw new Error(error);\n\n if (paramsError) throw new Error(paramsError);\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n return null;\n};\n","/* eslint-disable complexity */\n/* eslint-disable no-nested-ternary */\nimport type { FC } from 'react';\nimport * as Yup from 'yup';\nimport { withHydration } from '@/hocs/with-hydration';\nimport type { SuccessAuthRedirect } from '@/types';\nimport { VerifyChallengeApproval } from './verify-challenge-approval';\nimport { VerifyChallengeOTPManual } from './verify-challenge-otp-manual';\nimport { VerifyChallengeOTPRedirect } from './verify-challenge-otp-redirect';\n\nimport '@/styles/index.css';\nimport { useUrlParams, verificationLinkErrorMessage } from '@/utils';\n\ntype TVerifyChallengeOTP = {\n numInputs: number;\n shouldAutoFocus: boolean;\n signUpPath: string;\n successAuthRedirect?: SuccessAuthRedirect;\n twoFactorVerifyPath?: string;\n};\n\nconst redirectSearchParamsVerifyChallengeOtpSchema = Yup.object().shape({\n appId: Yup.string().required(),\n challengeId: Yup.string().required(),\n otp: Yup.string().required(),\n});\n\nconst searchParamsVerifyChallengeOtpSchema = Yup.object().shape({\n challengeId: Yup.string().required(),\n identity: Yup.string().oneOf(['email', 'phone']).required(),\n identityValue: Yup.string().required(),\n challengeType: Yup.string().required(),\n type: Yup.string().oneOf(['passwordless', 'passkey']).optional(),\n});\n\nconst VerifyChallengeOTPScreen: FC<TVerifyChallengeOTP> = ({\n successAuthRedirect,\n numInputs,\n shouldAutoFocus,\n signUpPath,\n twoFactorVerifyPath,\n}) => {\n const { get } = useUrlParams({\n otp: '',\n app_id: '',\n challenge_id: '',\n identity: '',\n identity_value: '',\n challenge_type: '',\n type: '',\n flow: '',\n });\n\n // The approving device never completes the link itself, so nothing below applies to it.\n if (get('flow') === 'approval') return <VerifyChallengeApproval challengeId={get('challenge_id')} otp={get('otp')} />;\n\n const typeChallenge = get('type');\n\n if (typeChallenge !== 'passwordless' && typeChallenge !== 'passkey') {\n const redirectParams = {\n appId: get('app_id'),\n challengeId: get('challenge_id'),\n otp: get('otp'),\n };\n\n try {\n redirectSearchParamsVerifyChallengeOtpSchema.validateSync(redirectParams, { abortEarly: false });\n } catch (error) {\n console.error('[passflow] invalid passwordless verification redirect', error);\n throw new Error(verificationLinkErrorMessage);\n }\n\n const { appId, otp, challengeId } = redirectParams;\n\n return (\n <VerifyChallengeOTPRedirect appId={appId} challengeId={challengeId} otp={otp} twoFactorVerifyPath={twoFactorVerifyPath} />\n );\n }\n\n const params = {\n challengeId: get('challenge_id'),\n identity: get('email') ? 'email' : get('phone') ? 'phone' : null,\n identityValue: get('email') ? get('email') : get('phone') ? get('phone') : null,\n challengeType: get('challenge_type'),\n type: get('type'),\n };\n\n try {\n searchParamsVerifyChallengeOtpSchema.validateSync(params, { abortEarly: false });\n } catch (error) {\n console.error('[passflow] invalid passwordless verification link', error);\n throw new Error(verificationLinkErrorMessage);\n }\n\n const { challengeId, identity, identityValue, challengeType, type } = params;\n\n if (!type) {\n console.error('[passflow] passwordless verification link is missing its flow type');\n throw new Error(verificationLinkErrorMessage);\n }\n\n return (\n <VerifyChallengeOTPManual\n identity={identity}\n identityValue={identityValue}\n challengeType={challengeType}\n challengeId={challengeId}\n type={type as 'passwordless' | 'passkey'}\n numInputs={numInputs}\n shouldAutoFocus={shouldAutoFocus}\n signUpPath={signUpPath}\n successAuthRedirect={successAuthRedirect}\n twoFactorVerifyPath={twoFactorVerifyPath}\n />\n );\n};\n\nexport const VerifyChallengeOTP = withHydration(VerifyChallengeOTPScreen);\n","/**\n * The flow's own router: no router library. PassflowFlow has a fixed set of\n * screens, one path parameter (`:token`) and search params, so it matches paths\n * itself and keeps one of three histories, or takes the location from the host.\n *\n * Browser history is the default and works on its own or inside a host router\n * (React Router, TanStack Router, Wouter): the flow moves the URL with\n * `history.pushState` and then fires `popstate`, the event every browser-history\n * router listens to, so the host's location follows. Back and Forward reach the\n * flow through the same event.\n */\nimport { routes } from '@/context';\n\nexport type FlowLocation = { pathname: string; search: string; hash?: string };\nexport type FlowNavigateOptions = { replace: boolean };\nexport type FlowNavigate = (location: FlowLocation, options: FlowNavigateOptions) => void;\n\nexport type FlowHistory = {\n /** The current location. Returns the same object until the location changes. */\n read: () => FlowLocation;\n subscribe: (listener: () => void) => () => void;\n navigate: FlowNavigate;\n};\n\n/** The screens PassflowFlow renders, keyed as in `routes`. */\nexport const FLOW_SCREENS = [\n 'signin',\n 'signup',\n 'verify_otp',\n 'verify_magic_link',\n 'forgot_password',\n 'forgot_password_success',\n 'reset_password',\n 'invitation',\n 'two_factor_verify',\n 'two_factor_setup',\n 'two_factor_setup_magic_link',\n] as const satisfies readonly (keyof typeof routes)[];\n\nexport type FlowScreen = (typeof FLOW_SCREENS)[number];\n\nexport type FlowMatch = { screen: FlowScreen; params: Record<string, string> };\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/** `/two-factor-setup-magic-link/:token` → a pattern for the path's segments, capturing params. */\nconst patternSource = (path: string) =>\n path\n .split('/')\n .map((segment) => (segment.startsWith(':') ? '([^/]+)' : escapeRegExp(segment)))\n .join('/');\n\nconst paramNames = (path: string) =>\n path\n .split('/')\n .filter((segment) => segment.startsWith(':'))\n .map((segment) => segment.slice(1));\n\n// Longest first, so `/forgot-password/success` wins over `/forgot-password`.\nconst SCREENS_BY_LENGTH = [...FLOW_SCREENS].sort((a, b) => routes[b].path.length - routes[a].path.length);\n\nconst decode = (value: string) => {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n};\n\n/** `'/auth/'` → `'/auth'`, `'auth'` → `'/auth'`, `'/'` or `''` → `''`. */\nexport const normalizePrefix = (prefix: string | undefined): string => {\n const trimmed = (prefix ?? '').replace(/^\\/+|\\/+$/g, '');\n return trimmed ? `/${trimmed}` : '';\n};\n\nconst trimTrailingSlash = (pathname: string) => (pathname.length > 1 ? pathname.replace(/\\/+$/, '') : pathname);\n\n/** The screen at `pathname` under `prefix`, or null when the path is not one of the flow's screens. */\nexport const matchScreen = (pathname: string, prefix: string): FlowMatch | null => {\n const path = trimTrailingSlash(pathname);\n for (const screen of SCREENS_BY_LENGTH) {\n const route = routes[screen].path;\n const match = new RegExp(`^${escapeRegExp(prefix)}${patternSource(route)}$`).exec(path);\n if (match) {\n const names = paramNames(route);\n return { screen, params: Object.fromEntries(names.map((name, index) => [name, decode(match[index + 1] ?? '')])) };\n }\n }\n return null;\n};\n\n/**\n * Where the flow is mounted, worked out from the first URL it sees: the part in\n * front of a screen path (`/auth/signin` → `/auth`), or the whole path when it\n * names no screen (`/auth` → `/auth`, `/` → `''`).\n */\nexport const detectPrefix = (pathname: string): string => {\n const path = trimTrailingSlash(pathname);\n for (const screen of SCREENS_BY_LENGTH) {\n const match = new RegExp(`^(.*?)${patternSource(routes[screen].path)}$`).exec(path);\n if (match) return normalizePrefix(match[1]);\n }\n return normalizePrefix(path);\n};\n\n/** The absolute path of a screen under `prefix`; `params` fill `:name` segments. */\nexport const screenPath = (screen: FlowScreen, prefix: string, params: Record<string, string> = {}): string =>\n `${prefix}${routes[screen].path.replace(/:(\\w+)/g, (_, name: string) => encodeURIComponent(params[name] ?? ''))}`;\n\nexport const isUnderPrefix = (pathname: string, prefix: string) =>\n prefix === '' || pathname === prefix || pathname.startsWith(`${prefix}/`);\n\nexport const withQuestionMark = (search: string) => (search && !search.startsWith('?') ? `?${search}` : search);\n\n/** Keeps `read` stable between changes, as `useSyncExternalStore` requires. */\nconst cached = (compute: () => FlowLocation) => {\n let last: FlowLocation | null = null;\n return () => {\n const next = compute();\n if (!last || last.pathname !== next.pathname || last.search !== next.search) last = next;\n return last;\n };\n};\n\nconst listenTo = (events: string[]) => (listener: () => void) => {\n for (const event of events) window.addEventListener(event, listener);\n return () => {\n for (const event of events) window.removeEventListener(event, listener);\n };\n};\n\n/** Tells every browser-history router on the page (the flow included) that the URL moved. */\nconst announceUrlChange = () => window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));\n\nexport const createBrowserHistory = (): FlowHistory => ({\n read: cached(() => ({ pathname: window.location.pathname, search: window.location.search })),\n subscribe: listenTo(['popstate']),\n navigate: ({ pathname, search, hash = '' }, { replace }) => {\n const url = `${pathname}${withQuestionMark(search)}${hash}`;\n // The current state is kept so a host router's own bookkeeping (its history\n // index and key) stays readable after the move.\n if (replace) window.history.replaceState(window.history.state, '', url);\n else window.history.pushState(window.history.state, '', url);\n announceUrlChange();\n },\n});\n\nconst readHash = (): FlowLocation => {\n const raw = window.location.hash.replace(/^#/, '') || '/';\n const queryAt = raw.indexOf('?');\n const pathname = queryAt >= 0 ? raw.slice(0, queryAt) : raw;\n return { pathname: pathname.startsWith('/') ? pathname : `/${pathname}`, search: queryAt >= 0 ? raw.slice(queryAt) : '' };\n};\n\nexport const createHashHistory = (): FlowHistory => ({\n read: cached(readHash),\n subscribe: listenTo(['popstate', 'hashchange']),\n navigate: ({ pathname, search }, { replace }) => {\n const url = `${window.location.pathname}${window.location.search}#${pathname}${withQuestionMark(search)}`;\n if (replace) window.history.replaceState(window.history.state, '', url);\n else window.history.pushState(window.history.state, '', url);\n announceUrlChange();\n },\n});\n\nexport const createMemoryHistory = (initial: FlowLocation = { pathname: '/', search: '' }): FlowHistory => {\n const entries: FlowLocation[] = [initial];\n const listeners = new Set<() => void>();\n return {\n read: () => entries[entries.length - 1] as FlowLocation,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n navigate: ({ pathname, search }, { replace }) => {\n const next = { pathname, search: withQuestionMark(search) };\n if (replace) entries[entries.length - 1] = next;\n else entries.push(next);\n for (const listener of listeners) listener();\n },\n };\n};\n","import { type FC, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { TwoFactorSetupFlow } from '@/components/flow/two-factor-setup';\nimport { TwoFactorSetupMagicLinkFlow } from '@/components/flow/two-factor-setup-magic-link';\nimport { TwoFactorVerifyFlow } from '@/components/flow/two-factor-verify';\nimport {\n ForgotPassword,\n ForgotPasswordSuccess,\n InvitationJoin,\n ResetPassword,\n SignIn,\n SignUp,\n VerifyChallengeMagicLink,\n VerifyChallengeOTP,\n} from '@/components/form';\nimport { NavigationContext, SearchContext, type SearchSource } from '@/context';\nimport '@/styles/index.css';\nimport { ErrorComponent } from '@/components/error';\nimport { SignInEndingScreen } from '@/components/form/signed-in';\nimport { withError } from '@/hocs';\nimport { useNavigation, usePassflow, useSignInEnding } from '@/hooks';\nimport type { FederatedLanding, SuccessAuthRedirect } from '@/types';\nimport { authRedirectErrorFrom, getUrlErrors, inAppPath, passwordlessSignInFailedMessage } from '@/utils';\nimport {\n createBrowserHistory,\n createHashHistory,\n createMemoryHistory,\n detectPrefix,\n FLOW_SCREENS,\n type FlowHistory,\n type FlowLocation,\n type FlowMatch,\n type FlowNavigate,\n type FlowScreen,\n isUnderPrefix,\n matchScreen,\n normalizePrefix,\n screenPath,\n withQuestionMark,\n} from './flow-router';\n\nexport type { FlowLocation as PassflowFlowLocation, FlowNavigate as PassflowFlowNavigate } from './flow-router';\n\ntype PassflowBaseProps = {\n successAuthRedirect?: SuccessAuthRedirect;\n federatedDisplayMode?: 'modal' | 'redirect';\n /**\n * Where a federated redirect comes back. `app` (the default) keeps today's redirect URL. `login-page`, for a hosted\n * login page on a PKCE app, comes back to this page, which exchanges the code and forwards the tokens to\n * `successAuthRedirect`, else the app's default redirect.\n */\n federatedLanding?: FederatedLanding;\n error?: string;\n relyingPartyId?: string;\n /**\n * Where the flow is mounted, such as `/auth`: its screens are then `/auth/signin`,\n * `/auth/signup`, and so on. Leave it out and the flow works it out from the first\n * URL it sees (`/auth/signin` or `/auth` → `/auth`; `/` → none).\n */\n pathPrefix?: string;\n /**\n * The history the flow keeps when the app does not pass `location`. `browser`\n * (the default) uses the address bar, on its own or inside the app's router;\n * `hash` keeps the flow's path after `#`; `memory` leaves the URL alone.\n */\n routerType?: 'browser' | 'hash' | 'memory';\n /** @deprecated Never had an effect. Use `pathPrefix`. */\n basename?: string;\n};\n\nexport type PassflowProps = PassflowBaseProps &\n (\n | {\n location?: undefined;\n navigate?: undefined;\n }\n | {\n /**\n * Full control: the app's router owns the location. Pass its current\n * `{ pathname, search }` and a `navigate` that moves it; `routerType` is then\n * not used. A move to an address with a fragment also carries `hash`. Not needed for an app router in browser mode, which the default\n * already follows.\n */\n location: FlowLocation;\n navigate: FlowNavigate;\n }\n );\n\ntype RouterKind = NonNullable<PassflowBaseProps['routerType']>;\n\nconst createHistory = (routerType: RouterKind): FlowHistory => {\n if (routerType === 'hash') return createHashHistory();\n if (routerType === 'memory') return createMemoryHistory();\n return createBrowserHistory();\n};\n\nconst noLocation = () => null;\n\n/**\n * The location the flow renders and how it moves: its own history, or the app's when it passes both. Null on the\n * server and during hydration of a browser or hash history: the server has no URL, so it renders no screen, and the\n * screen appears in the render right after hydration.\n */\nconst useFlowLocation = (\n routerType: RouterKind,\n controlledLocation: FlowLocation | undefined,\n controlledNavigate: FlowNavigate | undefined,\n): { location: FlowLocation | null; navigate: FlowNavigate } => {\n const history = useMemo(() => createHistory(routerType), [routerType]);\n const ownLocation = useSyncExternalStore(\n history.subscribe,\n history.read,\n routerType === 'memory' ? history.read : noLocation,\n );\n if (controlledLocation && controlledNavigate) {\n return {\n location: { pathname: controlledLocation.pathname, search: withQuestionMark(controlledLocation.search ?? '') },\n navigate: controlledNavigate,\n };\n }\n return { location: ownLocation, navigate: history.navigate };\n};\n\ntype PassflowRoutesProps = Required<Pick<PassflowBaseProps, 'federatedDisplayMode' | 'federatedLanding' | 'relyingPartyId'>> &\n Pick<PassflowBaseProps, 'successAuthRedirect' | 'pathPrefix'> & {\n location: FlowLocation;\n navigate: FlowNavigate;\n };\n\nconst PassflowRoutes: FC<PassflowRoutesProps> = ({\n successAuthRedirect,\n federatedDisplayMode,\n federatedLanding,\n relyingPartyId,\n pathPrefix,\n location,\n navigate,\n}) => {\n // Fixed from the first URL unless the app names it.\n const [detectedPrefix] = useState(() => detectPrefix(location.pathname));\n const prefix = pathPrefix === undefined ? detectedPrefix : normalizePrefix(pathPrefix);\n\n const paths = useMemo(\n () => Object.fromEntries(FLOW_SCREENS.map((screen) => [screen, screenPath(screen, prefix)])) as Record<FlowScreen, string>,\n [prefix],\n );\n\n // The forms navigate through the provider. Registered once, reading the latest\n // `navigate` through a ref: an app's inline `navigate` prop changes every render,\n // and re-registering it would re-render the provider and loop.\n const navigateRef = useRef(navigate);\n navigateRef.current = navigate;\n const { setNavigate } = useContext(NavigationContext);\n useEffect(() => {\n setNavigate(({ to, search = '', replace = false }) => {\n const hashAt = to.indexOf('#');\n const hash = hashAt >= 0 ? to.slice(hashAt) : '';\n const target = hashAt >= 0 ? to.slice(0, hashAt) : to;\n const queryAt = target.indexOf('?');\n const pathname = queryAt >= 0 ? target.slice(0, queryAt) : target;\n const query = search || (queryAt >= 0 ? target.slice(queryAt) : '');\n navigateRef.current({ pathname, search: withQuestionMark(query), ...(hash ? { hash } : {}) }, { replace });\n });\n }, [setNavigate]);\n\n // A landing that owes its second factor goes to this flow's own (prefixed)\n // 2FA route; PassflowProvider does the navigation.\n const { setTwoFactorVerifyPath, setSignInPath } = useNavigation();\n useEffect(() => {\n setTwoFactorVerifyPath?.(paths.two_factor_verify);\n return () => setTwoFactorVerifyPath?.(null);\n }, [setTwoFactorVerifyPath, paths.two_factor_verify]);\n useEffect(() => {\n setSignInPath?.(paths.signin);\n return () => setSignInPath?.(null);\n }, [setSignInPath, paths.signin]);\n\n const match = matchScreen(location.pathname, prefix);\n // A path inside the flow that names no screen goes to sign-in, keeping its search\n // params. A path outside the flow belongs to the app: the flow renders nothing.\n const strayInsideFlow = !match && isUnderPrefix(location.pathname, prefix);\n useEffect(() => {\n if (strayInsideFlow) navigateRef.current({ pathname: paths.signin, search: location.search }, { replace: true });\n }, [strayInsideFlow, paths.signin, location.search]);\n\n // The forms read and write search params through the flow's location, not the\n // address bar, so memory, hash and app-driven flows carry them too. A write can\n // happen while a form renders (default params), so it moves after the render.\n const pathnameRef = useRef(location.pathname);\n pathnameRef.current = location.pathname;\n const searchSource = useMemo<SearchSource>(\n () => ({\n read: () => location.search,\n write: (search, { replace }) =>\n queueMicrotask(() => navigateRef.current({ pathname: pathnameRef.current, search }, { replace })),\n }),\n [location.search],\n );\n\n if (!match) return null;\n\n return (\n <SearchContext.Provider value={searchSource}>\n <FlowScreenView\n match={match}\n paths={paths}\n successAuthRedirect={successAuthRedirect}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n relyingPartyId={relyingPartyId}\n />\n </SearchContext.Provider>\n );\n};\n\ntype FlowScreenViewProps = Pick<\n PassflowRoutesProps,\n 'successAuthRedirect' | 'federatedDisplayMode' | 'federatedLanding' | 'relyingPartyId'\n> & {\n match: FlowMatch;\n paths: Record<FlowScreen, string>;\n};\n\n/** The screen a matched path names, wired to the flow's other screens. */\nconst FlowScreenView: FC<FlowScreenViewProps> = ({\n match,\n paths,\n successAuthRedirect,\n federatedDisplayMode,\n federatedLanding,\n relyingPartyId,\n}) => {\n switch (match.screen) {\n case 'signin':\n return (\n <SignIn\n successAuthRedirect={successAuthRedirect}\n relyingPartyId={relyingPartyId}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n signUpPath={paths.signup}\n forgotPasswordPath={paths.forgot_password}\n verifyMagicLinkPath={paths.verify_magic_link}\n verifyOTPPath={paths.verify_otp}\n twoFactorVerifyPath={paths.two_factor_verify}\n />\n );\n case 'signup':\n return (\n <SignUp\n successAuthRedirect={successAuthRedirect}\n relyingPartyId={relyingPartyId}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n signInPath={paths.signin}\n verifyMagicLinkPath={paths.verify_magic_link}\n verifyOTPPath={paths.verify_otp}\n twoFactorVerifyPath={paths.two_factor_verify}\n />\n );\n case 'verify_otp':\n return (\n <VerifyChallengeOTP\n successAuthRedirect={successAuthRedirect}\n numInputs={6}\n shouldAutoFocus\n signUpPath={paths.signup}\n twoFactorVerifyPath={paths.two_factor_verify}\n />\n );\n case 'verify_magic_link':\n return <VerifyChallengeMagicLink signInPath={paths.signin} />;\n case 'forgot_password':\n return (\n <ForgotPassword\n successResetRedirect={successAuthRedirect}\n signInPath={paths.signin}\n forgotPasswordSuccessPath={paths.forgot_password_success}\n />\n );\n case 'forgot_password_success':\n return <ForgotPasswordSuccess />;\n case 'reset_password':\n return (\n <ResetPassword\n successAuthRedirect={successAuthRedirect}\n twoFactorVerifyPath={paths.two_factor_verify}\n signInPath={paths.signin}\n />\n );\n case 'invitation':\n return <InvitationJoin successAuthRedirect={successAuthRedirect} signInPath={paths.signin} signUpPath={paths.signup} />;\n case 'two_factor_verify':\n return <TwoFactorVerifyFlow successAuthRedirect={successAuthRedirect} signInPath={paths.signin} />;\n case 'two_factor_setup':\n return (\n <TwoFactorSetupFlow\n successAuthRedirect={successAuthRedirect}\n twoFactorVerifyPath={paths.two_factor_verify}\n signInPath={paths.signin}\n />\n );\n case 'two_factor_setup_magic_link':\n return <TwoFactorSetupMagicLinkFlow token={match.params.token ?? ''} signInPath={paths.signin} />;\n }\n};\n\nconst PassflowWrapper: FC<PassflowProps> = ({\n successAuthRedirect: requestedRedirect,\n federatedDisplayMode = 'redirect',\n federatedLanding = 'app',\n error = undefined,\n relyingPartyId = window.location.hostname,\n pathPrefix,\n routerType = 'browser',\n location: controlledLocation,\n navigate: controlledNavigate,\n}) => {\n const { error: errorUrlSuccess, message: messageUrlSuccess } = getUrlErrors(requestedRedirect);\n // On an app's own page with the flow's browser router, a full address on this origin is a page of the same app: the\n // sign-in moves there in the app, with no new page load. A hash or memory flow, a location the app passes (offered\n // for routers in hash or memory mode) and a hosted login page keep it as an address to load.\n const followsAddressPath = controlledLocation === undefined && routerType === 'browser';\n const successAuthRedirect =\n federatedLanding === 'app' && followsAddressPath && requestedRedirect\n ? (inAppPath(requestedRedirect) ?? requestedRedirect)\n : requestedRedirect;\n const { location, navigate } = useFlowLocation(routerType, controlledLocation, controlledNavigate);\n const passflow = usePassflow();\n const { federatedLandingOutcome } = useContext(NavigationContext);\n const { ending, retry, finishSignIn } = useSignInEnding();\n\n // Only a code this tab exchanged arms the forward, never the URL or another\n // sign-in. Settings are read here because `appSettings` state may still be null.\n const forwardedRef = useRef(false);\n // Only the outcome arms the forward; any `passflow` instance reads the tokens from storage, so a newer one changes nothing.\n useEffect(() => {\n if (federatedLanding === 'login-page' && federatedLandingOutcome === 'tokens-in-url') void finishSignIn();\n if (federatedLanding !== 'login-page' || federatedLandingOutcome !== 'signed-in' || forwardedRef.current) return;\n forwardedRef.current = true;\n\n const forward = async () => {\n try {\n await finishSignIn(\n successAuthRedirect,\n successAuthRedirect ? undefined : (await passflow.getAppSettings()).defaults?.redirect,\n );\n } catch {\n // No target to forward to: the user stays signed in on this page.\n await finishSignIn();\n }\n };\n void forward();\n }, [federatedLandingOutcome]);\n\n if (federatedLandingOutcome === 'failed') throw new Error(passwordlessSignInFailedMessage);\n\n if (ending !== 'none') return <SignInEndingScreen ending={ending} onRetry={retry} />;\n\n if (errorUrlSuccess) {\n console.error('[passflow] authentication redirect returned an error', {\n error: errorUrlSuccess,\n message: messageUrlSuccess,\n });\n // A federated redirect lands here before SignIn / SignUp mount: allow-listed ids keep the server's localized text.\n throw new Error(authRedirectErrorFrom(errorUrlSuccess, messageUrlSuccess));\n }\n\n if (error) throw new Error(error);\n\n if (!location) return null;\n\n return (\n <PassflowRoutes\n successAuthRedirect={successAuthRedirect}\n federatedDisplayMode={federatedDisplayMode}\n federatedLanding={federatedLanding}\n relyingPartyId={relyingPartyId}\n pathPrefix={pathPrefix}\n location={location}\n navigate={navigate}\n />\n );\n};\n\nexport const PassflowFlow = withError(PassflowWrapper, ErrorComponent);\n","import type { AuthRedirectOptions } from '@passflow/core';\nimport { type FC, type ReactElement, type ReactNode, useState } from 'react';\nimport { type LoginButtonAppearance, LoginButtonView } from '@/components/ui/login-button';\nimport { useAuth } from '@/hooks/use-auth';\nimport { usePassflow } from '@/hooks/use-passflow';\nimport { type PassflowUser, useUser } from '@/hooks/use-user';\nimport { startHostedSignIn } from '@/utils/hosted-sign-in';\n\n/** What a function child of `LoginButton` receives. */\nexport type LoginButtonRenderProps = {\n isSignedIn: boolean;\n /** The label the default button would show now: `signInLabel`, or the signed-in label. */\n label: ReactNode;\n user: PassflowUser;\n /** True while the sign-out is in flight; a click then does nothing. */\n busy: boolean;\n};\n\nexport type LoginButtonProps = {\n /** Shown while signed out. Default \"Sign in\". */\n signInLabel?: ReactNode;\n /** Shown while signed in. Default: the user's email, else the phone, else \"Sign out\". */\n signedInLabel?: (user: PassflowUser) => ReactNode;\n /** Read by assistive technology after the signed-in label, since a click signs out. Default \"Sign out\". */\n signOutDescription?: string;\n /**\n * Passed to `passflow.authRedirect()` on sign-in. Without `redirectUrl`, the hosted login returns to the app\n * root, `${origin}/` (the URL to register), and the provider then takes the user back to the page they\n * started on. A `redirectUrl` given here is used as it is.\n */\n authRedirectOptions?: AuthRedirectOptions;\n /** After a hosted sign-in: where the hosted login sends the browser once signed out. */\n postLogoutRedirectUri?: string;\n /** The look of the default button. Default `passflow`; `shadcn` follows the host app's shadcn/ui theme. */\n appearance?: LoginButtonAppearance;\n /**\n * Your own element as the button, in place of the default one. It is cloned\n * with a click handler that first calls its own `onClick`, then signs in or\n * out unless that called `event.preventDefault()`. A child that calls\n * `onClick()` with no event still signs in or out. Its content is kept as it\n * is: no label is injected. While the sign-out is in flight it gets\n * `disabled` and `aria-busy`; otherwise those stay as you passed them. For a\n * label that switches, pass a function that returns the element; it also\n * receives `busy`.\n */\n children?: ReactElement | ((props: LoginButtonRenderProps) => ReactElement);\n};\n\nconst defaultSignedInLabel = (user: PassflowUser): ReactNode => user.email ?? user.phone ?? 'Sign out';\n\n/**\n * One button that signs in or out. Signed out, a click starts the hosted\n * sign-in (`startHostedSignIn()`); signed in, it shows who is signed in and\n * a click signs out (`useAuth().logout()`). It switches on sign-in and\n * sign-out events.\n *\n * @example\n * ```tsx\n * <LoginButton />\n * <LoginButton appearance='shadcn' postLogoutRedirectUri='https://app.example.com/' />\n * <LoginButton><MyButton>Account</MyButton></LoginButton>\n * <LoginButton>{({ label }) => <MyButton>{label}</MyButton>}</LoginButton>\n * ```\n */\nexport const LoginButton: FC<LoginButtonProps> = ({\n signInLabel = 'Sign in',\n signedInLabel = defaultSignedInLabel,\n signOutDescription,\n authRedirectOptions,\n postLogoutRedirectUri,\n appearance,\n children,\n}) => {\n const passflow = usePassflow();\n const { isSignedIn, logout } = useAuth();\n const user = useUser();\n const [signingOut, setSigningOut] = useState(false);\n\n const label = isSignedIn ? signedInLabel(user) : signInLabel;\n\n // A failure is reported by core's Error event; the button only returns to its idle state.\n const handleClick = () => {\n if (signingOut) return;\n if (!isSignedIn) {\n startHostedSignIn(passflow, authRedirectOptions).catch(() => undefined);\n return;\n }\n setSigningOut(true);\n logout(postLogoutRedirectUri ? { postLogoutRedirectUri } : undefined)\n .catch(() => undefined)\n .finally(() => setSigningOut(false));\n };\n\n return (\n <LoginButtonView\n state={signingOut ? 'signing-out' : isSignedIn ? 'signed-in' : 'signed-out'}\n label={label}\n signOutDescription={signOutDescription}\n appearance={appearance}\n onClick={handleClick}\n >\n {typeof children === 'function' ? children({ isSignedIn, label, user, busy: signingOut }) : children}\n </LoginButtonView>\n );\n};\n"],"mappings":";8B,mqCCSsB,oBAAXsF,SACTA,OAAOC,wBAAA,KAELC,QAAQC,IAAI,yBCThB,IAAMC,EAAwE,CAC5E,UAAW,CACTC,SAAU,CACRC,QAAS,6DACTC,MAAO,eAETC,aAAc,CACZF,QAAS,+EACTC,MAAO,QAETE,QAAS,CACPH,QAAS,iFACTC,MAAO,SAGX,UAAW,CACTF,SAAU,CACRC,QAAS,oFACTC,MAAO,QAETC,aAAc,CACZF,QAAS,oFACTC,MAAO,QAETE,QAAS,CACPH,QAAS,sFACTC,M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